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

//! Field and array assertions shared by property tests and fuzz targets.
//!
//! Explicit targets must agree with their exported Arrow types. Default exports can choose a
//! different physical representation, so imports retain the field metadata with that actual type.

use std::sync::Arc;

use arrow_array::Array;
use arrow_ord::cmp;
use arrow_schema::DataType;
use arrow_schema::Field;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::ExtensionArray;
use vortex_array::arrays::FixedSizeListArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::ListViewArray;
use vortex_array::arrays::MapArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::RunEnd;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::extension::ExtensionArrayExt;
use vortex_array::assert_arrays_eq;
use vortex_array::builtins::ArrayBuiltins;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::scalar_fn::builtin::operators::CompareOperator;
use vortex_array::validity::Validity;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_functions::builtins::ArrayFunctions;

use crate::ArrowSessionExt;
use crate::ExecuteArrowExt;

/// Checks extension import, explicit export, round trips, and batch selections.
///
/// The caller builds both representations and the expected field independently from source
/// values. The Vortex array must have an extension dtype. Arrow data equality ignores values
/// masked by nulls.
///
/// Also check the export against the Vortex storage for nulls, equality, and order where the Arrow
/// comparison kernels support the output type.
#[track_caller]
pub fn check_arrow(
    array: ArrayRef,
    field: &Field,
    expected: arrow_array::ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
    let exported = check_arrow_values(array.clone(), field, Arc::clone(&expected), ctx)?;
    check_exported_values(array.clone(), exported.as_ref(), ctx)?;
    check_nested_arrow(array.clone(), field, Arc::clone(&expected), ctx)?;
    let len = array.len();
    let indices: Vec<_> = (0..u32::try_from(len)?)
        .rev()
        .flat_map(|i| [i, i])
        .collect();
    let mask: Vec<_> = (0..len).map(|i| i % 2 == 0).collect();
    let selected = [
        (
            "slice",
            array.slice(len / 2..len)?,
            expected.slice(len / 2, len - len / 2),
        ),
        (
            "take",
            array.take(PrimitiveArray::from_iter(indices.clone()).into_array())?,
            reference_take(expected.as_ref(), &indices)?,
        ),
        (
            "filter",
            array.filter(vortex_mask::Mask::from_iter(mask.iter().copied()))?,
            reference_take(
                expected.as_ref(),
                &(0..u32::try_from(len)?)
                    .filter(|&i| mask[usize::try_from(i).vortex_expect("row index fits usize")])
                    .collect::<Vec<_>>(),
            )?,
        ),
    ];
    for (operation, selected, expected) in selected {
        assert_eq!(selected.dtype(), array.dtype(), "{operation} dtype");
        let selected = selected.execute::<ExtensionArray>(ctx)?.into_array();
        let exported = selected.execute_arrow(Some(field), ctx)?;
        assert_eq!(exported.to_data(), expected.to_data(), "{operation} values");
    }

    Ok(())
}

