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

vortex-data / vortex / 16935267080

13 Aug 2025 11:00AM UTC coverage: 24.312% (-63.3%) from 87.658%
16935267080

Pull #4226

github

web-flow
Merge 81b48c7fb into baa6ea202
Pull Request #4226: Support converting TimestampTZ to and from duckdb

0 of 2 new or added lines in 1 file covered. (0.0%)

20666 existing lines in 469 files now uncovered.

8726 of 35892 relevant lines covered (24.31%)

147.74 hits per line

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

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

4
use std::any::Any;
5
use std::sync::LazyLock;
6

7
use arcref::ArcRef;
8
use vortex_dtype::DType;
9
use vortex_error::{VortexError, VortexResult, vortex_bail, vortex_err};
10
use vortex_scalar::{NumericOperator, Scalar};
11

12
use crate::arrays::ConstantArray;
13
use crate::arrow::{Datum, from_arrow_array_with_len};
14
use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
15
use crate::vtable::VTable;
16
use crate::{Array, ArrayRef, IntoArray};
17

UNCOV
18
static NUMERIC_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
×
UNCOV
19
    let compute = ComputeFn::new("numeric".into(), ArcRef::new_ref(&Numeric));
×
UNCOV
20
    for kernel in inventory::iter::<NumericKernelRef> {
×
UNCOV
21
        compute.register_kernel(kernel.0.clone());
×
UNCOV
22
    }
×
UNCOV
23
    compute
×
UNCOV
24
});
×
25

26
/// Point-wise add two numeric arrays.
27
///
28
/// Errs at runtime if the sum would overflow or underflow.
29
///
30
/// The result is null at any index that either input is null.
31
pub fn add(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
×
32
    numeric(lhs, rhs, NumericOperator::Add)
×
33
}
×
34

35
/// Point-wise add a scalar value to this array on the right-hand-side.
UNCOV
36
pub fn add_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
×
UNCOV
37
    numeric(
×
UNCOV
38
        lhs,
×
UNCOV
39
        &ConstantArray::new(rhs, lhs.len()).into_array(),
×
UNCOV
40
        NumericOperator::Add,
×
41
    )
UNCOV
42
}
×
43

44
/// Point-wise subtract two numeric arrays.
45
pub fn sub(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
×
46
    numeric(lhs, rhs, NumericOperator::Sub)
×
47
}
×
48

49
/// Point-wise subtract a scalar value from this array on the right-hand-side.
UNCOV
50
pub fn sub_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
×
UNCOV
51
    numeric(
×
UNCOV
52
        lhs,
×
UNCOV
53
        &ConstantArray::new(rhs, lhs.len()).into_array(),
×
UNCOV
54
        NumericOperator::Sub,
×
55
    )
UNCOV
56
}
×
57

58
/// Point-wise multiply two numeric arrays.
59
pub fn mul(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
×
60
    numeric(lhs, rhs, NumericOperator::Mul)
×
61
}
×
62

63
/// Point-wise multiply a scalar value into this array on the right-hand-side.
64
pub fn mul_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
×
65
    numeric(
×
66
        lhs,
×
67
        &ConstantArray::new(rhs, lhs.len()).into_array(),
×
68
        NumericOperator::Mul,
×
69
    )
70
}
×
71

72
/// Point-wise divide two numeric arrays.
73
pub fn div(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
×
74
    numeric(lhs, rhs, NumericOperator::Div)
×
75
}
×
76

77
/// Point-wise divide a scalar value into this array on the right-hand-side.
78
pub fn div_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
×
79
    numeric(
×
80
        lhs,
×
81
        &ConstantArray::new(rhs, lhs.len()).into_array(),
×
82
        NumericOperator::Mul,
×
83
    )
84
}
×
85

