Skip to main content

vortex_array/scalar_fn/builtin/compare/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Native comparison kernels.
5//!
6//! `execute_compare` dispatches on the logical [`DType`] of its operands and evaluates every
7//! comparison directly over Vortex canonical arrays: bit buffers for booleans, [`RowFn`] for
8//! primitives, lane kernels from `vortex-compute` for decimals, binary views for strings/bytes, and
9//! a row-wise comparator for nested types. There is no Arrow fallback.
10//!
11//! Floating-point values use the same total ordering as [`Scalar`]: negative NaNs sort below
12//! negative infinity, positive NaNs sort above positive infinity, and `-0.0 < +0.0`. Equality is
13//! bitwise, so signed zeros and distinct NaN payloads remain distinct.
14//!
15//! [`Compare`] binds a [`CompareOperator`] to two operands. It can execute through
16//! encoding-specific kernels before reaching the native dispatcher. [`CompareExecuteAdaptor`]
17//! connects these execution paths to [`CompareKernel`], which lets an encoding compare values
18//! without first converting them to canonical arrays.
19//!
20//! [`RowFn`]: crate::scalar_fn::unstable::row::RowFn
21
22use std::cmp::Ordering;
23use std::fmt::Formatter;
24
25use prost::Message;
26use vortex_error::VortexResult;
27use vortex_error::vortex_bail;
28use vortex_error::vortex_ensure;
29use vortex_error::vortex_err;
30use vortex_session::VortexSession;
31use vortex_session::registry::CachedId;
32
33use crate::ArrayRef;
34use crate::Canonical;
35use crate::ExecutionCtx;
36use crate::IntoArray;
37use crate::array::ArrayView;
38use crate::array::VTable;
39use crate::arrays::Constant;
40use crate::arrays::ConstantArray;
41use crate::arrays::ExtensionArray;
42use crate::arrays::ScalarFn;
43use crate::arrays::ScalarFnArray;
44use crate::arrays::extension::ExtensionArrayExt;
45use crate::arrays::scalar_fn::ExactScalarFn;
46use crate::arrays::scalar_fn::ScalarFnArrayExt;
47use crate::arrays::scalar_fn::ScalarFnArrayView;
48use crate::dtype::DType;
49use crate::dtype::Nullability;
50use crate::kernel::ExecuteParentKernel;
51use crate::proto::expr as pb;
52use crate::scalar::Scalar;
53use crate::scalar_fn::Arity;
54use crate::scalar_fn::ChildName;
55use crate::scalar_fn::ExecutionArgs;
56use crate::scalar_fn::ReduceNode;
57use crate::scalar_fn::ScalarFnExecutionResult;
58use crate::scalar_fn::ScalarFnId;
59use crate::scalar_fn::ScalarFnVTable;
60use crate::scalar_fn::ScalarFnVTableExt;
61use crate::scalar_fn::builtin::binary::binary_child_name;
62use crate::scalar_fn::builtin::binary::execute_strict_step;
63use crate::scalar_fn::builtin::binary::fmt_infix;
64use crate::scalar_fn::builtin::operators::CompareOperator;
65use crate::scalar_fn::display::ExprDisplay;
66use crate::validity::Validity;
67
68mod boolean;
69mod bytes;
70mod decimal;
71
72mod nested;
73pub use nested::RowComparator;
74pub use nested::build_comparator as build_row_comparator;
75
76mod primitive;
77
78/// A comparison of two operands with a [`CompareOperator`].
79///
80/// The result is null where an operand is null.
81#[derive(Clone)]
82pub struct Compare;
83
84impl Compare {
85    /// Creates a lazy comparison of `lhs` and `rhs`.
86    ///
87    /// The operands must have the same logical dtype, ignoring nullability, even when they are
88    /// empty or null. Extension dtypes must match, including their metadata; storage dtypes are
89    /// distinct.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the children have different lengths or incompatible dtypes.
94    pub fn try_new(
95        lhs: ArrayRef,
96        rhs: ArrayRef,
97        operator: CompareOperator,
98    ) -> VortexResult<ScalarFnArray> {
99        ScalarFnArray::try_new(Compare.bind(operator), [lhs, rhs])
100    }
101}
102
103impl ScalarFnVTable for Compare {
104    type Options = CompareOperator;
105
106    fn id(&self) -> ScalarFnId {
107        static ID: CachedId = CachedId::new("vortex.compare");
108        *ID
109    }
110
111    fn serialize(&self, operator: &CompareOperator) -> VortexResult<Option<Vec<u8>>> {
112        Ok(Some(
113            pb::CompareOpts {
114                op: pb::compare_opts::CompareOp::from(*operator).into(),
115            }
116            .encode_to_vec(),
117        ))
118    }
119
120    fn deserialize(
121        &self,
122        metadata: &[u8],
123        _session: &VortexSession,
124    ) -> VortexResult<CompareOperator> {
125        let opts = pb::CompareOpts::decode(metadata)?;
126
127        Ok(pb::compare_opts::CompareOp::try_from(opts.op)?.into())
128    }
129
130    fn arity(&self, _operator: &CompareOperator) -> Arity {
131        Arity::Exact(2)
132    }
133
134    fn child_name(&self, _operator: &CompareOperator, child_idx: usize) -> ChildName {
135        binary_child_name(child_idx)
136    }
137
138    fn fmt_sql(
139        &self,
140        operator: &CompareOperator,
141        expr: &dyn ExprDisplay,
142        f: &mut Formatter<'_>,
143    ) -> std::fmt::Result {
144        fmt_infix(operator, expr, f)
145    }
146
147    fn return_dtype(
148        &self,
149        _operator: &CompareOperator,
150        arg_dtypes: &[DType],
151    ) -> VortexResult<DType> {
152        let lhs = &arg_dtypes[0];
153        let rhs = &arg_dtypes[1];
154        validate_comparison_dtypes(lhs, rhs)?;
155
156        Ok(DType::Bool((lhs.is_nullable() || rhs.is_nullable()).into()))
157    }
158
159    fn execute(
160        &self,
161        operator: &CompareOperator,
162        args: &dyn ExecutionArgs,
163        ctx: &mut ExecutionCtx,
164    ) -> VortexResult<ArrayRef> {
165        let lhs = args.get(0)?;
166        let rhs = args.get(1)?;
167
168        execute_compare(&lhs, &rhs, *operator, ctx)
169    }
170
171    fn simplify<T: ReduceNode>(
172        &self,
173        _operator: &CompareOperator,
174        node: &T,
175    ) -> VortexResult<Option<T>> {
176        let is_constant_null = |node: &T| node.as_constant().is_some_and(|s| s.is_null());
177
178        // Binding already rejected ill-typed comparisons such as `int_col = null_utf8`, so a
179        // comparison against a null constant always evaluates to null.
180        if is_constant_null(&node.child(0)) || is_constant_null(&node.child(1)) {
181            return Ok(Some(
182                node.new_constant(Scalar::null(DType::Bool(Nullability::Nullable))),
183            ));
184        }
185
186        Ok(None)
187    }
188
189    fn execute_step(
190        &self,
191        operator: &CompareOperator,
192        args: &dyn ExecutionArgs,
193        ctx: &mut ExecutionCtx,
194    ) -> VortexResult<ScalarFnExecutionResult> {
195        execute_strict_step(self, operator, args, ctx)
196    }
197
198    fn is_strict(&self, _operator: &CompareOperator) -> bool {
199        true
200    }
201
202    fn is_infallible(&self, _operator: &CompareOperator) -> bool {
203        true
204    }
205}
206
207/// Trait for encoding-specific comparison kernels that operate in encoded space.
208///
209/// Implementations can compare an encoded array against another array (typically a constant)
210/// without first decompressing. The adaptor normalizes operand order so `array` is always
211/// the left-hand side, swapping the operator when necessary.
212pub trait CompareKernel: VTable {
213    /// Compares `lhs` with `rhs`, or returns `None` to use the default comparison path.
214    ///
215    /// Operand dtypes must match, ignoring nullability. [`CompareExecuteAdaptor`] checks this before
216    /// dispatch; direct callers must satisfy the same requirement.
217    fn compare(
218        lhs: ArrayView<'_, Self>,
219        rhs: &ArrayRef,
220        operator: CompareOperator,
221        ctx: &mut ExecutionCtx,
222    ) -> VortexResult<Option<ArrayRef>>;
223}
224
225/// Adaptor that bridges [`CompareKernel`] implementations to [`ExecuteParentKernel`].
226///
227/// When a `ScalarFnArray(Compare, cmp_op)` wraps a child that implements `CompareKernel`,
228/// this adaptor extracts the comparison operator and other operand, normalizes operand order
229/// (swapping the operator if the encoded array is on the RHS), and delegates to the kernel.
230#[derive(Default, Debug)]
231pub struct CompareExecuteAdaptor<V>(
232    /// The encoding whose comparison kernel handles the normalized operands.
233    pub V,
234);
235
236impl<V> ExecuteParentKernel<V> for CompareExecuteAdaptor<V>
237where
238    V: CompareKernel,
239{
240    type Parent = ExactScalarFn<Compare>;
241
242    fn execute_parent(
243        &self,
244        array: ArrayView<'_, V>,
245        parent: ScalarFnArrayView<'_, Compare>,
246        child_idx: usize,
247        ctx: &mut ExecutionCtx,
248    ) -> VortexResult<Option<ArrayRef>> {
249        let cmp_op = *parent.options;
250
251        // Get the ScalarFnArray to access children
252        let Some(scalar_fn_array) = parent.as_opt::<ScalarFn>() else {
253            return Ok(None);
254        };
255        // Normalize so `array` is always LHS, swapping the operator if needed
256        // TODO(joe): should be go this here or in the Rule/Kernel
257        let (cmp_op, other) = match child_idx {
258            0 => (cmp_op, scalar_fn_array.get_child(1)),
259            1 => (cmp_op.swap(), scalar_fn_array.get_child(0)),
260            _ => return Ok(None),
261        };
262
263        validate_comparison_dtypes(array.dtype(), other.dtype())?;
264
265        let len = array.len();
266        let nullable = array.dtype().is_nullable() || other.dtype().is_nullable();
267
268        // Empty array → empty bool result
269        if len == 0 {
270            return Ok(Some(
271                Canonical::empty(&DType::Bool(nullable.into())).into_array(),
272            ));
273        }
274
275        // Null constant on either side → all-null bool result
276        if other.as_constant().is_some_and(|s| s.is_null()) {
277            return Ok(Some(
278                ConstantArray::new(Scalar::null(DType::Bool(nullable.into())), len).into_array(),
279            ));
280        }
281
282        V::compare(array, other, cmp_op, ctx)
283    }
284}
285
286/// Execute a compare operation between two arrays.
287///
288/// This is the entry point for compare operations from the [`Compare`] function.
289/// Handles empty, constant-null, and constant-constant directly, otherwise dispatches to a
290/// native per-dtype kernel.
291pub(crate) fn execute_compare(
292    lhs: &ArrayRef,
293    rhs: &ArrayRef,
294    op: CompareOperator,
295    ctx: &mut ExecutionCtx,
296) -> VortexResult<ArrayRef> {
297    validate_comparison_dtypes(lhs.dtype(), rhs.dtype())?;
298
299    let nullable = lhs.dtype().is_nullable() || rhs.dtype().is_nullable();
300
301    if lhs.len() != rhs.len() {
302        vortex_bail!(
303            "compare operator requires equal lengths, got {} and {}",
304            lhs.len(),
305            rhs.len()
306        );
307    }
308
309    if lhs.is_empty() {
310        return Ok(Canonical::empty(&DType::Bool(nullable.into())).into_array());
311    }
312
313    let left_constant_null = lhs.as_constant().map(|l| l.is_null()).unwrap_or(false);
314    let right_constant_null = rhs.as_constant().map(|r| r.is_null()).unwrap_or(false);
315    if left_constant_null || right_constant_null {
316        return Ok(
317            ConstantArray::new(Scalar::null(DType::Bool(nullable.into())), lhs.len()).into_array(),
318        );
319    }
320
321    // Constant-constant fast path
322    if let (Some(lhs_const), Some(rhs_const)) = (lhs.as_opt::<Constant>(), rhs.as_opt::<Constant>())
323    {
324        let result = scalar_cmp(lhs_const.scalar(), rhs_const.scalar(), op)?;
325        return Ok(ConstantArray::new(result, lhs.len()).into_array());
326    }
327
328    compare_arrays(lhs, rhs, op, ctx)
329}
330
331/// Dispatches operands with matching logical dtypes to their native comparison kernel.
332///
333/// Extension operands are unwrapped before dispatch to the storage kernel.
334fn compare_arrays(
335    lhs: &ArrayRef,
336    rhs: &ArrayRef,
337    op: CompareOperator,
338    ctx: &mut ExecutionCtx,
339) -> VortexResult<ArrayRef> {
340    let nullability = Nullability::from(lhs.dtype().is_nullable() || rhs.dtype().is_nullable());
341
342    if lhs.dtype().is_extension() {
343        let lhs = extension_storage(lhs, ctx)?;
344        let rhs = extension_storage(rhs, ctx)?;
345
346        return compare_arrays(&lhs, &rhs, op, ctx);
347    }
348
349    validate_comparison_dtypes(lhs.dtype(), rhs.dtype())?;
350
351    match lhs.dtype() {
352        // Every value of the null dtype is null, so every comparison result is null.
353        DType::Null => Ok(ConstantArray::new(
354            Scalar::null(DType::Bool(Nullability::Nullable)),
355            lhs.len(),
356        )
357        .into_array()),
358        DType::Bool(_) => boolean::compare_bool(lhs, rhs, op, nullability, ctx),
359        DType::Primitive(..) => primitive::compare_primitive(lhs, rhs, op, ctx),
360        DType::Decimal(..) => decimal::compare_decimal(lhs, rhs, op, nullability, ctx),
361        DType::Utf8(_) | DType::Binary(_) => bytes::compare_bytes(lhs, rhs, op, nullability, ctx),
362        DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) | DType::Map(..) => {
363            nested::compare_nested(lhs, rhs, op, nullability, ctx)
364        }
365        DType::Union(..) | DType::Variant(_) | DType::Extension(_) => {
366            vortex_bail!("compare is not supported for dtype {}", lhs.dtype())
367        }
368    }
369}
370
371/// Returns the storage of an extension array or constant.
372///
373/// Extension constants retain their constant encoding. Other extension arrays execute to their
374/// canonical representation so that the caller can access their storage.
375fn extension_storage(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
376    if let Some(constant) = array.as_opt::<Constant>() {
377        return Ok(ConstantArray::new(
378            constant.scalar().as_extension().to_storage_scalar(),
379            constant.len(),
380        )
381        .into_array());
382    }
383
384    let ext = array.clone().execute::<ExtensionArray>(ctx)?;
385
386    Ok(ext.storage_array().clone())
387}
388
389/// Compares scalars with matching dtypes, ignoring nullability.
390///
391/// Returns null if either operand is null, and an error if the operand dtypes differ.
392pub fn scalar_cmp(lhs: &Scalar, rhs: &Scalar, operator: CompareOperator) -> VortexResult<Scalar> {
393    validate_comparison_dtypes(lhs.dtype(), rhs.dtype())?;
394
395    if lhs.is_null() | rhs.is_null() {
396        return Ok(Scalar::null(DType::Bool(Nullability::Nullable)));
397    }
398
399    let nullability = lhs.dtype().nullability() | rhs.dtype().nullability();
400
401    // Some values, such as variants, have no scalar ordering even when their dtypes match.
402    let ordering = lhs.partial_cmp(rhs).ok_or_else(|| {
403        vortex_err!(
404            "Scalar comparison requires comparable values, got {} and {}",
405            lhs.dtype(),
406            rhs.dtype()
407        )
408    })?;
409
410    let result = match operator {
411        CompareOperator::Eq => ordering.is_eq(),
412        CompareOperator::NotEq => ordering.is_ne(),
413        CompareOperator::Gt => ordering.is_gt(),
414        CompareOperator::Gte => ordering.is_ge(),
415        CompareOperator::Lt => ordering.is_lt(),
416        CompareOperator::Lte => ordering.is_le(),
417    };
418
419    Ok(Scalar::bool(result, nullability))
420}
421
422/// Checks the shared dtype requirement before comparison fast paths or encoding kernels run.
423pub(super) fn validate_comparison_dtypes(lhs: &DType, rhs: &DType) -> VortexResult<()> {
424    vortex_ensure!(
425        lhs.eq_ignore_nullability(rhs),
426        "Comparison requires equal dtypes ignoring nullability, got {lhs} and {rhs}"
427    );
428
429    Ok(())
430}
431
432/// Returns the predicate `Ordering -> bool` for a comparison operator.
433#[inline]
434pub(super) fn ordering_predicate(op: CompareOperator) -> fn(Ordering) -> bool {
435    match op {
436        CompareOperator::Eq => Ordering::is_eq,
437        CompareOperator::NotEq => Ordering::is_ne,
438        CompareOperator::Gt => Ordering::is_gt,
439        CompareOperator::Gte => Ordering::is_ge,
440        CompareOperator::Lt => Ordering::is_lt,
441        CompareOperator::Lte => Ordering::is_le,
442    }
443}
444
445/// Combine operand validities into the validity of a comparison result with the given result
446/// nullability.
447pub(super) fn compare_validity(
448    lhs: Validity,
449    rhs: Validity,
450    nullability: Nullability,
451) -> VortexResult<Validity> {
452    Ok(lhs.and(rhs)?.union_nullability(nullability))
453}
454
455#[cfg(test)]
456mod tests;