Skip to main content

vortex_array/arrays/scalar_fn/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3mod operations;
4mod validity;
5
6use std::hash::Hash;
7use std::hash::Hasher;
8use std::marker::PhantomData;
9use std::ops::Deref;
10
11use itertools::Itertools;
12use validity::ValidityArray;
13use vortex_error::VortexResult;
14use vortex_error::vortex_ensure;
15use vortex_error::vortex_ensure_eq;
16use vortex_error::vortex_panic;
17use vortex_session::registry::CachedId;
18
19use crate::ArrayEq;
20use crate::ArrayHash;
21use crate::ArrayRef;
22use crate::EqMode;
23use crate::IntoArray;
24use crate::array::Array;
25use crate::array::ArrayId;
26use crate::array::ArrayParts;
27use crate::array::ArrayView;
28use crate::array::VTable;
29use crate::array::ValidityVTable;
30use crate::array::with_empty_buffers;
31use crate::arrays::scalar_fn::array::ScalarFnArrayExt;
32use crate::arrays::scalar_fn::array::ScalarFnData;
33use crate::arrays::scalar_fn::rules::RULES;
34use crate::buffer::BufferHandle;
35use crate::dtype::DType;
36use crate::executor::ExecutionCtx;
37use crate::executor::ExecutionResult;
38use crate::matcher::Matcher;
39use crate::scalar_fn;
40use crate::scalar_fn::ArrayReduceNode;
41use crate::scalar_fn::ReduceNode;
42use crate::scalar_fn::ReduceNodeValidity;
43use crate::scalar_fn::ScalarFnExecutionStep;
44use crate::scalar_fn::ScalarFnId;
45use crate::scalar_fn::VecExecutionArgs;
46use crate::validity::Validity;
47
48/// A [`ScalarFn`]-encoded Vortex array.
49pub type ScalarFnArray = Array<ScalarFn>;
50
51#[derive(Clone, Debug)]
52pub struct ScalarFn {
53    pub(super) id: ScalarFnId,
54}
55
56impl ArrayHash for ScalarFnData {
57    fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
58        self.scalar_fn().hash(state);
59    }
60}
61
62impl ArrayEq for ScalarFnData {
63    fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
64        self.scalar_fn() == other.scalar_fn()
65    }
66}
67
68impl VTable for ScalarFn {
69    type TypedArrayData = ScalarFnData;
70    type OperationsVTable = Self;
71    type ValidityVTable = Self;
72
73    fn id(&self) -> ArrayId {
74        self.id
75    }
76
77    fn validate(
78        &self,
79        data: &ScalarFnData,
80        dtype: &DType,
81        len: usize,
82        slots: &[Option<ArrayRef>],
83    ) -> VortexResult<()> {
84        let scalar_fn = data.scalar_fn();
85        vortex_ensure_eq!(
86            scalar_fn.id(),
87            self.id,
88            "ScalarFnArray data scalar_fn does not match vtable",
89        );
90
91        Array::<ScalarFn>::validate_not_literal(scalar_fn)?;
92
93        let missing_children = slots.iter().filter(|slot| slot.is_none()).count();
94        vortex_ensure_eq!(
95            missing_children,
96            0,
97            "ScalarFnArray requires every child slot to be present",
98        );
99
100        let arity = scalar_fn.signature().arity();
101        vortex_ensure!(
102            arity.matches(slots.len()),
103            "ScalarFnArray requires {arity} children, got {}",
104            slots.len()
105        );
106        vortex_ensure!(
107            slots.iter().flatten().all(|c| c.len() == len),
108            "All child arrays must have the same length as the scalar function array"
109        );
110
111        let child_dtypes = slots
112            .iter()
113            .flatten()
114            .map(|c| c.dtype().clone())
115            .collect_vec();
116        vortex_ensure_eq!(
117            scalar_fn.return_dtype(&child_dtypes)?,
118            *dtype,
119            "ScalarFnArray dtype does not match scalar function return dtype",
120        );
121        Ok(())
122    }
123
124    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
125        0
126    }
127
128    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
129        vortex_panic!("ScalarFnArray buffer index {idx} out of bounds")
130    }
131
132    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
133        None
134    }
135
136    fn with_buffers(
137        &self,
138        array: ArrayView<'_, Self>,
139        buffers: &[BufferHandle],
140    ) -> VortexResult<ArrayParts<Self>> {
141        with_empty_buffers(self, array, buffers)
142    }
143
144    fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String {
145        array
146            .scalar_fn()
147            .signature()
148            .child_name(idx)
149            .as_ref()
150            .to_string()
151    }
152
153    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
154        let args = VecExecutionArgs::new(array.children(), array.len());
155        match array.scalar_fn().execute_step(&args, ctx)?.into_step() {
156            ScalarFnExecutionStep::Done(result) => Ok(ExecutionResult::done(result)),
157            ScalarFnExecutionStep::ExecuteInput(idx, done) => Ok(
158                ExecutionResult::execute_slot_until(array.into_array(), idx, done),
159            ),
160        }
161    }
162
163    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
164        RULES.evaluate(array)
165    }
166}
167
168/// A matcher that matches any scalar function expression.
169#[derive(Debug)]
170pub struct AnyScalarFn;
171
172impl AnyScalarFn {
173    /// The parent id under which parent-reduce kernels that apply to any scalar function are
174    /// registered.
175    ///
176    /// A scalar function array's encoding id is its function's id, so these kernels cannot be
177    /// keyed by one encoding id. The optimizer tries them after the kernels registered for the
178    /// function's own id.
179    pub fn id(&self) -> ArrayId {
180        static ID: CachedId = CachedId::new("vortex.scalar_fn.any");
181        *ID
182    }
183}
184impl Matcher for AnyScalarFn {
185    type Match<'a> = ArrayView<'a, ScalarFn>;
186
187    fn matches(array: &ArrayRef) -> bool {
188        array.is::<ScalarFn>()
189    }
190
191    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
192        array.as_opt::<ScalarFn>()
193    }
194}
195
196/// A matcher that matches a specific scalar function expression.
197#[derive(Debug, Default)]
198pub struct ExactScalarFn<F: scalar_fn::ScalarFnVTable>(PhantomData<F>);
199
200impl<F: scalar_fn::ScalarFnVTable> Matcher for ExactScalarFn<F> {
201    type Match<'a> = ScalarFnArrayView<'a, F>;
202
203    fn matches(array: &ArrayRef) -> bool {
204        if let Some(scalar_fn_array) = array.as_opt::<ScalarFn>() {
205            scalar_fn_array.data().scalar_fn().is::<F>()
206        } else {
207            false
208        }
209    }
210
211    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
212        let scalar_fn_array = array.as_opt::<ScalarFn>()?;
213        let scalar_fn_data = scalar_fn_array.data();
214        let scalar_fn = scalar_fn_data.scalar_fn().downcast_ref::<F>()?;
215        Some(ScalarFnArrayView {
216            array,
217            vtable: scalar_fn.vtable(),
218            options: scalar_fn.options(),
219        })
220    }
221}
222
223pub struct ScalarFnArrayView<'a, F: scalar_fn::ScalarFnVTable> {
224    array: &'a ArrayRef,
225    pub vtable: &'a F,
226    pub options: &'a F::Options,
227}
228
229impl<F: scalar_fn::ScalarFnVTable> Deref for ScalarFnArrayView<'_, F> {
230    type Target = ArrayRef;
231
232    fn deref(&self) -> &Self::Target {
233        self.array
234    }
235}
236
237impl ValidityVTable<ScalarFn> for ScalarFn {
238    fn validity(view: ArrayView<'_, ScalarFn>) -> VortexResult<Validity> {
239        let node = ArrayReduceNode::new(view.as_ref());
240        Ok(Validity::Array(match node.validity()? {
241            ReduceNodeValidity::Reduced(reduced) => reduced.into_array(),
242            ReduceNodeValidity::Irreducible => ValidityArray::new(node.into_array()).into_array(),
243        }))
244    }
245}