86
/// Point-wise numeric operation between two arrays of the same type and length.
UNCOV
87
pub fn numeric(lhs: &dyn Array, rhs: &dyn Array, op: NumericOperator) -> VortexResult<ArrayRef> {
×
UNCOV
88
    NUMERIC_FN
×
UNCOV
89
        .invoke(&InvocationArgs {
×
UNCOV
90
            inputs: &[lhs.into(), rhs.into()],
×
UNCOV
91
            options: &op,
×
UNCOV
92
        })?
×
UNCOV
93
        .unwrap_array()
×
UNCOV
94
}
×
95

96
pub struct NumericKernelRef(ArcRef<dyn Kernel>);
97
inventory::collect!(NumericKernelRef);
98

99
pub trait NumericKernel: VTable {
100
    fn numeric(
101
        &self,
102
        array: &Self::Array,
103
        other: &dyn Array,
104
        op: NumericOperator,
105
    ) -> VortexResult<Option<ArrayRef>>;
106
}
107

108
#[derive(Debug)]
109
pub struct NumericKernelAdapter<V: VTable>(pub V);
110

111
impl<V: VTable + NumericKernel> NumericKernelAdapter<V> {
112
    pub const fn lift(&'static self) -> NumericKernelRef {
×
113
        NumericKernelRef(ArcRef::new_ref(self))
×
114
    }
×
115
}
116

117
impl<V: VTable + NumericKernel> Kernel for NumericKernelAdapter<V> {
UNCOV
118
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
×
UNCOV
119
        let inputs = NumericArgs::try_from(args)?;
×
UNCOV
120
        let Some(lhs) = inputs.lhs.as_opt::<V>() else {
×
UNCOV
121
            return Ok(None);
×
122
        };
UNCOV
123
        Ok(V::numeric(&self.0, lhs, inputs.rhs, inputs.operator)?.map(|array| array.into()))
×
UNCOV
124
    }
×
125
}
126

127
struct Numeric;
128

129
impl ComputeFnVTable for Numeric {
UNCOV
130
    fn invoke(
×
UNCOV
131
        &self,
×
UNCOV
132
        args: &InvocationArgs,
×
UNCOV
133
        kernels: &[ArcRef<dyn Kernel>],
×
UNCOV
134
    ) -> VortexResult<Output> {
×
UNCOV
135
        let NumericArgs { lhs, rhs, operator } = NumericArgs::try_from(args)?;
×
136

137
        // Check if LHS supports the operation directly.
UNCOV
138
        for kernel in kernels {
×
UNCOV
139
            if let Some(output) = kernel.invoke(args)? {
×
UNCOV
140
                return Ok(output);
×
UNCOV
141
            }
×
142
        }
UNCOV
143
        if let Some(output) = lhs.invoke(&NUMERIC_FN, args)? {
×
UNCOV
144
            return Ok(output);
×
UNCOV
145
        }
×
146

147
        // Check if RHS supports the operation directly.
UNCOV
148
        let inverted_args = InvocationArgs {
×
UNCOV
149
            inputs: &[rhs.into(), lhs.into()],
×
UNCOV
150
            options: &operator.swap(),
×
UNCOV
151
        };
×
UNCOV
152
        for kernel in kernels {
×
UNCOV
153
            if let Some(output) = kernel.invoke(&inverted_args)? {
×
UNCOV
154
                return Ok(output);
×
UNCOV
155
            }
×
156
        }
UNCOV
157
        if let Some(output) = rhs.invoke(&NUMERIC_FN, &inverted_args)? {
×
UNCOV
158
            return Ok(output);
×
UNCOV
159
        }
×
160

UNCOV
161
        log::debug!(
×
162
            "No numeric implementation found for LHS {}, RHS {}, and operator {:?}",
×
163
            lhs.encoding_id(),
×
164
            rhs.encoding_id(),
×
165
            operator,
166
        );
167

168
        // If neither side implements the trait, then we delegate to Arrow compute.
UNCOV
169
        Ok(arrow_numeric(lhs, rhs, operator)?.into())
×
UNCOV
170
    }
×
171

UNCOV
172
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
×
UNCOV
173
        let NumericArgs { lhs, rhs, .. } = NumericArgs::try_from(args)?;
×
174
        if !matches!(
×
UNCOV
175
            (lhs.dtype(), rhs.dtype()),
×
176
            (DType::Primitive(..), DType::Primitive(..)) | (DType::Decimal(..), DType::Decimal(..))
UNCOV
177
        ) || !lhs.dtype().eq_ignore_nullability(rhs.dtype())
×
178
        {
UNCOV
179
            vortex_bail!(
×
UNCOV
180
                "Numeric operations are only supported on two arrays sharing the same numeric type: {} {}",
×
UNCOV
181
                lhs.dtype(),
×
UNCOV
182
                rhs.dtype()
×
183
            )
UNCOV
184
        }
×
UNCOV
185
        Ok(lhs.dtype().union_nullability(rhs.dtype().nullability()))
×
UNCOV
186
    }
