1use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::hash::Hash;
8use std::hash::Hasher;
9use std::sync::Arc;
10
11use parking_lot::Mutex;
12use vortex_array::ArrayRef;
13use vortex_array::ExecutionCtx;
14use vortex_array::IntoArray;
15use vortex_array::arrays::ConstantArray;
16use vortex_array::dtype::DType;
17use vortex_array::scalar::Scalar;
18use vortex_array::scalar::ScalarValue;
19use vortex_array::scalar_fn::Arity;
20use vortex_array::scalar_fn::ChildName;
21use vortex_array::scalar_fn::ExecutionArgs;
22use vortex_array::scalar_fn::ScalarFnId;
23use vortex_array::scalar_fn::ScalarFnVTable;
24use vortex_array::scalar_fn::ScalarFnVTableExt;
25use vortex_array::scalar_fn::VecExecutionArgs;
26use vortex_array::scalar_fn::builtin::compare::Compare;
27use vortex_array::scalar_fn::builtin::operators::CompareOperator;
28use vortex_array::scalar_fn::display::ExprDisplay;
29use vortex_error::VortexExpect;
30use vortex_error::VortexResult;
31use vortex_error::vortex_bail;
32use vortex_expr::BoundExpression;
33use vortex_expr::traversal::NodeExt;
34use vortex_expr::traversal::NodeVisitor;
35use vortex_expr::traversal::TraversalOrder;
36use vortex_session::registry::CachedId;
37
38use crate::dynamic_expression::DynamicExpression;
39use crate::dynamic_expression::DynamicExpressionSource;
40
41#[derive(Clone)]
45pub struct DynamicComparison;
46
47impl ScalarFnVTable for DynamicComparison {
48 type Options = DynamicComparisonExpr;
49
50 fn id(&self) -> ScalarFnId {
51 static ID: CachedId = CachedId::new("vortex.dynamic");
52 *ID
53 }
54
55 fn arity(&self, _options: &Self::Options) -> Arity {
56 Arity::Exact(1)
57 }
58
59 fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
60 match child_idx {
61 0 => ChildName::from("lhs"),
62 _ => unreachable!(),
63 }
64 }
65
66 fn fmt_sql(
67 &self,
68 dynamic: &DynamicComparisonExpr,
69 expr: &dyn ExprDisplay,
70 f: &mut Formatter<'_>,
71 ) -> std::fmt::Result {
72 Display::fmt(expr.display_child(0), f)?;
73 write!(f, " {} dynamic(", dynamic.operator)?;
74 match dynamic.scalar() {
75 None => write!(f, "scalar=<none>")?,
76 Some(scalar) => write!(f, "scalar={scalar}")?,
77 }
78 write!(f, ")")
79 }
80
81 fn return_dtype(
82 &self,
83 dynamic: &DynamicComparisonExpr,
84 arg_dtypes: &[DType],
85 ) -> VortexResult<DType> {
86 let lhs = &arg_dtypes[0];
87 if !dynamic.rhs.dtype.eq_ignore_nullability(lhs) {
88 vortex_bail!(
89 "Incompatible dtypes for dynamic comparison: expected {} (ignore nullability) but got {}",
90 &dynamic.rhs.dtype,
91 lhs
92 );
93 }
94 Ok(DType::Bool(
95 lhs.nullability() | dynamic.rhs.dtype.nullability(),
96 ))
97 }
98
99 fn execute(
100 &self,
101 data: &Self::Options,
102 args: &dyn ExecutionArgs,
103 ctx: &mut ExecutionCtx,
104 ) -> VortexResult<ArrayRef> {
105 if let Some(scalar) = data.rhs.scalar() {
106 let lhs = args.get(0)?;
107 let rhs = ConstantArray::new(scalar, args.row_count()).into_array();
108
109 let delegate_args = VecExecutionArgs::new(vec![lhs, rhs], args.row_count());
110 return Compare.bind(data.operator).execute(&delegate_args, ctx);
111 }
112 let ret_dtype =
113 DType::Bool(args.get(0)?.dtype().nullability() | data.rhs.dtype.nullability());
114
115 Ok(ConstantArray::new(
116 Scalar::try_new(ret_dtype, Some(data.default.into()))?,
117 args.row_count(),
118 )
119 .into_array())
120 }
121
122 fn is_strict(&self, _options: &Self::Options) -> bool {
123 false
124 }
125
126 fn is_infallible(&self, _options: &Self::Options) -> bool {
129 true
130 }
131}
132
133#[derive(Clone, Debug)]
134pub struct DynamicComparisonExpr {
135 pub(crate) operator: CompareOperator,
136 pub(crate) rhs: Arc<Rhs>,
137 pub(crate) default: bool,
139}
140
141impl DynamicComparisonExpr {
142 pub fn operator(&self) -> CompareOperator {
144 self.operator
145 }
146
147 pub fn default(&self) -> bool {
149 self.default
150 }
151
152 pub fn dtype(&self) -> &DType {
154 &self.rhs.dtype
155 }
156
157 pub fn with_operator(&self, operator: CompareOperator, default: bool) -> Self {
159 Self {
160 operator,
161 rhs: Arc::clone(&self.rhs),
162 default,
163 }
164 }
165
166 pub fn scalar(&self) -> Option<Scalar> {
167 (self.rhs.value)().map(|v| {
168 Scalar::try_new(self.rhs.dtype.clone(), Some(v))
169 .vortex_expect("`DynamicComparisonExpr` was invalid")
170 })
171 }
172}
173
174impl Display for DynamicComparisonExpr {
175 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
176 write!(
177 f,
178 "{} {}",
179 self.operator,
180 self.scalar()
181 .map_or_else(|| "<none>".to_string(), |v| v.to_string())
182 )
183 }
184}
185
186impl PartialEq for DynamicComparisonExpr {
187 fn eq(&self, other: &Self) -> bool {
188 self.operator == other.operator
189 && Arc::ptr_eq(&self.rhs, &other.rhs)
190 && self.default == other.default
191 }
192}
193impl Eq for DynamicComparisonExpr {}
194
195impl Hash for DynamicComparisonExpr {
196 fn hash<H: Hasher>(&self, state: &mut H) {
197 self.operator.hash(state);
198 Arc::as_ptr(&self.rhs).hash(state);
199 self.default.hash(state);
200 }
201}
202
203pub(crate) struct Rhs {
206 pub(crate) value: Arc<dyn Fn() -> Option<ScalarValue> + Send + Sync>,
208 pub(crate) dtype: DType,
210}
211
212impl Rhs {
213 pub fn scalar(&self) -> Option<Scalar> {
214 (self.value)().map(|v| {
215 Scalar::try_new(self.dtype.clone(), Some(v)).vortex_expect("`Rhs` was invalid")
216 })
217 }
218}
219
220impl Debug for Rhs {
221 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
222 f.debug_struct("Rhs")
223 .field("value", &"<dyn Fn() -> Option<ScalarValue> + Send + Sync>")
224 .field("dtype", &self.dtype)
225 .finish()
226 }
227}
228
229pub struct DynamicExprUpdates {
231 exprs: Box<[DynamicComparisonExpr]>,
232 sources: Box<[Arc<dyn DynamicExpressionSource>]>,
233 prev_versions: Mutex<ObservedVersions>,
235}
236
237struct ObservedVersions {
238 version: u64,
239 scalars: Vec<Option<Scalar>>,
240 generations: Vec<u64>,
241}
242
243impl DynamicExprUpdates {
244 pub fn new(expr: &BoundExpression) -> Option<Self> {
246 #[derive(Default)]
247 struct Visitor {
248 exprs: Vec<DynamicComparisonExpr>,
249 sources: Vec<Arc<dyn DynamicExpressionSource>>,
250 }
251
252 impl NodeVisitor<'_> for Visitor {
253 type NodeTy = BoundExpression;
254
255 fn visit_down(&mut self, node: &'_ Self::NodeTy) -> VortexResult<TraversalOrder> {
256 if let Some(dynamic) = node.as_opt::<DynamicComparison>() {
257 self.exprs.push(dynamic.clone());
258 }
259 if let Some(dynamic) = node.as_opt::<DynamicExpression>() {
260 self.sources.push(Arc::clone(dynamic.source()));
261 }
262 Ok(TraversalOrder::Continue)
263 }
264 }
265
266 let mut visitor = Visitor::default();
267 expr.accept(&mut visitor).vortex_expect("Infallible");
268
269 if visitor.exprs.is_empty() && visitor.sources.is_empty() {
270 return None;
271 }
272
273 let exprs = visitor.exprs.into_boxed_slice();
274 let sources = visitor.sources.into_boxed_slice();
275 let scalars = exprs
276 .iter()
277 .map(|expr| {
278 (expr.rhs.value)().map(|v| {
279 Scalar::try_new(expr.rhs.dtype.clone(), Some(v))
280 .vortex_expect("`DynamicExprUpdates` was invalid")
281 })
282 })
283 .collect();
284 let generations = sources.iter().map(|source| source.generation()).collect();
285
286 Some(Self {
287 exprs,
288 sources,
289 prev_versions: Mutex::new(ObservedVersions {
290 version: 0,
291 scalars,
292 generations,
293 }),
294 })
295 }
296
297 pub fn version(&self) -> u64 {
298 let mut guard = self.prev_versions.lock();
299
300 let mut updated = false;
301 for (i, expr) in self.exprs.iter().enumerate() {
302 let current = expr.scalar();
303 if current != guard.scalars[i] {
304 updated = true;
308 guard.scalars[i] = current;
309 }
310 }
311 for (i, source) in self.sources.iter().enumerate() {
312 let current = source.generation();
313 if current != guard.generations[i] {
314 updated = true;
315 guard.generations[i] = current;
316 }
317 }
318
319 if updated {
320 guard.version += 1;
321 }
322
323 guard.version
324 }
325}
326
327#[cfg(test)]
328mod tests {
329 use std::sync::LazyLock;
330 use std::sync::atomic::AtomicI32;
331 use std::sync::atomic::Ordering;
332
333 use vortex_array::IntoArray;
334 use vortex_array::VortexSessionExecute;
335 use vortex_array::arrays::BoolArray;
336 use vortex_array::assert_arrays_eq;
337 use vortex_array::dtype::DType;
338 use vortex_array::dtype::Nullability;
339 use vortex_array::dtype::PType;
340 use vortex_buffer::buffer;
341 use vortex_error::VortexResult;
342 use vortex_expr::ArrayExprExt;
343 use vortex_expr::root;
344 use vortex_session::VortexSession;
345
346 use super::*;
347 use crate::expr::dynamic;
348
349 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
350 let session = VortexSession::empty();
351
352 vortex_array::initialize(&session);
353
354 crate::initialize(&session);
355
356 session
357 });
358
359 #[test]
360 fn is_not_strict() {
361 let expr = dynamic(
362 CompareOperator::Lt,
363 || None,
364 DType::Primitive(PType::I32, Nullability::NonNullable),
365 true,
366 root(),
367 );
368
369 assert!(!expr.as_scalar().is_some_and(|f| f.signature().is_strict()));
370 }
371
372 #[test]
373 fn dtype_of_unknown_value() {
374 let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
375 let expr = dynamic(CompareOperator::Lt, || None, dtype.clone(), true, root());
376
377 let options = expr.as_::<DynamicComparison>();
378 assert_eq!(options.scalar(), None);
379 assert_eq!(options.dtype(), &dtype);
380 }
381
382 #[test]
383 fn return_dtype_bool() -> VortexResult<()> {
384 let expr = dynamic(
385 CompareOperator::Lt,
386 || Some(5i32.into()),
387 DType::Primitive(PType::I32, Nullability::NonNullable),
388 true,
389 root(),
390 );
391 let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
392 assert_eq!(
393 expr.return_dtype(&input_dtype)?,
394 DType::Bool(Nullability::NonNullable)
395 );
396 Ok(())
397 }
398
399 #[test]
400 fn execute_with_value() -> VortexResult<()> {
401 let mut ctx = SESSION.create_execution_ctx();
402 let input = buffer![1i32, 5, 10].into_array();
403 let expr = dynamic(
404 CompareOperator::Lt,
405 || Some(5i32.into()),
406 DType::Primitive(PType::I32, Nullability::NonNullable),
407 true,
408 root(),
409 );
410 let result = input.apply(&expr)?;
411 assert_arrays_eq!(result, BoolArray::from_iter([true, false, false]), &mut ctx);
412 Ok(())
413 }
414
415 #[test]
416 fn execute_without_value_default_true() -> VortexResult<()> {
417 let mut ctx = SESSION.create_execution_ctx();
418 let input = buffer![1i32, 5, 10].into_array();
419 let expr = dynamic(
420 CompareOperator::Lt,
421 || None,
422 DType::Primitive(PType::I32, Nullability::NonNullable),
423 true,
424 root(),
425 );
426 let result = input.apply(&expr)?;
427 assert_arrays_eq!(result, BoolArray::from_iter([true, true, true]), &mut ctx);
428 Ok(())
429 }
430
431 #[test]
432 fn execute_without_value_default_false() -> VortexResult<()> {
433 let mut ctx = SESSION.create_execution_ctx();
434 let input = buffer![1i32, 5, 10].into_array();
435 let expr = dynamic(
436 CompareOperator::Lt,
437 || None,
438 DType::Primitive(PType::I32, Nullability::NonNullable),
439 false,
440 root(),
441 );
442 let result = input.apply(&expr)?;
443 assert_arrays_eq!(
444 result,
445 BoolArray::from_iter([false, false, false]),
446 &mut ctx
447 );
448 Ok(())
449 }
450
451 #[test]
452 fn execute_value_flips() -> VortexResult<()> {
453 let mut ctx = SESSION.create_execution_ctx();
454 let threshold = Arc::new(AtomicI32::new(5));
455 let threshold_clone = Arc::clone(&threshold);
456 let expr = dynamic(
457 CompareOperator::Lt,
458 move || Some(threshold_clone.load(Ordering::SeqCst).into()),
459 DType::Primitive(PType::I32, Nullability::NonNullable),
460 true,
461 root(),
462 );
463 let input = buffer![1i32, 5, 10].into_array();
464
465 let result = input.clone().apply(&expr)?;
466 assert_arrays_eq!(result, BoolArray::from_iter([true, false, false]), &mut ctx);
467
468 threshold.store(10, Ordering::SeqCst);
469 let result = input.apply(&expr)?;
470 assert_arrays_eq!(result, BoolArray::from_iter([true, true, false]), &mut ctx);
471
472 Ok(())
473 }
474}