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 with_operator(&self, operator: CompareOperator, default: bool) -> Self {
154 Self {
155 operator,
156 rhs: Arc::clone(&self.rhs),
157 default,
158 }
159 }
160
161 pub fn scalar(&self) -> Option<Scalar> {
162 (self.rhs.value)().map(|v| {
163 Scalar::try_new(self.rhs.dtype.clone(), Some(v))
164 .vortex_expect("`DynamicComparisonExpr` was invalid")
165 })
166 }
167}
168
169impl Display for DynamicComparisonExpr {
170 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
171 write!(
172 f,
173 "{} {}",
174 self.operator,
175 self.scalar()
176 .map_or_else(|| "<none>".to_string(), |v| v.to_string())
177 )
178 }
179}
180
181impl PartialEq for DynamicComparisonExpr {
182 fn eq(&self, other: &Self) -> bool {
183 self.operator == other.operator
184 && Arc::ptr_eq(&self.rhs, &other.rhs)
185 && self.default == other.default
186 }
187}
188impl Eq for DynamicComparisonExpr {}
189
190impl Hash for DynamicComparisonExpr {
191 fn hash<H: Hasher>(&self, state: &mut H) {
192 self.operator.hash(state);
193 Arc::as_ptr(&self.rhs).hash(state);
194 self.default.hash(state);
195 }
196}
197
198pub(crate) struct Rhs {
201 pub(crate) value: Arc<dyn Fn() -> Option<ScalarValue> + Send + Sync>,
203 pub(crate) dtype: DType,
205}
206
207impl Rhs {
208 pub fn scalar(&self) -> Option<Scalar> {
209 (self.value)().map(|v| {
210 Scalar::try_new(self.dtype.clone(), Some(v)).vortex_expect("`Rhs` was invalid")
211 })
212 }
213}
214
215impl Debug for Rhs {
216 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
217 f.debug_struct("Rhs")
218 .field("value", &"<dyn Fn() -> Option<ScalarValue> + Send + Sync>")
219 .field("dtype", &self.dtype)
220 .finish()
221 }
222}
223
224pub struct DynamicExprUpdates {
226 exprs: Box<[DynamicComparisonExpr]>,
227 sources: Box<[Arc<dyn DynamicExpressionSource>]>,
228 prev_versions: Mutex<ObservedVersions>,
230}
231
232struct ObservedVersions {
233 version: u64,
234 scalars: Vec<Option<Scalar>>,
235 generations: Vec<u64>,
236}
237
238impl DynamicExprUpdates {
239 pub fn new(expr: &BoundExpression) -> Option<Self> {
241 #[derive(Default)]
242 struct Visitor {
243 exprs: Vec<DynamicComparisonExpr>,
244 sources: Vec<Arc<dyn DynamicExpressionSource>>,
245 }
246
247 impl NodeVisitor<'_> for Visitor {
248 type NodeTy = BoundExpression;
249
250 fn visit_down(&mut self, node: &'_ Self::NodeTy) -> VortexResult<TraversalOrder> {
251 if let Some(dynamic) = node.as_opt::<DynamicComparison>() {
252 self.exprs.push(dynamic.clone());
253 }
254 if let Some(dynamic) = node.as_opt::<DynamicExpression>() {
255 self.sources.push(Arc::clone(dynamic.source()));
256 }
257 Ok(TraversalOrder::Continue)
258 }
259 }
260
261 let mut visitor = Visitor::default();
262 expr.accept(&mut visitor).vortex_expect("Infallible");
263
264 if visitor.exprs.is_empty() && visitor.sources.is_empty() {
265 return None;
266 }
267
268 let exprs = visitor.exprs.into_boxed_slice();
269 let sources = visitor.sources.into_boxed_slice();
270 let scalars = exprs
271 .iter()
272 .map(|expr| {
273 (expr.rhs.value)().map(|v| {
274 Scalar::try_new(expr.rhs.dtype.clone(), Some(v))
275 .vortex_expect("`DynamicExprUpdates` was invalid")
276 })
277 })
278 .collect();
279 let generations = sources.iter().map(|source| source.generation()).collect();
280
281 Some(Self {
282 exprs,
283 sources,
284 prev_versions: Mutex::new(ObservedVersions {
285 version: 0,
286 scalars,
287 generations,
288 }),
289 })
290 }
291
292 pub fn version(&self) -> u64 {
293 let mut guard = self.prev_versions.lock();
294
295 let mut updated = false;
296 for (i, expr) in self.exprs.iter().enumerate() {
297 let current = expr.scalar();
298 if current != guard.scalars[i] {
299 updated = true;
303 guard.scalars[i] = current;
304 }
305 }
306 for (i, source) in self.sources.iter().enumerate() {
307 let current = source.generation();
308 if current != guard.generations[i] {
309 updated = true;
310 guard.generations[i] = current;
311 }
312 }
313
314 if updated {
315 guard.version += 1;
316 }
317
318 guard.version
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use std::sync::LazyLock;
325 use std::sync::atomic::AtomicI32;
326 use std::sync::atomic::Ordering;
327
328 use vortex_array::IntoArray;
329 use vortex_array::VortexSessionExecute;
330 use vortex_array::arrays::BoolArray;
331 use vortex_array::assert_arrays_eq;
332 use vortex_array::dtype::DType;
333 use vortex_array::dtype::Nullability;
334 use vortex_array::dtype::PType;
335 use vortex_buffer::buffer;
336 use vortex_error::VortexResult;
337 use vortex_expr::ArrayExprExt;
338 use vortex_expr::root;
339 use vortex_session::VortexSession;
340
341 use super::*;
342 use crate::expr::dynamic;
343
344 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
345 let session = VortexSession::empty();
346
347 vortex_array::initialize(&session);
348
349 crate::initialize(&session);
350
351 session
352 });
353
354 #[test]
355 fn is_not_strict() {
356 let expr = dynamic(
357 CompareOperator::Lt,
358 || None,
359 DType::Primitive(PType::I32, Nullability::NonNullable),
360 true,
361 root(),
362 );
363
364 assert!(!expr.as_scalar().is_some_and(|f| f.signature().is_strict()));
365 }
366
367 #[test]
368 fn return_dtype_bool() -> VortexResult<()> {
369 let expr = dynamic(
370 CompareOperator::Lt,
371 || Some(5i32.into()),
372 DType::Primitive(PType::I32, Nullability::NonNullable),
373 true,
374 root(),
375 );
376 let input_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
377 assert_eq!(
378 expr.return_dtype(&input_dtype)?,
379 DType::Bool(Nullability::NonNullable)
380 );
381 Ok(())
382 }
383
384 #[test]
385 fn execute_with_value() -> VortexResult<()> {
386 let mut ctx = SESSION.create_execution_ctx();
387 let input = buffer![1i32, 5, 10].into_array();
388 let expr = dynamic(
389 CompareOperator::Lt,
390 || Some(5i32.into()),
391 DType::Primitive(PType::I32, Nullability::NonNullable),
392 true,
393 root(),
394 );
395 let result = input.apply(&expr)?;
396 assert_arrays_eq!(result, BoolArray::from_iter([true, false, false]), &mut ctx);
397 Ok(())
398 }
399
400 #[test]
401 fn execute_without_value_default_true() -> VortexResult<()> {
402 let mut ctx = SESSION.create_execution_ctx();
403 let input = buffer![1i32, 5, 10].into_array();
404 let expr = dynamic(
405 CompareOperator::Lt,
406 || None,
407 DType::Primitive(PType::I32, Nullability::NonNullable),
408 true,
409 root(),
410 );
411 let result = input.apply(&expr)?;
412 assert_arrays_eq!(result, BoolArray::from_iter([true, true, true]), &mut ctx);
413 Ok(())
414 }
415
416 #[test]
417 fn execute_without_value_default_false() -> VortexResult<()> {
418 let mut ctx = SESSION.create_execution_ctx();
419 let input = buffer![1i32, 5, 10].into_array();
420 let expr = dynamic(
421 CompareOperator::Lt,
422 || None,
423 DType::Primitive(PType::I32, Nullability::NonNullable),
424 false,
425 root(),
426 );
427 let result = input.apply(&expr)?;
428 assert_arrays_eq!(
429 result,
430 BoolArray::from_iter([false, false, false]),
431 &mut ctx
432 );
433 Ok(())
434 }
435
436 #[test]
437 fn execute_value_flips() -> VortexResult<()> {
438 let mut ctx = SESSION.create_execution_ctx();
439 let threshold = Arc::new(AtomicI32::new(5));
440 let threshold_clone = Arc::clone(&threshold);
441 let expr = dynamic(
442 CompareOperator::Lt,
443 move || Some(threshold_clone.load(Ordering::SeqCst).into()),
444 DType::Primitive(PType::I32, Nullability::NonNullable),
445 true,
446 root(),
447 );
448 let input = buffer![1i32, 5, 10].into_array();
449
450 let result = input.clone().apply(&expr)?;
451 assert_arrays_eq!(result, BoolArray::from_iter([true, false, false]), &mut ctx);
452
453 threshold.store(10, Ordering::SeqCst);
454 let result = input.apply(&expr)?;
455 assert_arrays_eq!(result, BoolArray::from_iter([true, true, false]), &mut ctx);
456
457 Ok(())
458 }
459}