vortex-array 0.82.0

Vortex in memory columnar data format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! # Binary Numeric Conformance Tests
//!
//! This module provides conformance testing for binary numeric operations on Vortex arrays.
//! It ensures that all numeric array encodings produce identical results when performing
//! arithmetic operations (add, subtract, multiply, divide).
//!
//! ## Test Strategy
//!
//! For each array encoding, we test:
//! 1. All binary numeric operators against a constant scalar value
//! 2. Both left-hand and right-hand side operations (e.g., array + 1 and 1 + array)
//! 3. That results match the canonical primitive array implementation
//!
//! ## Supported Operations
//!
//! - Addition (`+`)
//! - Subtraction (`-`)
//! - Multiplication (`*`)
//! - Division (`/`)

use std::fmt::Debug;

use itertools::Itertools;
use num_traits::Bounded;
use num_traits::CheckedAdd;
use num_traits::CheckedSub;
use num_traits::Float;
use num_traits::Num;
use num_traits::Signed;
use vortex_error::VortexExpect;
use vortex_error::vortex_err;
use vortex_error::vortex_panic;

use crate::ArrayRef;
use crate::Canonical;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::RecursiveCanonical;
use crate::arrays::ConstantArray;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::DecimalDType;
use crate::dtype::NativeDecimalType;
use crate::dtype::NativePType;
use crate::dtype::PType;
use crate::dtype::i256;
use crate::scalar::DecimalValue;
use crate::scalar::NumericOperator;
use crate::scalar::PrimitiveScalar;
use crate::scalar::Scalar;
use crate::scalar_fn::fns::binary::numeric_op_result_decimal_dtype;

fn to_vec_of_scalar(array: &ArrayRef, ctx: &mut ExecutionCtx) -> Vec<Scalar> {
    // Not fast, but obviously correct
    (0..array.len())
        .map(|index| {
            array
                .execute_scalar(index, ctx)
                .vortex_expect("scalar_at should succeed in conformance test")
        })
        .collect_vec()
}

/// Tests binary numeric operations for conformance across array encodings.
///
/// # Type Parameters
///
/// * `T` - The native numeric type (e.g., i32, f64) that the array contains
///
/// # Arguments
///
/// * `array` - The array to test, which should contain numeric values of type `T`
///
/// # Test Details
///
/// This function:
/// 1. Canonicalizes the input array to primitive form to get expected values
/// 2. Tests all binary numeric operators against a constant value of 1
/// 3. Verifies results match the expected primitive array computation
/// 4. Tests both array-operator-scalar and scalar-operator-array forms
/// 5. Gracefully skips operations that would cause overflow/underflow
///
/// # Panics
///
/// Panics if:
/// - The array cannot be converted to primitive form
/// - Results don't match expected values (for operations that don't overflow)
fn test_binary_numeric_conformance<T: NativePType + Num + Copy>(
    array: &ArrayRef,
    ctx: &mut ExecutionCtx,
) where
    Scalar: From<T>,
{
    // First test with the standard scalar value of 1
    test_standard_binary_numeric::<T>(array, ctx);

    // Then test edge cases
    test_binary_numeric_edge_cases(array, ctx);
}

