Skip to main content

vortex_array/arrays/
arbitrary.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::iter;
5use std::ops::RangeInclusive;
6use std::sync::Arc;
7
8use arbitrary::Arbitrary;
9use arbitrary::Error::IncorrectFormat;
10use arbitrary::Result;
11use arbitrary::Unstructured;
12use vortex_buffer::BitBuffer;
13use vortex_buffer::Buffer;
14use vortex_error::VortexExpect;
15
16use crate::ArrayRef;
17use crate::IntoArray;
18use crate::arrays::BoolArray;
19use crate::arrays::ChunkedArray;
20use crate::arrays::NullArray;
21use crate::arrays::Primitive;
22use crate::arrays::PrimitiveArray;
23use crate::arrays::StructArray;
24use crate::arrays::VarBinArray;
25use crate::arrays::VarBinViewArray;
26use crate::arrays::primitive::PrimitiveArrayExt;
27use crate::builders::ArrayBuilder;
28use crate::builders::DecimalBuilder;
29use crate::builders::FixedSizeListBuilder;
30use crate::builders::ListViewBuilder;
31use crate::builders::MapBuilder;
32use crate::dtype::DType;
33use crate::dtype::IntegerPType;
34use crate::dtype::MapDType;
35use crate::dtype::NativePType;
36use crate::dtype::Nullability;
37use crate::dtype::OffsetBuilderPType;
38use crate::dtype::PType;
39use crate::scalar::Scalar;
40use crate::scalar::arbitrary::random_scalar;
41use crate::validity::Validity;
42
43/// A wrapper type to implement `Arbitrary` for `ArrayRef`.
44#[derive(Clone, Debug)]
45pub struct ArbitraryArray(pub ArrayRef);
46
47/// Trait for generating arbitrary values with a caller-provided configuration.
48pub trait ArbitraryWith<'a, C>: Sized {
49    /// Generate an arbitrary value using the provided configuration.
50    fn arbitrary_with_config(u: &mut Unstructured<'a>, config: &C) -> Result<Self>;
51}
52
53/// Configuration for arbitrary array generation.
54#[derive(Clone, Debug)]
55pub struct ArbitraryArrayConfig {
56    /// Fixed dtype, or `None` to generate one from [`Unstructured`].
57    pub dtype: Option<DType>,
58    /// Inclusive range for the total array length.
59    pub len: RangeInclusive<usize>,
60}
61
62impl<'a> ArbitraryWith<'a, ArbitraryArrayConfig> for ArbitraryArray {
63    fn arbitrary_with_config(
64        u: &mut Unstructured<'a>,
65        config: &ArbitraryArrayConfig,
66    ) -> Result<Self> {
67        if config.len.is_empty() {
68            return Err(IncorrectFormat);
69        }
70
71        let dtype = match &config.dtype {
72            Some(dtype) => dtype.clone(),
73            None => u.arbitrary()?,
74        };
75        let len = u.int_in_range(config.len.clone())?;
76
77        random_array(u, &dtype, Some(len)).map(ArbitraryArray)
78    }
79}
80
81fn split_number_into_parts(n: usize, parts: usize) -> Vec<usize> {
82    let reminder = n % parts;
83    let division = (n - reminder) / parts;
84    iter::repeat_n(division, parts - reminder)
85        .chain(iter::repeat_n(division + 1, reminder))
86        .collect()
87}
88
89/// Creates a random array with a random number of chunks.
90fn random_array(u: &mut Unstructured, dtype: &DType, len: Option<usize>) -> Result<ArrayRef> {
91    let num_chunks = u.int_in_range(1..=3)?;
92    let chunk_lens = len.map(|l| split_number_into_parts(l, num_chunks));
93    let mut chunks = (0..num_chunks)
94        .map(|i| {
95            let chunk_len = chunk_lens.as_ref().map(|c| c[i]);
96            random_array_chunk(u, dtype, chunk_len)
97        })
98        .collect::<Result<Vec<_>>>()?;
99
100    if chunks.len() == 1 {
101        Ok(chunks.remove(0))
102    } else {
103        let dtype = chunks[0].dtype().clone();
104        Ok(ChunkedArray::try_new(chunks, dtype)
105            .vortex_expect("operation should succeed in arbitrary impl")
106            .into_array())
107    }
108}
109
110/// Creates a random array chunk.
111fn random_array_chunk(
112    u: &mut Unstructured<'_>,
113    dtype: &DType,
114    chunk_len: Option<usize>,
115) -> Result<ArrayRef> {
116    match dtype {
117        DType::Null => Ok(NullArray::new(
118            chunk_len
119                .map(Ok)
120                .unwrap_or_else(|| u.int_in_range(0..=100))?,
121        )
122        .into_array()),
123        DType::Bool(n) => random_bool(u, *n, chunk_len),
124        DType::Primitive(ptype, n) => match ptype {
125            PType::U8 => random_primitive::<u8>(u, *n, chunk_len),
126            PType::U16 => random_primitive::<u16>(u, *n, chunk_len),
127            PType::U32 => random_primitive::<u32>(u, *n, chunk_len),
128            PType::U64 => random_primitive::<u64>(u, *n, chunk_len),
129            PType::I8 => random_primitive::<i8>(u, *n, chunk_len),
130            PType::I16 => random_primitive::<i16>(u, *n, chunk_len),
131            PType::I32 => random_primitive::<i32>(u, *n, chunk_len),
132            PType::I64 => random_primitive::<i64>(u, *n, chunk_len),
133            PType::F16 => {
134                let prim = random_primitive::<u16>(u, *n, chunk_len)?
135                    .as_::<Primitive>()
136                    .reinterpret_cast(PType::F16)
137                    .into_array();
138                Ok(prim)
139            }
140            PType::F32 => random_primitive::<f32>(u, *n, chunk_len),
141            PType::F64 => random_primitive::<f64>(u, *n, chunk_len),
142        },
143        d @ DType::Decimal(decimal, n) => {
144            let elem_len = chunk_len.unwrap_or(u.int_in_range(0..=20)?);
145            let mut builder = DecimalBuilder::new_in(
146                *decimal,
147                *n,
148                vortex_buffer::BufferAllocatorRef::static_ref(),
149            );
150            for _ in 0..elem_len {
151                let scalar = random_scalar(u, d)?;
152                builder
153                    .append_scalar(&scalar)
154                    .vortex_expect("random scalar has the builder's decimal dtype");
155            }
156            Ok(builder.finish())
157        }
158        DType::Utf8(n) => random_string(u, *n, chunk_len),
159        DType::Binary(n) => random_bytes(u, *n, chunk_len),
160        DType::List(elem_dtype, null) => random_list(u, elem_dtype, *null, chunk_len),
161        DType::FixedSizeList(elem_dtype, list_size, null) => {
162            random_fixed_size_list(u, elem_dtype, *list_size, *null, chunk_len)
163        }
164        DType::Map(map_dtype, nullability) => {
165            random_map(u, map_dtype.clone(), *nullability, chunk_len)
166        }
167        DType::Struct(sdt, n) => {
168            let first_array = sdt
169                .fields()
170                .next()
171                .map(|d| random_array(u, &d, chunk_len))
172                .transpose()?;
173            let resolved_len = first_array
174                .as_ref()
175                .map(|a| a.len())
176                .or(chunk_len)
177                .map(Ok)
178                .unwrap_or_else(|| u.int_in_range(0..=100))?;
179            let children = first_array
180                .into_iter()
181                .map(Ok)
182                .chain(
183                    sdt.fields()
184                        .skip(1)
185                        .map(|d| random_array(u, &d, Some(resolved_len))),
186                )
187                .collect::<Result<Vec<_>>>()?;
188            Ok(StructArray::try_new(
189                sdt.names().clone(),
190                children,
191                resolved_len,
192                random_validity(u, *n, resolved_len)?,
193            )
194            .vortex_expect("operation should succeed in arbitrary impl")
195            .into_array())
196        }
197        DType::Union(..) | DType::Variant(_) | DType::Extension(..) => Err(IncorrectFormat),
198    }
199}
200
201fn random_map(
202    u: &mut Unstructured,
203    map_dtype: MapDType,
204    nullability: Nullability,
205    chunk_len: Option<usize>,
206) -> Result<ArrayRef> {
207    let array_length = chunk_len.unwrap_or(u.int_in_range(0..=20)?);
208    let key_dtype = map_dtype.key_dtype();
209    let value_dtype = map_dtype.value_dtype();
210    let dtype = DType::Map(map_dtype.clone(), nullability);
211    let mut builder = MapBuilder::<u64, u64>::with_capacity_in(
212        map_dtype,
213        nullability,
214        array_length,
215        vortex_buffer::BufferAllocatorRef::static_ref(),
216    );
217
218    for _ in 0..array_length {
219        if nullability == Nullability::Nullable && u.arbitrary::<bool>()? {
220            builder.append_null();
221        } else {
222            let entry_count = u.int_in_range(0..=20)?;
223            let entries = (0..entry_count)
224                .map(|_| {
225                    let key = random_scalar(u, &key_dtype)?;
226                    let value = random_scalar(u, &value_dtype)?;
227                    Ok((key, value))
228                })
229                .collect::<Result<Vec<_>>>()?;
230            let scalar = Scalar::try_map(dtype.clone(), entries)
231                .vortex_expect("generated map scalar should be valid");
232            builder
233                .append_scalar(&scalar)
234                .vortex_expect("generated map scalar should append");
235        }
236    }
237
238    Ok(builder.finish_into_map().into_array())
239}
240
241/// Creates a random fixed-size list array.
242///
243/// If the `chunk_len` is specified, the length of the array will be equal to the chunk length.
244fn random_fixed_size_list(
245    u: &mut Unstructured,
246    elem_dtype: &Arc<DType>,
247    list_size: u32,
248    null: Nullability,
249    chunk_len: Option<usize>,
250) -> Result<ArrayRef> {
251    let array_length = chunk_len.unwrap_or(u.int_in_range(0..=20)?);
252
253    let mut builder = FixedSizeListBuilder::with_capacity_in(
254        Arc::clone(elem_dtype),
255        list_size,
256        null,
257        array_length,
258        vortex_buffer::BufferAllocatorRef::static_ref(),
259    );
260
261    for _ in 0..array_length {
262        if null == Nullability::Nullable && u.arbitrary::<bool>()? {
263            builder.append_null();
264        } else {
265            builder
266                .append_value(random_list_scalar(u, elem_dtype, list_size, null)?.as_list())
267                .vortex_expect("can append value");
268        }
269    }
270
271    Ok(builder.finish())
272}
273
274/// Creates a random list array.
275///
276/// If the `chunk_len` is specified, the length of the array will be equal to the chunk length.
277fn random_list(
278    u: &mut Unstructured,
279    elem_dtype: &Arc<DType>,
280    null: Nullability,
281    chunk_len: Option<usize>,
282) -> Result<ArrayRef> {
283    let array_length = chunk_len.unwrap_or(u.int_in_range(0..=20)?);
284    // Worst-case total elements: each list can have up to 20 elements.
285    let max_total_elements = array_length as u64 * 20;
286
287    match u.int_in_range(0..=3)? {
288        0 if i32::max_value_as_u64() >= max_total_elements => {
289            random_list_with_offset_type::<i32>(u, elem_dtype, null, array_length)
290        }
291        1 if u32::max_value_as_u64() >= max_total_elements => {
292            random_list_with_offset_type::<u32>(u, elem_dtype, null, array_length)
293        }
294        // i64 and u64 always fit; also the fallback for when narrower types don't.
295        _ => {
296            if u.arbitrary::<bool>()? {
297                random_list_with_offset_type::<i64>(u, elem_dtype, null, array_length)
298            } else {
299                random_list_with_offset_type::<u64>(u, elem_dtype, null, array_length)
300            }
301        }
302    }
303}
304
305/// Creates a random list array with the given [`OffsetBuilderPType`] for the internal offsets child.
306fn random_list_with_offset_type<O: OffsetBuilderPType>(
307    u: &mut Unstructured,
308    elem_dtype: &Arc<DType>,
309    null: Nullability,
310    array_length: usize,
311) -> Result<ArrayRef> {
312    let mut builder = ListViewBuilder::<O, O>::with_capacity_in(
313        Arc::clone(elem_dtype),
314        null,
315        10,
316        vortex_buffer::BufferAllocatorRef::static_ref(),
317    );
318
319    for _ in 0..array_length {
320        if null == Nullability::Nullable && u.arbitrary::<bool>()? {
321            builder.append_null();
322        } else {
323            let list_size = u.int_in_range(0..=20)?;
324            builder
325                .append_value(random_list_scalar(u, elem_dtype, list_size, null)?.as_list())
326                .vortex_expect("can append value");
327        }
328    }
329
330    Ok(builder.finish())
331}
332
333/// Creates a random list scalar with the specified list size.
334fn random_list_scalar(
335    u: &mut Unstructured,
336    elem_dtype: &Arc<DType>,
337    list_size: u32,
338    null: Nullability,
339) -> Result<Scalar> {
340    let elems = (0..list_size)
341        .map(|_| random_scalar(u, elem_dtype))
342        .collect::<Result<Vec<_>>>()?;
343    Ok(Scalar::list(Arc::clone(elem_dtype), elems, null))
344}
345
346fn random_string(
347    u: &mut Unstructured,
348    nullability: Nullability,
349    len: Option<usize>,
350) -> Result<ArrayRef> {
351    match nullability {
352        Nullability::NonNullable => {
353            let v = arbitrary_vec_of_len::<String>(u, len)?;
354            Ok(match u.int_in_range(0..=1)? {
355                0 => VarBinArray::from_vec(v, DType::Utf8(Nullability::NonNullable)).into_array(),
356                1 => VarBinViewArray::from_iter_str(v).into_array(),
357                _ => unreachable!(),
358            })
359        }
360        Nullability::Nullable => {
361            let v = arbitrary_vec_of_len::<Option<String>>(u, len)?;
362            Ok(match u.int_in_range(0..=1)? {
363                0 => VarBinArray::from_iter(v, DType::Utf8(Nullability::Nullable)).into_array(),
364                1 => VarBinViewArray::from_iter_nullable_str(v).into_array(),
365                _ => unreachable!(),
366            })
367        }
368    }
369}
370
371fn random_bytes(
372    u: &mut Unstructured,
373    nullability: Nullability,
374    len: Option<usize>,
375) -> Result<ArrayRef> {
376    match nullability {
377        Nullability::NonNullable => {
378            let v = arbitrary_vec_of_len::<Vec<u8>>(u, len)?;
379            Ok(match u.int_in_range(0..=1)? {
380                0 => VarBinArray::from_vec(v, DType::Binary(Nullability::NonNullable)).into_array(),
381                1 => VarBinViewArray::from_iter_bin(v).into_array(),
382                _ => unreachable!(),
383            })
384        }
385        Nullability::Nullable => {
386            let v = arbitrary_vec_of_len::<Option<Vec<u8>>>(u, len)?;
387            Ok(match u.int_in_range(0..=1)? {
388                0 => VarBinArray::from_iter(v, DType::Binary(Nullability::Nullable)).into_array(),
389                1 => VarBinViewArray::from_iter_nullable_bin(v).into_array(),
390                _ => unreachable!(),
391            })
392        }
393    }
394}
395
396fn random_primitive<'a, T: Arbitrary<'a> + NativePType>(
397    u: &mut Unstructured<'a>,
398    nullability: Nullability,
399    len: Option<usize>,
400) -> Result<ArrayRef> {
401    let v = arbitrary_vec_of_len::<T>(u, len)?;
402    let validity = random_validity(u, nullability, v.len())?;
403    Ok(PrimitiveArray::new(Buffer::copy_from(v), validity).into_array())
404}
405
406fn random_bool(
407    u: &mut Unstructured,
408    nullability: Nullability,
409    len: Option<usize>,
410) -> Result<ArrayRef> {
411    let v = arbitrary_vec_of_len(u, len)?;
412    let validity = random_validity(u, nullability, v.len())?;
413    Ok(BoolArray::new(BitBuffer::from(v), validity).into_array())
414}
415
416pub fn random_validity(
417    u: &mut Unstructured,
418    nullability: Nullability,
419    len: usize,
420) -> Result<Validity> {
421    match nullability {
422        Nullability::NonNullable => Ok(Validity::NonNullable),
423        Nullability::Nullable => Ok(match u.int_in_range(0..=2)? {
424            0 => Validity::AllValid,
425            1 => Validity::AllInvalid,
426            2 => Validity::from_iter(arbitrary_vec_of_len::<bool>(u, Some(len))?),
427            _ => unreachable!(),
428        }),
429    }
430}
431
432fn arbitrary_vec_of_len<'a, T: Arbitrary<'a>>(
433    u: &mut Unstructured<'a>,
434    len: Option<usize>,
435) -> Result<Vec<T>> {
436    len.map(|l| (0..l).map(|_| T::arbitrary(u)).collect::<Result<Vec<_>>>())
437        .unwrap_or_else(|| Vec::<T>::arbitrary(u))
438}