Skip to main content

vortex_array/scalar_fn/unstable/row/
vtable.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Adapts [`RowFn`] implementations to the scalar-function interface.
5//!
6//! The blanket [`ScalarFnVTable`] implementation supplies common arity, validity, fallibility, and
7//! execution behavior. The visitor layer validates and executes the concrete signature selected by
8//! dispatch. [`row_fn_return_dtype`] and [`execute_rows`] expose the same paths to public vtables
9//! that delegate to a private row kernel.
10
11use smallvec::SmallVec;
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure_eq;
14use vortex_mask::MaskValuesRef;
15use vortex_session::VortexSession;
16
17use super::batch::ArrayInputs;
18use super::batch::BatchInputs;
19use super::batch::BatchProbe;
20use super::batch::BorrowedRowFnArgs;
21use super::batch::RowInputs;
22use super::batch::finalize_kernel_output;
23use super::row_fn::RowFn;
24use super::visitor::BatchPlanner;
25use super::visitor::ExecuteDenseWithRetry;
26use super::visitor::ExecuteFilteredRows;
27use super::visitor::ExecuteRows;
28use super::visitor::ExecuteValidRows;
29use crate::ArrayRef;
30use crate::ExecutionCtx;
31use crate::dtype::DType;
32use crate::scalar_fn::Arity;
33use crate::scalar_fn::ChildName;
34use crate::scalar_fn::ExecutionArgs;
35use crate::scalar_fn::ReduceNode;
36use crate::scalar_fn::ReduceNodeValidity;
37use crate::scalar_fn::ScalarFnId;
38use crate::scalar_fn::ScalarFnVTable;
39use crate::scalar_fn::union_child_validities;
40use crate::scalar_fn::unstable::row::execute::DenseAttempt;
41
42impl<F: RowFn> ScalarFnVTable for F {
43    type Options = F::Options;
44
45    fn id(&self) -> ScalarFnId {
46        RowFn::id(self)
47    }
48
49    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
50        RowFn::serialize(self, options)
51    }
52
53    fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult<Self::Options> {
54        RowFn::deserialize(self, metadata, session)
55    }
56
57    fn arity(&self, _options: &Self::Options) -> Arity {
58        Arity::Exact(F::ARG_NAMES.len())
59    }
60
61    fn child_name(&self, _options: &Self::Options, child_index: usize) -> ChildName {
62        ChildName::from(F::ARG_NAMES[child_index])
63    }
64
65    fn return_dtype(&self, options: &Self::Options, args: &[DType]) -> VortexResult<DType> {
66        row_fn_return_dtype(self, options, args)
67    }
68
69    fn execute(
70        &self,
71        options: &Self::Options,
72        args: &dyn ExecutionArgs,
73        ctx: &mut ExecutionCtx,
74    ) -> VortexResult<ArrayRef> {
75        execute_rows(self, options, args, ctx)
76    }
77
78    fn validity<T: ReduceNode>(
79        &self,
80        _options: &Self::Options,
81        node: &T,
82    ) -> VortexResult<ReduceNodeValidity<T>> {
83        Ok(ReduceNodeValidity::Reduced(union_child_validities(node)?))
84    }
85
86    // `RowFn` is stricter than `ScalarFnVTable::is_strict`: its kernel cannot produce null from
87    // valid inputs, so batch execution derives output validity only from input validity.
88    fn is_strict(&self, _options: &Self::Options) -> bool {
89        true
90    }
91
92    fn is_infallible(&self, _options: &Self::Options) -> bool {
93        F::INFALLIBLE
94    }
95}
96
97/// Compute the return dtype of a [`RowFn`] kernel without invoking its blanket vtable.
98pub fn row_fn_return_dtype<F: RowFn>(
99    function: &F,
100    options: &F::Options,
101    args: &[DType],
102) -> VortexResult<DType> {
103    ensure_arity(function, args.len())?;
104
105    let plan = function.dispatch(options, args, BatchPlanner::<F>::new(args))?;
106
107    Ok(plan.result_dtype(args))
108}
109
110/// Execute a [`RowFn`] without using its blanket [`ScalarFnVTable`] implementation.
111///
112/// A type cannot implement both [`RowFn`] and [`ScalarFnVTable`] because every `RowFn` receives the
113/// standard vtable automatically. Existing vtables can keep their custom hooks on one type and
114/// delegate row execution to a private `RowFn` kernel through this function.
115///
116/// Nullary functions execute for `args.row_count()` rows without batch validity handling because
117/// they have no input validity to propagate.
118pub fn execute_rows<F: RowFn>(
119    function: &F,
120    options: &F::Options,
121    args: &dyn ExecutionArgs,
122    ctx: &mut ExecutionCtx,
123) -> VortexResult<ArrayRef> {
124    let arrays = (0..args.num_inputs())
125        .map(|index| args.get(index))
126        .collect::<VortexResult<SmallVec<[ArrayRef; 4]>>>()?;
127
128    execute_row_inputs(
129        function,
130        options,
131        &ArrayInputs::new(&arrays, args.row_count()),
132        ctx,
133    )
134}
135
136/// Execute a row function over borrowed input columns.
137///
138/// Callers that already hold their operands avoid collecting another owned argument list.
139/// Batch inspection validates the lengths before planning or decoding the inputs.
140pub(crate) fn execute_row_inputs<F: RowFn, I: RowInputs + ?Sized>(
141    function: &F,
142    options: &F::Options,
143    inputs: &I,
144    ctx: &mut ExecutionCtx,
145) -> VortexResult<ArrayRef> {
146    ensure_arity(function, inputs.num_inputs())?;
147
148    if inputs.num_inputs() == 0 {
149        return execute_nullary_rows(function, options, inputs.row_count(), ctx);
150    }
151
152    let probe = BatchProbe::new(|| RowFn::id(function), inputs)?;
153    let collected: SmallVec<[DType; 4]>;
154    let arg_dtypes = match inputs.dtypes() {
155        Some(dtypes) => dtypes,
156        None => {
157            collected = (0..inputs.num_inputs())
158                .map(|index| inputs.input(index).dtype().clone())
159                .collect();
160            &collected
161        }
162    };
163
164    let plan = function.dispatch(options, arg_dtypes, BatchPlanner::<F>::new(arg_dtypes))?;
165    let batch = BatchInputs::new(RowFn::id(function), probe, inputs);
166
167    batch.with_plan(arg_dtypes, plan).execute(
168        |args, ctx| execute_row_kernel(function, options, args, ctx),
169        |args, ctx| execute_dense_attempt(function, options, args, ctx),
170        |args, valid, ctx| try_execute_valid_rows(function, options, args, valid, ctx),
171        |args, valid, ctx| execute_filtered_rows(function, options, args, valid, ctx),
172        ctx,
173    )
174}
175
176/// Execute a nullary kernel without batch validity or constant handling.
177fn execute_nullary_rows<F: RowFn>(
178    function: &F,
179    options: &F::Options,
180    row_count: usize,
181    ctx: &mut ExecutionCtx,
182) -> VortexResult<ArrayRef> {
183    let plan = function.dispatch(options, &[], BatchPlanner::<F>::new(&[]))?;
184    let result_dtype = plan.result_dtype(&[]);
185    let args = BorrowedRowFnArgs::new(&[], row_count, &[], &plan);
186
187    // A nullary function has no input validity to propagate, so its kernel output is the finished
188    // column and this path labels it directly.
189    let values = plan.relabel_output(execute_row_kernel(function, options, args, ctx)?)?;
190
191    finalize_kernel_output(RowFn::id(function), &result_dtype, row_count, values, ctx)
192}
193
194fn ensure_arity<F: RowFn>(function: &F, actual: usize) -> VortexResult<()> {
195    let expected = F::ARG_NAMES.len();
196    vortex_ensure_eq!(
197        actual,
198        expected,
199        "row function {} has the wrong arity",
200        RowFn::id(function),
201    );
202
203    Ok(())
204}
205
206fn execute_row_kernel<F: RowFn>(
207    function: &F,
208    options: &F::Options,
209    args: BorrowedRowFnArgs<'_>,
210    ctx: &mut ExecutionCtx,
211) -> VortexResult<ArrayRef> {
212    function.dispatch(
213        options,
214        args.dtypes(),
215        ExecuteRows::<F>::new(&args, args.dtypes(), args.plan(), ctx),
216    )
217}
218
219fn execute_dense_attempt<F: RowFn>(
220    function: &F,
221    options: &F::Options,
222    args: BorrowedRowFnArgs<'_>,
223    ctx: &mut ExecutionCtx,
224) -> VortexResult<DenseAttempt> {
225    function.dispatch(
226        options,
227        args.dtypes(),
228        ExecuteDenseWithRetry::<F>::new(&args, ctx),
229    )
230}
231
232fn try_execute_valid_rows<F: RowFn>(
233    function: &F,
234    options: &F::Options,
235    args: BorrowedRowFnArgs<'_>,
236    valid: MaskValuesRef,
237    ctx: &mut ExecutionCtx,
238) -> VortexResult<Option<ArrayRef>> {
239    function.dispatch(
240        options,
241        args.dtypes(),
242        ExecuteValidRows::<F>::new(&args, args.dtypes(), args.plan(), valid, ctx),
243    )
244}
245
246/// Execute valid rows over `args` filtered to the valid row domain of `valid`.
247fn execute_filtered_rows<F: RowFn>(
248    function: &F,
249    options: &F::Options,
250    args: BorrowedRowFnArgs<'_>,
251    valid: MaskValuesRef,
252    ctx: &mut ExecutionCtx,
253) -> VortexResult<ArrayRef> {
254    function.dispatch(
255        options,
256        args.dtypes(),
257        ExecuteFilteredRows::<F>::new(&args, args.dtypes(), args.plan(), valid, ctx),
258    )
259}
260
261#[cfg(test)]
262mod tests {
263    use std::sync::Arc;
264    use std::sync::LazyLock;
265    use std::sync::atomic::AtomicUsize;
266    use std::sync::atomic::Ordering;
267
268    use rstest::rstest;
269    use vortex_error::VortexError;
270    use vortex_error::VortexResult;
271    use vortex_session::VortexSession;
272    use vortex_session::registry::CachedId;
273
274    use super::execute_rows;
275    use super::row_fn_return_dtype;
276    use crate::IntoArray;
277    use crate::VortexSessionExecute;
278    use crate::arrays::PrimitiveArray;
279    use crate::assert_arrays_eq;
280    use crate::dtype::DType;
281    use crate::scalar_fn::EmptyOptions;
282    use crate::scalar_fn::ScalarFnId;
283    use crate::scalar_fn::VecExecutionArgs;
284    use crate::scalar_fn::unstable::row::RowFn;
285    use crate::scalar_fn::unstable::row::RowVisitor;
286    use crate::validity::Validity;
287
288    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
289
290    #[derive(Clone)]
291    struct IndexingRowFn;
292
293    #[derive(Clone)]
294    struct NullarySeven;
295
296    #[derive(Clone)]
297    struct ChangingDispatchRowFn {
298        dispatches: Arc<AtomicUsize>,
299        change: DispatchChange,
300    }
301
302    #[derive(Clone, Copy)]
303    enum DispatchChange {
304        Policy,
305        Element,
306    }
307
308    impl RowFn for NullarySeven {
309        type Options = EmptyOptions;
310
311        const ARG_NAMES: &'static [&'static str] = &[];
312        const INFALLIBLE: bool = true;
313
314        fn id(&self) -> ScalarFnId {
315            static ID: CachedId = CachedId::new("test.nullary_seven");
316            *ID
317        }
318
319        fn dispatch<V: RowVisitor>(
320            &self,
321            _options: &Self::Options,
322            _args: &[DType],
323            visitor: V,
324        ) -> VortexResult<V::VisitResult> {
325            visitor.visit::<(), i64>(|()| 7)
326        }
327    }
328
329    impl RowFn for IndexingRowFn {
330        type Options = EmptyOptions;
331
332        const ARG_NAMES: &'static [&'static str] = &["value"];
333
334        const INFALLIBLE: bool = true;
335
336        fn id(&self) -> ScalarFnId {
337            static ID: CachedId = CachedId::new("test.indexing_row_fn");
338            *ID
339        }
340
341        fn dispatch<V: RowVisitor>(
342            &self,
343            _options: &Self::Options,
344            args: &[DType],
345            visitor: V,
346        ) -> VortexResult<V::VisitResult> {
347            _ = &args[0];
348
349            visitor.visit::<(i64,), i64>(|(value,)| value)
350        }
351    }
352
353    impl RowFn for ChangingDispatchRowFn {
354        type Options = EmptyOptions;
355
356        const ARG_NAMES: &'static [&'static str] = &["value"];
357        const INFALLIBLE: bool = false;
358
359        fn id(&self) -> ScalarFnId {
360            static ID: CachedId = CachedId::new("test.changing_dispatch_row_fn");
361            *ID
362        }
363
364        fn dispatch<V: RowVisitor>(
365            &self,
366            _options: &Self::Options,
367            _args: &[DType],
368            visitor: V,
369        ) -> VortexResult<V::VisitResult> {
370            if self.dispatches.fetch_add(1, Ordering::Relaxed) == 0 {
371                visitor.visit::<(i64,), i64>(|(value,)| value)
372            } else {
373                match self.change {
374                    DispatchChange::Policy => visitor
375                        .visit_deferred::<(i64,), i64, bool>(|(value,)| (value, false), |_| Ok(())),
376                    DispatchChange::Element => visitor.visit::<(u64,), u64>(|(value,)| value),
377                }
378            }
379        }
380    }
381
382    #[test]
383    fn test_return_dtype_rejects_wrong_arity_before_dispatch() {
384        let error = row_fn_return_dtype(&IndexingRowFn, &EmptyOptions, &[])
385            .expect_err("wrong arity must fail before dispatch");
386
387        assert_arity_error(error);
388    }
389
390    #[test]
391    fn test_execute_rejects_wrong_arity_before_dispatch() {
392        let args = VecExecutionArgs::new(vec![], 0);
393        let mut ctx = SESSION.create_execution_ctx();
394        let error = execute_rows(&IndexingRowFn, &EmptyOptions, &args, &mut ctx)
395            .expect_err("wrong arity must fail before dispatch");
396
397        assert_arity_error(error);
398    }
399
400    #[rstest]
401    #[case::empty(0)]
402    #[case::nonempty(3)]
403    fn test_execute_nullary_rows(#[case] row_count: usize) -> VortexResult<()> {
404        let args = VecExecutionArgs::new(vec![], row_count);
405        let mut ctx = SESSION.create_execution_ctx();
406
407        let actual = execute_rows(&NullarySeven, &EmptyOptions, &args, &mut ctx)?;
408        let expected = PrimitiveArray::from_iter(vec![7_i64; row_count]).into_array();
409
410        assert_arrays_eq!(&actual, &expected, &mut ctx);
411        Ok(())
412    }
413
414    #[test]
415    fn test_execute_rejects_dispatch_that_changes_after_planning() -> VortexResult<()> {
416        let function = ChangingDispatchRowFn {
417            dispatches: Arc::new(AtomicUsize::new(0)),
418            change: DispatchChange::Policy,
419        };
420        let input = PrimitiveArray::new(vec![1_i64, 2], Validity::NonNullable).into_array();
421        let args = VecExecutionArgs::new(vec![input], 2);
422        let mut ctx = SESSION.create_execution_ctx();
423
424        let error = match execute_rows(&function, &EmptyOptions, &args, &mut ctx) {
425            Err(error) => error,
426            Ok(_) => {
427                vortex_error::vortex_bail!("dispatch must not change after planning")
428            }
429        };
430        let message = error.to_string();
431
432        assert!(
433            message.contains("row dispatch must select the planned nullable execution policy"),
434            "unexpected error: {error}",
435        );
436        assert!(
437            message.contains("planned Dense, got DenseWithRetry"),
438            "unexpected error: {error}",
439        );
440        Ok(())
441    }
442
443    #[test]
444    fn test_execute_revalidates_element_types_after_planning() -> VortexResult<()> {
445        let function = ChangingDispatchRowFn {
446            dispatches: Arc::new(AtomicUsize::new(0)),
447            change: DispatchChange::Element,
448        };
449        let input = PrimitiveArray::new(vec![1_i64, 2], Validity::NonNullable).into_array();
450        let args = VecExecutionArgs::new(vec![input], 2);
451        let mut ctx = SESSION.create_execution_ctx();
452
453        let error = match execute_rows(&function, &EmptyOptions, &args, &mut ctx) {
454            Err(error) => error,
455            Ok(_) => {
456                vortex_error::vortex_bail!("dispatch must preserve its planned element types")
457            }
458        };
459
460        assert!(
461            error
462                .to_string()
463                .contains("row input column has the wrong ptype"),
464            "unexpected error: {error}",
465        );
466        Ok(())
467    }
468
469    #[track_caller]
470    fn assert_arity_error(error: VortexError) {
471        assert!(
472            error.to_string().contains("has the wrong arity"),
473            "unexpected error: {error}",
474        );
475    }
476}