1use 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
52static FN_HASHER: LazyLock<DefaultHashBuilder> = LazyLock::new(DefaultHashBuilder::default);
54
55pub(crate) trait DynReduceParentKernel: Debug + Send + Sync + 'static {
57 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#[derive(Clone, Debug, Default)]
70pub(crate) struct ParentReduceKernels {
71 kernels: HashMap<ReduceParentFnId, Box<[ReduceParentKernelRef]>>,
73 children: HashMap<Id, Box<[Id]>>,
76}
77
78impl ParentReduceKernels {
79 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 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
106fn 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 const fn lift(rule: &'static R) -> ReduceParentKernelRef {
123 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
172pub type ExecuteParentFn = fn(
181 child: &ArrayRef,
182 parent: &ArrayRef,
183 child_idx: usize,
184 ctx: &mut ExecutionCtx,
185) -> VortexResult<Option<ArrayRef>>;
186
187pub trait DynExecuteParentKernel: Debug + Send + Sync + 'static {
189 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
263pub trait ReduceParent<Kind> {
270 fn parent_id(&self) -> Id;
272}
273
274#[derive(Debug)]
276pub struct EncodingParent;
277
278#[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#[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 pub fn empty() -> Self {
318 Self {
319 reduce_parent: Arc::default(),
320 execute_parent: Arc::default(),
321 }
322 }
323
324 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 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 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 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 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 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 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 pub(crate) fn reduce_parent_snapshot(&self) -> Arc<ParentReduceKernels> {
453 self.reduce_parent.load_full()
454 }
455
456 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 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
474pub(crate) fn execute_parent_key(parent: Id, child: Id) -> u64 {
476 hash_fn_id(parent, child)
477}
478
479pub(crate) fn execute_parent_marker_key(parent: Id) -> u64 {
485 FN_HASHER.hash_one(("execute_parent", parent))
486}
487
488#[derive(Clone, Debug)]
495pub struct KernelSession {
496 kernels: ArrayKernels,
497}
498
499impl KernelSession {
500 pub fn empty() -> Self {
502 Self {
503 kernels: ArrayKernels::empty(),
504 }
505 }
506
507 pub fn kernels(&self) -> &ArrayKernels {
509 &self.kernels
510 }
511}
512
513impl 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 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
549pub trait ArrayKernelsExt: SessionExt {
551 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 assert!(
617 session
618 .kernels()
619 .has_execute_parent(Boolean.id(), Bool.id())
620 );
621 }
622}