vortex-arrow 0.94.0

Apache Arrow interoperability for Vortex arrays
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Decimal export from stored values with the logical precision and scale.
//!
//! Exporting a `Widen` child directly avoids an intermediate widening copy. Narrowing conversions
//! ignore null payloads because those bytes do not constrain the Arrow value width.

use std::sync::Arc;

use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_array::Decimal32Array as ArrowDecimal32Array;
use arrow_array::Decimal64Array as ArrowDecimal64Array;
use arrow_array::Decimal128Array as ArrowDecimal128Array;
use arrow_array::Decimal256Array as ArrowDecimal256Array;
use arrow_buffer::i256;
use arrow_schema::DataType;
use itertools::Itertools;
use num_traits::AsPrimitive;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::arrays::DecimalArray;
use vortex_array::arrays::Widen;
use vortex_array::arrays::widen::WidenArraySlotsExt;
use vortex_array::dtype::BigCast;
use vortex_array::dtype::DecimalDType;
use vortex_array::dtype::DecimalType;
use vortex_array::dtype::NativeDecimalType;
use vortex_buffer::Buffer;
use vortex_error::VortexResult;
use vortex_error::vortex_err;
use vortex_mask::AllOr;
use vortex_mask::Mask;

use crate::null_buffer::to_null_buffer;

pub(super) fn to_arrow_decimal(
    array: ArrayRef,
    data_type: &DataType,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
    let decimal_dtype = *array.dtype().as_decimal_opt().ok_or_else(|| {
        vortex_err!(
            "Cannot convert Vortex array with dtype {} to an Arrow {} array",
            array.dtype(),
            data_type
        )
    })?;

    // A `Widen` holds the same values in a narrower child. Exporting the child copies each value
    // once, into the Arrow width. Executing the `Widen` first would also copy each value into the
    // canonical width of `decimal_dtype`.
    let array = array.execute_until::<Widen>(ctx)?;
    let values = match array.as_opt::<Widen>() {
        Some(widen) => widen.values().clone(),
        None => array,
    };
    let values = values.execute::<DecimalArray>(ctx)?;

    match data_type {
        DataType::Decimal32(..) => to_arrow_decimal32(values, decimal_dtype, ctx),
        DataType::Decimal64(..) => to_arrow_decimal64(values, decimal_dtype, ctx),
        DataType::Decimal128(..) => to_arrow_decimal128(values, decimal_dtype, ctx),
        DataType::Decimal256(..) => to_arrow_decimal256(values, decimal_dtype, ctx),
        _ => unreachable!("to_arrow_decimal called with non-decimal type"),
    }
}

