diff --git a/docs/developer-guide/internals/execution.md b/docs/developer-guide/internals/execution.md index da11e6a8641..f39d889b666 100644 --- a/docs/developer-guide/internals/execution.md +++ b/docs/developer-guide/internals/execution.md @@ -210,12 +210,13 @@ execute_until(root): │ restore builder, │ │ loop ▼ │ ┌────────────────────────────────────────────┐ - │ │ Step 2a: execute_parent_for_child( │ - │ │ stack.top.parent_array, │ - │ │ current_array ) │ - │ │ lookup session kernels by key: │ - │ │ (parent.encoding_id(), │ - │ │ child.encoding_id()) │ + │ │ Step 2a: if stack.top exists and │ + │ │ stack.top.parent_builder is None and │ + │ │ kernels exist for (parent, child): │ + │ │ reattach child into parent │ + │ │ execute_parent_for_child(parent, child) │ + │ │ - Some -> pop, inherit stats, replace │ + │ │ - None -> detach child again │ │ ├────────────┬───────────────────────────────┘ │ │ Some │ None │ │ │ @@ -253,9 +254,12 @@ execute_until(root): └────────────────────────────────────────────────────── ``` -Step 2a and Step 2b are skipped while `current_builder` is active. `AppendChild` partially -consumes `current_array`: some slots already live in the builder, so a parent rewrite would -observe inconsistent state and could discard accumulated builder data. +Step 2a is skipped while a builder is active on either `current_array` or `stack.top`, and Step 2b +is skipped while `current_builder` is active. `AppendChild` partially consumes an array: some slots +already live in the builder, so a parent rewrite would observe inconsistent state and could lose or +duplicate accumulated builder data. When Step 2a probes registered kernels, it temporarily reattaches +`current_array` into `stack.top.parent_array` so kernels never observe a detached `None` slot, and +detaches it again if all kernels decline. Both Step 2a and Step 2b route through `execute_parent_for_child`, which looks up `(parent.encoding_id(), child.encoding_id())` in the session kernel snapshot. diff --git a/vortex-array/src/arrays/runend/rules.rs b/vortex-array/src/arrays/runend/rules.rs index 6c4c59dc37b..731c617ff77 100644 --- a/vortex-array/src/arrays/runend/rules.rs +++ b/vortex-array/src/arrays/runend/rules.rs @@ -110,7 +110,6 @@ fn supports_run_values(parent: ArrayView<'_, ScalarFn>, child_idx: usize) -> boo parent.dtype(), DType::Bool(_) | DType::Primitive(..) | DType::Utf8(_) ); - // During execution the current child can be detached from its parent. supported_dtype && (0..parent.nchildren()) .all(|idx| idx == child_idx || parent.get_child(idx).is::()) diff --git a/vortex-array/src/executor.rs b/vortex-array/src/executor/mod.rs similarity index 89% rename from vortex-array/src/executor.rs rename to vortex-array/src/executor/mod.rs index e1e4cba9d1f..b8c8cec4051 100644 --- a/vortex-array/src/executor.rs +++ b/vortex-array/src/executor/mod.rs @@ -171,11 +171,13 @@ impl ArrayRef { /// - yes -> skip Step 2a / 2b /// - no -> try parent kernels /// - /// Step 2a: if stack.top exists: - /// parent = stack.top.parent_array - /// child = current_array - /// kernels[(parent.encoding_id(), child.encoding_id())] - /// .try_execute_parent(child, parent, stack.top.slot_idx) + /// Step 2a: if stack.top exists and neither activation has an active builder: + /// if kernels exist for (stack.top.parent_array, current_array): + /// reattach child into parent + /// kernels[(parent.encoding_id(), child.encoding_id())] + /// .try_execute_parent(child, parent, stack.top.slot_idx) + /// - rewritten -> pop, the result replaces the parent + /// - none -> detach child again /// /// Step 2b: if current_array's encoding has any registered kernel, /// for child in current_array.children(): @@ -195,10 +197,10 @@ impl ArrayRef { /// probe the registry once for each of its children. Step 2a probes only one pair, so a /// marker check there cannot remove a probe. /// - /// Step 2a and Step 2b are skipped while `current_builder` is active. `AppendChild` - /// partially consumes `current_array`: some slots already live in the builder, so a - /// parent rewrite would observe inconsistent state and could discard accumulated builder - /// data. + /// Step 2a is skipped while a builder is active on either `current_array` or `stack.top`, and + /// Step 2b is skipped while `current_builder` is active. `AppendChild` partially consumes an + /// array: some slots already live in the builder, so a parent rewrite would observe + /// inconsistent state and could lose or duplicate accumulated builder data. #[allow(clippy::cognitive_complexity)] pub fn execute_until( self, @@ -339,32 +341,70 @@ impl ArrayRef { // the suspended parent on the stack. This lets kernels like RunEnd's // FilterKernel fire before the child is forced to canonical. // - // Skip when a builder is active: the current array has been partially - // consumed by AppendChild (some slots are already in the builder), so - // a parent rewrite would see inconsistent state and the builder data - // would be lost when we restore frame.parent_builder. + // Skip when a builder is active at either level: the array with an + // active builder has been partially consumed by AppendChild (some + // slots are already in the builder), so a parent rewrite would see + // inconsistent state and could lose or duplicate builder data. if current_builder.is_none() - && let Some(frame) = stack.last() - && let Some(result) = { - execute_parent_for_child( - "stack_execute_parent", + && stack + .last() + .is_some_and(|frame| frame.parent_builder.is_none()) + { + let has_kernel = { + let frame = stack.last().vortex_expect("just peeked"); + has_execute_parent_kernel_for_child( + kernels, &frame.parent_array, ¤t_array, - frame.slot_idx, + ) + }; + if has_kernel { + let frame = stack.pop().vortex_expect("just peeked"); + let slot_idx = frame.slot_idx; + debug_assert_eq!( + current_array.dtype(), + &frame.original_dtype, + "child dtype changed during execution" + ); + debug_assert_eq!( + current_array.len(), + frame.original_len, + "child len changed during execution" + ); + // SAFETY: `current_array` is the executed slot, so it has the slot's dtype + // and len. Reattaching it ensures parent kernels never observe a `None` slot. + let parent = unsafe { + frame + .parent_array + .put_slot_unchecked(slot_idx, current_array) + }?; + let child = parent.slots()[slot_idx] + .as_ref() + .vortex_expect("slot was just put back"); + if let Some(result) = execute_parent_for_child( + "stack_execute_parent", + &parent, + child, + slot_idx, kernels, ctx, - )? + )? { + result.statistics().inherit_from(parent.statistics()); + let optimized = optimizer.optimize_array(&result)?; + trace_op!(record_execute_optimized(&result, &optimized)); + current_array = optimized; + current_builder = frame.parent_builder; + child_rewritten = !stack.is_empty(); + continue; + } + // SAFETY: the slot is put back unchanged before the parent leaves the executor. + let (parent, child) = unsafe { parent.take_slot_unchecked(slot_idx) }?; + stack.push(StackFrame { + parent_array: parent, + ..frame + }); + current_array = child; } - { - let frame = stack.pop().vortex_expect("just peeked"); - let optimized = optimizer.optimize_array(&result)?; - trace_op!(record_execute_optimized(&result, &optimized)); - current_array = optimized; - current_builder = frame.parent_builder; - child_rewritten = !stack.is_empty(); - continue; - } - if current_builder.is_none() && stack.last().is_some() { trace_op!(record_execute_parent_none( "stack_execute_parent", ¤t_array, @@ -1020,6 +1060,20 @@ fn log_parent_rewrite( )); } +/// Whether any execute-parent kernel is registered for `(parent, child)`. +#[inline] +fn has_execute_parent_kernel_for_child( + kernels: &ParentExecutionKernels, + parent: &ArrayRef, + child: &ArrayRef, +) -> bool { + execute_parent_ids(parent).any(|parent_id| { + kernels + .get(&execute_parent_key(parent_id, child.encoding_id())) + .is_some_and(|plugins| !plugins.is_empty()) + }) +} + /// Whether the parent has kernels of its own or a child that a generic scalar kernel handles. #[inline] fn has_execute_parent_kernels(kernels: &ParentExecutionKernels, parent: &ArrayRef) -> bool { @@ -1390,154 +1444,4 @@ impl VortexSessionExecute for VortexSession { } #[cfg(test)] -mod tests { - use static_assertions::assert_impl_all; - use vortex_session::VortexSession; - - use super::*; - use crate::VTable as _; - use crate::VortexSessionExecute; - use crate::arrays::Bool; - use crate::arrays::BoolArray; - use crate::arrays::Primitive; - use crate::memory::BufferAllocatorRef; - use crate::memory::MemorySession; - use crate::memory::MemorySessionExt; - use crate::optimizer::kernels::ExecuteParentFn; - use crate::optimizer::kernels::KernelSession; - use crate::optimizer::kernels::execute_parent_key; - - assert_impl_all!(ExecutionCtx: Send, Sync); - - fn noop_execute_parent( - _child: &ArrayRef, - _parent: &ArrayRef, - _child_idx: usize, - _ctx: &mut ExecutionCtx, - ) -> VortexResult> { - Ok(None) - } - - #[test] - fn execution_ctx_snapshots_execute_parent_kernels_at_creation() { - let session = VortexSession::empty().with_some(KernelSession::empty()); - let key = execute_parent_key(Bool.id(), Primitive.id()); - - let before_registration = session.create_execution_ctx(); - assert!( - !before_registration - .kernels - .execute_parent - .contains_key(&key) - ); - - let kernels = session.kernels(); - kernels.register_execute_parent( - Bool.id(), - Primitive.id(), - &[noop_execute_parent as ExecuteParentFn], - ); - - assert!( - !before_registration - .kernels - .execute_parent - .contains_key(&key) - ); - - let after_registration = session.create_execution_ctx(); - assert!(after_registration.kernels.execute_parent.contains_key(&key)); - } - - #[test] - fn execution_ctx_snapshot_marks_parents_with_kernels() { - let session = VortexSession::empty().with_some(KernelSession::empty()); - let bool_array = BoolArray::from_iter([true, false]).into_array(); - let primitive = vortex_buffer::buffer![1i32, 2].into_array(); - - let before = session.create_execution_ctx(); - assert!(!has_execute_parent_kernels( - &before.kernels.execute_parent, - &bool_array - )); - - session.kernels().register_execute_parent( - Bool.id(), - Primitive.id(), - &[noop_execute_parent as ExecuteParentFn], - ); - - let after = session.create_execution_ctx(); - assert!(has_execute_parent_kernels( - &after.kernels.execute_parent, - &bool_array - )); - assert!(!has_execute_parent_kernels( - &after.kernels.execute_parent, - &primitive - )); - } - - #[test] - fn execution_ctx_uses_default_iteration_limit() { - let ctx = VortexSession::empty().create_execution_ctx(); - assert_eq!(ctx.max_iterations(), 1 << 22); - } - - #[test] - fn execution_ctx_uses_session_iteration_limit() -> VortexResult<()> { - let session = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 0 }); - let array = BoolArray::from_iter([true, false]).into_array(); - let error = array - .clone() - .execute_until::(&mut session.create_execution_ctx()) - .unwrap_err(); - assert!( - error - .to_string() - .contains("Exceeded maximum execution iterations (0)") - ); - - let other = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 1 }); - array.execute_until::(&mut other.create_execution_ctx())?; - Ok(()) - } - - #[test] - fn execution_ctx_observes_session_iteration_limit_changes() -> VortexResult<()> { - let session = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 0 }); - let mut ctx = session.create_execution_ctx(); - let array = BoolArray::from_iter([true, false]).into_array(); - assert!( - array - .clone() - .execute_until::(&mut ctx) - .is_err() - ); - - session.register(ExecutionConfig { max_iterations: 1 }); - array.execute_until::(&mut ctx)?; - Ok(()) - } - - #[test] - fn execution_ctx_allocator_override() { - let first = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); - let second = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); - let third = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); - let session = VortexSession::empty() - .with::() - .with_allocator(first.clone()); - let ctx = session.create_execution_ctx(); - - let session = session.with_allocator(third.clone()); - - assert!(session.allocator().ptr_eq(&third)); - assert!(ctx.allocator().ptr_eq(&third)); - - let ctx = ctx.with_allocator(second.clone()); - let _session = session.with_allocator(first); - - assert!(ctx.allocator().ptr_eq(&second)); - } -} +mod tests; diff --git a/vortex-array/src/executor/tests.rs b/vortex-array/src/executor/tests.rs new file mode 100644 index 00000000000..de5d582bff2 --- /dev/null +++ b/vortex-array/src/executor/tests.rs @@ -0,0 +1,541 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::fmt::Formatter; +use std::hash::Hasher; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +use rstest::rstest; +use smallvec::smallvec; +use static_assertions::assert_impl_all; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_panic; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use super::*; +use crate::ArrayEq; +use crate::ArrayHash; +use crate::ArraySlots; +use crate::EqMode; +use crate::VTable; +use crate::VortexSessionExecute; +use crate::array::Array; +use crate::array::ArrayParts; +use crate::array::ArrayView; +use crate::array::EmptyArrayData; +use crate::array::vtable::NotSupported; +use crate::array::vtable::ValidityChild; +use crate::array::vtable::ValidityVTable; +use crate::array::vtable::ValidityVTableFromChild; +use crate::array::vtable::with_empty_buffers; +use crate::arrays::Bool; +use crate::arrays::BoolArray; +use crate::arrays::Primitive; +use crate::arrays::PrimitiveArray; +use crate::assert_arrays_eq; +use crate::buffer::BufferHandle; +use crate::kernel::ExecuteParentKernel; +use crate::memory::BufferAllocatorRef; +use crate::memory::MemorySession; +use crate::memory::MemorySessionExt; +use crate::optimizer::kernels::ExecuteParentFn; +use crate::optimizer::kernels::KernelSession; +use crate::optimizer::kernels::execute_parent_key; +use crate::session::ArraySession; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; +use crate::validity::Validity; + +assert_impl_all!(ExecutionCtx: Send, Sync); + +fn noop_execute_parent( + _child: &ArrayRef, + _parent: &ArrayRef, + _child_idx: usize, + _ctx: &mut ExecutionCtx, +) -> VortexResult> { + Ok(None) +} + +#[test] +fn execution_ctx_snapshots_execute_parent_kernels_at_creation() { + let session = VortexSession::empty().with_some(KernelSession::empty()); + let key = execute_parent_key(Bool.id(), Primitive.id()); + + let before_registration = session.create_execution_ctx(); + assert!( + !before_registration + .kernels + .execute_parent + .contains_key(&key) + ); + + let kernels = session.kernels(); + kernels.register_execute_parent( + Bool.id(), + Primitive.id(), + &[noop_execute_parent as ExecuteParentFn], + ); + + assert!( + !before_registration + .kernels + .execute_parent + .contains_key(&key) + ); + + let after_registration = session.create_execution_ctx(); + assert!(after_registration.kernels.execute_parent.contains_key(&key)); +} + +#[test] +fn execution_ctx_snapshot_marks_parents_with_kernels() { + let session = VortexSession::empty().with_some(KernelSession::empty()); + let bool_array = BoolArray::from_iter([true, false]).into_array(); + let primitive = vortex_buffer::buffer![1i32, 2].into_array(); + + let before = session.create_execution_ctx(); + assert!(!has_execute_parent_kernels( + &before.kernels.execute_parent, + &bool_array + )); + + session.kernels().register_execute_parent( + Bool.id(), + Primitive.id(), + &[noop_execute_parent as ExecuteParentFn], + ); + + let after = session.create_execution_ctx(); + assert!(has_execute_parent_kernels( + &after.kernels.execute_parent, + &bool_array + )); + assert!(!has_execute_parent_kernels( + &after.kernels.execute_parent, + &primitive + )); +} + +#[test] +fn execution_ctx_uses_default_iteration_limit() { + let ctx = VortexSession::empty().create_execution_ctx(); + assert_eq!(ctx.max_iterations(), 1 << 22); +} + +#[test] +fn execution_ctx_uses_session_iteration_limit() -> VortexResult<()> { + let session = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 0 }); + let array = BoolArray::from_iter([true, false]).into_array(); + let error = array + .clone() + .execute_until::(&mut session.create_execution_ctx()) + .unwrap_err(); + assert!( + error + .to_string() + .contains("Exceeded maximum execution iterations (0)") + ); + + let other = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 1 }); + array.execute_until::(&mut other.create_execution_ctx())?; + Ok(()) +} + +#[test] +fn execution_ctx_observes_session_iteration_limit_changes() -> VortexResult<()> { + let session = VortexSession::empty().with_some(ExecutionConfig { max_iterations: 0 }); + let mut ctx = session.create_execution_ctx(); + let array = BoolArray::from_iter([true, false]).into_array(); + assert!( + array + .clone() + .execute_until::(&mut ctx) + .is_err() + ); + + session.register(ExecutionConfig { max_iterations: 1 }); + array.execute_until::(&mut ctx)?; + Ok(()) +} + +#[test] +fn execution_ctx_allocator_override() { + let first = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); + let second = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); + let third = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator); + let session = VortexSession::empty() + .with::() + .with_allocator(first.clone()); + let ctx = session.create_execution_ctx(); + + let session = session.with_allocator(third.clone()); + + assert!(session.allocator().ptr_eq(&third)); + assert!(ctx.allocator().ptr_eq(&third)); + + let ctx = ctx.with_allocator(second.clone()); + let _session = session.with_allocator(first); + + assert!(ctx.allocator().ptr_eq(&second)); +} + +#[derive(Clone, Debug)] +struct TestValuesData { + values: PrimitiveArray, +} + +impl Display for TestValuesData { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.write_str("test-values") + } +} + +impl ArrayHash for TestValuesData { + fn array_hash(&self, state: &mut H, eq_mode: EqMode) { + self.values.as_array().array_hash(state, eq_mode); + } +} + +impl ArrayEq for TestValuesData { + fn array_eq(&self, other: &Self, eq_mode: EqMode) -> bool { + self.values + .as_array() + .array_eq(other.values.as_array(), eq_mode) + } +} + +#[derive(Clone, Debug)] +struct TestChild; + +impl ValidityVTable for TestChild { + fn validity(array: ArrayView<'_, TestChild>) -> VortexResult { + array.data().values.validity() + } +} + +impl VTable for TestChild { + type TypedArrayData = TestValuesData; + type OperationsVTable = NotSupported; + type ValidityVTable = Self; + + fn id(&self) -> ArrayId { + static ID: CachedId = CachedId::new("vortex.test.executor-test-child"); + *ID + } + + fn validate( + &self, + data: &Self::TypedArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + vortex_ensure_eq!(data.values.dtype(), dtype); + vortex_ensure_eq!(data.values.len(), len); + vortex_ensure!(slots.is_empty(), "TestChild must not have slots"); + Ok(()) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("TestChild buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option { + None + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + with_empty_buffers(self, array, buffers) + } + + fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { + vortex_panic!("TestChild slot index {idx} out of bounds") + } + + fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { + Ok(ExecutionResult::done(array.data().values.clone())) + } +} + +fn test_child(values: PrimitiveArray) -> VortexResult { + let dtype = values.dtype().clone(); + let len = values.len(); + Ok(Array::try_from_parts(ArrayParts::new( + TestChild, + dtype, + len, + TestValuesData { values }, + ArraySlots::new(), + ))? + .into_array()) +} + +/// Parent with 1 or 2 child slots: +/// - 1 slot: suspends via `ExecuteSlot(0)` without a builder and returns the executed child. +/// - 2 slots: appends slot 0 into the builder, suspends via `ExecuteSlot(1)` with an active +/// `parent_builder`, then appends slot 1 and finishes the builder. +#[derive(Clone, Debug)] +struct TestParent; + +impl ValidityChild for TestParent { + fn validity_child(array: ArrayView<'_, TestParent>) -> ArrayRef { + array + .slots() + .last() + .and_then(Option::clone) + .vortex_expect("TestParent child slot must be present") + } +} + +impl VTable for TestParent { + type TypedArrayData = EmptyArrayData; + type OperationsVTable = NotSupported; + type ValidityVTable = ValidityVTableFromChild; + + fn id(&self) -> ArrayId { + static ID: CachedId = CachedId::new("vortex.test.executor-test-parent"); + *ID + } + + fn validate( + &self, + _data: &Self::TypedArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + vortex_ensure!( + matches!(slots.len(), 1 | 2), + "TestParent expects 1 or 2 slots" + ); + let mut total_len = 0; + for slot in slots { + let Some(child) = slot else { + vortex_bail!("TestParent child slot is missing"); + }; + vortex_ensure_eq!(child.dtype(), dtype); + total_len += child.len(); + } + vortex_ensure_eq!(total_len, len); + Ok(()) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("TestParent buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option { + None + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + with_empty_buffers(self, array, buffers) + } + + fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { + match idx { + 0 => "first".to_string(), + 1 => "second".to_string(), + _ => vortex_panic!("TestParent slot index {idx} out of bounds"), + } + } + + fn execute(array: Array, _ctx: &mut ExecutionCtx) -> VortexResult { + if array.slots().len() == 1 { + let child = array.slots()[0] + .as_ref() + .vortex_expect("TestParent child slot must be present"); + if !child.is::() { + return Ok(ExecutionResult::execute_slot::(array, 0)); + } + return Ok(ExecutionResult::done(child.clone())); + } + + if array.slots()[0].is_some() { + return Ok(ExecutionResult::append_child(array, 0)); + } + if let Some(second) = array.slots()[1].as_ref() { + if !second.is::() { + return Ok(ExecutionResult::execute_slot::(array, 1)); + } + return Ok(ExecutionResult::append_child(array, 1)); + } + Ok(ExecutionResult::done_into_builder(array)) + } +} + +#[derive(Debug)] +struct ForbiddenBuilderParentKernel { + called: Arc, +} + +impl ExecuteParentKernel for ForbiddenBuilderParentKernel { + type Parent = TestParent; + + fn execute_parent( + &self, + _array: ArrayView<'_, TestChild>, + parent: ::Match<'_>, + _child_idx: usize, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + // Decline Step 2b before AppendChild(0) runs; any call after slot 0 is taken proves + // Step 2a fired while frame.parent_builder was active. + if parent.slots()[0].is_some() { + return Ok(None); + } + self.called.store(true, Ordering::SeqCst); + Ok(Some( + PrimitiveArray::from_iter(0..i32::try_from(parent.len()).vortex_expect("len")) + .into_array(), + )) + } +} + +#[test] +fn test_stack_execute_parent_skips_when_parent_builder_is_active() -> VortexResult<()> { + let called = Arc::new(AtomicBool::new(false)); + let session = VortexSession::empty().with::(); + session.kernels().register_execute_parent_kernel( + TestParent.id(), + TestChild, + ForbiddenBuilderParentKernel { + called: Arc::clone(&called), + }, + ); + let mut ctx = session.create_execution_ctx(); + + let first = PrimitiveArray::from_iter([10i32, 20]).into_array(); + let second = test_child(PrimitiveArray::from_iter([30i32, 40]))?; + let parent = Array::try_from_parts(ArrayParts::new( + TestParent, + first.dtype().clone(), + first.len() + second.len(), + EmptyArrayData, + smallvec![Some(first), Some(second)], + ))? + .into_array(); + + let output = parent.execute::(&mut ctx)?; + assert!( + !called.load(Ordering::SeqCst), + "stack_execute_parent must not run while frame.parent_builder is active" + ); + assert_arrays_eq!( + output, + PrimitiveArray::from_iter([10i32, 20, 30, 40]), + &mut ctx + ); + Ok(()) +} + +#[derive(Debug)] +struct InspectSlotParentKernel { + seen_once: AtomicBool, + called: Arc, + rewrite_to: Option, +} + +impl ExecuteParentKernel for InspectSlotParentKernel { + type Parent = TestParent; + + fn execute_parent( + &self, + array: ArrayView<'_, TestChild>, + parent: ::Match<'_>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + // Decline the initial Step 2b probe so TestParent suspends via ExecuteSlot(0), then + // verify the Step 2a probe observes the child slot reattached. + if !self.seen_once.swap(true, Ordering::Relaxed) { + return Ok(None); + } + self.called.store(true, Ordering::SeqCst); + let slot = parent.slots()[child_idx] + .as_ref() + .expect("parent slot must be reattached during stack_execute_parent"); + assert!(ArrayRef::ptr_eq(slot, array.array())); + let mask = parent.validity()?.execute_mask(parent.len(), ctx)?; + assert_eq!(mask, Mask::from_iter([true, false, true])); + Ok(self.rewrite_to.clone().map(IntoArray::into_array)) + } +} + +#[rstest] +#[case::rewrite( + Some(PrimitiveArray::from_option_iter([Some(100i32), None, Some(300)])), + PrimitiveArray::from_option_iter([Some(100i32), None, Some(300)]) +)] +#[case::decline( + None, + PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]) +)] +fn test_stack_execute_parent_reattaches_slot_before_kernel( + #[case] rewrite_to: Option, + #[case] expected: PrimitiveArray, +) -> VortexResult<()> { + let called = Arc::new(AtomicBool::new(false)); + let session = VortexSession::empty().with::(); + session.kernels().register_execute_parent_kernel( + TestParent.id(), + TestChild, + InspectSlotParentKernel { + seen_once: AtomicBool::new(false), + called: Arc::clone(&called), + rewrite_to, + }, + ); + let mut ctx = session.create_execution_ctx(); + + let child = test_child(PrimitiveArray::from_option_iter([ + Some(1i32), + None, + Some(3), + ]))?; + let parent = Array::try_from_parts(ArrayParts::new( + TestParent, + child.dtype().clone(), + child.len(), + EmptyArrayData, + smallvec![Some(child)], + ))? + .into_array(); + parent + .statistics() + .set(Stat::NullCount, Precision::exact(1u64)); + + let output = parent.execute::(&mut ctx)?; + assert!( + called.load(Ordering::SeqCst), + "stack_execute_parent kernel should have been invoked" + ); + assert_eq!( + output.statistics().get_as::(Stat::NullCount), + Precision::exact(1u64) + ); + assert_arrays_eq!(output, expected, &mut ctx); + Ok(()) +} diff --git a/vortex-array/src/test_harness/trace/tests.rs b/vortex-array/src/test_harness/trace/tests.rs index 3c9167bbfcd..d3c67181de5 100644 --- a/vortex-array/src/test_harness/trace/tests.rs +++ b/vortex-array/src/test_harness/trace/tests.rs @@ -5,6 +5,8 @@ use std::fmt::Display; use std::fmt::Formatter; use std::hash::Hasher; use std::sync::LazyLock; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use rstest::fixture; use rstest::rstest; @@ -80,7 +82,11 @@ fn stack_parent_session() -> VortexSession { let session = VortexSession::empty().with::(); let kernels = session.kernels(); kernels.register_execute_parent_kernel(StackParent.id(), StackChild, StackDeclineKernel); - kernels.register_execute_parent_kernel(StackParent.id(), StackChild, StackParentKernel); + kernels.register_execute_parent_kernel( + StackParent.id(), + StackChild, + StackParentKernel::default(), + ); drop(kernels); session } @@ -306,8 +312,10 @@ impl ExecuteParentKernel for StackDeclineKernel { } } -#[derive(Debug)] -struct StackParentKernel; +#[derive(Debug, Default)] +struct StackParentKernel { + seen_once: AtomicBool, +} impl ExecuteParentKernel for StackParentKernel { type Parent = StackParent; @@ -319,11 +327,10 @@ impl ExecuteParentKernel for StackParentKernel { child_idx: usize, _ctx: &mut ExecutionCtx, ) -> VortexResult> { - if parent - .slots() - .get(child_idx) - .is_some_and(|slot| slot.is_none()) - { + // Decline the initial child_execute_parent probe so the parent suspends via ExecuteSlot, + // then accept the stack_execute_parent probe with the child slot restored. + if self.seen_once.swap(true, Ordering::Relaxed) { + assert!(parent.slots()[child_idx].is_some()); return Ok(Some(PrimitiveArray::from_iter([1i32, 2, 3]).into_array())); }