fn test_standard_binary_numeric<T: NativePType + Num + Copy>(
    array: &ArrayRef,
    ctx: &mut ExecutionCtx,
) where
    Scalar: From<T>,
{
    let canonicalized_array = array
        .clone()
        .execute::<Canonical>(ctx)
        .vortex_expect("Must be able to canonicalise")
        .into_array();
    let original_values = to_vec_of_scalar(&canonicalized_array, ctx);

    let one = T::from(1)
        .ok_or_else(|| vortex_err!("could not convert 1 into array native type"))
        .vortex_expect("operation should succeed in conformance test");
    let scalar_one = Scalar::from(one)
        .cast(array.dtype())
        .vortex_expect("operation should succeed in conformance test");

    let operators: [NumericOperator; 4] = [
        NumericOperator::Add,
        NumericOperator::Sub,
        NumericOperator::Mul,
        NumericOperator::Div,
    ];

    for operator in operators {
        let op = operator;
        let rhs_const = ConstantArray::new(scalar_one.clone(), array.len()).into_array();

        // Test array operator scalar (e.g., array + 1)
        let result = array
            .binary(rhs_const.clone(), op.into())
            .vortex_expect("apply shouldn't fail")
            .execute::<RecursiveCanonical>(ctx)
            .map(|c| c.0.into_array());

        // Skip this operator if the entire operation fails
        // This can happen for some edge cases in specific encodings
        let Ok(result) = result else {
            continue;
        };

        let actual_values = to_vec_of_scalar(&result, ctx);

        // Check each element for overflow/underflow
        let expected_results: Vec<Option<Scalar>> = original_values
            .iter()
            .map(|x| {
                x.as_primitive()
                    .checked_binary_numeric(&scalar_one.as_primitive(), op)
                    .map(<Scalar as From<PrimitiveScalar<'_>>>::from)
            })
            .collect();

        // For elements that didn't overflow, check they match
        for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
            if let Some(expected_value) = expected {
                assert_eq!(
                    actual,
                    expected_value,
                    "Binary numeric operation failed for encoding {} at index {}: \
                     ({array:?})[{idx}] {operator:?} {scalar_one} \
                     expected {expected_value:?}, got {actual:?}",
                    array.encoding_id(),
                    idx,
                );
            }
        }

        // Test scalar operator array (e.g., 1 + array)
        let result = rhs_const.binary(array.clone(), op.into()).and_then(|a| {
            a.execute::<RecursiveCanonical>(ctx)
                .map(|c| c.0.into_array())
        });

        // Skip this operator if the entire operation fails
        let Ok(result) = result else {
            continue;
        };

        let actual_values = to_vec_of_scalar(&result, ctx);

        // Check each element for overflow/underflow
        let expected_results: Vec<Option<Scalar>> = original_values
            .iter()
            .map(|x| {
                scalar_one
                    .as_primitive()
                    .checked_binary_numeric(&x.as_primitive(), op)
                    .map(<Scalar as From<PrimitiveScalar<'_>>>::from)
            })
            .collect();

        // For elements that didn't overflow, check they match
        for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
            if let Some(expected_value) = expected {
                assert_eq!(
                    actual,
                    expected_value,
                    "Binary numeric operation failed for encoding {} at index {}: \
                     {scalar_one} {operator:?} ({array:?})[{idx}] \
                     expected {expected_value:?}, got {actual:?}",
                    array.encoding_id(),
                    idx,
                );
            }
        }
    }
}

/// Entry point for binary numeric conformance testing for any array type.
///
/// This function automatically detects the array's numeric type and runs
/// the appropriate tests. It's designed to be called from rstest parameterized
/// tests without requiring explicit type parameters.
///
/// # Example
///
/// ```ignore
/// #[rstest]
/// #[case::i32_array(create_i32_array())]
/// #[case::f64_array(create_f64_array())]
/// fn test_my_encoding_binary_numeric(#[case] array: MyArray) {
///     test_binary_numeric_array(array.into_array());
/// }
/// ```
pub fn test_binary_numeric_array(array: &ArrayRef, ctx: &mut ExecutionCtx) {
    match array.dtype() {
        DType::Primitive(ptype, _) => match ptype {
            PType::I8 => test_binary_numeric_conformance::<i8>(array, ctx),
            PType::I16 => test_binary_numeric_conformance::<i16>(array, ctx),
            PType::I32 => test_binary_numeric_conformance::<i32>(array, ctx),
            PType::I64 => test_binary_numeric_conformance::<i64>(array, ctx),
            PType::U8 => test_binary_numeric_conformance::<u8>(array, ctx),
            PType::U16 => test_binary_numeric_conformance::<u16>(array, ctx),
            PType::U32 => test_binary_numeric_conformance::<u32>(array, ctx),
            PType::U64 => test_binary_numeric_conformance::<u64>(array, ctx),
            PType::F16 => {
                // F16 not supported in num-traits, skip
                eprintln!("Skipping f16 binary numeric tests (not supported)");
            }
            PType::F32 => test_binary_numeric_conformance::<f32>(array, ctx),
            PType::F64 => test_binary_numeric_conformance::<f64>(array, ctx),
        },
        DType::Decimal(decimal_dtype, _) => {
            test_binary_numeric_conformance_decimal(array, *decimal_dtype, ctx)
        }
        dtype => vortex_panic!(
            "Binary numeric tests are only supported for primitive and decimal types, got {dtype}",
        ),
    }
}

