• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16473770414

23 Jul 2025 02:38PM UTC coverage: 80.988% (-0.07%) from 81.055%
16473770414

push

github

web-flow
chore[duckdb]: scan log info -> trace (#3989)

Signed-off-by: Joe Isaacs <joe.isaacs@live.co.uk>

1 of 1 new or added line in 1 file covered. (100.0%)

35 existing lines in 7 files now uncovered.

42052 of 51924 relevant lines covered (80.99%)

173623.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.85
/vortex-array/src/compute/compare.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use core::fmt;
5
use std::any::Any;
6
use std::fmt::{Display, Formatter};
7
use std::sync::LazyLock;
8

9
use arcref::ArcRef;
10
use arrow_buffer::BooleanBuffer;
11
use arrow_ord::cmp;
12
use vortex_dtype::{DType, NativePType, Nullability};
13
use vortex_error::{VortexError, VortexExpect, VortexResult, vortex_bail, vortex_err};
14
use vortex_scalar::Scalar;
15

16
use crate::arrays::ConstantArray;
17
use crate::arrow::{Datum, from_arrow_array_with_len};
18
use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
19
use crate::vtable::VTable;
20
use crate::{Array, ArrayRef, Canonical, IntoArray};
21

22
/// Compares two arrays and returns a new boolean array with the result of the comparison.
23
/// Or, returns None if comparison is not supported for these arrays.
24
pub fn compare(left: &dyn Array, right: &dyn Array, operator: Operator) -> VortexResult<ArrayRef> {
15,762✔
25
    COMPARE_FN
15,762✔
26
        .invoke(&InvocationArgs {
15,762✔
27
            inputs: &[left.into(), right.into()],
15,762✔
28
            options: &operator,
15,762✔
29
        })?
15,762✔
30
        .unwrap_array()
15,762✔
31
}
15,762✔
32

33
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Hash)]
34
pub enum Operator {
35
    Eq,
36
    NotEq,
37
    Gt,
38
    Gte,
39
    Lt,
40
    Lte,
41
}
42

43
impl Display for Operator {
UNCOV
44
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
×
UNCOV
45
        let display = match &self {
×
46
            Operator::Eq => "=",
×
47
            Operator::NotEq => "!=",
×
48
            Operator::Gt => ">",
×
49
            Operator::Gte => ">=",
×
UNCOV
50
            Operator::Lt => "<",
×
UNCOV
51
            Operator::Lte => "<=",
×
52
        };
UNCOV
53
        Display::fmt(display, f)
×
UNCOV
54
    }
×
55
}
56

57
impl Operator {
58
    pub fn inverse(self) -> Self {
×
59
        match self {
×
60
            Operator::Eq => Operator::NotEq,
×
61
            Operator::NotEq => Operator::Eq,
×
62
            Operator::Gt => Operator::Lte,
×
63
            Operator::Gte => Operator::Lt,
×
64
            Operator::Lt => Operator::Gte,
×
65
            Operator::Lte => Operator::Gt,
×
66
        }
67
    }
×
68

69
    /// Change the sides of the operator, where changing lhs and rhs won't change the result of the operation
70
    pub fn swap(self) -> Self {
10,421✔
71
        match self {
10,421✔
72
            Operator::Eq => Operator::Eq,
4,499✔
73
            Operator::NotEq => Operator::NotEq,
967✔
74
            Operator::Gt => Operator::Lt,
1,386✔
75
            Operator::Gte => Operator::Lte,
1,209✔
76
            Operator::Lt => Operator::Gt,
1,020✔
77
            Operator::Lte => Operator::Gte,
1,340✔
78
        }
79
    }
10,421✔
80
}
81

82
pub struct CompareKernelRef(ArcRef<dyn Kernel>);
83
inventory::collect!(CompareKernelRef);
84

85
pub trait CompareKernel: VTable {
86
    fn compare(
87
        &self,
88
        lhs: &Self::Array,
89
        rhs: &dyn Array,
90
        operator: Operator,
91
    ) -> VortexResult<Option<ArrayRef>>;
92
}
93