×
187

UNCOV
188
    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
×
UNCOV
189
        let NumericArgs { lhs, rhs, .. } = NumericArgs::try_from(args)?;
×
UNCOV
190
        if lhs.len() != rhs.len() {
×
191
            vortex_bail!(
×
192
                "Numeric operations aren't supported on arrays of different lengths {} {}",
×
193
                lhs.len(),
×
194
                rhs.len()
×
195
            )
UNCOV
196
        }
×
UNCOV
197
        Ok(lhs.len())
×
UNCOV
198
    }
×
199

UNCOV
200
    fn is_elementwise(&self) -> bool {
×
UNCOV
201
        true
×
UNCOV
202
    }
×
203
}
204

205
struct NumericArgs<'a> {
206
    lhs: &'a dyn Array,
207
    rhs: &'a dyn Array,
208
    operator: NumericOperator,
209
}
210

211
impl<'a> TryFrom<&InvocationArgs<'a>> for NumericArgs<'a> {
212
    type Error = VortexError;
213

UNCOV
214
    fn try_from(args: &InvocationArgs<'a>) -> VortexResult<Self> {
×
UNCOV
215
        if args.inputs.len() != 2 {
×
216
            vortex_bail!("Numeric operations require exactly 2 inputs");
×
UNCOV
217
        }
×
UNCOV
218
        let lhs = args.inputs[0]
×
UNCOV
219
            .array()
×
UNCOV
220
            .ok_or_else(|| vortex_err!("LHS is not an array"))?;
×
UNCOV
221
        let rhs = args.inputs[1]
×
UNCOV
222
            .array()
×
UNCOV
223
            .ok_or_else(|| vortex_err!("RHS is not an array"))?;
×
UNCOV
224
        let operator = *args
×
UNCOV
225
            .options
×
UNCOV
226
            .as_any()
×
UNCOV
227
            .downcast_ref::<NumericOperator>()
×
UNCOV
228
            .ok_or_else(|| vortex_err!("Operator is not a numeric operator"))?;
×
UNCOV
229
        Ok(Self { lhs, rhs, operator })
×
UNCOV
230
    }
×
231
}
232

233
impl Options for NumericOperator {
UNCOV
234
    fn as_any(&self) -> &dyn Any {
×
UNCOV
235
        self
×
UNCOV
236
    }
×
237
}
238

239
/// Implementation of `BinaryNumericFn` using the Arrow crate.
240
///
241
/// Note that other encodings should handle a constant RHS value, so we can assume here that
242
/// the RHS is not constant and expand to a full array.
UNCOV
243
fn arrow_numeric(
×
UNCOV
244
    lhs: &dyn Array,
×
UNCOV
245
    rhs: &dyn Array,
×
UNCOV
246
    operator: NumericOperator,
×
UNCOV
247
) -> VortexResult<ArrayRef> {
×
UNCOV
248
    let nullable = lhs.dtype().is_nullable() || rhs.dtype().is_nullable();
×
UNCOV
249
    let len = lhs.len();
×
250

UNCOV
251
    let left = Datum::try_new(lhs)?;
×
UNCOV
252
    let right = Datum::try_new(rhs)?;
×
253

UNCOV
254
    let array = match operator {
×
UNCOV
255
        NumericOperator::Add => arrow_arith::numeric::add(&left, &right)?,
×
UNCOV
256
        NumericOperator::Sub => arrow_arith::numeric::sub(&left, &right)?,
×
UNCOV
257
        NumericOperator::RSub => arrow_arith::numeric::sub(&right, &left)?,
×
UNCOV
258
        NumericOperator::Mul => arrow_arith::numeric::mul(&left, &right)?,
×
UNCOV
259
        NumericOperator::Div => arrow_arith::numeric::div(&left, &right)?,
×
UNCOV
260
        NumericOperator::RDiv => arrow_arith::numeric::div(&right, &left)?,
×
261
    };
262

UNCOV
263
    from_arrow_array_with_len(array.as_ref(), len, nullable)
×
UNCOV
264
}
×
265