#[track_caller]
fn check_arrow_values(
    array: ArrayRef,
    field: &Field,
    expected: arrow_array::ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<arrow_array::ArrayRef> {
    let session = ctx.session().clone();
    let arrow = session.arrow();
    assert_eq!(expected.data_type(), field.data_type());
    let expected_data = expected.to_data();
    expected_data.validate_full()?;
    assert_eq!(arrow.from_arrow_field(field)?, *array.dtype());
    let imported = arrow.from_arrow_array(Arc::clone(&expected), field)?;
    assert_arrays_eq!(imported, array, ctx);

    let exported = array.clone().execute_arrow(Some(field), ctx)?;
    let data = exported.to_data();
    data.validate_full()?;
    assert_eq!(data, expected_data, "explicit export values");

    let round_tripped = arrow.from_arrow_array(Arc::clone(&exported), field)?;
    assert_arrays_eq!(round_tripped, array, ctx);

    Ok(exported)
}

/// Checks the nulls and comparable storage values against the exported array.
///
/// [`ArrowExportVTable::execute_arrow`] states the two rules. Check nulls across all rows, then
/// compare consecutive non-null rows. If the array contains distinct values, at least one pair
/// compares them. Nested exports only support the null check.
///
/// [`ArrowExportVTable::execute_arrow`]: crate::ArrowExportVTable::execute_arrow
#[track_caller]
fn check_exported_values(
    array: ArrayRef,
    exported: &dyn Array,
    ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
    let len = array.len();
    let nulls = exported.logical_nulls();
    let exported_is_null = match &nulls {
        Some(nulls) => BoolArray::from_iter(nulls.iter().map(|valid| !valid)),
        None => BoolArray::from_iter(std::iter::repeat_n(false, len)),
    };
    assert_arrays_eq!(exported_is_null.into_array(), array.is_null()?, ctx);

    if exported.data_type().is_nested() {
        return Ok(());
    }

    let indices = match nulls {
        Some(nulls) => nulls
            .valid_indices()
            .map(u32::try_from)
            .collect::<Result<Vec<_>, _>>()?,
        None => (0..u32::try_from(len)?).collect(),
    };
    if indices.len() < 2 {
        return Ok(());
    }

    let left_indices = &indices[..indices.len() - 1];
    let right_indices = &indices[1..];

    let session = ctx.session().clone();
    let extension = array.execute::<ExtensionArray>(ctx)?;
    let storage = extension.storage_array();
    let arrow_left = reference_take(exported, left_indices)?;
    let arrow_right = reference_take(exported, right_indices)?;
    let storage_left =
        storage.take(PrimitiveArray::from_iter(left_indices.iter().copied()).into_array())?;
    let storage_right =
        storage.take(PrimitiveArray::from_iter(right_indices.iter().copied()).into_array())?;

    let comparisons = [
        (CompareOperator::Eq, cmp::eq(&arrow_left, &arrow_right)?),
        (CompareOperator::Lt, cmp::lt(&arrow_left, &arrow_right)?),
    ];

    for (operator, in_arrow) in comparisons {
        let in_vortex = storage_left.compare(storage_right.clone(), operator)?;
        let in_arrow = session
            .arrow()
            .from_arrow_array(Arc::new(in_arrow), in_vortex.dtype().is_nullable())?;
        assert_arrays_eq!(in_arrow, in_vortex, ctx);
    }

    Ok(())
}

/// Builds parents independently around the two source representations.
#[track_caller]
fn check_nested_arrow(
    array: ArrayRef,
    field: &Field,
    expected: arrow_array::ArrayRef,
    ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
    let len = array.len();
    let validity = Validity::from_iter((0..len).map(|i| i != 1));
    let nulls = Some(arrow_buffer::NullBuffer::from(
        (0..len).map(|i| i != 1).collect::<Vec<_>>(),
    ));
    let child_field = Arc::new(field.clone().with_name("child"));
    let structure = StructArray::try_new(
        FieldNames::from(["child"]),
        vec![array.clone()],
        len,
        validity.clone(),
    )?
    .into_array();
    let expected_structure = arrow_array::StructArray::try_new_with_length(
        vec![Arc::clone(&child_field)].into(),
        vec![Arc::clone(&expected)],
        nulls.clone(),
        len,
    )?;
    let structure_field = Field::new("container", expected_structure.data_type().clone(), true);
    check_arrow_values(
        structure,
        &structure_field,
        Arc::new(expected_structure),
        ctx,
    )?;

    let fixed = FixedSizeListArray::try_new(array.clone(), 1, validity.clone(), len)?.into_array();
    let expected_fixed = arrow_array::FixedSizeListArray::try_new_with_length(
        Arc::clone(&child_field),
        1,
        Arc::clone(&expected),
        nulls.clone(),
        len,
    )?;
    let fixed_field = Field::new("container", expected_fixed.data_type().clone(), true);
    check_arrow_values(fixed, &fixed_field, Arc::new(expected_fixed), ctx)?;

    let mut offsets: Vec<_> = (0..=i32::try_from(len)?).map(|i| i - i % 2).collect();
    *offsets
        .last_mut()
        .vortex_expect("list offsets include the initial zero") = i32::try_from(len)?;
    let list = ListArray::try_new(
        array.clone(),
        PrimitiveArray::from_iter(offsets.clone()).into_array(),
        validity,
        ctx,
    )?
    .into_array();
    let expected_list = arrow_array::ListArray::try_new(
        child_field,
        arrow_buffer::OffsetBuffer::new(offsets.into()),
        Arc::clone(&expected),
        nulls,
    )?;
    let list_field = Field::new("container", expected_list.data_type().clone(), true);
    check_arrow_values(list, &list_field, Arc::new(expected_list), ctx)?;

    let keys = (0..u32::try_from(len)?).collect::<Vec<_>>();
    let entries = StructArray::try_new(
        FieldNames::from(["key", "value"]),
        vec![
            PrimitiveArray::from_iter(keys.clone()).into_array(),
            array.clone(),
        ],
        len,
        Validity::NonNullable,
    )?
    .into_array();
    let entries = ListViewArray::try_new(
        entries,
        PrimitiveArray::from_iter(0..u32::try_from(len)?).into_array(),
        PrimitiveArray::from_iter(std::iter::repeat_n(1u32, len)).into_array(),
        Validity::from_iter((0..len).map(|i| i != 1)),
        ctx,
    )?;
    let map_dtype = DType::map(
        DType::Primitive(PType::U32, Nullability::NonNullable),
        array.dtype().clone(),
        true,
        Nullability::Nullable,
    )?;
    let map = MapArray::try_new(
        map_dtype
            .into_map_opt()
            .vortex_expect("DType::map constructed a map"),
        entries,
    )?
    .into_array();
    let entry_fields = vec![
        Field::new("key", DataType::UInt32, false),
        field.clone().with_name("value"),
    ];
    let expected_entries = arrow_array::StructArray::try_new_with_length(
        entry_fields.clone().into(),
        vec![
            Arc::new(arrow_array::UInt32Array::from(keys)),
            Arc::clone(&expected),
        ],
        None,
        len,
    )?;
    let expected_map = arrow_array::MapArray::try_new(
        Arc::new(Field::new(
            "entries",
            DataType::Struct(entry_fields.into()),
            false,
        )),
        arrow_buffer::OffsetBuffer::new((0..=i32::try_from(len)?).collect::<Vec<_>>().into()),
        expected_entries,
        Some(arrow_buffer::NullBuffer::from(
            (0..len).map(|i| i != 1).collect::<Vec<_>>(),
        )),
        true,
    )?;
    let map_field = Field::new("container", expected_map.data_type().clone(), true);
    check_arrow_values(map, &map_field, Arc::new(expected_map), ctx)?;

    let codes: Vec<_> = (0..i32::try_from(len)?)
        .rev()
        .flat_map(|i| [i, i])
        .collect();
    let dict = DictArray::try_new(
        PrimitiveArray::from_iter(
            codes
                .iter()
                .copied()
                .map(u32::try_from)
                .collect::<Result<Vec<_>, _>>()?,
        )
        .into_array(),
        array.clone(),
    )?
    .into_array();
    let expected_dict = arrow_array::DictionaryArray::<arrow_array::types::Int32Type>::try_new(
        arrow_array::Int32Array::from(codes),
        Arc::clone(&expected),
    )?;
    let dict_field = field
        .clone()
        .with_data_type(expected_dict.data_type().clone());
    check_arrow_values(dict, &dict_field, Arc::new(expected_dict), ctx)?;

    let ends: Vec<_> = (1..=i32::try_from(len)?).map(|i| i * (i + 1) / 2).collect();
    let runs = RunEnd::try_new(
        PrimitiveArray::from_iter(
            ends.iter()
                .copied()
                .map(u32::try_from)
                .collect::<Result<Vec<_>, _>>()?,
        )
        .into_array(),
        array,
        ctx,
    )?
    .into_array();
    let expected_runs = arrow_array::RunArray::<arrow_array::types::Int32Type>::try_new(
        &arrow_array::Int32Array::from(ends),
        expected.as_ref(),
    )?;
    let DataType::RunEndEncoded(ends_field, _) = expected_runs.data_type() else {
        unreachable!("RunArray has run-end dtype")
    };
    let run_field = Field::new(
        "runs",
        DataType::RunEndEncoded(Arc::clone(ends_field), Arc::new(field.clone())),
        field.is_nullable(),
    );
    let expected_runs = arrow_array::make_array(
        expected_runs
            .to_data()
            .into_builder()
            .data_type(run_field.data_type().clone())
            .build()?,
    );
    check_arrow_values(runs, &run_field, expected_runs, ctx)?;

    Ok(())
}

/// Selects source rows while retaining the row count of zero-width lists.
fn reference_take(array: &dyn Array, indices: &[u32]) -> VortexResult<arrow_array::ArrayRef> {
    if let DataType::FixedSizeList(field, 0) = array.data_type() {
        let values = array
            .as_any()
            .downcast_ref::<arrow_array::FixedSizeListArray>()
            .vortex_expect("fixed-size-list dtype");

        // Arrow's take kernel derives this length from the empty child, losing nonempty rows.
        let nulls = array.nulls().map(|_| {
            arrow_buffer::NullBuffer::from(
                indices
                    .iter()
                    .map(|&i| {
                        array.is_valid(usize::try_from(i).vortex_expect("row index fits usize"))
                    })
                    .collect::<Vec<_>>(),
            )
        });
        return Ok(Arc::new(
            arrow_array::FixedSizeListArray::try_new_with_length(
                Arc::clone(field),
                0,
                Arc::clone(values.values()),
                nulls,
                indices.len(),
            )?,
        ));
    }

    Ok(arrow_select::take::take(
        array,
        &arrow_array::UInt32Array::from(indices.to_vec()),
        None,
    )?)
}

/// Checks canonical field and schema inference against an independent expected field.
#[cfg(feature = "_test-harness-hegel")]
#[track_caller]
pub(super) fn check_canonical_field(
    dtype: &DType,
    field: &Field,
    ctx: &ExecutionCtx,
) -> VortexResult<()> {
    let arrow = ctx.session().arrow();
    let inferred = arrow.to_arrow_field(field.name(), dtype)?;
    assert_eq!(inferred, *field);
    assert_eq!(arrow.from_arrow_field(&inferred)?, *dtype);

    let struct_dtype = DType::struct_(
        [(field.name().as_str(), dtype.clone())],
        Nullability::NonNullable,
    );
    let schema = arrow_schema::Schema::new(vec![field.clone()]);
    let inferred_schema = arrow.to_arrow_schema(&struct_dtype)?;
    assert_eq!(inferred_schema, schema);
    assert_eq!(arrow.from_arrow_schema(&inferred_schema)?, struct_dtype);

    Ok(())
}

/// Checks dtype and values and returns the export for comparison against an Arrow reference.
#[track_caller]
pub(super) fn check_field_round_trip(
    array: &ArrayRef,
    field: &Field,
    target: Option<&Field>,
    ctx: &mut ExecutionCtx,
) -> VortexResult<arrow_array::ArrayRef> {
    let session = ctx.session().clone();
    let arrow = session.arrow();
    assert_eq!(arrow.from_arrow_field(field)?, *array.dtype());

    let exported = array.clone().execute_arrow(target, ctx)?;
    exported.to_data().validate_full()?;
    if target.is_some() {
        assert_eq!(exported.data_type(), field.data_type());
    }

    let actual_field = field.clone().with_data_type(exported.data_type().clone());
    let imported = arrow.from_arrow_array(Arc::clone(&exported), &actual_field)?;
    assert_arrays_eq!(imported, array, ctx);

    Ok(exported)
}

/// Checks an array at the top level and in every required container.
///
/// The top-level array is also exported without a target field, so the exporter must infer the
/// field. Containers with validity are checked with both parent nullabilities, including a masked
/// second row when one exists. Empty arrays retain all placements, including dictionary and
/// run-end fields.
#[track_caller]
pub fn check_containers(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()> {
    let values_field = ctx
        .session()
        .arrow()
        .to_arrow_field("value", array.dtype())?;
    check_field_round_trip(&array, &values_field, Some(&values_field), ctx)?;
    check_field_round_trip(&array, &values_field, None, ctx)?;

    check_nested_round_trips(array, &values_field, ctx)
}

/// Checks container placements using the leaf's canonical field for dictionary and run values.
#[track_caller]
pub(super) fn check_nested_round_trips(
    array: ArrayRef,
    values_field: &Field,
    ctx: &mut ExecutionCtx,
) -> VortexResult<()> {
    let session = ctx.session().clone();
    let arrow = session.arrow();
    let len = array.len();

    for nullable in [false, true] {
        let validity = if nullable {
            Validity::from_iter((0..len).map(|i| i != 1))
        } else {
            Validity::NonNullable
        };
        let structure = StructArray::try_new(
            FieldNames::from(["child"]),
            vec![array.clone()],
            len,
            validity.clone(),
        )?
        .into_array();
        let list = ListArray::try_new(
            array.clone(),
            PrimitiveArray::from_iter(0..=u64::try_from(len)?).into_array(),
            validity.clone(),
            ctx,
        )?
        .into_array();
        let fixed =
            FixedSizeListArray::try_new(array.clone(), 1, validity.clone(), len)?.into_array();
        let entries = StructArray::try_new(
            FieldNames::from(["key", "value"]),
            vec![
                PrimitiveArray::from_iter(0..u32::try_from(len)?).into_array(),
                array.clone(),
            ],
            len,
            Validity::NonNullable,
        )?
        .into_array();
        let entries = ListViewArray::try_new(
            entries,
            PrimitiveArray::from_iter(0..u64::try_from(len)?).into_array(),
            PrimitiveArray::from_iter(std::iter::repeat_n(1u64, len)).into_array(),
            validity,
            ctx,
        )?;
        let map_dtype = DType::map(
            DType::Primitive(PType::U32, Nullability::NonNullable),
            array.dtype().clone(),
            true,
            nullable.into(),
        )?;
        let map = MapArray::try_new(
            map_dtype
                .into_map_opt()
                .vortex_expect("DType::map constructed a map dtype"),
            entries,
        )?
        .into_array();

        for array in [structure, list, fixed, map] {
            let field = arrow.to_arrow_field("container", array.dtype())?;
            check_field_round_trip(&array, &field, Some(&field), ctx)?;
            check_field_round_trip(&array, &field, None, ctx)?;
        }
    }

    let dictionary = DictArray::try_new(
        PrimitiveArray::from_iter((0..u32::try_from(len)?).rev().flat_map(|i| [i, i])).into_array(),
        array.clone(),
    )?
    .into_array();
    let field = values_field.clone().with_data_type(DataType::Dictionary(
        Box::new(DataType::Int32),
        Box::new(values_field.data_type().clone()),
    ));
    check_field_round_trip(&dictionary, &field, Some(&field), ctx)?;

    let run_end = RunEnd::try_new(
        PrimitiveArray::from_iter((1..=u32::try_from(len)?).map(|i| i * (i + 1) / 2)).into_array(),
        array,
        ctx,
    )?
    .into_array();
    let field = Field::new(
        "runs",
        DataType::RunEndEncoded(
            Arc::new(Field::new("run_ends", DataType::Int32, false)),
            Arc::new(values_field.clone()),
        ),
        run_end.dtype().is_nullable(),
    );

    check_field_round_trip(&run_end, &field, Some(&field), ctx)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use arrow_array::Date32Array;
    use vortex_array::VortexSessionExecute as _;
    use vortex_error::VortexExpect;
    use vortex_session::VortexSession;

    use super::check_exported_values;
    use crate::ArrowSessionExt;

    #[test]
    #[should_panic(expected = "assertion failed: arrays do not match")]
    fn test_export_order_check_pairs_non_null_rows() {
        let session = VortexSession::empty();
        let storage_order = Date32Array::from(vec![Some(1), Some(2), None, None]);
        let reversed_order = Date32Array::from(vec![Some(2), Some(1), None, None]);
        let array = session
            .arrow()
            .from_arrow_array(Arc::new(storage_order), true)
            .vortex_expect("Date32 imports as a Vortex date array");

        check_exported_values(array, &reversed_order, &mut session.create_execution_ctx())
            .vortex_expect("Date32 comparisons are supported");
    }
}