94
#[derive(Debug)]
95
pub struct CompareKernelAdapter<V: VTable>(pub V);
96

97
impl<V: VTable + CompareKernel> CompareKernelAdapter<V> {
98
    pub const fn lift(&'static self) -> CompareKernelRef {
×
99
        CompareKernelRef(ArcRef::new_ref(self))
×
100
    }
×
101
}
102

103
impl<V: VTable + CompareKernel> Kernel for CompareKernelAdapter<V> {
104
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
157,132✔
105
        let inputs = CompareArgs::try_from(args)?;
157,132✔
106
        let Some(array) = inputs.lhs.as_opt::<V>() else {
157,132✔
107
            return Ok(None);
142,913✔
108
        };
109
        Ok(V::compare(&self.0, array, inputs.rhs, inputs.operator)?.map(|array| array.into()))
14,219✔
110
    }
157,132✔
111
}
112

113
pub static COMPARE_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
2,763✔
114
    let compute = ComputeFn::new("compare".into(), ArcRef::new_ref(&Compare));
2,763✔
115
    for kernel in inventory::iter::<CompareKernelRef> {
22,376✔
116
        compute.register_kernel(kernel.0.clone());
19,613✔
117
    }
19,613✔
118
    compute
2,763✔
119
});
2,763✔
120

121
struct Compare;
122

123
impl ComputeFnVTable for Compare {
124
    fn invoke(
15,762✔
125
        &self,
15,762✔
126
        args: &InvocationArgs,
15,762✔
127
        kernels: &[ArcRef<dyn Kernel>],
15,762✔
128
    ) -> VortexResult<Output> {
15,762✔
129
        let CompareArgs { lhs, rhs, operator } = CompareArgs::try_from(args)?;
15,762✔
130

131
        let return_dtype = self.return_dtype(args)?;
15,762✔
132

133
        if lhs.is_empty() {
15,762✔
134
            return Ok(Canonical::empty(&return_dtype).into_array().into());
1✔
135
        }
15,761✔
136

137
        let left_constant_null = lhs.as_constant().map(|l| l.is_null()).unwrap_or(false);
15,761✔
138
        let right_constant_null = rhs.as_constant().map(|r| r.is_null()).unwrap_or(false);
15,761✔
139
        if left_constant_null || right_constant_null {
15,761✔
140
            return Ok(ConstantArray::new(Scalar::null(return_dtype), lhs.len())
112✔
141
                .into_array()
112✔
142
                .into());
112✔
143
        }
15,649✔
144

145
        let right_is_constant = rhs.is_constant();
15,649✔
146

147
        // Always try to put constants on the right-hand side so encodings can optimise themselves.
148
        if lhs.is_constant() && !right_is_constant {
15,649✔
149
            return Ok(compare(rhs, lhs, operator.swap())?.into());
1,320✔
150
        }
14,329✔
151

152
        // First try lhs op rhs, then invert and try again.
153
        for kernel in kernels {
111,373✔
154
            if let Some(output) = kernel.invoke(args)? {
102,272✔
155
                return Ok(output);
5,228✔
156
            }
97,044✔
157
        }
158
        if let Some(output) = lhs.invoke(&COMPARE_FN, args)? {
9,101✔
159
            return Ok(output);
×
160
        }
9,101✔
161

162
        // Try inverting the operator and swapping the arguments
163
        let inverted_args = InvocationArgs {
9,101✔
164
            inputs: &[rhs.into(), lhs.into()],
9,101✔
165
            options: &operator.swap(),
9,101✔
166
        };
9,101✔
167
        for kernel in kernels {
75,525✔
168
            if let Some(output) = kernel.invoke(&inverted_args)? {
69,423✔
169
                return Ok(output);
2,999✔
170
            }
66,424✔
171
        }
172
        if let Some(output) = rhs.invoke(&COMPARE_FN, &inverted_args)? {
6,102✔
173
            return Ok(output);
×
174
        }
6,102✔
175

176
        // Only log missing compare implementation if there's possibly better one than arrow,
177
        // i.e. lhs isn't arrow or rhs isn't arrow or constant
178
        if !(lhs.is_arrow() && (rhs.is_arrow() || right_is_constant)) {
6,102✔
179
            log::debug!(
3,701✔
180
                "No compare implementation found for LHS {}, RHS {}, and operator {} (or inverse)",
×
181
                lhs.encoding_id(),
×
182
                rhs.encoding_id(),
×
183
                operator,
184
            );
185
        }
2,401✔
186

187
        // Fallback to arrow on canonical types
188
        Ok(arrow_compare(lhs, rhs, operator)?.into())
6,102✔
189
    }
15,762✔
190

191
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
31,524✔
192
        let CompareArgs { lhs, rhs, .. } = CompareArgs::try_from(args)?;
31,524✔
193

194
        if !lhs.dtype().eq_ignore_nullability(rhs.dtype()) {
31,524✔
195
            vortex_bail!(
×
196
                "Cannot compare different DTypes {} and {}",
×
197
                lhs.dtype(),
×
198
                rhs.dtype()
×
199
            );
200
        }
31,524✔
201

202
        // TODO(ngates): no reason why not
203
        if lhs.dtype().is_struct() {
31,524✔
204
            vortex_bail!(
×
205
                "Compare does not support arrays with Struct DType, got: {} and {}",
×
206
                lhs.dtype(),
×
207
                rhs.dtype()
×
208
            )
209
        }
31,524✔
210

211
        Ok(DType::Bool(
31,524✔
212
            lhs.dtype().nullability() | rhs.dtype().nullability(),
31,524✔
213
        ))
31,524✔
214
    }
