1use 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::BatchProbe;
19use super::batch::BorrowedRowFnArgs;
20use super::batch::RowInputs;
21use super::batch::finalize_kernel_output;
22use super::row_fn::RowFn;
23use super::visitor::BatchPlanner;
24use super::visitor::ExecuteDenseWithRetry;
25use super::visitor::ExecuteFilteredRows;
26use super::visitor::ExecuteFused;
27use super::visitor::ExecuteRows;
28use super::visitor::ExecuteValidRows;
29use super::visitor::Fused;
30use crate::ArrayRef;
31use crate::ExecutionCtx;
32use crate::dtype::DType;
33use crate::scalar_fn::Arity;
34use crate::scalar_fn::ChildName;
35use crate::scalar_fn::ExecutionArgs;
36use crate::scalar_fn::ReduceNode;
37use crate::scalar_fn::ReduceNodeValidity;
38use crate::scalar_fn::ScalarFnId;
39use crate::scalar_fn::ScalarFnVTable;
40use crate::scalar_fn::union_child_validities;
41use crate::scalar_fn::unstable::row::execute::DenseAttempt;
42
43impl<F: RowFn> ScalarFnVTable for F {
44 type Options = F::Options;
45
46 fn id(&self) -> ScalarFnId {
47 RowFn::id(self)
48 }
49
50 fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
51 RowFn::serialize(self, options)
52 }
53
54 fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult<Self::Options> {
55 RowFn::deserialize(self, metadata, session)
56 }
57
58 fn arity(&self, _options: &Self::Options) -> Arity {
59 Arity::Exact(F::ARG_NAMES.len())
60 }
61
62 fn child_name(&self, _options: &Self::Options, child_index: usize) -> ChildName {
63 ChildName::from(F::ARG_NAMES[child_index])
64 }
65
66 fn return_dtype(&self, options: &Self::Options, args: &[DType]) -> VortexResult<DType> {
67 row_fn_return_dtype(self, options, args)
68 }
69
70 fn execute(
71 &self,
72 options: &Self::Options,
73 args: &dyn ExecutionArgs,
74 ctx: &mut ExecutionCtx,
75 ) -> VortexResult<ArrayRef> {
76 execute_rows(self, options, args, ctx)
77 }
78
79 fn validity<T: ReduceNode>(
80 &self,
81 _options: &Self::Options,
82 node: &T,
83 ) -> VortexResult<ReduceNodeValidity<T>> {
84 Ok(ReduceNodeValidity::Reduced(union_child_validities(node)?))
85 }
86
87 fn is_strict(&self, _options: &Self::Options) -> bool {
90 true
91 }
92
93 fn is_infallible(&self, _options: &Self::Options) -> bool {
94 F::INFALLIBLE
95 }
96}
97
98pub fn row_fn_return_dtype<F: RowFn>(
100 function: &F,
101 options: &F::Options,
102 args: &[DType],
103) -> VortexResult<DType> {
104 ensure_arity(function, args.len())?;
105
106 let plan = function.dispatch(options, args, BatchPlanner::<F>::new(args))?;
107
108 Ok(plan.result_dtype(args))
109}
110
111pub fn execute_rows<F: RowFn>(
120 function: &F,
121 options: &F::Options,
122 args: &dyn ExecutionArgs,
123 ctx: &mut ExecutionCtx,
124) -> VortexResult<ArrayRef> {
125 let arrays = (0..args.num_inputs())
126 .map(|index| args.get(index))
127 .collect::<VortexResult<SmallVec<[ArrayRef; 4]>>>()?;
128
129 execute_row_inputs(
130 function,
131 options,
132 &ArrayInputs::new(&arrays, args.row_count()),
133 ctx,
134 )
135}
136
137pub(crate) fn execute_row_inputs<F: RowFn, I: RowInputs + ?Sized>(
142 function: &F,
143 options: &F::Options,
144 inputs: &I,
145 ctx: &mut ExecutionCtx,
146) -> VortexResult<ArrayRef> {
147 ensure_arity(function, inputs.num_inputs())?;
148
149 if inputs.num_inputs() == 0 {
150 return execute_nullary_rows(function, options, inputs.row_count(), ctx);
151 }
152
153 let probe = BatchProbe::new(|| RowFn::id(function), inputs)?;
156 let collected: SmallVec<[DType; 4]>;
157 let arg_dtypes = match inputs.dtypes() {
158 Some(dtypes) => dtypes,
159 None => {
160 collected = (0..inputs.num_inputs())
161 .map(|index| inputs.input(index).dtype().clone())
162 .collect();
163 &collected
164 }
165 };
166
167 let batch = match function.dispatch(
171 options,
172 arg_dtypes,
173 ExecuteFused::<F, I>::new(function, inputs, probe, arg_dtypes, ctx),
174 )? {
175 Fused::Done(values) => return Ok(values),
176 Fused::Partial(batch) => batch,
177 };
178
179 batch.execute(
180 arg_dtypes,
181 |args, ctx| execute_row_kernel(function, options, args, ctx),
182 |args, ctx| execute_dense_attempt(function, options, args, ctx),
183 |args, valid, ctx| try_execute_valid_rows(function, options, args, valid, ctx),
184 |args, valid, ctx| execute_filtered_rows(function, options, args, valid, ctx),
185 ctx,
186 )
187}
188
189fn execute_nullary_rows<F: RowFn>(
191 function: &F,
192 options: &F::Options,
193 row_count: usize,
194 ctx: &mut ExecutionCtx,
195) -> VortexResult<ArrayRef> {
196 let plan = function.dispatch(options, &[], BatchPlanner::<F>::new(&[]))?;
197 let result_dtype = plan.result_dtype(&[]);
198 let args = BorrowedRowFnArgs::new(&[], row_count, &[], &plan);
199
200 let values = plan.relabel_output(execute_row_kernel(function, options, args, ctx)?)?;
203
204 finalize_kernel_output(RowFn::id(function), &result_dtype, row_count, values, ctx)
205}
206
207fn ensure_arity<F: RowFn>(function: &F, actual: usize) -> VortexResult<()> {
208 let expected = F::ARG_NAMES.len();
209 vortex_ensure_eq!(
210 actual,
211 expected,
212 "row function {} has the wrong arity",
213 RowFn::id(function),
214 );
215
216 Ok(())
217}
218
219fn execute_row_kernel<F: RowFn>(
220 function: &F,
221 options: &F::Options,
222 args: BorrowedRowFnArgs<'_>,
223 ctx: &mut ExecutionCtx,
224) -> VortexResult<ArrayRef> {
225 function.dispatch(
226 options,
227 args.dtypes(),
228 ExecuteRows::<F>::new(&args, args.dtypes(), args.plan(), ctx),
229 )
230}
231
232fn execute_dense_attempt<F: RowFn>(
233 function: &F,
234 options: &F::Options,
235 args: BorrowedRowFnArgs<'_>,
236 ctx: &mut ExecutionCtx,
237) -> VortexResult<DenseAttempt> {
238 function.dispatch(
239 options,
240 args.dtypes(),
241 ExecuteDenseWithRetry::<F>::new(&args, ctx),
242 )
243}
244
245fn try_execute_valid_rows<F: RowFn>(
246 function: &F,
247 options: &F::Options,
248 args: BorrowedRowFnArgs<'_>,
249 valid: MaskValuesRef,
250 ctx: &mut ExecutionCtx,
251) -> VortexResult<Option<ArrayRef>> {
252 function.dispatch(
253 options,
254 args.dtypes(),
255 ExecuteValidRows::<F>::new(&args, args.dtypes(), args.plan(), valid, ctx),
256 )
257}
258
259fn execute_filtered_rows<F: RowFn>(
261 function: &F,
262 options: &F::Options,
263 args: BorrowedRowFnArgs<'_>,
264 valid: MaskValuesRef,
265 ctx: &mut ExecutionCtx,
266) -> VortexResult<ArrayRef> {
267 function.dispatch(
268 options,
269 args.dtypes(),
270 ExecuteFilteredRows::<F>::new(&args, args.dtypes(), args.plan(), valid, ctx),
271 )
272}
273
274#[cfg(test)]
275mod tests {
276 use std::sync::Arc;
277 use std::sync::LazyLock;
278 use std::sync::atomic::AtomicUsize;
279 use std::sync::atomic::Ordering;
280
281 use rstest::rstest;
282 use vortex_error::VortexError;
283 use vortex_error::VortexResult;
284 use vortex_session::VortexSession;
285 use vortex_session::registry::CachedId;
286
287 use super::execute_rows;
288 use super::row_fn_return_dtype;
289 use crate::IntoArray;
290 use crate::VortexSessionExecute;
291 use crate::arrays::PrimitiveArray;
292 use crate::assert_arrays_eq;
293 use crate::dtype::DType;
294 use crate::scalar_fn::EmptyOptions;
295 use crate::scalar_fn::ScalarFnId;
296 use crate::scalar_fn::VecExecutionArgs;
297 use crate::scalar_fn::unstable::row::RowFn;
298 use crate::scalar_fn::unstable::row::RowVisitor;
299 use crate::validity::Validity;
300
301 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
302
303 #[derive(Clone)]
304 struct IndexingRowFn;
305
306 #[derive(Clone)]
307 struct NullarySeven;
308
309 #[derive(Clone)]
310 struct ChangingDispatchRowFn {
311 dispatches: Arc<AtomicUsize>,
312 change: DispatchChange,
313 }
314
315 #[derive(Clone, Copy)]
316 enum DispatchChange {
317 Policy,
318 Element,
319 }
320
321 impl RowFn for NullarySeven {
322 type Options = EmptyOptions;
323
324 const ARG_NAMES: &'static [&'static str] = &[];
325 const INFALLIBLE: bool = true;
326
327 fn id(&self) -> ScalarFnId {
328 static ID: CachedId = CachedId::new("test.nullary_seven");
329 *ID
330 }
331
332 fn dispatch<V: RowVisitor>(
333 &self,
334 _options: &Self::Options,
335 _args: &[DType],
336 visitor: V,
337 ) -> VortexResult<V::VisitResult> {
338 visitor.visit::<(), i64>(|()| 7)
339 }
340 }
341
342 impl RowFn for IndexingRowFn {
343 type Options = EmptyOptions;
344
345 const ARG_NAMES: &'static [&'static str] = &["value"];
346
347 const INFALLIBLE: bool = true;
348
349 fn id(&self) -> ScalarFnId {
350 static ID: CachedId = CachedId::new("test.indexing_row_fn");
351 *ID
352 }
353
354 fn dispatch<V: RowVisitor>(
355 &self,
356 _options: &Self::Options,
357 args: &[DType],
358 visitor: V,
359 ) -> VortexResult<V::VisitResult> {
360 _ = &args[0];
361
362 visitor.visit::<(i64,), i64>(|(value,)| value)
363 }
364 }
365
366 impl RowFn for ChangingDispatchRowFn {
367 type Options = EmptyOptions;
368
369 const ARG_NAMES: &'static [&'static str] = &["value"];
370 const INFALLIBLE: bool = false;
371
372 fn id(&self) -> ScalarFnId {
373 static ID: CachedId = CachedId::new("test.changing_dispatch_row_fn");
374 *ID
375 }
376
377 fn dispatch<V: RowVisitor>(
378 &self,
379 _options: &Self::Options,
380 _args: &[DType],
381 visitor: V,
382 ) -> VortexResult<V::VisitResult> {
383 if self.dispatches.fetch_add(1, Ordering::Relaxed) == 0 {
386 visitor.visit_deferred::<(i64,), i64, bool>(|(value,)| (value, false), |_| Ok(()))
387 } else {
388 match self.change {
389 DispatchChange::Policy => visitor.visit::<(i64,), i64>(|(value,)| value),
390 DispatchChange::Element => visitor
391 .visit_deferred::<(u64,), u64, bool>(|(value,)| (value, false), |_| Ok(())),
392 }
393 }
394 }
395 }
396
397 #[test]
398 fn test_return_dtype_rejects_wrong_arity_before_dispatch() {
399 let error = row_fn_return_dtype(&IndexingRowFn, &EmptyOptions, &[])
400 .expect_err("wrong arity must fail before dispatch");
401
402 assert_arity_error(error);
403 }
404
405 #[test]
406 fn test_execute_rejects_wrong_arity_before_dispatch() {
407 let args = VecExecutionArgs::new(vec![], 0);
408 let mut ctx = SESSION.create_execution_ctx();
409 let error = execute_rows(&IndexingRowFn, &EmptyOptions, &args, &mut ctx)
410 .expect_err("wrong arity must fail before dispatch");
411
412 assert_arity_error(error);
413 }
414
415 #[rstest]
416 #[case::empty(0)]
417 #[case::nonempty(3)]
418 fn test_execute_nullary_rows(#[case] row_count: usize) -> VortexResult<()> {
419 let args = VecExecutionArgs::new(vec![], row_count);
420 let mut ctx = SESSION.create_execution_ctx();
421
422 let actual = execute_rows(&NullarySeven, &EmptyOptions, &args, &mut ctx)?;
423 let expected = PrimitiveArray::from_iter(vec![7_i64; row_count]).into_array();
424
425 assert_arrays_eq!(&actual, &expected, &mut ctx);
426 Ok(())
427 }
428
429 #[test]
430 fn test_execute_dispatches_once_without_retry() -> VortexResult<()> {
431 let dispatches = Arc::new(AtomicUsize::new(0));
432 let function = ChangingDispatchRowFn {
433 dispatches: Arc::clone(&dispatches),
434 change: DispatchChange::Policy,
435 };
436 let input = PrimitiveArray::new(vec![1_i64, 2], Validity::NonNullable).into_array();
437 let args = VecExecutionArgs::new(vec![input.clone()], 2);
438 let mut ctx = SESSION.create_execution_ctx();
439
440 let actual = execute_rows(&function, &EmptyOptions, &args, &mut ctx)?;
441
442 assert_eq!(dispatches.load(Ordering::Relaxed), 1);
443 assert_arrays_eq!(&actual, &input, &mut ctx);
444 Ok(())
445 }
446
447 #[test]
448 fn test_execute_rejects_dispatch_that_changes_after_planning() -> VortexResult<()> {
449 let function = ChangingDispatchRowFn {
450 dispatches: Arc::new(AtomicUsize::new(0)),
451 change: DispatchChange::Policy,
452 };
453 let validity = Validity::from_iter([true, false]);
454 let input = PrimitiveArray::new(vec![1_i64, 2], validity).into_array();
455 let args = VecExecutionArgs::new(vec![input], 2);
456 let mut ctx = SESSION.create_execution_ctx();
457
458 let error = match execute_rows(&function, &EmptyOptions, &args, &mut ctx) {
459 Err(error) => error,
460 Ok(_) => {
461 vortex_error::vortex_bail!("dispatch must not change after planning")
462 }
463 };
464 let message = error.to_string();
465
466 assert!(
467 message.contains("row dispatch must select the planned nullable execution policy"),
468 "unexpected error: {error}",
469 );
470 assert!(
471 message.contains("planned DenseWithRetry, got Dense"),
472 "unexpected error: {error}",
473 );
474 Ok(())
475 }
476
477 #[test]
478 fn test_execute_revalidates_element_types_after_planning() -> VortexResult<()> {
479 let function = ChangingDispatchRowFn {
480 dispatches: Arc::new(AtomicUsize::new(0)),
481 change: DispatchChange::Element,
482 };
483 let validity = Validity::from_iter([true, false]);
484 let input = PrimitiveArray::new(vec![1_i64, 2], validity).into_array();
485 let args = VecExecutionArgs::new(vec![input], 2);
486 let mut ctx = SESSION.create_execution_ctx();
487
488 let error = match execute_rows(&function, &EmptyOptions, &args, &mut ctx) {
489 Err(error) => error,
490 Ok(_) => {
491 vortex_error::vortex_bail!("dispatch must preserve its planned element types")
492 }
493 };
494
495 assert!(
496 error
497 .to_string()
498 .contains("row input column has the wrong ptype"),
499 "unexpected error: {error}",
500 );
501 Ok(())
502 }
503
504 #[track_caller]
505 fn assert_arity_error(error: VortexError) {
506 assert!(
507 error.to_string().contains("has the wrong arity"),
508 "unexpected error: {error}",
509 );
510 }
511}