|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// SPDX-FileCopyrightText: Copyright the Vortex contributors |
| 3 | + |
| 4 | +//! Session-scoped registry for optimizer kernels. |
| 5 | +//! |
| 6 | +//! [`ArrayKernels`] stores function pointers that participate in array optimization without |
| 7 | +//! adding rules to an encoding vtable. The optimizer currently consults it for parent-reduce |
| 8 | +//! rewrites before the child encoding's static `PARENT_RULES`. A registered function can |
| 9 | +//! therefore add a rule for an extension encoding or take precedence over a built-in rule. |
| 10 | +//! |
| 11 | +//! Kernel entries are addressed by `(outer_id, child_id, kind)`. For parent-reduce kernels, |
| 12 | +//! `outer_id` is the id returned by the parent array's `encoding_id()` and `child_id` is the |
| 13 | +//! child array's `encoding_id()`. For [`ScalarFn`](crate::arrays::ScalarFn) parents, the parent |
| 14 | +//! id is the scalar function id. |
| 15 | +//! |
| 16 | +//! Sessions created by the top-level `vortex` crate install an empty registry by default. Other |
| 17 | +//! sessions can add it with [`VortexSession::with`](vortex_session::VortexSession::with) or rely |
| 18 | +//! on [`ArrayKernelsExt::kernels`] to insert the default value. |
| 19 | +
|
| 20 | +use std::hash::BuildHasher; |
| 21 | +use std::sync::Arc; |
| 22 | +use std::sync::LazyLock; |
| 23 | + |
| 24 | +use arc_swap::ArcSwap; |
| 25 | +use vortex_error::VortexResult; |
| 26 | +use vortex_session::Ref; |
| 27 | +use vortex_session::SessionExt; |
| 28 | +use vortex_session::registry::Id; |
| 29 | +use vortex_utils::aliases::DefaultHashBuilder; |
| 30 | +use vortex_utils::aliases::hash_map::HashMap; |
| 31 | + |
| 32 | +use crate::ArrayRef; |
| 33 | + |
| 34 | +/// Shared hasher used to combine `(outer, child, FnKind)` tuples into [`FnRegistry`] keys. |
| 35 | +static FN_HASHER: LazyLock<DefaultHashBuilder> = LazyLock::new(DefaultHashBuilder::default); |
| 36 | + |
| 37 | +/// Function pointer for a plugin-provided parent-reduce rewrite. |
| 38 | +/// |
| 39 | +/// The optimizer calls this with the matched `child`, its `parent`, and the slot index where the |
| 40 | +/// child appears. Return `Ok(Some(new_parent))` to replace the parent, or `Ok(None)` when the |
| 41 | +/// rewrite does not apply. |
| 42 | +/// |
| 43 | +/// Implementations must preserve the parent's logical length and dtype, matching the invariant |
| 44 | +/// required of static parent-reduce rules. |
| 45 | +pub type ReduceParentFn = |
| 46 | + fn(child: &ArrayRef, parent: &ArrayRef, child_idx: usize) -> VortexResult<Option<ArrayRef>>; |
| 47 | + |
| 48 | +/// Session-scoped registry of optimizer kernel functions. |
| 49 | +#[derive(Debug, Default)] |
| 50 | +pub struct ArrayKernels { |
| 51 | + reduce_parent: ArcSwap<HashMap<u64, Arc<[ReduceParentFn]>>>, |
| 52 | +} |
| 53 | + |
| 54 | +impl ArrayKernels { |
| 55 | + /// Create an empty [`ArrayKernels`] with no kernels registered. |
| 56 | + pub fn empty() -> Self { |
| 57 | + Self::default() |
| 58 | + } |
| 59 | + |
| 60 | + /// Register a [`ReduceParentFn`] for `(outer, child)`. |
| 61 | + /// |
| 62 | + /// The optimizer will invoke `f` when it sees a parent with encoding id `outer` holding a |
| 63 | + /// child with encoding id `child` during a `reduce_parent` step, before trying the child |
| 64 | + /// encoding's static `PARENT_RULES`. `outer` is usually the parent array's encoding id. For |
| 65 | + /// `ScalarFnArray`, it is the scalar function id, for example `Cast.id()`. |
| 66 | + /// |
| 67 | + /// Replaces any function already registered for the same pair. |
| 68 | + pub fn register_reduce_parent<I: IntoIterator<Item = ReduceParentFn>>( |
| 69 | + &self, |
| 70 | + parent: Id, |
| 71 | + child: Id, |
| 72 | + fns: I, |
| 73 | + ) { |
| 74 | + let registry = self.reduce_parent.load(); |
| 75 | + let id = self.hash_fn_ids(parent, child); |
| 76 | + let mut owned_registry = registry.as_ref().clone(); |
| 77 | + if let Some(existing) = owned_registry.remove(&id) { |
| 78 | + owned_registry.insert(id, existing.as_ref().iter().cloned().chain(fns).collect()); |
| 79 | + } else { |
| 80 | + owned_registry.insert(id, fns.into_iter().collect()); |
| 81 | + } |
| 82 | + self.reduce_parent.store(Arc::new(owned_registry)); |
| 83 | + } |
| 84 | + |
| 85 | + /// Look up the [`ReduceParentFn`] registered for `(outer, child)`. |
| 86 | + /// |
| 87 | + /// Returns an owned [`Arc`] so the session-variable borrow can be dropped before invoking the |
| 88 | + /// function. |
| 89 | + pub fn find_reduce_parent(&self, parent: Id, child: Id) -> Option<Arc<[ReduceParentFn]>> { |
| 90 | + let id = self.hash_fn_ids(parent, child); |
| 91 | + let map = self.reduce_parent.load(); |
| 92 | + let entry = map.get(&id)?; |
| 93 | + Some(Arc::clone(entry)) |
| 94 | + } |
| 95 | + |
| 96 | + /// Combine a typed kernel id tuple into the `u64` key expected by the underlying |
| 97 | + /// [`FnRegistry`]. All typed helpers use this path so registration and lookup agree. |
| 98 | + fn hash_fn_ids(&self, parent: Id, child: Id) -> u64 { |
| 99 | + FN_HASHER.hash_one((parent, child)) |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +/// Extension trait for accessing optimizer kernels from a |
| 104 | +/// [`VortexSession`](vortex_session::VortexSession). |
| 105 | +pub trait ArrayKernelsExt: SessionExt { |
| 106 | + /// Returns the [`ArrayKernels`] session variable, inserting a default-constructed one if |
| 107 | + /// none has been registered on the session yet. |
| 108 | + fn kernels(&self) -> Ref<'_, ArrayKernels> { |
| 109 | + self.get::<ArrayKernels>() |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +impl<S: SessionExt> ArrayKernelsExt for S {} |
0 commit comments