31,524✔
215

216
    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
15,762✔
217
        let CompareArgs { lhs, rhs, .. } = CompareArgs::try_from(args)?;
15,762✔
218
        if lhs.len() != rhs.len() {
15,762✔
219
            vortex_bail!(
×
220
                "Compare operations only support arrays of the same length, got {} and {}",
×
221
                lhs.len(),
×
222
                rhs.len()
×
223
            );
224
        }
15,762✔
225
        Ok(lhs.len())
15,762✔
226
    }
15,762✔
227

228
    fn is_elementwise(&self) -> bool {
15,762✔
229
        true
15,762✔
230
    }
15,762✔
231
}
232

233
struct CompareArgs<'a> {
234
    lhs: &'a dyn Array,
235
    rhs: &'a dyn Array,
236
    operator: Operator,
237
}
238

239
impl Options for Operator {
240
    fn as_any(&self) -> &dyn Any {
234,743✔
241
        self
234,743✔
242
    }
234,743✔
243
}
244

245
impl<'a> TryFrom<&InvocationArgs<'a>> for CompareArgs<'a> {
246
    type Error = VortexError;
247

248
    fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
234,743✔
249
        if value.inputs.len() != 2 {
234,743✔
250
            vortex_bail!("Expected 2 inputs, found {}", value.inputs.len());
×
251
        }
234,743✔
252
        let lhs = value.inputs[0]
234,743✔
253
            .array()
234,743✔
254
            .ok_or_else(|| vortex_err!("Expected first input to be an array"))?;
234,743✔
255
        let rhs = value.inputs[1]
234,743✔
256
            .array()
234,743✔
257
            .ok_or_else(|| vortex_err!("Expected second input to be an array"))?;
234,743✔
258
        let operator = *value
234,743✔
259
            .options
234,743✔
260
            .as_any()
234,743✔
261
            .downcast_ref::<Operator>()
234,743✔
262
            .vortex_expect("Expected options to be an operator");
234,743✔
263

264
        Ok(CompareArgs { lhs, rhs, operator })
234,743✔
265
    }
234,743✔
266
}
267

