use std::any::Any;
use std::any::TypeId;
use std::borrow::Borrow;
use std::fmt::Debug;
use std::hash::BuildHasher;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr;
use std::sync::Arc;
use std::sync::LazyLock;
use arc_swap::ArcSwap;
use vortex_error::VortexResult;
use vortex_session::SessionExt;
use vortex_session::SessionGuard;
use vortex_session::SessionVar;
use vortex_session::VortexSession;
use vortex_session::registry::Id;
use vortex_utils::aliases::DefaultHashBuilder;
use vortex_utils::aliases::hash_map::HashMap;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::array::VTable;
use crate::arrays::ScalarFn;
use crate::arrays::scalar_fn::AnyScalarFn;
use crate::kernel::ExecuteParentKernel;
use crate::matcher::Matcher;
use crate::optimizer::reduce_parent_with_kernels;
use crate::optimizer::rules::ArrayParentReduceRule;
use crate::scalar_fn::ScalarFnVTable;
static FN_HASHER: LazyLock<DefaultHashBuilder> = LazyLock::new(DefaultHashBuilder::default);
pub(crate) trait DynReduceParentKernel: Debug + Send + Sync + 'static {
fn reduce_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
) -> VortexResult<Option<ArrayRef>>;
}
pub(crate) type ReduceParentKernelRef = &'static dyn DynReduceParentKernel;
#[derive(Clone, Debug, Default)]
pub(crate) struct ParentReduceKernels {
kernels: HashMap<ReduceParentFnId, Box<[ReduceParentKernelRef]>>,
children: HashMap<Id, Box<[Id]>>,
}
impl ParentReduceKernels {
pub(crate) fn get(&self, parent: Id, child: Id) -> Option<&[ReduceParentKernelRef]> {
self.kernels
.get(&hash_fn_id(parent, child))
.map(AsRef::as_ref)
}
pub(crate) fn children(&self, parent: Id) -> Option<&[Id]> {
self.children.get(&parent).map(AsRef::as_ref)
}
fn push(&mut self, parent: Id, child: Id, kernel: ReduceParentKernelRef) {
append(
self.kernels
.entry(hash_fn_id(parent, child).into())
.or_default(),
[kernel],
);
let children = self.children.entry(parent).or_default();
if !children.contains(&child) {
append(children, [child]);
}
}
}
fn append<T>(slice: &mut Box<[T]>, items: impl IntoIterator<Item = T>) {
let mut items_vec = std::mem::take(slice).into_vec();
items_vec.extend(items);
*slice = items_vec.into_boxed_slice();
}
#[repr(transparent)]
struct RegisteredReduceParentRule<V, R> {
rule: R,
_child: PhantomData<V>,
}
impl<V: VTable, R: ArrayParentReduceRule<V>> RegisteredReduceParentRule<V, R> {
const fn lift(rule: &'static R) -> ReduceParentKernelRef {
unsafe { &*ptr::from_ref(rule).cast::<Self>() }
}
}
impl<V, R: Debug> Debug for RegisteredReduceParentRule<V, R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegisteredReduceParentRule")
.field("rule", &self.rule)
.finish()
}
}
impl<V, R> DynReduceParentKernel for RegisteredReduceParentRule<V, R>
where
V: VTable,
R: ArrayParentReduceRule<V>,
{
fn reduce_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
) -> VortexResult<Option<ArrayRef>> {
let (Some(child), Some(parent)) = (child.as_opt::<V>(), R::Parent::try_match(parent))
else {
return Ok(None);
};
self.rule.reduce_parent(child, parent, child_idx)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[repr(transparent)]
pub(crate) struct ReduceParentFnId(u64);
impl From<u64> for ReduceParentFnId {
fn from(id: u64) -> Self {
Self(id)
}
}
impl Borrow<u64> for ReduceParentFnId {
fn borrow(&self) -> &u64 {
&self.0
}
}
pub type ExecuteParentFn = fn(
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>>;
pub trait DynExecuteParentKernel: Debug + Send + Sync + 'static {
fn execute_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>>;
}
pub(crate) type ExecuteParentKernelRef = Arc<dyn DynExecuteParentKernel>;
pub(crate) type ParentExecutionKernels = HashMap<ExecuteParentFnId, Box<[ExecuteParentKernelRef]>>;
#[derive(Debug)]
struct ExecuteParentFnKernel(ExecuteParentFn);
impl DynExecuteParentKernel for ExecuteParentFnKernel {
fn execute_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>> {
self.0(child, parent, child_idx, ctx)
}
}
#[derive(Debug)]
struct RegisteredExecuteParentKernel<V, K> {
_child: V,
kernel: K,
}
impl<V, K> DynExecuteParentKernel for RegisteredExecuteParentKernel<V, K>
where
V: VTable,
K: ExecuteParentKernel<V>,
{
fn execute_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>> {
let Some(child) = child.as_opt::<V>() else {
return Ok(None);
};
let Some(parent) = K::Parent::try_match(parent) else {
return Ok(None);
};
self.kernel.execute_parent(child, parent, child_idx, ctx)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
#[repr(transparent)]
pub(crate) struct ExecuteParentFnId(u64);
impl From<u64> for ExecuteParentFnId {
fn from(id: u64) -> Self {
Self(id)
}
}
impl Borrow<u64> for ExecuteParentFnId {
fn borrow(&self) -> &u64 {
&self.0
}
}
pub trait ReduceParent<Kind> {
fn parent_id(&self) -> Id;
}
#[derive(Debug)]
pub struct EncodingParent;
#[derive(Debug)]
pub struct ScalarFnParent;
impl<V: VTable> ReduceParent<EncodingParent> for V {
fn parent_id(&self) -> Id {
VTable::id(self)
}
}
impl<F: ScalarFnVTable> ReduceParent<ScalarFnParent> for F {
fn parent_id(&self) -> Id {
ScalarFnVTable::id(self)
}
}
impl ReduceParent<AnyScalarFn> for AnyScalarFn {
fn parent_id(&self) -> Id {
self.id()
}
}
#[derive(Clone, Debug)]
pub struct ArrayKernels {
reduce_parent: Arc<ArcSwap<ParentReduceKernels>>,
execute_parent: Arc<ArcSwap<ParentExecutionKernels>>,
}
impl Default for ArrayKernels {
fn default() -> ArrayKernels {
Self::empty()
}
}
impl ArrayKernels {
pub fn empty() -> Self {
Self {
reduce_parent: Arc::default(),
execute_parent: Arc::default(),
}
}
pub fn register_reduce_parent_rule<P, Kind, V, R>(&self, parent: P, child: V, rule: &'static R)
where
P: ReduceParent<Kind>,
V: VTable,
R: ArrayParentReduceRule<V>,
{
debug_assert!(
TypeId::of::<V>() != TypeId::of::<ScalarFn>(),
"register scalar function children with register_scalar_fn_reduce_parent_rule"
);
self.push_reduce_parent_rule::<V, R>(parent.parent_id(), child.id(), rule);
}
pub fn register_scalar_fn_reduce_parent_rule<P, Kind, R>(&self, parent: P, rule: &'static R)
where
P: ReduceParent<Kind>,
R: ArrayParentReduceRule<ScalarFn>,
{
self.push_reduce_parent_rule::<ScalarFn, R>(parent.parent_id(), AnyScalarFn.id(), rule);
}
fn push_reduce_parent_rule<V, R>(&self, parent: Id, child: Id, rule: &'static R)
where
V: VTable,
R: ArrayParentReduceRule<V>,
{
let kernel = RegisteredReduceParentRule::<V, R>::lift(rule);
self.reduce_parent.rcu(|current| {
let mut next = ParentReduceKernels::clone(current);
next.push(parent, child, kernel);
next
});
}
pub fn reduce_parent(
&self,
child: &ArrayRef,
parent: &ArrayRef,
child_idx: usize,
) -> VortexResult<Option<ArrayRef>> {
self.with_reduce_parent_kernels(|kernels| {
reduce_parent_with_kernels(kernels, parent, child, child_idx)
})
}
pub fn register_execute_parent(&self, parent: Id, child: Id, fns: &[ExecuteParentFn]) {
let kernels: Vec<ExecuteParentKernelRef> = fns
.iter()
.map(|f| Arc::new(ExecuteParentFnKernel(*f)) as ExecuteParentKernelRef)
.collect();
self.push_execute_parent(parent, child, &kernels);
}
pub fn register_execute_parent_kernel<V, K>(&self, parent: Id, child: V, kernel: K)
where
V: VTable,
K: ExecuteParentKernel<V>,
{
let child_id = child.id();
let kernel: ExecuteParentKernelRef = Arc::new(RegisteredExecuteParentKernel {
_child: child,
kernel,
});
self.push_execute_parent(parent, child_id, &[kernel]);
}
fn push_execute_parent(&self, parent: Id, child: Id, kernels: &[ExecuteParentKernelRef]) {
self.execute_parent.rcu(|current| {
let mut next = ParentExecutionKernels::clone(current);
append(
next.entry(hash_fn_id(parent, child).into()).or_default(),
kernels.iter().cloned(),
);
next.entry(execute_parent_marker_key(parent).into())
.or_default();
next
});
}
pub fn has_execute_parent(&self, parent: Id, child: Id) -> bool {
self.execute_parent
.load()
.contains_key(&hash_fn_id(parent, child))
}
pub(crate) fn reduce_parent_snapshot(&self) -> Arc<ParentReduceKernels> {
self.reduce_parent.load_full()
}
pub(crate) fn with_reduce_parent_kernels<R>(
&self,
f: impl FnOnce(&ParentReduceKernels) -> R,
) -> R {
f(&self.reduce_parent.load())
}
pub(crate) fn execute_parent_snapshot(&self) -> Arc<ParentExecutionKernels> {
self.execute_parent.load_full()
}
}
fn hash_fn_id(parent: Id, child: Id) -> u64 {
FN_HASHER.hash_one((parent, child))
}
pub(crate) fn execute_parent_key(parent: Id, child: Id) -> u64 {
hash_fn_id(parent, child)
}
pub(crate) fn execute_parent_marker_key(parent: Id) -> u64 {
FN_HASHER.hash_one(("execute_parent", parent))
}
#[derive(Clone, Debug)]
pub struct KernelSession {
kernels: ArrayKernels,
}
impl KernelSession {
pub fn empty() -> Self {
Self {
kernels: ArrayKernels::empty(),
}
}
pub fn kernels(&self) -> &ArrayKernels {
&self.kernels
}
}
impl Deref for KernelSession {
type Target = ArrayKernels;
fn deref(&self) -> &ArrayKernels {
&self.kernels
}
}
impl Default for KernelSession {
fn default() -> Self {
let this = Self {
kernels: ArrayKernels::empty(),
};
let session = VortexSession::empty().with_some(this.clone());
crate::arrays::initialize(&session);
this
}
}
impl SessionVar for KernelSession {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub trait ArrayKernelsExt: SessionExt {
fn kernels(&self) -> SessionGuard<'_, KernelSession> {
self.get::<KernelSession>()
}
}
impl<S: SessionExt> ArrayKernelsExt for S {}
#[cfg(test)]
mod tests {
use std::sync::LazyLock;
use vortex_session::VortexSession;
use super::ArrayKernelsExt;
use super::KernelSession;
use crate::ArrayVTable;
use crate::arrays::Bool;
use crate::scalar_fn::ScalarFnVTable;
use crate::scalar_fn::builtin::boolean::Boolean;
static SESSION: LazyLock<VortexSession> =
LazyLock::new(|| VortexSession::empty().with::<KernelSession>());
#[test]
fn kernel_session_default_registers_builtin_kernels() {
assert!(
SESSION
.kernels()
.has_execute_parent(Boolean.id(), Bool.id())
);
}
#[test]
fn initialize_registers_builtin_kernels_into_empty_kernel_session() {
let session = VortexSession::empty().with_some(KernelSession::empty());
assert!(
!session
.kernels()
.has_execute_parent(Boolean.id(), Bool.id())
);
crate::initialize(&session);
assert!(
session
.kernels()
.has_execute_parent(Boolean.id(), Bool.id())
);
}
#[test]
fn kernels_inserts_default_kernel_session() {
let session = VortexSession::empty();
assert!(
session
.kernels()
.has_execute_parent(Boolean.id(), Bool.id())
);
}
}