/// Tests binary numeric operations on a decimal array against the decimal scalar
/// implementation, using a set of representative constants: stored `0`, `1`, `-1`, the decimal
/// `1.0` (when it fits the precision), and the largest stored value for the precision.
fn test_binary_numeric_conformance_decimal(
    array: &ArrayRef,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) {
    let precision = decimal_dtype.precision() as usize;
    let prec_max = <i256 as NativeDecimalType>::MAX_BY_PRECISION[precision];

    let mut constants = vec![
        i256::from_i128(0),
        i256::from_i128(1),
        i256::from_i128(-1),
        prec_max,
    ];
    // The decimal value 1.0 (stored 10^s), when representable within the precision.
    if decimal_dtype.scale() >= 0
        && let Some(one) = i256::from_i128(10).checked_pow(decimal_dtype.scale() as u32)
        && one <= prec_max
    {
        constants.push(one);
    }

    for constant in constants {
        let value = DecimalValue::try_from_i256(constant, decimal_dtype)
            .vortex_expect("conformance constants fit the precision");
        test_decimal_binary_numeric_with_scalar(array, value, decimal_dtype, ctx);
    }
}

fn test_decimal_binary_numeric_with_scalar(
    array: &ArrayRef,
    value: DecimalValue,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) {
    let canonicalized_array = array
        .clone()
        .execute::<Canonical>(ctx)
        .vortex_expect("Must be able to canonicalise")
        .into_array();
    let original_values = to_vec_of_scalar(&canonicalized_array, ctx);

    let scalar = Scalar::decimal(value, decimal_dtype, array.dtype().nullability());

    // Decimal Mul/Div are not yet implemented.
    for operator in [NumericOperator::Add, NumericOperator::Sub] {
        for lhs_is_array in [true, false] {
            test_decimal_binary_numeric_direction(
                array,
                &original_values,
                &scalar,
                decimal_dtype,
                operator,
                lhs_is_array,
                ctx,
            );
        }
    }
}

fn test_decimal_binary_numeric_direction(
    array: &ArrayRef,
    original_values: &[Scalar],
    scalar: &Scalar,
    decimal_dtype: DecimalDType,
    operator: NumericOperator,
    lhs_is_array: bool,
    ctx: &mut ExecutionCtx,
) {
    let result_decimal_dtype = numeric_op_result_decimal_dtype(decimal_dtype, operator)
        .vortex_expect("decimal Add/Sub must have a result dtype");
    let result_dtype = DType::Decimal(result_decimal_dtype, array.dtype().nullability());
    let expected_results = expected_decimal_results(
        original_values,
        scalar,
        operator,
        result_decimal_dtype,
        &result_dtype,
        lhs_is_array,
    );

    let constant = ConstantArray::new(scalar.clone(), array.len()).into_array();
    let (lhs, rhs) = if lhs_is_array {
        (array.clone(), constant)
    } else {
        (constant, array.clone())
    };
    let result = lhs
        .binary(rhs, operator.into())
        .vortex_expect("binary decimal op shouldn't fail")
        .execute::<RecursiveCanonical>(ctx)
        .map(|c| c.0.into_array());

    assert_decimal_results(
        result,
        &expected_results,
        array,
        scalar,
        operator,
        lhs_is_array,
        ctx,
    );
}

fn expected_decimal_results(
    original_values: &[Scalar],
    scalar: &Scalar,
    operator: NumericOperator,
    result_decimal_dtype: DecimalDType,
    result_dtype: &DType,
    lhs_is_array: bool,
) -> Vec<Option<Scalar>> {
    original_values
        .iter()
        .map(|value| {
            let (lhs, rhs) = if lhs_is_array {
                (value.as_decimal(), scalar.as_decimal())
            } else {
                (scalar.as_decimal(), value.as_decimal())
            };
            let (Some(lhs), Some(rhs)) = (lhs.decimal_value(), rhs.decimal_value()) else {
                return Some(Scalar::null(result_dtype.clone()));
            };
            let value = match operator {
                NumericOperator::Add => lhs.as_i256().checked_add(&rhs.as_i256()),
                NumericOperator::Sub => lhs.as_i256().checked_sub(&rhs.as_i256()),
                NumericOperator::Mul | NumericOperator::Div => unreachable!(),
            }?;
            let value = DecimalValue::try_from_i256(value, result_decimal_dtype).ok()?;
            Some(Scalar::decimal(
                value,
                result_decimal_dtype,
                result_dtype.nullability(),
            ))
        })
        .collect()
}