266
#[cfg(test)]
267
mod test {
268
    use vortex_buffer::buffer;
269
    use vortex_scalar::Scalar;
270

271
    use crate::IntoArray;
272
    use crate::arrays::PrimitiveArray;
273
    use crate::canonical::ToCanonical;
274
    use crate::compute::sub_scalar;
275

276
    #[test]
277
    fn test_scalar_subtract_unsigned() {
278
        let values = buffer![1u16, 2, 3].into_array();
279
        let results = sub_scalar(&values, 1u16.into())
280
            .unwrap()
281
            .to_primitive()
282
            .unwrap()
283
            .as_slice::<u16>()
284
            .to_vec();
285
        assert_eq!(results, &[0u16, 1, 2]);
286
    }
287

288
    #[test]
289
    fn test_scalar_subtract_signed() {
290
        let values = buffer![1i64, 2, 3].into_array();
291
        let results = sub_scalar(&values, (-1i64).into())
292
            .unwrap()
293
            .to_primitive()
294
            .unwrap()
295
            .as_slice::<i64>()
296
            .to_vec();
297
        assert_eq!(results, &[2i64, 3, 4]);
298
    }
299

300
    #[test]
301
    fn test_scalar_subtract_nullable() {
302
        let values = PrimitiveArray::from_option_iter([Some(1u16), Some(2), None, Some(3)]);
303
        let result = sub_scalar(values.as_ref(), Some(1u16).into())
304
            .unwrap()
305
            .to_primitive()
306
            .unwrap();
307

308
        let actual = (0..result.len())
309
            .map(|index| result.scalar_at(index).unwrap())
310
            .collect::<Vec<_>>();
311
        assert_eq!(
312
            actual,
313
            vec![
314
                Scalar::from(Some(0u16)),
315
                Scalar::from(Some(1u16)),
316
                Scalar::from(None::<u16>),
317
                Scalar::from(Some(2u16))
318
            ]
319
        );
320
    }
321

322
    #[test]
323
    fn test_scalar_subtract_float() {
324
        let values = buffer![1.0f64, 2.0, 3.0].into_array();
325
        let to_subtract = -1f64;
326
        let results = sub_scalar(&values, to_subtract.into())
327
            .unwrap()
328
            .to_primitive()
329
            .unwrap()
330
            .as_slice::<f64>()
331
            .to_vec();
332
        assert_eq!(results, &[2.0f64, 3.0, 4.0]);
333
    }
334

335
    #[test]
336
    fn test_scalar_subtract_float_underflow_is_ok() {
337
        let values = buffer![f32::MIN, 2.0, 3.0].into_array();
338
        let _results = sub_scalar(&values, 1.0f32.into()).unwrap();
339
        let _results = sub_scalar(&values, f32::MAX.into()).unwrap();
340
    }
341

342
    #[test]
343
    fn test_scalar_subtract_type_mismatch_fails() {
344
        let values = buffer![1u64, 2, 3].into_array();
345
        // Subtracting incompatible dtypes should fail
346
        let _results =
347
            sub_scalar(&values, 1.5f64.into()).expect_err("Expected type mismatch error");
348
    }
349
}
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