/// Exports `values` as an Arrow `Decimal32` with the precision and scale of `decimal_dtype`.
///
/// `values` can be the narrower child of a [`Widen`], whose own decimal dtype has a smaller
/// precision. The Arrow precision and scale therefore come from `decimal_dtype`, never from
/// `values`.
fn to_arrow_decimal32(
    values: DecimalArray,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
    let validity = values
        .as_ref()
        .validity()?
        .execute_mask(values.as_ref().len(), ctx)?;

    let buffer: Buffer<i32> = match values.values_type() {
        DecimalType::I8 => {
            Buffer::from_trusted_len_iter(values.buffer::<i8>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I16 => {
            Buffer::from_trusted_len_iter(values.buffer::<i16>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I32 => values.buffer::<i32>(),
        DecimalType::I64 => narrow_values::<i64, i32>(values.buffer::<i64>(), &validity)?,
        DecimalType::I128 => narrow_values::<i128, i32>(values.buffer::<i128>(), &validity)?,
        DecimalType::I256 => narrow_values::<vortex_array::dtype::i256, i32>(
            values.buffer::<vortex_array::dtype::i256>(),
            &validity,
        )?,
    };

    Ok(Arc::new(
        ArrowDecimal32Array::new(buffer.into_arrow_scalar_buffer(), to_null_buffer(validity))
            .with_precision_and_scale(decimal_dtype.precision(), decimal_dtype.scale())?,
    ))
}

/// Like [`to_arrow_decimal32`], but exports an Arrow `Decimal64`.
fn to_arrow_decimal64(
    values: DecimalArray,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
    let validity = values
        .as_ref()
        .validity()?
        .execute_mask(values.as_ref().len(), ctx)?;

    let buffer: Buffer<i64> = match values.values_type() {
        DecimalType::I8 => {
            Buffer::from_trusted_len_iter(values.buffer::<i8>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I16 => {
            Buffer::from_trusted_len_iter(values.buffer::<i16>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I32 => {
            Buffer::from_trusted_len_iter(values.buffer::<i32>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I64 => values.buffer::<i64>(),
        DecimalType::I128 => narrow_values::<i128, i64>(values.buffer::<i128>(), &validity)?,
        DecimalType::I256 => narrow_values::<vortex_array::dtype::i256, i64>(
            values.buffer::<vortex_array::dtype::i256>(),
            &validity,
        )?,
    };

    Ok(Arc::new(
        ArrowDecimal64Array::new(buffer.into_arrow_scalar_buffer(), to_null_buffer(validity))
            .with_precision_and_scale(decimal_dtype.precision(), decimal_dtype.scale())?,
    ))
}

/// Like [`to_arrow_decimal32`], but exports an Arrow `Decimal128`.
fn to_arrow_decimal128(
    values: DecimalArray,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
    let validity = values
        .as_ref()
        .validity()?
        .execute_mask(values.as_ref().len(), ctx)?;

    let buffer: Buffer<i128> = match values.values_type() {
        DecimalType::I8 => {
            Buffer::from_trusted_len_iter(values.buffer::<i8>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I16 => {
            Buffer::from_trusted_len_iter(values.buffer::<i16>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I32 => {
            Buffer::from_trusted_len_iter(values.buffer::<i32>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I64 => {
            Buffer::from_trusted_len_iter(values.buffer::<i64>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I128 => values.buffer::<i128>(),
        DecimalType::I256 => narrow_values::<vortex_array::dtype::i256, i128>(
            values.buffer::<vortex_array::dtype::i256>(),
            &validity,
        )?,
    };

    Ok(Arc::new(
        ArrowDecimal128Array::new(buffer.into_arrow_scalar_buffer(), to_null_buffer(validity))
            .with_precision_and_scale(decimal_dtype.precision(), decimal_dtype.scale())?,
    ))
}

/// Like [`to_arrow_decimal32`], but exports an Arrow `Decimal256`.
fn to_arrow_decimal256(
    values: DecimalArray,
    decimal_dtype: DecimalDType,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
    let validity = values
        .as_ref()
        .validity()?
        .execute_mask(values.as_ref().len(), ctx)?;

    let buffer: Buffer<i256> = match values.values_type() {
        DecimalType::I8 => {
            Buffer::from_trusted_len_iter(values.buffer::<i8>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I16 => {
            Buffer::from_trusted_len_iter(values.buffer::<i16>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I32 => {
            Buffer::from_trusted_len_iter(values.buffer::<i32>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I64 => {
            Buffer::from_trusted_len_iter(values.buffer::<i64>().into_iter().map(|x| x.as_()))
        }
        DecimalType::I128 => Buffer::from_trusted_len_iter(
            values
                .buffer::<i128>()
                .into_iter()
                .map(|x| vortex_array::dtype::i256::from_i128(x).into()),
        ),
        DecimalType::I256 => {
            Buffer::<i256>::from_byte_buffer(values.buffer_handle().clone().into_host_sync())
        }
    };

    Ok(Arc::new(
        ArrowDecimal256Array::new(buffer.into_arrow_scalar_buffer(), to_null_buffer(validity))
            .with_precision_and_scale(decimal_dtype.precision(), decimal_dtype.scale())?,
    ))
}

/// Narrows the decimal `values` to `T`, and writes zero into every null row.
///
/// Every valid value **must** fit in `T`, or this returns an error. A null row can hold any value,
/// including one that does not fit in `T`, so this never converts it. The zeroed null rows match
/// [`copy_to_canonical_width`], but unlike it, this checks only that each valid value fits in `T`,
/// not that it fits the precision.
///
/// [`copy_to_canonical_width`]: vortex_array::arrays::decimal::copy_to_canonical_width
fn narrow_values<S: NativeDecimalType, T: NativeDecimalType>(
    values: Buffer<S>,
    validity: &Mask,
) -> VortexResult<Buffer<T>> {
    let narrow = |value: S| {
        <T as BigCast>::from(value).ok_or_else(|| {
            vortex_err!(
                "every valid {} value must fit in {} to narrow, got {value}",
                S::DECIMAL_TYPE,
                T::DECIMAL_TYPE,
            )
        })
    };

    match validity.bit_buffer() {
        AllOr::All => values
            .into_iter()
            .map(narrow)
            .process_results(|iter| Buffer::from_trusted_len_iter(iter)),
        AllOr::None => Ok(Buffer::zeroed(values.len())),
        AllOr::Some(is_valid) => values
            .into_iter()
            .zip(is_valid.iter())
            .map(|(value, is_valid)| {
                if is_valid {
                    narrow(value)
                } else {
                    Ok(T::default())
                }
            })
            .process_results(|iter| Buffer::from_trusted_len_iter(iter)),
    }
}

#[cfg(test)]
mod tests {
    //! Decimal export equivalence and width checks for canonical arrays and `Widen` children.

    use std::sync::Arc;
    use std::sync::LazyLock;

    use arrow_array::Array;
    use arrow_array::Decimal128Array;
    use arrow_array::Decimal256Array;
    use arrow_array::StructArray as ArrowStructArray;
    use arrow_buffer::i256;
    use arrow_schema::DataType;
    use arrow_schema::Field;
    use rstest::rstest;
    use vortex_array::ArrayRef;
    use vortex_array::IntoArray;
    use vortex_array::VortexSessionExecute;
    use vortex_array::arrays::DecimalArray;
    use vortex_array::arrays::StructArray;
    use vortex_array::arrays::WidenArray;
    use vortex_array::dtype::DType;
    use vortex_array::dtype::DecimalDType;
    use vortex_array::dtype::DecimalType;
    use vortex_array::dtype::NativeDecimalType;
    use vortex_array::validity::Validity;
    use vortex_buffer::Buffer;
    use vortex_buffer::buffer;
    use vortex_error::VortexExpect;
    use vortex_error::VortexResult;
    use vortex_mask::Mask;
    use vortex_session::VortexSession;

    use super::narrow_values;
    use crate::ExecuteArrowExt;

    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

    /// Checks the concrete Arrow array type and compares its dtype, values, and nulls.
    #[track_caller]
    fn assert_arrow_eq<T: Array + 'static>(actual: &arrow_array::ArrayRef, expected: T) {
        assert!(actual.as_any().is::<T>());
        let expected: arrow_array::ArrayRef = Arc::new(expected);
        assert_eq!(actual, &expected);
    }

    /// Presents `values` as a `Widen` with the logical `precision`, and the scale and nullability
    /// of `values`.
    fn widen(values: DecimalArray, precision: u8) -> VortexResult<ArrayRef> {
        let decimal_dtype = DecimalDType::new(precision, values.decimal_dtype().scale());
        let dtype = DType::Decimal(decimal_dtype, values.dtype().nullability());

        Ok(WidenArray::try_new(values.into_array(), dtype)?.into_array())
    }

    /// A child at the largest precision that `T` holds, with the smallest and largest values of
    /// that precision in its valid rows.
    ///
    /// A nullable child holds `garbage` in its null rows. Arrow equality ignores null rows, so the
    /// export must match the canonical export whatever the null rows hold.
    fn widen_child<T: NativeDecimalType>(garbage: T, nullable: bool) -> DecimalArray {
        let decimal_dtype = DecimalDType::new(T::MAX_PRECISION, 1);
        let min = T::MIN_BY_PRECISION[usize::from(T::MAX_PRECISION)];
        let max = T::MAX_BY_PRECISION[usize::from(T::MAX_PRECISION)];

        if nullable {
            DecimalArray::new(
                Buffer::from_iter([min, garbage, max, min, garbage]),
                decimal_dtype,
                Validity::from_iter([true, false, true, true, false]),
                &mut SESSION.create_execution_ctx(),
            )
        } else {
            DecimalArray::new(
                Buffer::from_iter([min, max, max, min, max]),
                decimal_dtype,
                Validity::NonNullable,
                &mut SESSION.create_execution_ctx(),
            )
        }
    }

    #[test]
    fn decimal_to_arrow() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let decimal_vortex = DecimalArray::new(
            buffer![1i128, 2i128, 3i128, 4i128, 5i128],
            DecimalDType::new(19, 2),
            Validity::NonNullable,
            &mut ctx,
        );
        let arrow = decimal_vortex.into_array().execute_arrow(
            Some(&Field::new("", DataType::Decimal128(19, 2), false)),
            &mut ctx,
        )?;
        assert_arrow_eq(
            &arrow,
            Decimal128Array::from(vec![1, 2, 3, 4, 5]).with_precision_and_scale(19, 2)?,
        );

        Ok(())
    }

    #[rstest]
    #[case::decimal32(DataType::Decimal32, 9)]
    #[case::decimal64(DataType::Decimal64, 18)]
    #[case::decimal128(DataType::Decimal128, 38)]
    #[case::decimal256(DataType::Decimal256, 76)]
    fn test_to_arrow_decimal(
        #[case] arrow_type: fn(u8, i8) -> DataType,
        #[case] max_precision: u8,
    ) -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let values = [-12, 0, 11];
        let reference = Decimal256Array::from_iter_values(values.map(i256::from_i128))
            .with_precision_and_scale(76, 1)?;

        for (precision, values_type) in [
            (2, DecimalType::I8),
            (4, DecimalType::I16),
            (9, DecimalType::I32),
            (18, DecimalType::I64),
            (38, DecimalType::I128),
            (76, DecimalType::I256),
        ] {
            if precision > max_precision {
                break;
            }

            let decimal = DecimalArray::from_iter(values, DecimalDType::new(precision, 1));
            assert_eq!(decimal.values_type(), values_type);

            let field = Field::new("", arrow_type(precision, 1), false);
            let actual = decimal.execute_arrow(Some(&field), &mut ctx)?;
            let expected = arrow_cast::cast(&reference, field.data_type())?;
            assert_eq!(&actual, &expected, "exporting {values_type} to {field}");
        }

        Ok(())
    }

    #[rstest]
    #[case::i8_p4_decimal32(i8::MAX, 4, DataType::Decimal32(4, 1))]
    #[case::i8_p4_decimal64(i8::MAX, 4, DataType::Decimal64(4, 1))]
    #[case::i8_p4_decimal128(i8::MAX, 4, DataType::Decimal128(4, 1))]
    #[case::i8_p4_decimal256(i8::MAX, 4, DataType::Decimal256(4, 1))]
    #[case::i32_p18_decimal64(i32::MAX, 18, DataType::Decimal64(18, 1))]
    #[case::i32_p18_decimal128(i32::MAX, 18, DataType::Decimal128(18, 1))]
    #[case::i32_p18_decimal256(i32::MAX, 18, DataType::Decimal256(18, 1))]
    #[case::i64_p38_decimal128(i64::MAX, 38, DataType::Decimal128(38, 1))]
    #[case::i64_p38_decimal256(i64::MAX, 38, DataType::Decimal256(38, 1))]
    #[case::i128_p76_decimal256(i128::MAX, 76, DataType::Decimal256(76, 1))]
    fn test_widen_to_arrow_matches_canonical<T: NativeDecimalType>(
        #[case] garbage: T,
        #[case] precision: u8,
        #[case] data_type: DataType,
        #[values(false, true)] nullable: bool,
    ) -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let array = widen(widen_child(garbage, nullable), precision)?;
        let canonical = array
            .clone()
            .execute::<DecimalArray>(&mut ctx)?
            .into_array();

        let field = Field::new("", data_type.clone(), nullable);
        let actual = array.execute_arrow(Some(&field), &mut ctx)?;
        let expected = canonical.execute_arrow(Some(&field), &mut ctx)?;
        assert_eq!(actual.data_type(), &data_type);
        assert_eq!(&actual, &expected);

        Ok(())
    }

    #[test]
    fn test_widen_to_arrow_uses_logical_precision() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let values = DecimalArray::new(
            buffer![-99i8, 0, 99],
            DecimalDType::new(2, 1),
            Validity::NonNullable,
            &mut ctx,
        );

        let arrow = widen(values, 4)?.execute_arrow(None, &mut ctx)?;
        assert_arrow_eq(
            &arrow,
            Decimal128Array::from(vec![-99, 0, 99]).with_precision_and_scale(4, 1)?,
        );

        Ok(())
    }

    #[test]
    fn test_sliced_widen_to_arrow() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let values = DecimalArray::new(
            buffer![10i32, i32::MAX, 30, 40, 50],
            DecimalDType::new(9, 2),
            Validity::from_iter([true, false, true, true, true]),
            &mut ctx,
        );

        let sliced = widen(values, 18)?.slice(1..4)?;
        let field = Field::new("", DataType::Decimal128(18, 2), true);
        let arrow = sliced.execute_arrow(Some(&field), &mut ctx)?;
        assert_arrow_eq(
            &arrow,
            Decimal128Array::from(vec![None, Some(30), Some(40)])
                .with_precision_and_scale(18, 2)?,
        );

        Ok(())
    }

    #[test]
    fn test_struct_with_widen_field_to_arrow() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let values = DecimalArray::new(
            buffer![1i32, 2, 3],
            DecimalDType::new(9, 2),
            Validity::NonNullable,
            &mut ctx,
        );
        let array = StructArray::from_fields(&[("price", widen(values, 18)?)])?.into_array();

        let arrow = array.execute_arrow(None, &mut ctx)?;
        let arrow = arrow
            .as_any()
            .downcast_ref::<ArrowStructArray>()
            .vortex_expect("the requested Arrow type fixes the concrete array type");
        assert_arrow_eq(
            arrow.column(0),
            Decimal128Array::from(vec![1, 2, 3]).with_precision_and_scale(18, 2)?,
        );

        Ok(())
    }

    #[rstest]
    #[case::partially_null(Mask::from_iter([true, false]), [1, 0])]
    #[case::all_null(Mask::new_false(2), [0, 0])]
    fn test_narrow_values_skips_null_rows(
        #[case] validity: Mask,
        #[case] expected: [i64; 2],
    ) -> VortexResult<()> {
        let values = narrow_values::<i128, i64>(buffer![1i128, i128::MAX], &validity)?;
        assert_eq!(values.as_slice(), &expected);

        Ok(())
    }

    #[rstest]
    #[case::all_valid(Validity::NonNullable)]
    #[case::partially_valid(Validity::from_iter([true, false]))]
    fn test_to_arrow_rejects_valid_value_that_does_not_fit(
        #[case] validity: Validity,
    ) -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let values = DecimalArray::new(
            buffer![i128::from(i64::MAX) + 1, 0],
            DecimalDType::new(19, 2),
            validity,
            &mut ctx,
        );
        let field = Field::new("", DataType::Decimal64(18, 2), values.dtype().is_nullable());

        let err = values
            .into_array()
            .execute_arrow(Some(&field), &mut ctx)
            .expect_err("a valid value outside the target width must fail");
        assert!(
            err.to_string()
                .contains("every valid i128 value must fit in i64 to narrow")
        );

        Ok(())
    }
}