fn assert_decimal_results(
    result: vortex_error::VortexResult<ArrayRef>,
    expected_results: &[Option<Scalar>],
    array: &ArrayRef,
    scalar: &Scalar,
    operator: NumericOperator,
    lhs_is_array: bool,
    ctx: &mut ExecutionCtx,
) {
    if expected_results.iter().any(Option::is_none) {
        assert!(
            result.is_err(),
            "Decimal binary numeric operation should overflow for encoding {}: \
             {operator:?} {scalar} (lhs_is_array: {lhs_is_array})",
            array.encoding_id(),
        );
        return;
    }

    let result = result.unwrap_or_else(|err| {
        vortex_panic!(
            "Decimal binary numeric operation unexpectedly failed for encoding {}: \
             {operator:?} {scalar} (lhs_is_array: {lhs_is_array}): {err}",
            array.encoding_id(),
        )
    });

    let actual_values = to_vec_of_scalar(&result, ctx);
    for (idx, (actual, expected)) in actual_values.iter().zip(expected_results).enumerate() {
        let expected_value = expected
            .as_ref()
            .vortex_expect("non-overflowing decimal lane must have an expected value");
        assert_eq!(
            actual,
            expected_value,
            "Decimal binary numeric operation failed for encoding {} at index {}: \
             ({array:?})[{idx}] {operator:?} {scalar} (lhs_is_array: {lhs_is_array}) \
             expected {expected_value:?}, got {actual:?}",
            array.encoding_id(),
            idx,
        );
    }
}

/// Tests binary numeric operations with edge case scalar values.
///
/// This function tests operations with scalar values:
/// - Zero (identity for addition/subtraction, absorbing for multiplication)
/// - Negative one (tests signed arithmetic)
/// - Maximum value (tests overflow behavior)
/// - Minimum value (tests underflow behavior)
fn test_binary_numeric_edge_cases(array: &ArrayRef, ctx: &mut ExecutionCtx) {
    match array.dtype() {
        DType::Primitive(ptype, _) => match ptype {
            PType::I8 => test_binary_numeric_edge_cases_signed::<i8>(array, ctx),
            PType::I16 => test_binary_numeric_edge_cases_signed::<i16>(array, ctx),
            PType::I32 => test_binary_numeric_edge_cases_signed::<i32>(array, ctx),
            PType::I64 => test_binary_numeric_edge_cases_signed::<i64>(array, ctx),
            PType::U8 => test_binary_numeric_edge_cases_unsigned::<u8>(array, ctx),
            PType::U16 => test_binary_numeric_edge_cases_unsigned::<u16>(array, ctx),
            PType::U32 => test_binary_numeric_edge_cases_unsigned::<u32>(array, ctx),
            PType::U64 => test_binary_numeric_edge_cases_unsigned::<u64>(array, ctx),
            PType::F16 => {
                eprintln!("Skipping f16 edge case tests (not supported)");
            }
            PType::F32 => test_binary_numeric_edge_cases_float::<f32>(array, ctx),
            PType::F64 => test_binary_numeric_edge_cases_float::<f64>(array, ctx),
        },
        dtype => vortex_panic!(
            "Binary numeric edge case tests are only supported for primitive numeric types, got {dtype}"
        ),
    }
}

fn test_binary_numeric_edge_cases_signed<T>(array: &ArrayRef, ctx: &mut ExecutionCtx)
where
    T: NativePType + Num + Copy + Debug + Bounded + Signed,
    Scalar: From<T>,
{
    // Test with zero
    test_binary_numeric_with_scalar(array, T::zero(), ctx);

    // Test with -1
    test_binary_numeric_with_scalar(array, -T::one(), ctx);

    // Test with max value
    test_binary_numeric_with_scalar(array, T::max_value(), ctx);

    // Test with min value
    test_binary_numeric_with_scalar(array, T::min_value(), ctx);
}

