Skip to main content

vortex_arrow/test_harness/
generate.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Shrinkable storage values and extra nesting for the Arrow round-trip suites.
5//!
6//! Draws are separate so Hegel can reduce lengths, null masks, and values independently. Extension
7//! metadata and logical value constraints belong to the generators in the owning plugin crates.
8
9use std::sync::Arc;
10
11use arrow_array::ArrayRef as ArrowArrayRef;
12use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
13use arrow_array::PrimitiveArray as ArrowPrimitiveArray;
14use arrow_array::types::Float16Type;
15use arrow_array::types::Float32Type;
16use arrow_array::types::Float64Type;
17use arrow_array::types::Int8Type;
18use arrow_array::types::Int16Type;
19use arrow_array::types::Int32Type;
20use arrow_array::types::Int64Type;
21use arrow_array::types::UInt8Type;
22use arrow_array::types::UInt16Type;
23use arrow_array::types::UInt32Type;
24use arrow_array::types::UInt64Type;
25use arrow_buffer::NullBuffer;
26use arrow_schema::Field;
27use half::f16;
28use hegel::TestCase;
29use hegel::generators as gs;
30use vortex_array::ArrayRef;
31use vortex_array::ExecutionCtx;
32use vortex_array::IntoArray;
33use vortex_array::arrays::FixedSizeListArray;
34use vortex_array::arrays::ListArray;
35use vortex_array::arrays::PrimitiveArray;
36use vortex_array::arrays::StructArray;
37use vortex_array::dtype::DType;
38use vortex_array::dtype::FieldNames;
39use vortex_array::dtype::Nullability;
40use vortex_array::dtype::PType;
41use vortex_array::dtype::session::DTypeSessionExt;
42use vortex_array::validity::Validity;
43use vortex_buffer::Buffer;
44use vortex_error::VortexExpect;
45use vortex_error::VortexResult;
46use vortex_error::vortex_err;
47
48use super::check_arrow;
49use super::check_containers;
50use super::round_trip::check_canonical_field;
51use super::round_trip::check_field_round_trip;
52use super::round_trip::check_nested_round_trips;
53
54/// A storage array and its independent Arrow reference, built from the same source draws.
55pub struct StorageCase {
56    /// Vortex storage to wrap in the owning extension.
57    pub array: ArrayRef,
58    /// Arrow storage built directly with arrow-rs constructors.
59    pub arrow: ArrowArrayRef,
60}
61
62/// Draws numeric and fixed-size-list storage without invoking Arrow transport.
63///
64/// Callers bound row counts, list widths, and nesting.
65/// Returns an error for unsupported dtypes or lengths that do not fit the storage layout.
66pub fn draw_storage_case(
67    tc: &TestCase,
68    dtype: &DType,
69    len: usize,
70    ctx: &mut ExecutionCtx,
71) -> VortexResult<StorageCase> {
72    let validity = draw_validity(tc, dtype.nullability(), len);
73    let mask = validity.execute_mask(len, ctx)?;
74    let nulls = dtype
75        .is_nullable()
76        .then(|| NullBuffer::from((0..len).map(|i| mask.value(i)).collect::<Vec<_>>()));
77    let (array, arrow): (ArrayRef, ArrowArrayRef) = match dtype {
78        DType::FixedSizeList(child, size, _) => {
79            let child = draw_storage_case(
80                tc,
81                child,
82                len.checked_mul(usize::try_from(*size)?)
83                    .ok_or_else(|| vortex_err!("storage length overflow"))?,
84                ctx,
85            )?;
86            let field = Arc::new(Field::new(
87                "item",
88                child.arrow.data_type().clone(),
89                child.array.dtype().is_nullable(),
90            ));
91            let arrow = ArrowFixedSizeListArray::try_new_with_length(
92                field,
93                i32::try_from(*size)?,
94                child.arrow,
95                nulls,
96                len,
97            )?;
98            let array =
99                FixedSizeListArray::try_new(child.array, *size, validity, len)?.into_array();
100            (array, Arc::new(arrow))
101        }
102        DType::Primitive(ptype, _) => {
103            macro_rules! primitive {
104                ($t:ty, $arrow:ty, $draw:expr) => {{
105                    let values = (0..len).map(|_| $draw).collect::<Vec<$t>>();
106                    let array =
107                        PrimitiveArray::new(Buffer::from(values.clone()), validity).into_array();
108                    let arrow = ArrowPrimitiveArray::<$arrow>::new(values.into(), nulls);
109                    (array, Arc::new(arrow) as ArrowArrayRef)
110                }};
111            }
112            match ptype {
113                PType::U8 => primitive!(u8, UInt8Type, tc.draw(gs::integers::<u8>())),
114                PType::U16 => primitive!(u16, UInt16Type, tc.draw(gs::integers::<u16>())),
115                PType::U32 => primitive!(u32, UInt32Type, tc.draw(gs::integers::<u32>())),
116                PType::U64 => primitive!(u64, UInt64Type, tc.draw(gs::integers::<u64>())),
117                PType::I8 => primitive!(i8, Int8Type, tc.draw(gs::integers::<i8>())),
118                PType::I16 => primitive!(i16, Int16Type, tc.draw(gs::integers::<i16>())),
119                PType::I32 => primitive!(i32, Int32Type, tc.draw(gs::integers::<i32>())),
120                PType::I64 => primitive!(i64, Int64Type, tc.draw(gs::integers::<i64>())),
121                PType::F16 => primitive!(
122                    f16,
123                    Float16Type,
124                    f16::from_bits(tc.draw(gs::integers::<u16>()))
125                ),
126                PType::F32 => primitive!(f32, Float32Type, tc.draw(gs::floats::<f32>())),
127                PType::F64 => primitive!(f64, Float64Type, tc.draw(gs::floats::<f64>())),
128            }
129        }
130        _ => return Err(vortex_err!("no independent storage generator for {dtype}")),
131    };
132
133    Ok(StorageCase { array, arrow })
134}
135
136pub(super) fn draw_validity(tc: &TestCase, nullability: Nullability, len: usize) -> Validity {
137    match nullability {
138        Nullability::Nullable => {
139            Validity::from_iter(tc.draw(gs::vecs(gs::booleans()).min_size(len).max_size(len)))
140        }
141        Nullability::NonNullable => Validity::NonNullable,
142    }
143}
144
145/// Checks the Arrow contract against a canonical reference and through generated containers.
146///
147/// The leaf must have an extension dtype. Build the canonical Arrow field and values from the
148/// source fixture. The same reference checks explicit and default exports. Use
149/// [`check_arrow`] to cover other explicit targets.
150///
151/// Extension leaves retain metadata and nested storage across top-level nullability changes and
152/// reconstruction from serialized metadata and stored storage.
153///
154/// Extra struct, list, and fixed-size-list parents preserve the leaf's row count and independently
155/// draw their nullability and validity.
156#[track_caller]
157pub fn check_generated(
158    tc: &TestCase,
159    leaf: ArrayRef,
160    canonical_field: &Field,
161    expected: ArrowArrayRef,
162    ctx: &mut ExecutionCtx,
163) -> VortexResult<()> {
164    check_canonical_field(leaf.dtype(), canonical_field, ctx)?;
165    check_arrow(leaf.clone(), canonical_field, Arc::clone(&expected), ctx)?;
166    let default = check_field_round_trip(&leaf, canonical_field, None, ctx)?;
167    assert_eq!(
168        default.to_data(),
169        expected.to_data(),
170        "default export values"
171    );
172
173    if let DType::Extension(dtype) = leaf.dtype() {
174        let metadata = dtype.serialize_metadata()?;
175        let dtypes = ctx.session().dtypes();
176        let plugin = dtypes
177            .registry()
178            .get(&dtype.id())
179            .vortex_expect("the owning crate registered its dtype");
180
181        for nullability in [Nullability::NonNullable, Nullability::Nullable] {
182            let changed = dtype.with_nullability(nullability);
183            assert!(changed.eq_ignore_nullability(dtype));
184            assert_eq!(
185                changed.storage_dtype(),
186                &dtype.storage_dtype().with_nullability(nullability)
187            );
188            assert_eq!(changed.serialize_metadata()?, metadata);
189            assert_eq!(
190                plugin.deserialize(&metadata, changed.storage_dtype().clone())?,
191                changed
192            );
193        }
194    }
195
196    check_nested_round_trips(leaf.clone(), canonical_field, ctx)?;
197    check_generated_containers(tc, leaf, ctx)
198}
199
200/// Checks round trips with extra generated struct, list, and fixed-size-list parents.
201#[track_caller]
202pub fn check_generated_containers(
203    tc: &TestCase,
204    leaf: ArrayRef,
205    ctx: &mut ExecutionCtx,
206) -> VortexResult<()> {
207    let depth = tc.draw(gs::integers::<usize>().max_value(3));
208    let mut array = leaf;
209
210    for _ in 0..depth {
211        let len = array.len();
212        let validity = draw_validity(tc, tc.draw(gs::booleans()).into(), len);
213        array = match tc.draw(gs::integers::<u8>().max_value(2)) {
214            0 => StructArray::try_new(FieldNames::from(["child"]), vec![array], len, validity)?
215                .into_array(),
216            1 => ListArray::try_new(
217                array,
218                PrimitiveArray::from_iter(0..=u32::try_from(len)?).into_array(),
219                validity,
220                ctx,
221            )?
222            .into_array(),
223            _ => FixedSizeListArray::try_new(array, 1, validity, len)?.into_array(),
224        };
225    }
226
227    if depth > 0 {
228        check_containers(array, ctx)?;
229    }
230
231    Ok(())
232}