Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions docs/developer-guide/internals/execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,13 @@ execute_until<M>(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
│ │ │
Expand Down Expand Up @@ -253,9 +254,12 @@ execute_until<M>(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.
Expand Down
1 change: 0 additions & 1 deletion vortex-array/src/arrays/runend/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Constant>())
Expand Down
264 changes: 84 additions & 180 deletions vortex-array/src/executor.rs → vortex-array/src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
/// 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
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
///
/// Step 2b: if current_array's encoding has any registered kernel,
/// for child in current_array.children():
Expand All @@ -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<M: Matcher + 'static>(
self,
Expand Down Expand Up @@ -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,
&current_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",
&current_array,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Option<ArrayRef>> {
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::<AnyCanonical>(&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::<AnyCanonical>(&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::<AnyCanonical>(&mut ctx)
.is_err()
);

session.register(ExecutionConfig { max_iterations: 1 });
array.execute_until::<AnyCanonical>(&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::<MemorySession>()
.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;
Loading
Loading