Skip to main content

vortex_array/optimizer/
kernels.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Session-scoped registry of parent kernels.
5//!
6//! [`ArrayKernels`] holds two kinds of kernels. Each kernel is registered for a parent and a child:
7//!
8//! - The optimizer uses parent-reduce rules to rewrite a parent array from one of its children,
9//!   without decoding data.
10//! - The executor uses execute-parent kernels to execute a parent array through one of its
11//!   children.
12//!
13//! The parent is the encoding of the parent array, or the function of a scalar function array.
14//! When more than one kernel is registered for the same parent and child, they are tried in
15//! registration order until one applies.
16//!
17//! [`KernelSession`] is the session variable that holds the registry. Its [`Default`]
18//! implementation registers the built-in kernels of `vortex-array`.
19
20use std::any::Any;
21use std::any::TypeId;
22use std::borrow::Borrow;
23use std::fmt::Debug;
24use std::hash::BuildHasher;
25use std::marker::PhantomData;
26use std::ops::Deref;
27use std::ptr;
28use std::sync::Arc;
29use std::sync::LazyLock;
30
31use arc_swap::ArcSwap;
32use vortex_error::VortexResult;
33use vortex_session::SessionExt;
34use vortex_session::SessionGuard;
35use vortex_session::SessionVar;
36use vortex_session::VortexSession;
37use vortex_session::registry::Id;
38use vortex_utils::aliases::DefaultHashBuilder;
39use vortex_utils::aliases::hash_map::HashMap;
40
41use crate::ArrayRef;
42use crate::ExecutionCtx;
43use crate::array::VTable;
44use crate::arrays::ScalarFn;
45use crate::arrays::scalar_fn::AnyScalarFn;
46use crate::kernel::ExecuteParentKernel;
47use crate::matcher::Matcher;
48use crate::optimizer::reduce_parent_with_kernels;
49use crate::optimizer::rules::ArrayParentReduceRule;
50use crate::scalar_fn::ScalarFnVTable;
51
52/// Shared hasher used to combine `(outer, child)` tuples into registry keys.
53static FN_HASHER: LazyLock<DefaultHashBuilder> = LazyLock::new(DefaultHashBuilder::default);
54
55/// Type-erased parent-reduce kernel stored in the session registry.
56pub(crate) trait DynReduceParentKernel: Debug + Send + Sync + 'static {
57    /// Attempt to rewrite `parent` given its child at `child_idx`.
58    fn reduce_parent(
59        &self,
60        child: &ArrayRef,
61        parent: &ArrayRef,
62        child_idx: usize,
63    ) -> VortexResult<Option<ArrayRef>>;
64}
65
66pub(crate) type ReduceParentKernelRef = &'static dyn DynReduceParentKernel;
67
68/// A snapshot of the session's parent-reduce kernels, as the optimizer consults them.
69#[derive(Clone, Debug, Default)]
70pub(crate) struct ParentReduceKernels {
71    /// Kernels keyed by hashed `(parent, child)` pair.
72    kernels: HashMap<ReduceParentFnId, Box<[ReduceParentKernelRef]>>,
73    /// The child ids each parent id has kernels for, so a parent can skip children that no kernel
74    /// is registered for without probing each pair.
75    children: HashMap<Id, Box<[Id]>>,
76}
77
78impl ParentReduceKernels {
79    /// Returns the kernels registered for `(parent, child)`.
80    pub(crate) fn get(&self, parent: Id, child: Id) -> Option<&[ReduceParentKernelRef]> {
81        self.kernels
82            .get(&hash_fn_id(parent, child))
83            .map(AsRef::as_ref)
84    }
85
86    /// Returns the child ids that kernels are registered for under `parent`.
87    pub(crate) fn children(&self, parent: Id) -> Option<&[Id]> {
88        self.children.get(&parent).map(AsRef::as_ref)
89    }
90
91    fn push(&mut self, parent: Id, child: Id, kernel: ReduceParentKernelRef) {
92        append(
93            self.kernels
94                .entry(hash_fn_id(parent, child).into())
95                .or_default(),
96            [kernel],
97        );
98
99        let children = self.children.entry(parent).or_default();
100        if !children.contains(&child) {
101            append(children, [child]);
102        }
103    }
104}
105
106/// Appends `items` to a boxed slice. Registration replaces the kernel maps rather than growing
107/// them in place, so the slices keep no spare capacity.
108fn append<T>(slice: &mut Box<[T]>, items: impl IntoIterator<Item = T>) {
109    let mut items_vec = std::mem::take(slice).into_vec();
110    items_vec.extend(items);
111    *slice = items_vec.into_boxed_slice();
112}
113
114#[repr(transparent)]
115struct RegisteredReduceParentRule<V, R> {
116    rule: R,
117    _child: PhantomData<V>,
118}
119
120impl<V: VTable, R: ArrayParentReduceRule<V>> RegisteredReduceParentRule<V, R> {
121    /// Views a static rule as a parent-reduce kernel for the `V` child encoding.
122    const fn lift(rule: &'static R) -> ReduceParentKernelRef {
123        // SAFETY: `RegisteredReduceParentRule` is `repr(transparent)` over `rule`, and its only
124        // other field is a zero-sized `PhantomData`, so it has the same layout as `R`.
125        unsafe { &*ptr::from_ref(rule).cast::<Self>() }
126    }
127}
128
129impl<V, R: Debug> Debug for RegisteredReduceParentRule<V, R> {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        f.debug_struct("RegisteredReduceParentRule")
132            .field("rule", &self.rule)
133            .finish()
134    }
135}
136
137impl<V, R> DynReduceParentKernel for RegisteredReduceParentRule<V, R>
138where
139    V: VTable,
140    R: ArrayParentReduceRule<V>,
141{
142    fn reduce_parent(
143        &self,
144        child: &ArrayRef,
145        parent: &ArrayRef,
146        child_idx: usize,
147    ) -> VortexResult<Option<ArrayRef>> {
148        let (Some(child), Some(parent)) = (child.as_opt::<V>(), R::Parent::try_match(parent))
149        else {
150            return Ok(None);
151        };
152        self.rule.reduce_parent(child, parent, child_idx)
153    }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
157#[repr(transparent)]
158pub(crate) struct ReduceParentFnId(u64);
159
160impl From<u64> for ReduceParentFnId {
161    fn from(id: u64) -> Self {
162        Self(id)
163    }
164}
165
166impl Borrow<u64> for ReduceParentFnId {
167    fn borrow(&self) -> &u64 {
168        &self.0
169    }
170}
171
172/// Function pointer for a plugin-provided parent execution.
173///
174/// The executor calls this with the matched `child`, its `parent`, the slot index where the child
175/// appears, and the current [`ExecutionCtx`]. Return `Ok(Some(new_parent))` to replace the parent
176/// with an executed result, or `Ok(None)` when the kernel does not apply.
177///
178/// Implementations must preserve the parent's logical length and dtype, matching the invariant
179/// required of static `execute_parent` kernels.
180pub type ExecuteParentFn = fn(
181    child: &ArrayRef,
182    parent: &ArrayRef,
183    child_idx: usize,
184    ctx: &mut ExecutionCtx,
185) -> VortexResult<Option<ArrayRef>>;
186
187/// Type-erased execute-parent kernel stored in the session registry.
188pub trait DynExecuteParentKernel: Debug + Send + Sync + 'static {
189    /// Attempt to execute the parent array fused with the child array.
190    fn execute_parent(
191        &self,
192        child: &ArrayRef,
193        parent: &ArrayRef,
194        child_idx: usize,
195        ctx: &mut ExecutionCtx,
196    ) -> VortexResult<Option<ArrayRef>>;
197}
198
199pub(crate) type ExecuteParentKernelRef = Arc<dyn DynExecuteParentKernel>;
200
201pub(crate) type ParentExecutionKernels = HashMap<ExecuteParentFnId, Box<[ExecuteParentKernelRef]>>;
202
203#[derive(Debug)]
204struct ExecuteParentFnKernel(ExecuteParentFn);
205
206impl DynExecuteParentKernel for ExecuteParentFnKernel {
207    fn execute_parent(
208        &self,
209        child: &ArrayRef,
210        parent: &ArrayRef,
211        child_idx: usize,
212        ctx: &mut ExecutionCtx,
213    ) -> VortexResult<Option<ArrayRef>> {
214        self.0(child, parent, child_idx, ctx)
215    }
216}
217
218#[derive(Debug)]
219struct RegisteredExecuteParentKernel<V, K> {
220    _child: V,
221    kernel: K,
222}
223
224impl<V, K> DynExecuteParentKernel for RegisteredExecuteParentKernel<V, K>
225where
226    V: VTable,
227    K: ExecuteParentKernel<V>,
228{
229    fn execute_parent(
230        &self,
231        child: &ArrayRef,
232        parent: &ArrayRef,
233        child_idx: usize,
234        ctx: &mut ExecutionCtx,
235    ) -> VortexResult<Option<ArrayRef>> {
236        let Some(child) = child.as_opt::<V>() else {
237            return Ok(None);
238        };
239        let Some(parent) = K::Parent::try_match(parent) else {
240            return Ok(None);
241        };
242
243        self.kernel.execute_parent(child, parent, child_idx, ctx)
244    }
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
248#[repr(transparent)]
249pub(crate) struct ExecuteParentFnId(u64);
250
251impl From<u64> for ExecuteParentFnId {
252    fn from(id: u64) -> Self {
253        Self(id)
254    }
255}
256
257impl Borrow<u64> for ExecuteParentFnId {
258    fn borrow(&self) -> &u64 {
259        &self.0
260    }
261}
262
263/// The parent that a parent-reduce rule is registered under.
264///
265/// A parent is an array encoding, such as [`Filter`](crate::arrays::Filter), or a scalar function,
266/// such as [`Cast`](crate::scalar_fn::builtin::cast::Cast), because a `ScalarFnArray` is identified by
267/// its function. [`AnyScalarFn`] is the parent for a rule that applies to any scalar function
268/// array. The `Kind` parameter only keeps these implementations apart, and callers never name it.
269pub trait ReduceParent<Kind> {
270    /// The id that the parent is registered under.
271    fn parent_id(&self) -> Id;
272}
273
274/// The [`ReduceParent`] kind of an array encoding.
275#[derive(Debug)]
276pub struct EncodingParent;
277
278/// The [`ReduceParent`] kind of a scalar function.
279#[derive(Debug)]
280pub struct ScalarFnParent;
281
282impl<V: VTable> ReduceParent<EncodingParent> for V {
283    fn parent_id(&self) -> Id {
284        VTable::id(self)
285    }
286}
287
288impl<F: ScalarFnVTable> ReduceParent<ScalarFnParent> for F {
289    fn parent_id(&self) -> Id {
290        ScalarFnVTable::id(self)
291    }
292}
293
294impl ReduceParent<AnyScalarFn> for AnyScalarFn {
295    fn parent_id(&self) -> Id {
296        self.id()
297    }
298}
299
300/// Session-scoped registry of parent-reduce rules and execute-parent kernels.
301///
302/// Kernels registered for the same parent and child are tried in registration order.
303#[derive(Clone, Debug)]
304pub struct ArrayKernels {
305    reduce_parent: Arc<ArcSwap<ParentReduceKernels>>,
306    execute_parent: Arc<ArcSwap<ParentExecutionKernels>>,
307}
308
309impl Default for ArrayKernels {
310    fn default() -> ArrayKernels {
311        Self::empty()
312    }
313}
314
315impl ArrayKernels {
316    /// Create an empty [`ArrayKernels`] with no kernels registered.
317    pub fn empty() -> Self {
318        Self {
319            reduce_parent: Arc::default(),
320            execute_parent: Arc::default(),
321        }
322    }
323
324    /// Register an [`ArrayParentReduceRule`] for a `child` encoding under `parent`.
325    ///
326    /// The optimizer tries the rules registered for a pair in registration order when it sees a
327    /// `parent` holding a child of the `child` encoding. The child id comes from the vtable that
328    /// the rule applies to, so it always matches the rule. The parent is an encoding, such as
329    /// `Filter`, or a scalar function, such as `Cast`, or [`AnyScalarFn`] for a rule that applies
330    /// to any scalar function array. Rules for the exact parent are tried before those registered
331    /// under [`AnyScalarFn`].
332    ///
333    /// Use [`Self::register_scalar_fn_reduce_parent_rule`] for a rule on a scalar function child.
334    ///
335    /// Pass the rule as `const { &rule }` so that it lives in static memory.
336    pub fn register_reduce_parent_rule<P, Kind, V, R>(&self, parent: P, child: V, rule: &'static R)
337    where
338        P: ReduceParent<Kind>,
339        V: VTable,
340        R: ArrayParentReduceRule<V>,
341    {
342        debug_assert!(
343            TypeId::of::<V>() != TypeId::of::<ScalarFn>(),
344            "register scalar function children with register_scalar_fn_reduce_parent_rule"
345        );
346        self.push_reduce_parent_rule::<V, R>(parent.parent_id(), child.id(), rule);
347    }
348
349    /// Register an [`ArrayParentReduceRule`] for a scalar function child, of any function, under
350    /// `parent`.
351    ///
352    /// The rule is keyed by [`AnyScalarFn::id`] on the child side. See
353    /// [`Self::register_reduce_parent_rule`] for how `parent` is identified and how to pass `rule`.
354    pub fn register_scalar_fn_reduce_parent_rule<P, Kind, R>(&self, parent: P, rule: &'static R)
355    where
356        P: ReduceParent<Kind>,
357        R: ArrayParentReduceRule<ScalarFn>,
358    {
359        self.push_reduce_parent_rule::<ScalarFn, R>(parent.parent_id(), AnyScalarFn.id(), rule);
360    }
361
362    fn push_reduce_parent_rule<V, R>(&self, parent: Id, child: Id, rule: &'static R)
363    where
364        V: VTable,
365        R: ArrayParentReduceRule<V>,
366    {
367        let kernel = RegisteredReduceParentRule::<V, R>::lift(rule);
368
369        self.reduce_parent.rcu(|current| {
370            let mut next = ParentReduceKernels::clone(current);
371            next.push(parent, child, kernel);
372            next
373        });
374    }
375
376    /// Try the parent-reduce kernels registered for `parent` and `child` once, without
377    /// optimizing the result.
378    pub fn reduce_parent(
379        &self,
380        child: &ArrayRef,
381        parent: &ArrayRef,
382        child_idx: usize,
383    ) -> VortexResult<Option<ArrayRef>> {
384        self.with_reduce_parent_kernels(|kernels| {
385            reduce_parent_with_kernels(kernels, parent, child, child_idx)
386        })
387    }
388
389    /// Register [`ExecuteParentFn`]s for `(parent, child)`.
390    ///
391    /// The executor invokes these functions in registration order when it sees a parent with
392    /// encoding id `parent` holding a child with encoding id `child` during a parent execution
393    /// step.
394    ///
395    /// If functions have already been registered for the same pair, these functions are appended
396    /// after them.
397    pub fn register_execute_parent(&self, parent: Id, child: Id, fns: &[ExecuteParentFn]) {
398        let kernels: Vec<ExecuteParentKernelRef> = fns
399            .iter()
400            .map(|f| Arc::new(ExecuteParentFnKernel(*f)) as ExecuteParentKernelRef)
401            .collect();
402        self.push_execute_parent(parent, child, &kernels);
403    }
404
405    /// Register a typed [`ExecuteParentKernel`] for `(parent, child.id())`.
406    ///
407    /// The executor invokes registered kernels in registration order before falling through to
408    /// later registered kernels for the same key. `parent` is usually the parent array's encoding
409    /// id. For `ScalarFnArray`, it is the scalar function id, for example `Cast.id()`.
410    ///
411    /// If kernels have already been registered for the same pair, this kernel is appended after
412    /// them; registering for an existing key cannot override built-in kernels installed earlier.
413    pub fn register_execute_parent_kernel<V, K>(&self, parent: Id, child: V, kernel: K)
414    where
415        V: VTable,
416        K: ExecuteParentKernel<V>,
417    {
418        let child_id = child.id();
419        let kernel: ExecuteParentKernelRef = Arc::new(RegisteredExecuteParentKernel {
420            _child: child,
421            kernel,
422        });
423        self.push_execute_parent(parent, child_id, &[kernel]);
424    }
425
426    /// Append `kernels` for `(parent, child)` and record that `parent` owns execute-parent kernels.
427    ///
428    /// The marker lives in the same map as the kernels, under a key no `(parent, child)` pair
429    /// hashes to, so the executor's snapshot answers "does this parent have any kernel?" with
430    /// one probe and no extra state. The marker's kernel list is empty.
431    fn push_execute_parent(&self, parent: Id, child: Id, kernels: &[ExecuteParentKernelRef]) {
432        self.execute_parent.rcu(|current| {
433            let mut next = ParentExecutionKernels::clone(current);
434            append(
435                next.entry(hash_fn_id(parent, child).into()).or_default(),
436                kernels.iter().cloned(),
437            );
438            next.entry(execute_parent_marker_key(parent).into())
439                .or_default();
440            next
441        });
442    }
443
444    /// Returns true when one or more execute-parent kernels are registered for `(parent, child)`.
445    pub fn has_execute_parent(&self, parent: Id, child: Id) -> bool {
446        self.execute_parent
447            .load()
448            .contains_key(&hash_fn_id(parent, child))
449    }
450
451    /// Return the currently published parent-reduce kernel snapshot.
452    pub(crate) fn reduce_parent_snapshot(&self) -> Arc<ParentReduceKernels> {
453        self.reduce_parent.load_full()
454    }
455
456    /// Passes the currently published parent-reduce kernels to `f` without copying them.
457    pub(crate) fn with_reduce_parent_kernels<R>(
458        &self,
459        f: impl FnOnce(&ParentReduceKernels) -> R,
460    ) -> R {
461        f(&self.reduce_parent.load())
462    }
463
464    /// Return the currently published execute-parent kernel snapshot.
465    pub(crate) fn execute_parent_snapshot(&self) -> Arc<ParentExecutionKernels> {
466        self.execute_parent.load_full()
467    }
468}
469
470fn hash_fn_id(parent: Id, child: Id) -> u64 {
471    FN_HASHER.hash_one((parent, child))
472}
473
474/// Return the registry key for execute-parent kernels registered for `(parent, child)`.
475pub(crate) fn execute_parent_key(parent: Id, child: Id) -> u64 {
476    hash_fn_id(parent, child)
477}
478
479/// Return the registry key under which `parent` is marked as owning execute-parent kernels.
480///
481/// Hashed from a different tuple type than the `(Id, Id)` pair keys, so it cannot equal a pair
482/// key by construction, only by a 64-bit collision; either way a hit is harmless, as the marker's
483/// kernel list is empty and the prefilter only decides whether to probe the pairs.
484pub(crate) fn execute_parent_marker_key(parent: Id) -> u64 {
485    FN_HASHER.hash_one(("execute_parent", parent))
486}
487
488/// Session-scoped holder for the optimizer kernel registry.
489///
490/// `KernelSession` is the session variable that owns an [`ArrayKernels`] registry. Its [`Default`]
491/// implementation installs vortex-array's built-in parent-reduce and execute-parent kernels,
492/// mirroring how [`ScalarFnSession`](crate::scalar_fn::session::ScalarFnSession) and the other
493/// session variables register their built-ins.
494#[derive(Clone, Debug)]
495pub struct KernelSession {
496    kernels: ArrayKernels,
497}
498
499impl KernelSession {
500    /// Create a [`KernelSession`] with an empty kernel registry.
501    pub fn empty() -> Self {
502        Self {
503            kernels: ArrayKernels::empty(),
504        }
505    }
506
507    /// Returns the [`ArrayKernels`] registry held by this session.
508    pub fn kernels(&self) -> &ArrayKernels {
509        &self.kernels
510    }
511}
512
513/// Derefs to the held [`ArrayKernels`] registry, so a [`KernelSession`] (or a
514/// [`SessionGuard<KernelSession>`](SessionGuard) read from a session) can be used wherever an
515/// `&ArrayKernels` is expected.
516impl Deref for KernelSession {
517    type Target = ArrayKernels;
518
519    fn deref(&self) -> &ArrayKernels {
520        &self.kernels
521    }
522}
523
524impl Default for KernelSession {
525    fn default() -> Self {
526        // The built-in parent-reduce rules and execute-parent kernels are registered by the
527        // per-encoding `initialize` functions, which operate on a session. `KernelSession` clones
528        // share their registry storage, so kernels registered into the temporary session land in
529        // `this.kernels`.
530        let this = Self {
531            kernels: ArrayKernels::empty(),
532        };
533        let session = VortexSession::empty().with_some(this.clone());
534        crate::arrays::initialize(&session);
535        this
536    }
537}
538
539impl SessionVar for KernelSession {
540    fn as_any(&self) -> &dyn Any {
541        self
542    }
543
544    fn as_any_mut(&mut self) -> &mut dyn Any {
545        self
546    }
547}
548
549/// Extension trait for accessing the optimizer kernel registry from a [`VortexSession`].
550pub trait ArrayKernelsExt: SessionExt {
551    /// Returns the session's [`KernelSession`], inserting a default one (with the built-in
552    /// kernels) if it does not exist.
553    ///
554    /// The returned [`SessionGuard`] borrows the session snapshot it was read from (so the registry
555    /// stays alive even if the session is concurrently mutated) and derefs through [`KernelSession`]
556    /// to the [`ArrayKernels`] registry, so it can be used wherever an `&ArrayKernels` is expected.
557    /// The registry shares its storage with the session, so kernels registered through it remain
558    /// visible to the session.
559    fn kernels(&self) -> SessionGuard<'_, KernelSession> {
560        self.get::<KernelSession>()
561    }
562}
563
564impl<S: SessionExt> ArrayKernelsExt for S {}
565
566#[cfg(test)]
567mod tests {
568    use std::sync::LazyLock;
569
570    use vortex_session::VortexSession;
571
572    use super::ArrayKernelsExt;
573    use super::KernelSession;
574    use crate::ArrayVTable;
575    use crate::arrays::Bool;
576    use crate::scalar_fn::ScalarFnVTable;
577    use crate::scalar_fn::builtin::boolean::Boolean;
578
579    static SESSION: LazyLock<VortexSession> =
580        LazyLock::new(|| VortexSession::empty().with::<KernelSession>());
581
582    #[test]
583    fn kernel_session_default_registers_builtin_kernels() {
584        assert!(
585            SESSION
586                .kernels()
587                .has_execute_parent(Boolean.id(), Bool.id())
588        );
589    }
590
591    #[test]
592    fn initialize_registers_builtin_kernels_into_empty_kernel_session() {
593        let session = VortexSession::empty().with_some(KernelSession::empty());
594
595        assert!(
596            !session
597                .kernels()
598                .has_execute_parent(Boolean.id(), Bool.id())
599        );
600
601        crate::initialize(&session);
602
603        assert!(
604            session
605                .kernels()
606                .has_execute_parent(Boolean.id(), Bool.id())
607        );
608    }
609
610    #[test]
611    fn kernels_inserts_default_kernel_session() {
612        let session = VortexSession::empty();
613
614        // `kernels()` uses `get`, so it inserts a default `KernelSession` (with the built-in
615        // kernels) rather than returning `None`.
616        assert!(
617            session
618                .kernels()
619                .has_execute_parent(Boolean.id(), Bool.id())
620        );
621    }
622}