fn test_binary_numeric_edge_cases_unsigned<T>(array: &ArrayRef, ctx: &mut ExecutionCtx)
where
    T: NativePType + Num + Copy + Debug + Bounded,
    Scalar: From<T>,
{
    // Test with zero
    test_binary_numeric_with_scalar(array, T::zero(), ctx);

    // Test with max value
    test_binary_numeric_with_scalar(array, T::max_value(), ctx);
}

fn test_binary_numeric_edge_cases_float<T>(array: &ArrayRef, ctx: &mut ExecutionCtx)
where
    T: NativePType + Num + Copy + Debug + Float,
    Scalar: From<T>,
{
    // Test with zero
    test_binary_numeric_with_scalar(array, T::zero(), ctx);

    // Test with -1
    test_binary_numeric_with_scalar(array, -T::one(), ctx);

    // Test with max value
    test_binary_numeric_with_scalar(array, T::max_value(), ctx);

    // Test with min value
    test_binary_numeric_with_scalar(array, T::min_value(), ctx);

    // Test with small positive value
    test_binary_numeric_with_scalar(array, T::epsilon(), ctx);

    // Test with min positive value (subnormal)
    test_binary_numeric_with_scalar(array, T::min_positive_value(), ctx);

    // Test with special float values (NaN, Infinity)
    test_binary_numeric_with_scalar(array, T::nan(), ctx);
    test_binary_numeric_with_scalar(array, T::infinity(), ctx);
    test_binary_numeric_with_scalar(array, T::neg_infinity(), ctx);
}

fn test_binary_numeric_with_scalar<T>(array: &ArrayRef, scalar_value: T, ctx: &mut ExecutionCtx)
where
    T: NativePType + Num + Copy + Debug,
    Scalar: From<T>,
{
    let canonicalized_array = array
        .clone()
        .execute::<Canonical>(ctx)
        .vortex_expect("Must be able to canonicalise")
        .into_array();
    let original_values = to_vec_of_scalar(&canonicalized_array, ctx);

    let scalar = Scalar::from(scalar_value)
        .cast(array.dtype())
        .vortex_expect("operation should succeed in conformance test");

    // Only test operators that make sense for the given scalar
    let operators = if scalar_value == T::zero() {
        // Skip division by zero
        vec![
            NumericOperator::Add,
            NumericOperator::Sub,
            NumericOperator::Mul,
        ]
    } else {
        vec![
            NumericOperator::Add,
            NumericOperator::Sub,
            NumericOperator::Mul,
            NumericOperator::Div,
        ]
    };

    for operator in operators {
        let op = operator;
        let rhs_const = ConstantArray::new(scalar.clone(), array.len()).into_array();

        // Test array operator scalar
        let result = array
            .binary(rhs_const, op.into())
            .vortex_expect("apply failed")
            .execute::<RecursiveCanonical>(ctx)
            .map(|x| x.0.into_array());

        // Skip if the entire operation fails
        // TODO(joe): this is odd.
        if result.is_err() {
            continue;
        }

        let result = result.vortex_expect("operation should succeed in conformance test");
        let actual_values = to_vec_of_scalar(&result, ctx);

        // Check each element for overflow/underflow
        let expected_results: Vec<Option<Scalar>> = original_values
            .iter()
            .map(|x| {
                x.as_primitive()
                    .checked_binary_numeric(&scalar.as_primitive(), op)
                    .map(<Scalar as From<PrimitiveScalar<'_>>>::from)
            })
            .collect();

        // For elements that didn't overflow, check they match
        for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
            if let Some(expected_value) = expected {
                assert_eq!(
                    actual,
                    expected_value,
                    "Binary numeric operation failed for encoding {} at index {} with scalar {:?}: \
                     ({array:?})[{idx}] {operator:?} {scalar} \
                     expected {expected_value:?}, got {actual:?}",
                    array.encoding_id(),
                    idx,
                    scalar_value,
                );
            }
        }
    }
}