Skip to main content

vortex_array/
executor.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Iterative array execution.
5//!
6//! The single-step [`Executable`] implementation for [`ArrayRef`] tries `reduce`,
7//! `reduce_parent`, `execute_parent`, then `execute` once. The matcher-driven
8//! [`ArrayRef::execute_until`] loop interprets [`ExecutionStep::ExecuteSlot`],
9//! [`ExecutionStep::AppendChild`], and [`ExecutionStep::Done`] using an explicit stack plus an
10//! optional builder, so encodings can advance without recursive descent.
11//!
12//! See <https://docs.vortex.dev/developer-guide/internals/execution> for the full execution
13//! narrative, diagrams, and walkthroughs.
14
15use std::any::TypeId;
16use std::env::VarError;
17use std::fmt;
18use std::fmt::Display;
19use std::sync::Arc;
20use std::sync::LazyLock;
21use std::sync::OnceLock;
22#[cfg(debug_assertions)]
23use std::sync::atomic::AtomicUsize;
24#[cfg(debug_assertions)]
25use std::sync::atomic::Ordering;
26
27use vortex_error::VortexExpect;
28use vortex_error::VortexResult;
29use vortex_error::vortex_bail;
30use vortex_error::vortex_ensure_eq;
31use vortex_error::vortex_panic;
32use vortex_session::VortexSession;
33
34use crate::AnyCanonical;
35use crate::ArrayRef;
36use crate::IntoArray;
37use crate::aggregate_fn::session::AggregateFnSessionExt;
38use crate::aggregate_fn::session::AggregateKernels;
39use crate::array::ArrayId;
40use crate::builders::ArrayBuilder;
41use crate::builders::builder_with_capacity_in;
42use crate::dtype::DType;
43use crate::matcher::Matcher;
44use crate::memory::BufferAllocatorRef;
45use crate::memory::MemorySessionExt;
46use crate::optimizer::Optimizer;
47use crate::optimizer::kernels::ArrayKernelsExt;
48use crate::optimizer::kernels::ParentExecutionKernels;
49use crate::optimizer::kernels::ParentReduceKernels;
50use crate::optimizer::kernels::execute_parent_key;
51use crate::optimizer::kernels::execute_parent_marker_key;
52use crate::optimizer::optimize_with_kernels;
53use crate::stats::ArrayStats;
54use crate::trace_op;
55
56/// Returns the maximum number of iterations to attempt when executing an array before giving up and returning
57/// an error, can be by the `VORTEX_MAX_ITERATIONS` env variables, otherwise defaults to 2^22.
58pub(crate) fn max_iterations() -> usize {
59    static MAX_ITERATIONS: LazyLock<usize> = LazyLock::new(|| {
60        match std::env::var("VORTEX_MAX_ITERATIONS") {
61            Ok(val) => val.parse::<usize>().unwrap_or_else(|e| {
62                vortex_panic!("VORTEX_MAX_ITERATIONS is not a valid usize: {e}")
63            }),
64            Err(VarError::NotPresent) => 2 << 21, // 2 ^ 22
65            Err(VarError::NotUnicode(_)) => {
66                vortex_panic!("VORTEX_MAX_ITERATIONS is not a valid unicode string")
67            }
68        }
69    });
70    *MAX_ITERATIONS
71}
72
73/// Marker trait for types that an [`ArrayRef`] can be executed into.
74///
75/// Implementors must provide an implementation of `execute` that takes
76/// an [`ArrayRef`] and an [`ExecutionCtx`], and produces an instance of the
77/// implementor type.
78///
79/// Users should use the `Array::execute` or `Array::execute_as` methods
80pub trait Executable: Sized {
81    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self>;
82}
83
84#[expect(clippy::same_name_method)]
85impl ArrayRef {
86    /// Execute this array to produce an instance of `E`.
87    ///
88    /// See the [`Executable`] implementation for details on how this execution is performed.
89    pub fn execute<E: Executable>(self, ctx: &mut ExecutionCtx) -> VortexResult<E> {
90        E::execute(self, ctx)
91    }
92
93    /// Execute this array, labeling the execution step with a name for tracing.
94    pub fn execute_as<E: Executable>(
95        self,
96        _name: &'static str,
97        ctx: &mut ExecutionCtx,
98    ) -> VortexResult<E> {
99        E::execute(self, ctx)
100    }
101
102    /// Iteratively execute this array until the [`Matcher`] matches, using an explicit work
103    /// stack plus an optional builder for `AppendChild`.
104    ///
105    /// Note: the returned array may not match `M`. If execution converges to a canonical form
106    /// that does not match `M`, the canonical array is returned since no further execution
107    /// progress is possible.
108    ///
109    /// For safety, this errors once execution reaches a configurable maximum number of
110    /// iterations (default `2^22`, override with `VORTEX_MAX_ITERATIONS`).
111    ///
112    /// # Loop state
113    ///
114    /// - `current_array: ArrayRef` -- the array currently in focus.
115    /// - `current_builder: Option<Box<dyn ArrayBuilder>>` -- active only for builder-mode
116    ///   execution. `AppendChild` appends detached children here. `Done` finishes the builder
117    ///   and turns it back into the next `current_array`.
118    /// - `stack: Vec<StackFrame>` -- suspended parents from `ExecuteSlot`, including the
119    ///   detached slot index, its [`DonePredicate`], and the parent builder that was active
120    ///   before focus moved into the child.
121    ///
122    /// Example after `ExecuteSlot(1, pred)` has focused slot 1 of a parent:
123    ///
124    /// ```text
125    ///   stack[top].parent_array:
126    ///     RunEnd                          <-- suspended parent
127    ///     +-- slot 0: ends
128    ///     +-- slot 1: _  (detached)
129    ///
130    ///   current_array:
131    ///     DictEncoding                    <-- focused child
132    ///     +-- slot 0: codes
133    ///     +-- slot 1: dictionary
134    ///
135    ///   current_builder:
136    ///     None
137    /// ```
138    ///
139    /// Each loop iteration works like this:
140    ///
141    /// ```text
142    /// loop:
143    ///   Step 1: done(current_array)?
144    ///     - root activation   -> return current_array
145    ///     - ExecuteSlot frame -> pop, reattach child, resume parent
146    ///
147    ///   Step 1b: if current_array was rewritten under stack.top and no builder is active:
148    ///               reattach it, try its parent-reduce rules against the parent
149    ///     - rewritten -> pop, the result replaces the parent
150    ///     - none      -> detach it again
151    ///
152    ///   Step 2: current_builder active?
153    ///     - yes -> skip Step 2a / 2b
154    ///     - no  -> try parent kernels
155    ///
156    ///   Step 2a: if stack.top exists:
157    ///               parent = stack.top.parent_array
158    ///               child = current_array
159    ///               kernels[(parent.encoding_id(), child.encoding_id())]
160    ///                 .try_execute_parent(child, parent, stack.top.slot_idx)
161    ///
162    ///   Step 2b: if current_array's encoding has any registered kernel,
163    ///            for child in current_array.children():
164    ///               parent = current_array
165    ///               kernels[(parent.encoding_id(), child.encoding_id())]
166    ///                 .try_execute_parent(child, parent, child.slot_idx)
167    ///
168    ///   Step 3: match current_array.execute()
169    ///     ExecuteSlot(i, pred) -> push parent on stack, focus child `i`
170    ///     AppendChild(i)       -> detach child `i`, append it into current_builder,
171    ///                             keep parent as current_array
172    ///     Done                 -> finish current_builder if present, else use returned array
173    /// ```
174    ///
175    /// Step 2b first checks whether `current_array`'s encoding owns any execute-parent kernel at
176    /// all (a marker entry in the same kernel snapshot), so a pure compression encoding does not
177    /// probe the registry once for each of its children. Step 2a probes only one pair, so a
178    /// marker check there cannot remove a probe.
179    ///
180    /// Step 2a and Step 2b are skipped while `current_builder` is active. `AppendChild`
181    /// partially consumes `current_array`: some slots already live in the builder, so a
182    /// parent rewrite would observe inconsistent state and could discard accumulated builder
183    /// data.
184    #[allow(clippy::cognitive_complexity)]
185    pub fn execute_until<M: Matcher + 'static>(
186        self,
187        ctx: &mut ExecutionCtx,
188    ) -> VortexResult<ArrayRef> {
189        // Cloning the context's kernels releases the borrow of `ctx`, which the kernels need.
190        let ctx_kernels = Arc::clone(&ctx.kernels);
191
192        // One optimizer serves the whole execution, so a shared node that one step rewrote is
193        // reused when a later step reaches it.
194        let mut optimizer = Optimizer::new(&ctx_kernels.reduce_parent);
195
196        // Constructors build lazy arrays, so each node is optimized when execution reaches it: the
197        // root here, with the nodes below it that were never optimized, and a child when execution
198        // focuses it.
199        let mut current_array = optimizer.optimize_array(&self)?;
200
201        // Release the caller's handle, so that the root is not shared for the whole execution.
202        // Encodings that decode a uniquely owned child buffer in place would otherwise copy it.
203        drop(self);
204        let mut current_builder: Option<Box<dyn ArrayBuilder>> = None;
205        let mut stack: Vec<StackFrame> = Vec::new();
206        // Whether `current_array` was rewritten since its parent was suspended, so its
207        // parent-reduce rules have not yet seen it under that parent.
208        let mut child_rewritten = false;
209        let kernels = ctx_kernels.execute_parent.as_ref();
210        let max_iterations = max_iterations();
211
212        trace_op!(record_execute_until_start::<M>(&current_array));
213
214        for _iteration in 0..max_iterations {
215            trace_op!(record_execute_until_iteration(
216                _iteration,
217                &current_array,
218                stack
219                    .last()
220                    .map(|frame| (&frame.parent_array, frame.slot_idx)),
221                current_builder.is_some(),
222            ));
223
224            let (done_target, done_canonical) = match stack.last() {
225                None => root_done_check::<M>(&current_array),
226                Some(frame) => (
227                    (frame.done)(&current_array),
228                    AnyCanonical::matches(&current_array),
229                ),
230            };
231            trace_op!(record_execute_until_done_check(done_target, done_canonical));
232
233            if done_target || done_canonical {
234                match stack.pop() {
235                    None => {
236                        debug_assert!(
237                            current_builder.is_none(),
238                            "root activation should not retain a builder"
239                        );
240                        // Kernels build their results with lazy constructors too, such as a
241                        // filtered validity, so optimize whatever execution produced. This is
242                        // free when the array is already marked as optimized.
243                        current_array = optimizer.optimize_array(&current_array)?;
244                        trace_op!(record_execute_until_return(&current_array));
245                        return Ok(current_array);
246                    }
247                    Some(frame) => {
248                        let _slot_idx = frame.slot_idx;
249                        (current_array, current_builder) = pop_frame(frame, current_array)?;
250                        child_rewritten = false;
251                        trace_op!(record_execute_until_pop_frame(_slot_idx, &current_array));
252                        continue;
253                    }
254                }
255            }
256
257            // Step 1b: parent-reduce rules against the suspended parent.
258            //
259            // Once execution rewrites the child into another encoding, its parent-reduce rules
260            // can match where they did not before, such as a slice that executed into a run-end
261            // array. Skipped while a builder is active at either level, as in Step 2a.
262            if child_rewritten
263                && current_builder.is_none()
264                && stack
265                    .last()
266                    .is_some_and(|frame| frame.parent_builder.is_none())
267            {
268                child_rewritten = false;
269                let frame = stack.pop().vortex_expect("just peeked");
270                let slot_idx = frame.slot_idx;
271                // SAFETY: `current_array` is the executed slot, so it has the slot's dtype and len.
272                let parent = unsafe {
273                    frame
274                        .parent_array
275                        .put_slot_unchecked(slot_idx, current_array)
276                }?;
277                if let Some(reduced) = optimizer.reduce_parent_of_slot(&parent, slot_idx)? {
278                    let child = parent.slots()[slot_idx]
279                        .as_ref()
280                        .vortex_expect("slot was just put back");
281                    log_parent_rewrite(
282                        ctx,
283                        "stack_reduce_parent",
284                        slot_idx,
285                        &parent,
286                        child,
287                        &reduced,
288                    );
289                    reduced.statistics().inherit_from(parent.statistics());
290                    current_array = optimizer.optimize_array(&reduced)?;
291                    current_builder = frame.parent_builder;
292                    // The rewrite replaced the parent, which is the child of the next frame.
293                    child_rewritten = true;
294                    continue;
295                }
296                // SAFETY: the slot is put back unchanged before the parent leaves the executor.
297                let (parent, child) = unsafe { parent.take_slot_unchecked(slot_idx) }?;
298                stack.push(StackFrame {
299                    parent_array: parent,
300                    ..frame
301                });
302                current_array = child;
303            }
304
305            // Step 2a: execute_parent against the suspended parent from ExecuteSlot.
306            //
307            // When executing a child for ExecuteSlot, try execute_parent against
308            // the suspended parent on the stack. This lets kernels like RunEnd's
309            // FilterKernel fire before the child is forced to canonical.
310            //
311            // Skip when a builder is active: the current array has been partially
312            // consumed by AppendChild (some slots are already in the builder), so
313            // a parent rewrite would see inconsistent state and the builder data
314            // would be lost when we restore frame.parent_builder.
315            if current_builder.is_none()
316                && let Some(frame) = stack.last()
317                && let Some(result) = {
318                    execute_parent_for_child(
319                        "stack_execute_parent",
320                        &frame.parent_array,
321                        &current_array,
322                        frame.slot_idx,
323                        kernels,
324                        ctx,
325                    )?
326                }
327            {
328                let frame = stack.pop().vortex_expect("just peeked");
329                let optimized = optimizer.optimize_array(&result)?;
330                trace_op!(record_execute_optimized(&result, &optimized));
331                current_array = optimized;
332                current_builder = frame.parent_builder;
333                child_rewritten = !stack.is_empty();
334                continue;
335            }
336            if current_builder.is_none() && stack.last().is_some() {
337                trace_op!(record_execute_parent_none(
338                    "stack_execute_parent",
339                    &current_array,
340                ));
341            }
342
343            // Step 2b: execute_parent against current_array's own children.
344            if current_builder.is_none()
345                && has_execute_parent_kernels(kernels, &current_array)
346                && let Some(rewritten) = try_execute_parent(&current_array, kernels, ctx)?
347            {
348                let optimized = optimizer.optimize_array(&rewritten)?;
349                trace_op!(record_execute_optimized(&rewritten, &optimized));
350                current_array = optimized;
351                child_rewritten = !stack.is_empty();
352                continue;
353            }
354            if current_builder.is_none() {
355                trace_op!(record_execute_parent_none(
356                    "child_execute_parent",
357                    &current_array,
358                ));
359            }
360
361            let expected_len = current_array.len();
362            // Only the debug postcondition compares dtypes, so skip the clone otherwise.
363            let expected_dtype = cfg!(debug_assertions).then(|| current_array.dtype().clone());
364            // Share the existing stats handle instead of cloning the set; uninitialised stats stay lazy.
365            let stats = current_array.statistics().share_existing();
366            let encoding_id = current_array.encoding_id();
367            trace_op!(record_execute_encoding(&current_array));
368            let result = current_array.execute_encoding_unchecked(ctx)?;
369            let (array, step) = result.into_parts();
370            match step {
371                ExecutionStep::ExecuteSlot(i, done) => {
372                    let (parent, child) = unsafe { array.take_slot_unchecked(i) }?;
373
374                    trace_op!(record_execute_slot(i, &parent, &child));
375                    stack.push(StackFrame {
376                        parent_array: parent,
377                        parent_builder: current_builder.take(),
378                        slot_idx: i,
379                        done,
380                        original_dtype: child.dtype().clone(),
381                        original_len: child.len(),
382                    });
383                    current_array = optimizer.optimize_array(&child)?;
384                    current_builder = None;
385                    child_rewritten = false;
386                }
387                ExecutionStep::AppendChild(i) => {
388                    if current_builder.is_none() {
389                        trace_op!(record_builder_start(&array));
390                        let mut builder =
391                            builder_with_capacity_in(array.dtype(), array.len(), ctx.allocator());
392                        // The parent hands its children over one `AppendChild` at a time, so tell
393                        // the builder how many are coming. A nested builder keeps each appended
394                        // array as a chunk of its child, and without this every one of those chunk
395                        // lists grows incrementally: a 128-chunk array of 8-field structs pays 40
396                        // reallocations for what is eight reserves.
397                        builder.reserve_chunks(array.nchildren());
398                        current_builder = Some(builder);
399                    }
400                    let (parent, child) = unsafe { array.take_slot_unchecked(i) }?;
401
402                    trace_op!(record_append_child(i, &parent, &child));
403                    trace_op!(record_builder_append(&child));
404
405                    // `append_to_builder` optimizes the child itself. The shared optimizer here
406                    // also reuses a shared node that an earlier step of this execution rewrote.
407                    let child = optimizer.optimize_array(&child)?;
408
409                    // TODO(joe)[7674]: replace with a builder kernel registry so we don't
410                    // need to go through the VTable append_to_builder indirection.
411                    child.append_to_builder(
412                        current_builder
413                            .as_deref_mut()
414                            .vortex_expect("builder must exist"),
415                        ctx,
416                    )?;
417                    current_array = parent;
418                }
419                ExecutionStep::Done => {
420                    let had_builder = current_builder.is_some();
421                    trace_op!(record_execute_done(&array));
422                    (current_array, current_builder) = finalize_done(
423                        array,
424                        current_builder,
425                        expected_len,
426                        expected_dtype,
427                        stats,
428                        encoding_id,
429                    )?;
430                    if had_builder {
431                        trace_op!(record_builder_finish(&current_array));
432                    }
433                    // Kernels build their results with lazy constructors, such as a cast that only
434                    // changes nullability. Reduce them before execute-parent kernels see them.
435                    current_array = optimizer.optimize_array(&current_array)?;
436                    child_rewritten = !stack.is_empty();
437                }
438            }
439        }
440
441        vortex_bail!(
442            "Exceeded maximum execution iterations ({}) while executing array",
443            max_iterations,
444        )
445    }
446}
447
448struct StackFrame {
449    parent_array: ArrayRef,
450    parent_builder: Option<Box<dyn ArrayBuilder>>,
451    slot_idx: usize,
452    done: DonePredicate,
453    original_dtype: DType,
454    original_len: usize,
455}
456
457/// The kernels an [`ExecutionCtx`] snapshotted from its session when it was created.
458///
459/// The context holds them in its own `Arc`, which execution clones for each array it executes.
460/// Only this context and its clones share that `Arc`, so the clone does not write to a reference
461/// count that every thread shares, as cloning a snapshot of the session's registries would.
462#[derive(Debug)]
463struct ContextKernels {
464    execute_parent: Arc<ParentExecutionKernels>,
465    reduce_parent: Arc<ParentReduceKernels>,
466}
467
468/// Execution context for batch CPU compute.
469#[derive(Debug, Clone)]
470pub struct ExecutionCtx {
471    session: VortexSession,
472    // OnceLock avoids cloning the session allocator when a context does not allocate.
473    allocator: OnceLock<BufferAllocatorRef>,
474    kernels: Arc<ContextKernels>,
475    // OnceLock avoids snapshotting the aggregate kernels when a context does not aggregate.
476    aggregate_kernels: OnceLock<AggregateKernels>,
477    #[cfg(debug_assertions)]
478    id: usize,
479    #[cfg(debug_assertions)]
480    ops: Vec<String>,
481}
482
483impl ExecutionCtx {
484    /// Create a new execution context with the given session.
485    ///
486    /// This captures a snapshot of the session's execute-parent and parent-reduce kernel
487    /// registries. Kernels registered after this context is created are not visible to it; create
488    /// a new [`ExecutionCtx`] after registration to use newly registered kernels.
489    pub fn new(session: VortexSession) -> Self {
490        let session_kernels = session.kernels();
491        let kernels = Arc::new(ContextKernels {
492            execute_parent: session_kernels.execute_parent_snapshot(),
493            reduce_parent: session_kernels.reduce_parent_snapshot(),
494        });
495        drop(session_kernels);
496        Self {
497            session,
498            allocator: OnceLock::new(),
499            kernels,
500            aggregate_kernels: OnceLock::new(),
501            #[cfg(debug_assertions)]
502            id: {
503                static EXEC_CTX_ID: AtomicUsize = AtomicUsize::new(0);
504                EXEC_CTX_ID.fetch_add(1, Ordering::Relaxed)
505            },
506            #[cfg(debug_assertions)]
507            ops: Vec::new(),
508        }
509    }
510
511    /// Get the session associated with this execution context.
512    pub fn session(&self) -> &VortexSession {
513        &self.session
514    }
515
516    /// The parent-reduce kernels this context snapshotted from its session, which optimizing with
517    /// the context uses instead of looking up the session's kernels again.
518    pub(crate) fn reduce_parent_kernels(&self) -> &ParentReduceKernels {
519        &self.kernels.reduce_parent
520    }
521
522    /// Try to rewrite `array` using a registered execute-parent kernel on one of its children.
523    pub fn try_execute_parent(&mut self, array: &ArrayRef) -> VortexResult<Option<ArrayRef>> {
524        let kernels = Arc::clone(&self.kernels.execute_parent);
525        try_execute_parent(array, kernels.as_ref(), self)
526    }
527
528    /// Get the allocator for this execution context.
529    pub fn allocator(&self) -> &BufferAllocatorRef {
530        self.allocator.get_or_init(|| self.session.allocator())
531    }
532
533    /// Get the aggregate kernels for this execution context.
534    ///
535    /// The session's aggregate kernel registries are snapshotted on first use. Kernels registered
536    /// after that are not visible to this context.
537    pub(crate) fn aggregate_kernels(&self) -> &AggregateKernels {
538        self.aggregate_kernels
539            .get_or_init(|| self.session.aggregate_fns().kernels_snapshot())
540    }
541
542    /// Set the allocator for this execution context.
543    pub fn with_allocator(mut self, allocator: BufferAllocatorRef) -> Self {
544        self.allocator = OnceLock::from(allocator);
545        self
546    }
547
548    /// Log an execution step at the current depth.
549    ///
550    /// Steps are accumulated and dumped as a single trace on Drop at DEBUG level.
551    /// Individual steps are also logged at TRACE level for real-time following.
552    ///
553    /// Use the [`format_args!`] macro to create the `msg` argument.
554    pub fn log(&mut self, msg: fmt::Arguments<'_>) {
555        #[cfg(debug_assertions)]
556        if tracing::enabled!(tracing::Level::TRACE) {
557            let formatted = format!(" - {msg}");
558            tracing::trace!("exec[{}]: {formatted}", self.id);
559            self.ops.push(formatted);
560        }
561        let _ = msg;
562    }
563}
564
565impl Display for ExecutionCtx {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        #[cfg(debug_assertions)]
568        return write!(f, "exec[{}]", self.id);
569        #[cfg(not(debug_assertions))]
570        write!(f, "exec")
571    }
572}
573
574#[cfg(debug_assertions)]
575impl Drop for ExecutionCtx {
576    fn drop(&mut self) {
577        if !self.ops.is_empty() && tracing::enabled!(tracing::Level::DEBUG) {
578            // Unlike itertools `.format()` (panics in 0.14 on second format)
579            struct FmtOps<'a>(&'a [String]);
580            impl Display for FmtOps<'_> {
581                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582                    for (i, op) in self.0.iter().enumerate() {
583                        if i > 0 {
584                            f.write_str("\n")?;
585                        }
586                        f.write_str(op)?;
587                    }
588                    Ok(())
589                }
590            }
591            tracing::debug!("exec[{}] trace:\n{}", self.id, FmtOps(&self.ops));
592        }
593    }
594}
595
596/// Single-step execution: takes one step toward canonical form.
597///
598/// Steps through reduce, reduce_parent, execute_parent, then execute. For `ExecuteSlot`,
599/// only a single child execution step is performed — the child is executed once and put back,
600/// making this a lightweight, bounded operation.
601///
602/// **However**, if `execute_step` returns [`ExecutionStep::AppendChild`], this implementation
603/// drives the *entire* array to completion via [`execute_into_builder`] in a single call.
604/// This can do substantially more work than a normal step because it creates a builder and
605/// fully decodes the array into that builder before returning. Callers should be aware that a
606/// single `.execute::<ArrayRef>(ctx)` call may perform O(n_children * decode_cost) work when
607/// `AppendChild` is returned.
608impl Executable for ArrayRef {
609    fn execute(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
610        trace_op!(record_single_step_start(&array));
611
612        if array.is::<AnyCanonical>() {
613            trace_op!(record_single_step_applied("canonical", &array, &array));
614            return Ok(array);
615        }
616        trace_op!(record_single_step_phase_none("canonical", &array));
617
618        let optimized = optimize_with_kernels(&array, &ctx.kernels.reduce_parent)?;
619        if !ArrayRef::ptr_eq(&optimized, &array) {
620            optimized.statistics().inherit_from(array.statistics());
621            trace_op!(record_single_step_applied("optimize", &array, &optimized));
622            return Ok(optimized);
623        }
624        trace_op!(record_single_step_phase_none("optimize", &array));
625
626        let ctx_kernels = Arc::clone(&ctx.kernels);
627        let kernels = ctx_kernels.execute_parent.as_ref();
628        let has_parent_kernels = has_execute_parent_kernels(kernels, &array);
629
630        for (slot_idx, slot) in array.slots().iter().enumerate() {
631            let Some(child) = slot else { continue };
632            if has_parent_kernels
633                && let Some(executed_parent) = execute_parent_for_child(
634                    "single_step_execute_parent",
635                    &array,
636                    child,
637                    slot_idx,
638                    kernels,
639                    ctx,
640                )?
641            {
642                executed_parent
643                    .statistics()
644                    .inherit_from(array.statistics());
645                trace_op!(record_single_step_applied(
646                    "execute_parent",
647                    &array,
648                    &executed_parent,
649                ));
650                return Ok(executed_parent);
651            }
652        }
653        trace_op!(record_single_step_phase_none("execute_parent", &array));
654        trace_op!(record_execute_encoding(&array));
655
656        let result = array.execute_encoding(ctx)?;
657        let (array, step) = result.into_parts();
658        match step {
659            ExecutionStep::Done => {
660                trace_op!(record_execute_done(&array));
661                Ok(array)
662            }
663            ExecutionStep::ExecuteSlot(i, _) => {
664                let child = array.slots()[i].clone().vortex_expect("valid slot index");
665                let executed_child = child.execute::<ArrayRef>(ctx)?;
666                // SAFETY: execution of a child slot produces a logically equivalent array in a
667                // different physical representation, preserving parent values and statistics.
668                unsafe { array.with_slot(i, executed_child) }
669            }
670            ExecutionStep::AppendChild(_) => {
671                // Single-step: build the entire parent via the builder path.
672                trace_op!(record_builder_start(&array));
673                let builder = builder_with_capacity_in(array.dtype(), array.len(), ctx.allocator());
674                let mut builder = execute_into_builder(array, builder, ctx)?;
675                let output = builder.finish();
676                trace_op!(record_builder_finish(&output));
677                Ok(output)
678            }
679        }
680    }
681}
682
683/// Execute `array` into the given `builder`.
684///
685/// This uses the encoding's [`crate::array::VTable::append_to_builder`] implementation. Most
686/// encodings use the default path of `execute::<Canonical>` followed by re-dispatching
687/// `append_to_builder` on the canonical array, while encodings like `Chunked` can override that to
688/// append child-by-child without materializing the entire parent.
689///
690/// The builder must have a [`DType`] that is a nullability-superset of `array.dtype()`.
691pub fn execute_into_builder(
692    array: ArrayRef,
693    mut builder: Box<dyn ArrayBuilder>,
694    ctx: &mut ExecutionCtx,
695) -> VortexResult<Box<dyn ArrayBuilder>> {
696    array.append_to_builder(builder.as_mut(), ctx)?;
697    Ok(builder)
698}
699
700/// Returns `(matches M, is canonical)`, scanning once when `M` is [`AnyCanonical`].
701#[inline]
702fn root_done_check<M: Matcher + 'static>(array: &ArrayRef) -> (bool, bool) {
703    if TypeId::of::<M>() == TypeId::of::<AnyCanonical>() {
704        let canonical = AnyCanonical::matches(array);
705        return (canonical, canonical);
706    }
707    (M::matches(array), AnyCanonical::matches(array))
708}
709
710/// Pop a stack frame, restoring the parent with the finished child in its slot.
711fn pop_frame(
712    frame: StackFrame,
713    child: ArrayRef,
714) -> VortexResult<(ArrayRef, Option<Box<dyn ArrayBuilder>>)> {
715    debug_assert_eq!(
716        child.dtype(),
717        &frame.original_dtype,
718        "child dtype changed during execution"
719    );
720    debug_assert_eq!(
721        child.len(),
722        frame.original_len,
723        "child len changed during execution"
724    );
725    let parent_array = unsafe { frame.parent_array.put_slot_unchecked(frame.slot_idx, child) }?;
726    Ok((parent_array, frame.parent_builder))
727}
728
729fn finalize_done(
730    result: ArrayRef,
731    mut builder: Option<Box<dyn ArrayBuilder>>,
732    expected_len: usize,
733    expected_dtype: Option<DType>,
734    stats: ArrayStats,
735    encoding_id: ArrayId,
736) -> VortexResult<(ArrayRef, Option<Box<dyn ArrayBuilder>>)> {
737    let output = if let Some(mut builder) = builder.take() {
738        builder.finish()
739    } else {
740        result
741    };
742
743    if cfg!(debug_assertions) {
744        vortex_ensure_eq!(
745            output.len(),
746            expected_len,
747            "Result length mismatch for {:?}",
748            encoding_id
749        );
750        if let Some(expected_dtype) = expected_dtype {
751            vortex_ensure_eq!(
752                output.dtype(),
753                &expected_dtype,
754                "Executed canonical dtype mismatch for {:?}",
755                encoding_id
756            );
757        }
758    }
759
760    output.statistics().transfer_from(&stats);
761    Ok((output, None))
762}
763
764fn execute_parent_for_child(
765    phase: &'static str,
766    parent: &ArrayRef,
767    child: &ArrayRef,
768    slot_idx: usize,
769    kernels: &ParentExecutionKernels,
770    ctx: &mut ExecutionCtx,
771) -> VortexResult<Option<ArrayRef>> {
772    let key = execute_parent_key(parent.encoding_id(), child.encoding_id());
773    if let Some(plugins) = kernels.get(&key) {
774        #[allow(clippy::unused_enumerate_index)]
775        for (_plugin_idx, plugin) in plugins.iter().enumerate() {
776            if let Some(result) = plugin.execute_parent(child, parent, slot_idx, ctx)? {
777                if cfg!(debug_assertions) {
778                    vortex_ensure_eq!(
779                        result.len(),
780                        parent.len(),
781                        "Executed parent canonical length mismatch"
782                    );
783                    vortex_ensure_eq!(
784                        result.dtype(),
785                        parent.dtype(),
786                        "Executed parent canonical dtype mismatch"
787                    );
788                }
789                log_parent_rewrite(ctx, phase, slot_idx, parent, child, &result);
790                trace_op!(record_session_execute_parent_applied(
791                    phase,
792                    parent,
793                    child,
794                    slot_idx,
795                    _plugin_idx,
796                    &result,
797                ));
798                return Ok(Some(result));
799            }
800            trace_op!(record_session_execute_parent_declined(
801                phase,
802                parent,
803                child,
804                slot_idx,
805                _plugin_idx,
806            ));
807        }
808    }
809
810    Ok(None)
811}
812
813/// Log a parent rewrite to the execution log.
814fn log_parent_rewrite(
815    ctx: &mut ExecutionCtx,
816    phase: &'static str,
817    slot_idx: usize,
818    parent: &ArrayRef,
819    child: &ArrayRef,
820    output: &ArrayRef,
821) {
822    ctx.log(format_args!(
823        "{phase}: slot[{slot_idx}]({}) rewrote {parent} -> {output}",
824        child.encoding_id(),
825    ));
826}
827
828/// Whether any execute-parent kernel is registered with `parent`'s encoding as the parent.
829#[inline]
830fn has_execute_parent_kernels(kernels: &ParentExecutionKernels, parent: &ArrayRef) -> bool {
831    kernels.contains_key(&execute_parent_marker_key(parent.encoding_id()))
832}
833
834/// Try execute_parent on each occupied slot of the array.
835fn try_execute_parent(
836    array: &ArrayRef,
837    kernels: &ParentExecutionKernels,
838    ctx: &mut ExecutionCtx,
839) -> VortexResult<Option<ArrayRef>> {
840    for (slot_idx, slot) in array.slots().iter().enumerate() {
841        let Some(child) = slot else { continue };
842        if let Some(executed_parent) =
843            execute_parent_for_child("child_execute_parent", array, child, slot_idx, kernels, ctx)?
844        {
845            executed_parent
846                .statistics()
847                .inherit_from(array.statistics());
848            return Ok(Some(executed_parent));
849        }
850    }
851    Ok(None)
852}
853
854/// A predicate that determines when an array has reached a desired form during execution.
855pub type DonePredicate = fn(&ArrayRef) -> bool;
856
857/// Scheduler step indicator returned alongside an array in [`ExecutionResult`].
858///
859/// Instead of recursively executing children, encodings return an `ExecutionStep` that tells the
860/// scheduler what to do next. This enables the scheduler to manage execution iteratively using
861/// an explicit work stack plus an optional builder.
862///
863/// # Semantics
864///
865/// Each variant describes a different execution strategy with distinct cost profiles:
866///
867/// - [`Done`](ExecutionStep::Done): The current activation has finished its work. If no builder
868///   is active, the returned array is the result. If a builder is active, the scheduler ignores
869///   the placeholder array and finishes the builder instead. The scheduler may continue
870///   executing if the target form (e.g. canonical) has not yet been reached.
871///
872/// - [`ExecuteSlot`](ExecutionStep::ExecuteSlot): The encoding needs one of its children
873///   decoded before it can make further progress. The scheduler detaches that child, pushes
874///   the parent onto the explicit stack, executes the child until the [`DonePredicate`]
875///   matches, puts it back, and re-enters the parent. This is a cooperative yield: the
876///   encoding does a bounded amount of work per step while the loop tracks the parent-child
877///   relationship explicitly.
878///
879/// - [`AppendChild`](ExecutionStep::AppendChild): The encoding needs one child executed to
880///   canonical form and then appended into a builder owned by the current activation. The
881///   scheduler detaches that child, lazily creates `current_builder` if needed, appends the
882///   child into it, and keeps the parent as `current_array` for the next iteration. While the
883///   builder is active, parent-kernel rewrites are skipped because the parent is partially
884///   consumed. **Important:** in the single-step executor ([`Executable`] for [`ArrayRef`]),
885///   returning `AppendChild` still causes the executor to drive the *entire* array to
886///   completion via [`execute_into_builder`] in one call — this can do significantly more
887///   work than a single `ExecuteSlot` step.
888pub enum ExecutionStep {
889    /// Request that the scheduler execute the slot at the given index, using the provided
890    /// [`DonePredicate`] to determine when the slot is "done", then replace the slot in this
891    /// array and re-enter execution.
892    ///
893    /// Use [`ExecutionResult::execute_slot`] instead of constructing this variant directly.
894    ExecuteSlot(usize, DonePredicate),
895
896    /// Detach the slot at the given index, append that child into the current activation's
897    /// canonical builder, and keep the returned parent as `current_array`.
898    ///
899    /// `Done` finalizes that builder and turns it into the result of the activation.
900    ///
901    /// **Note:** In the single-step executor ([`Executable`] for [`ArrayRef`]), this variant
902    /// drives the entire parent to completion in one call via [`execute_into_builder`], which
903    /// may perform substantially more work than a single `ExecuteSlot` step.
904    AppendChild(usize),
905
906    /// Execution is complete. If no builder is active, the array in the accompanying
907    /// [`ExecutionResult`] is the result. Otherwise, the scheduler finalizes the active
908    /// builder and uses that finished array instead.
909    ///
910    /// The scheduler will continue executing if it has not yet reached the target form.
911    Done,
912}
913
914impl fmt::Debug for ExecutionStep {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        match self {
917            ExecutionStep::ExecuteSlot(idx, _) => f.debug_tuple("ExecuteSlot").field(idx).finish(),
918            ExecutionStep::AppendChild(idx) => f.debug_tuple("AppendChild").field(idx).finish(),
919            ExecutionStep::Done => write!(f, "Done"),
920        }
921    }
922}
923
924/// The result of a single execution step on an array encoding.
925///
926/// Combines an [`ArrayRef`] with an [`ExecutionStep`] to tell the scheduler both what to do next
927/// and what array to work with.
928pub struct ExecutionResult {
929    array: ArrayRef,
930    step: ExecutionStep,
931}
932
933impl ExecutionResult {
934    /// Signal that execution is complete with the given result array.
935    pub fn done(result: impl IntoArray) -> Self {
936        Self {
937            array: result.into_array(),
938            step: ExecutionStep::Done,
939        }
940    }
941
942    /// Signal that execution is complete and the result is in the executor's active builder.
943    ///
944    /// Pass the consumed parent array: the executor discards it after finishing the builder,
945    /// avoiding an allocation for a placeholder result.
946    ///
947    /// Only valid once at least one [`ExecutionStep::AppendChild`] has been returned, which
948    /// guarantees that the executor has an active builder. The parent may have empty child slots
949    /// because its children have already been appended; it must not escape the executor.
950    pub fn done_into_builder(array: impl IntoArray) -> Self {
951        Self {
952            array: array.into_array(),
953            step: ExecutionStep::Done,
954        }
955    }
956
957    /// Request execution of slot at `slot_idx` until it matches the given [`Matcher`].
958    ///
959    /// The provided array is the (possibly modified) parent that still needs its slot executed.
960    pub fn execute_slot<M: Matcher>(array: impl IntoArray, slot_idx: usize) -> Self {
961        let array = array.into_array();
962        Self {
963            array,
964            step: ExecutionStep::ExecuteSlot(slot_idx, M::matches),
965        }
966    }
967
968    /// Like [`execute_slot`](Self::execute_slot), but with a [`DonePredicate`] chosen at runtime.
969    pub(crate) fn execute_slot_until(
970        array: ArrayRef,
971        slot_idx: usize,
972        done: DonePredicate,
973    ) -> Self {
974        Self {
975            array,
976            step: ExecutionStep::ExecuteSlot(slot_idx, done),
977        }
978    }
979
980    /// Request that the child slot at `slot_idx` be detached, appended into the current
981    /// activation's canonical builder, and leave the returned parent as the next
982    /// `current_array`.
983    pub fn append_child(array: impl IntoArray, slot_idx: usize) -> Self {
984        let array = array.into_array();
985        Self {
986            array,
987            step: ExecutionStep::AppendChild(slot_idx),
988        }
989    }
990
991    /// Returns a reference to the array.
992    pub fn array(&self) -> &ArrayRef {
993        &self.array
994    }
995
996    /// Returns a reference to the step.
997    pub fn step(&self) -> &ExecutionStep {
998        &self.step
999    }
1000
1001    /// Decompose into parts.
1002    pub fn into_parts(self) -> (ArrayRef, ExecutionStep) {
1003        (self.array, self.step)
1004    }
1005}
1006
1007impl fmt::Debug for ExecutionResult {
1008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009        f.debug_struct("ExecutionResult")
1010            .field("array", &self.array)
1011            .field("step", &self.step)
1012            .finish()
1013    }
1014}
1015
1016/// Require that a child array matches `$M`. If the child already matches, returns the same
1017/// array unchanged. Otherwise, early-returns an [`ExecutionResult`] requesting execution of
1018/// child `$idx` until it matches `$M`.
1019///
1020/// ```ignore
1021/// let array = require_child!(array, array.codes(), 0 => Primitive);
1022/// let array = require_child!(array, array.values(), 1 => AnyCanonical);
1023/// ```
1024#[macro_export]
1025macro_rules! require_child {
1026    ($parent:expr, $child:expr, $idx:expr => $M:ty) => {{
1027        if !$child.is::<$M>() {
1028            return Ok($crate::ExecutionResult::execute_slot::<$M>(
1029                $parent.clone(),
1030                $idx,
1031            ));
1032        }
1033        $parent
1034    }};
1035}
1036
1037/// The scalar function counterpart of [`require_child!`]: require that input `$idx` of `$args`
1038/// matches `$M`. If it does not, early-returns a
1039/// [`ScalarFnExecutionResult`](crate::scalar_fn::ScalarFnExecutionResult) asking the executor to
1040/// execute that input until it matches, so the function is stepped again with the executed input.
1041///
1042/// ```ignore
1043/// require_input!(args, 0 => AnyColumnar);
1044/// ```
1045#[macro_export]
1046macro_rules! require_input {
1047    ($args:expr, $idx:expr => $M:ty) => {
1048        if !$args.input_matches($idx, <$M as $crate::matcher::Matcher>::matches)? {
1049            return Ok($crate::scalar_fn::ScalarFnExecutionResult::execute_input::<
1050                $M,
1051            >($idx));
1052        }
1053    };
1054}
1055
1056/// Like [`require_child!`], but for optional children. If the child is `None`, this is a no-op.
1057/// If the child is `Some` but does not match `$M`, early-returns an [`ExecutionResult`] requesting
1058/// execution of child `$idx`.
1059///
1060/// Unlike `require_child!`, this is a statement macro (no value produced) and does not clone
1061/// `$parent` - it is moved into the early-return path.
1062///
1063/// ```ignore
1064/// require_opt_child!(array, array.patches().map(|p| p.indices()), 1 => Primitive);
1065/// ```
1066#[macro_export]
1067macro_rules! require_opt_child {
1068    ($parent:expr, $child_opt:expr, $idx:expr => $M:ty) => {
1069        if $child_opt.is_some_and(|child| !child.is::<$M>()) {
1070            return Ok($crate::ExecutionResult::execute_slot::<$M>($parent, $idx));
1071        }
1072    };
1073}
1074
1075/// Require that patch slots (indices, values, and optionally chunk_offsets) are `Primitive`.
1076/// If no patches are present (slots are `None`), this is a no-op.
1077///
1078/// Like [`require_opt_child!`], `$parent` is moved (not cloned) into the early-return path.
1079///
1080/// ```ignore
1081/// require_patches!(
1082///     array,
1083///     MySlots::PATCH_INDICES,
1084///     MySlots::PATCH_VALUES,
1085///     MySlots::PATCH_CHUNK_OFFSETS
1086/// );
1087/// ```
1088#[macro_export]
1089macro_rules! require_patches {
1090    ($parent:expr, $indices_slot:expr, $values_slot:expr, $chunk_offsets_slot:expr) => {
1091        $crate::require_opt_child!(
1092            $parent,
1093            $parent.slots()[$indices_slot].as_ref(),
1094            $indices_slot => $crate::arrays::Primitive
1095        );
1096        $crate::require_opt_child!(
1097            $parent,
1098            $parent.slots()[$values_slot].as_ref(),
1099            $values_slot => $crate::arrays::Primitive
1100        );
1101        $crate::require_opt_child!(
1102            $parent,
1103            $parent.slots()[$chunk_offsets_slot].as_ref(),
1104            $chunk_offsets_slot => $crate::arrays::Primitive
1105        );
1106    };
1107}
1108
1109/// Require that the validity slot is columnar ([`Bool`](crate::arrays::Bool) or
1110/// [`Constant`](crate::arrays::Constant)). If validity is not array-backed (e.g. `NonNullable` or
1111/// `AllValid`), or is already a constant bool array (e.g. `AllInvalid`), this is a no-op.
1112/// Otherwise, early-returns an [`ExecutionResult`] requesting execution of the validity slot.
1113///
1114/// Like [`require_opt_child!`], `$parent` is moved (not cloned) into the early-return path.
1115///
1116/// ```ignore
1117/// require_validity!(array, MySlots::VALIDITY);
1118/// ```
1119#[macro_export]
1120macro_rules! require_validity {
1121    ($parent:expr, $idx:expr) => {
1122        $crate::require_opt_child!(
1123            $parent,
1124            $parent.slots()[$idx].as_ref(),
1125            $idx => $crate::AnyColumnar
1126        );
1127    };
1128}
1129
1130/// Extension trait for creating an execution context from a session.
1131pub trait VortexSessionExecute {
1132    /// Create a new execution context from this session.
1133    fn create_execution_ctx(&self) -> ExecutionCtx;
1134}
1135
1136impl VortexSessionExecute for VortexSession {
1137    fn create_execution_ctx(&self) -> ExecutionCtx {
1138        ExecutionCtx::new(self.clone())
1139    }
1140}
1141
1142#[cfg(test)]
1143mod tests {
1144    use static_assertions::assert_impl_all;
1145    use vortex_session::SessionExt;
1146    use vortex_session::VortexSession;
1147
1148    use super::*;
1149    use crate::VTable as _;
1150    use crate::VortexSessionExecute;
1151    use crate::arrays::Bool;
1152    use crate::arrays::BoolArray;
1153    use crate::arrays::Primitive;
1154    use crate::memory::BufferAllocatorRef;
1155    use crate::memory::MemorySession;
1156    use crate::memory::MemorySessionExt;
1157    use crate::optimizer::kernels::ExecuteParentFn;
1158    use crate::optimizer::kernels::KernelSession;
1159    use crate::optimizer::kernels::execute_parent_key;
1160
1161    assert_impl_all!(ExecutionCtx: Send, Sync);
1162
1163    fn noop_execute_parent(
1164        _child: &ArrayRef,
1165        _parent: &ArrayRef,
1166        _child_idx: usize,
1167        _ctx: &mut ExecutionCtx,
1168    ) -> VortexResult<Option<ArrayRef>> {
1169        Ok(None)
1170    }
1171
1172    #[test]
1173    fn execution_ctx_snapshots_execute_parent_kernels_at_creation() {
1174        let session = VortexSession::empty().with_some(KernelSession::empty());
1175        let key = execute_parent_key(Bool.id(), Primitive.id());
1176
1177        let before_registration = session.create_execution_ctx();
1178        assert!(
1179            !before_registration
1180                .kernels
1181                .execute_parent
1182                .contains_key(&key)
1183        );
1184
1185        let kernels = session.kernels();
1186        kernels.register_execute_parent(
1187            Bool.id(),
1188            Primitive.id(),
1189            &[noop_execute_parent as ExecuteParentFn],
1190        );
1191
1192        assert!(
1193            !before_registration
1194                .kernels
1195                .execute_parent
1196                .contains_key(&key)
1197        );
1198
1199        let after_registration = session.create_execution_ctx();
1200        assert!(after_registration.kernels.execute_parent.contains_key(&key));
1201    }
1202
1203    #[test]
1204    fn execution_ctx_snapshot_marks_parents_with_kernels() {
1205        let session = VortexSession::empty().with_some(KernelSession::empty());
1206        let bool_array = BoolArray::from_iter([true, false]).into_array();
1207        let primitive = vortex_buffer::buffer![1i32, 2].into_array();
1208
1209        let before = session.create_execution_ctx();
1210        assert!(!has_execute_parent_kernels(
1211            &before.kernels.execute_parent,
1212            &bool_array
1213        ));
1214
1215        session.kernels().register_execute_parent(
1216            Bool.id(),
1217            Primitive.id(),
1218            &[noop_execute_parent as ExecuteParentFn],
1219        );
1220
1221        let after = session.create_execution_ctx();
1222        assert!(has_execute_parent_kernels(
1223            &after.kernels.execute_parent,
1224            &bool_array
1225        ));
1226        assert!(!has_execute_parent_kernels(
1227            &after.kernels.execute_parent,
1228            &primitive
1229        ));
1230    }
1231
1232    #[test]
1233    fn execution_ctx_allocator_override() {
1234        let first = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator);
1235        let second = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator);
1236        let third = BufferAllocatorRef::new(vortex_buffer::StaticBufferAllocator);
1237        let session = VortexSession::empty()
1238            .with::<MemorySession>()
1239            .with_allocator(first.clone());
1240        let ctx = session.create_execution_ctx();
1241
1242        session
1243            .get_mut::<MemorySession>()
1244            .set_allocator(third.clone());
1245
1246        assert!(session.allocator().ptr_eq(&third));
1247        assert!(ctx.allocator().ptr_eq(&third));
1248
1249        let ctx = ctx.with_allocator(second.clone());
1250        session.get_mut::<MemorySession>().set_allocator(first);
1251
1252        assert!(ctx.allocator().ptr_eq(&second));
1253    }
1254}