268
/// Helper function to compare empty values with arrays that have external value length information
269
/// like `VarBin`.
270
pub fn compare_lengths_to_empty<P, I>(lengths: I, op: Operator) -> BooleanBuffer
44✔
271
where
44✔
272
    P: NativePType,
44✔
273
    I: Iterator<Item = P>,
44✔
274
{
275
    // All comparison can be expressed in terms of equality. "" is the absolute min of possible value.
276
    let cmp_fn = match op {
44✔
277
        Operator::Eq | Operator::Lte => |v| v == P::zero(),
120✔
278
        Operator::NotEq | Operator::Gt => |v| v != P::zero(),
8✔
279
        Operator::Gte => |_| true,
280
        Operator::Lt => |_| false,
281
    };
282

283
    lengths.map(cmp_fn).collect::<BooleanBuffer>()
44✔
284
}
44✔
285

286
/// Implementation of `CompareFn` using the Arrow crate.
287
fn arrow_compare(
6,103✔
288
    left: &dyn Array,
6,103✔
289
    right: &dyn Array,
6,103✔
290
    operator: Operator,
6,103✔
291
) -> VortexResult<ArrayRef> {
6,103✔
292
    let nullable = left.dtype().is_nullable() || right.dtype().is_nullable();
6,103✔
293
    let lhs = Datum::try_new(left)?;
6,103✔
294
    let rhs = Datum::try_new(right)?;
6,103✔
295

296
    let array = match operator {
6,103✔
297
        Operator::Eq => cmp::eq(&lhs, &rhs)?,
2,610✔
298
        Operator::NotEq => cmp::neq(&lhs, &rhs)?,
227✔
299
        Operator::Gt => cmp::gt(&lhs, &rhs)?,
793✔
300
        Operator::Gte => cmp::gt_eq(&lhs, &rhs)?,
981✔
301
        Operator::Lt => cmp::lt(&lhs, &rhs)?,
674✔
302
        Operator::Lte => cmp::lt_eq(&lhs, &rhs)?,
818✔
303
    };
304
    from_arrow_array_with_len(&array, left.len(), nullable)
6,103✔
305
}
6,103✔
306

307
pub fn scalar_cmp(lhs: &Scalar, rhs: &Scalar, operator: Operator) -> Scalar {
3,768✔
308
    if lhs.is_null() | rhs.is_null() {
3,768✔
309
        Scalar::null(DType::Bool(Nullability::Nullable))
×
310
    } else {
311
        let b = match operator {
3,768✔
312
            Operator::Eq => lhs == rhs,
713✔
313
            Operator::NotEq => lhs != rhs,
740✔
314
            Operator::Gt => lhs > rhs,
855✔
315
            Operator::Gte => lhs >= rhs,
376✔
316
            Operator::Lt => lhs < rhs,
856✔
317
            Operator::Lte => lhs <= rhs,
228✔
318
        };
319

320
        Scalar::bool(b, lhs.dtype().nullability() | rhs.dtype().nullability())
3,768✔
321
    }
322
}
3,768✔
323

324
#[cfg(test)]
325
mod tests {
326
    use arrow_buffer::BooleanBuffer;
327
    use rstest::rstest;
328

329
    use super::*;
330
    use crate::ToCanonical;
331
    use crate::arrays::{BoolArray, ConstantArray, VarBinArray, VarBinViewArray};
332
    use crate::test_harness::to_int_indices;
333
    use crate::validity::Validity;
334

335
    #[test]
336
    fn test_bool_basic_comparisons() {
1✔
337
        let arr = BoolArray::new(
1✔
338
            BooleanBuffer::from_iter([true, true, false, true, false]),
1✔
339
            Validity::from_iter([false, true, true, true, true]),
1✔
340
        );
341

342
        let matches = compare(arr.as_ref(), arr.as_ref(), Operator::Eq)
1✔
343
            .unwrap()
1✔
344
            .to_bool()
1✔
345
            .unwrap();
1✔
346

347
        assert_eq!(to_int_indices(matches).unwrap(), [1u64, 2, 3, 4]);
1✔
348

349
        let matches = compare(arr.as_ref(), arr.as_ref(), Operator::NotEq)
1✔
350
            .unwrap()
1✔
351
            .to_bool()
1✔
352
            .unwrap();
1✔
353
        let empty: [u64; 0] = [];
1✔
354
        assert_eq!(to_int_indices(matches).unwrap(), empty);
1✔
355

356
        let other = BoolArray::new(
1✔
357
            BooleanBuffer::from_iter([false, false, false, true, true]),
1✔
358
            Validity::from_iter([false, true, true, true, true]),
1✔
359
        );
360

361
        let matches = compare(arr.as_ref(), other.as_ref(), Operator::Lte)
1✔
362
            .unwrap()
1✔
363
            .to_bool()
1✔
364
            .unwrap();
1✔
365
        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
1✔
366

367
        let matches = compare(arr.as_ref(), other.as_ref(), Operator::Lt)
1✔
368
            .unwrap()
1✔
369
            .to_bool()
1✔
370
            .unwrap();
1✔
371
        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
1✔
372

373
        let matches = compare(other.as_ref(), arr.as_ref(), Operator::Gte)
1✔
374
            .unwrap()
1✔
375
            .to_bool()
1✔
376
            .unwrap();
1✔
377
        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
1✔
378

379
        let matches = compare(other.as_ref(), arr.as_ref(), Operator::Gt)
1✔
380
            .unwrap()
1✔
381
            .to_bool()
1✔
382
            .unwrap();
1✔
383
        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
1✔
384
    }
1✔
385

386
    #[test]
387
    fn constant_compare() {
1✔
388
        let left = ConstantArray::new(Scalar::from(2u32), 10);
1✔
389
        let right = ConstantArray::new(Scalar::from(10u32), 10);
1✔
390

391
        let compare = compare(left.as_ref(), right.as_ref(), Operator::Gt).unwrap();
1✔
392
        let res = compare.as_constant().unwrap();
1✔
393
        assert_eq!(res.as_bool().value(), Some(false));
1✔
394
        assert_eq!(compare.len(), 10);
1✔
395

396
        let compare = arrow_compare(&left.into_array(), &right.into_array(), Operator::Gt).unwrap();
1✔
397
        let res = compare.as_constant().unwrap();
1✔
398
        assert_eq!(res.as_bool().value(), Some(false));
1✔
399
        assert_eq!(compare.len(), 10);
1✔
400
    }
1✔
401

402
    #[rstest]
403
    #[case(Operator::Eq, vec![false, false, false, true])]
404
    #[case(Operator::NotEq, vec![true, true, true, false])]
405
    #[case(Operator::Gt, vec![true, true, true, false])]
406
    #[case(Operator::Gte, vec![true, true, true, true])]
407
    #[case(Operator::Lt, vec![false, false, false, false])]
408
    #[case(Operator::Lte, vec![false, false, false, true])]
409
    fn test_cmp_to_empty(#[case] op: Operator, #[case] expected: Vec<bool>) {
410
        let lengths: Vec<i32> = vec![1, 5, 7, 0];
411

412
        let output = compare_lengths_to_empty(lengths.iter().copied(), op);
413
        assert_eq!(Vec::from_iter(output.iter()), expected);
414
    }
415

416
    #[rstest]
417
    #[case(VarBinArray::from(vec!["a", "b"]).into_array(), VarBinViewArray::from_iter_str(["a", "b"]).into_array())]
418
    #[case(VarBinViewArray::from_iter_str(["a", "b"]).into_array(), VarBinArray::from(vec!["a", "b"]).into_array())]
419
    #[case(VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array())]
420
    #[case(VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array())]
421
    fn arrow_compare_different_encodings(#[case] left: ArrayRef, #[case] right: ArrayRef) {
422
        let res = compare(&left, &right, Operator::Eq).unwrap();
423
        assert_eq!(
424
            res.to_bool().unwrap().boolean_buffer().count_set_bits(),
425
            left.len()
426
        );
427
    }
428
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc