Skip to main content

vortex_array/arrays/list/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::sync::Arc;
7
8use num_traits::AsPrimitive;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_ensure_eq;
14
15use crate::ArrayRef;
16use crate::ArraySlots;
17use crate::Canonical;
18use crate::ExecutionCtx;
19use crate::IntoArray;
20use crate::array::Array;
21use crate::array::ArrayParts;
22use crate::array::TypedArrayRef;
23use crate::array::child_to_validity;
24use crate::array::validity_to_child;
25use crate::array_slots;
26use crate::arrays::ConstantArray;
27use crate::arrays::List;
28use crate::arrays::ListArray;
29use crate::arrays::Primitive;
30use crate::arrays::PrimitiveArray;
31use crate::builtins::ArrayBuiltins;
32use crate::dtype::DType;
33use crate::dtype::IntegerPType;
34use crate::match_each_integer_ptype;
35use crate::match_each_native_ptype;
36use crate::optimizer::ArrayOptimizer;
37use crate::scalar::NumericOperator;
38use crate::scalar::ScalarValue;
39use crate::stats::Precision;
40use crate::stats::Stat;
41use crate::validity::Validity;
42
43#[array_slots(List)]
44pub struct ListSlots {
45    /// The elements data array containing all list elements concatenated together.
46    #[slot(0)]
47    pub elements: ArrayRef,
48    /// The offsets array defining the start/end of each list within the elements array.
49    #[slot(1)]
50    pub offsets: ArrayRef,
51    /// The validity bitmap indicating which list elements are non-null.
52    #[slot(2)]
53    pub validity_child: Option<ArrayRef>,
54}
55
56/// A list array that stores variable-length lists of elements, similar to `Vec<Vec<T>>`.
57///
58/// This mirrors the Apache Arrow List array encoding and provides efficient storage
59/// for nested data where each row contains a list of elements of the same type.
60///
61/// ## Data Layout
62///
63/// The list array uses an offset-based encoding:
64/// - **Elements array**: A flat array containing all list elements concatenated together
65/// - **Offsets array**: Integer array where `offsets[i]` is an (inclusive) start index into
66///   the **elements** and `offsets[i+1]` is the (exclusive) stop index for the `i`th list.
67/// - **Validity**: Optional mask indicating which lists are null
68///
69/// This allows for excellent cascading compression of the elements and offsets, as similar values
70/// are clustered together and the offsets have a predictable pattern and small deltas between
71/// consecutive elements.
72///
73/// ## Offset Semantics
74///
75/// - Offsets must be non-nullable integers (i32, i64, etc.)
76/// - Offsets array has length `n+1` where `n` is the number of lists
77/// - List `i` contains elements from `elements[offsets[i]..offsets[i+1]]`
78/// - Offsets must be monotonically increasing
79///
80/// # Examples
81///
82/// ```
83/// use vortex_array::arrays::{ListArray, PrimitiveArray};
84/// use vortex_array::arrays::list::ListArrayExt;
85/// use vortex_array::validity::Validity;
86/// use vortex_session::VortexSession;
87/// use vortex_array::{IntoArray, VortexSessionExecute};
88/// use vortex_buffer::buffer;
89/// use std::sync::Arc;
90///
91/// // Create a list array representing [[1, 2], [3, 4, 5], []]
92/// let elements = buffer![1i32, 2, 3, 4, 5].into_array();
93/// let offsets = buffer![0u32, 2, 5, 5].into_array(); // 3 lists
94///
95/// let mut ctx = VortexSession::empty().create_execution_ctx();
96/// let list_array = ListArray::try_new(
97///     elements.into_array(),
98///     offsets.into_array(),
99///     Validity::NonNullable,
100///     &mut ctx,
101/// ).unwrap();
102///
103/// assert_eq!(list_array.len(), 3);
104///
105/// // Access individual lists
106/// let first_list = list_array.list_elements_at(0, &mut ctx).unwrap();
107/// assert_eq!(first_list.len(), 2); // [1, 2]
108///
109/// let third_list = list_array.list_elements_at(2, &mut ctx).unwrap();
110/// assert!(third_list.is_empty()); // []
111/// ```
112#[derive(Clone, Debug, Default)]
113pub struct ListData;
114
115impl Display for ListData {
116    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
117        Ok(())
118    }
119}
120
121pub struct ListDataParts {
122    pub elements: ArrayRef,
123    pub offsets: ArrayRef,
124    pub validity: Validity,
125    pub dtype: DType,
126}
127
128impl ListData {
129    pub(crate) fn make_slots(
130        elements: &ArrayRef,
131        offsets: &ArrayRef,
132        validity: &Validity,
133        len: usize,
134    ) -> ArraySlots {
135        ListSlots {
136            elements: elements.clone(),
137            offsets: offsets.clone(),
138            validity_child: validity_to_child(validity, len),
139        }
140        .into_slots()
141    }
142
143    /// Creates a new `ListArray`.
144    ///
145    /// # Panics
146    ///
147    /// Panics if the provided components do not satisfy the invariants documented
148    /// in `ListArray::new_unchecked`.
149    pub fn build(
150        elements: ArrayRef,
151        offsets: ArrayRef,
152        validity: Validity,
153        ctx: &mut ExecutionCtx,
154    ) -> Self {
155        Self::try_build(elements, offsets, validity, ctx).vortex_expect("ListArray new")
156    }
157
158    /// Constructs a new `ListArray`.
159    ///
160    /// See `ListArray::new_unchecked` for more information.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error if the provided components do not satisfy the invariants documented in
165    /// `ListArray::new_unchecked`.
166    pub(crate) fn try_build(
167        elements: ArrayRef,
168        offsets: ArrayRef,
169        validity: Validity,
170        ctx: &mut ExecutionCtx,
171    ) -> VortexResult<Self> {
172        Self::validate(&elements, &offsets, &validity, ctx)?;
173
174        // SAFETY: validate ensures all invariants are met.
175        Ok(unsafe { Self::new_unchecked() })
176    }
177
178    /// Creates a new `ListArray` without validation from these components:
179    ///
180    /// * `elements` is a flat array containing all list elements concatenated.
181    /// * `offsets` is an integer array where `offsets[i]` is the start index for list `i`.
182    /// * `validity` holds the null values.
183    ///
184    /// # Safety
185    ///
186    /// The caller must ensure all of the following invariants are satisfied:
187    ///
188    /// - Offsets must be a non-nullable integer array.
189    /// - Offsets must have at least one element (even for empty lists, it should contain \[0\]).
190    /// - Offsets must be sorted (monotonically increasing).
191    /// - All offset values must be non-negative.
192    /// - The maximum offset must not exceed `elements.len()`.
193    /// - If validity is an array, its length must equal `offsets.len() - 1`.
194    pub unsafe fn new_unchecked() -> Self {
195        Self
196    }
197
198    /// Validates the components that would be used to create a `ListArray`.
199    ///
200    /// This function checks all the invariants required by `ListArray::new_unchecked`.
201    pub fn validate(
202        elements: &ArrayRef,
203        offsets: &ArrayRef,
204        validity: &Validity,
205        ctx: &mut ExecutionCtx,
206    ) -> VortexResult<()> {
207        // Offsets must have at least one element
208        vortex_ensure!(
209            !offsets.is_empty(),
210            "Offsets must have at least one element, [0] for an empty list"
211        );
212
213        // Offsets must be of integer type, and cannot go lower than 0.
214        vortex_ensure!(
215            offsets.dtype().is_int() && !offsets.dtype().is_nullable(),
216            "offsets have invalid type {}",
217            offsets.dtype()
218        );
219
220        // Known gap: device-resident offsets cannot be read here, so only host-resident offsets
221        // are validated. Device consumers must not assume device offsets were checked.
222        if offsets.is_host() {
223            // Read the offset values and do not use the statistics of `offsets`. Statistics can
224            // come from untrusted input, for example a serialized file.
225            // TODO: keep this executed primitive array on the created ListArray to avoid re-decoding.
226            let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
227            let elements_len = elements.len();
228
229            match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |P| {
230                Self::validate_offset_slice(
231                    offsets,
232                    primitive_offsets.as_slice::<P>(),
233                    elements_len,
234                )
235            })?;
236        }
237
238        // If a validity array is present, it must be the same length as the ListArray
239        if let Some(validity_len) = validity.maybe_len() {
240            vortex_ensure_eq!(
241                validity_len,
242                offsets.len() - 1,
243                "validity length does not match array size",
244            );
245        }
246
247        Ok(())
248    }
249
250    fn validate_offset_slice<P>(
251        offsets: &ArrayRef,
252        offsets_slice: &[P],
253        elements_len: usize,
254    ) -> VortexResult<()>
255    where
256        P: IntegerPType + TryFrom<usize> + Into<ScalarValue>,
257    {
258        // Offsets must be sorted (but not strictly sorted, zero-length lists are allowed).
259        if let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1]) {
260            vortex_bail!(
261                "offsets must be sorted, but offset {} at index {idx} is greater than \
262                 offset {} at index {}",
263                offsets_slice[idx],
264                offsets_slice[idx + 1],
265                idx + 1
266            );
267        }
268
269        // The offsets are sorted, thus the first offset is the minimum and the last
270        // offset is the maximum.
271        if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
272            vortex_ensure!(
273                min >= P::zero(),
274                "offsets minimum {min} outside valid range [0, {max}]"
275            );
276
277            // An offset type too narrow for the elements length cannot exceed it.
278            vortex_ensure!(
279                P::try_from(elements_len).ok().is_none_or(|len| max <= len),
280                "Max offset {max} is beyond the length of the elements array {elements_len}"
281            );
282
283            // The checked values are exact, so keep them as statistics. This
284            // replaces any untrusted statistics on `offsets` and saves later scans.
285            let stats = offsets.statistics();
286            stats.set(Stat::IsSorted, Precision::exact(true));
287            stats.set(Stat::Min, Precision::exact(min));
288            stats.set(Stat::Max, Precision::exact(max));
289        }
290
291        Ok(())
292    }
293    // TODO(connor)[ListView]: Create 2 functions `reset_offsets` and `recursive_reset_offsets`,
294    // where `reset_offsets` is infallible.
295    // Also, `reset_offsets` can be made more efficient by replacing `sub_scalar` with a match on
296    // the offset type and manual subtraction.
297}
298
299pub trait ListArrayExt: TypedArrayRef<List> {
300    fn nullability(&self) -> crate::dtype::Nullability {
301        match self.dtype() {
302            DType::List(_, nullability) => *nullability,
303            _ => unreachable!("ListArrayExt requires a list dtype"),
304        }
305    }
306
307    fn list_validity(&self) -> Validity {
308        child_to_validity(self.validity_child(), self.nullability())
309    }
310
311    fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
312        vortex_ensure!(
313            index <= self.len(),
314            "Index {index} out of bounds 0..={}",
315            self.len()
316        );
317
318        if let Some(p) = self.offsets().as_opt::<Primitive>() {
319            Ok(match_each_native_ptype!(p.ptype(), |P| {
320                p.as_slice::<P>()[index].as_()
321            }))
322        } else {
323            self.offsets()
324                .execute_scalar(index, ctx)?
325                .as_primitive()
326                .as_::<usize>()
327                .ok_or_else(|| vortex_error::vortex_err!("offset value does not fit in usize"))
328        }
329    }
330
331    fn list_elements_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
332        let start = self.offset_at(index, ctx)?;
333        let end = self.offset_at(index + 1, ctx)?;
334        self.elements().slice(start..end)?.optimize_ctx(ctx)
335    }
336
337    fn sliced_elements(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
338        let start = self.offset_at(0, ctx)?;
339        let end = self.offset_at(self.len(), ctx)?;
340        self.elements().slice(start..end)?.optimize_ctx(ctx)
341    }
342
343    fn element_dtype(&self) -> &DType {
344        self.elements().dtype()
345    }
346
347    fn reset_offsets(&self, recurse: bool, ctx: &mut ExecutionCtx) -> VortexResult<Array<List>> {
348        let mut elements = self.sliced_elements(ctx)?;
349        if recurse && elements.is_canonical() {
350            let compacted = elements
351                .execute::<Canonical>(ctx)?
352                .compact(ctx)?
353                .into_array();
354            elements = compacted;
355        } else if recurse && let Some(child_list_array) = elements.as_opt::<List>() {
356            elements = child_list_array
357                .into_owned()
358                .reset_offsets(recurse, ctx)?
359                .into_array();
360        }
361
362        let offsets = self.offsets();
363        let first_offset = offsets.execute_scalar(0, ctx)?;
364        let adjusted_offsets = if first_offset.is_zero() == Some(true) {
365            offsets.clone()
366        } else {
367            offsets.clone().numeric(
368                ConstantArray::new(first_offset, offsets.len()).into_array(),
369                NumericOperator::Sub,
370            )?
371        };
372
373        // SAFETY: By resetting the offsets we simply "shift" everything left and discard trailing garbage, so all invariants remain the same.
374        Ok(unsafe { ListArray::new_unchecked(elements, adjusted_offsets, self.list_validity()) })
375    }
376}
377impl<T: TypedArrayRef<List>> ListArrayExt for T {}
378
379impl Array<List> {
380    /// Creates a new `ListArray`.
381    pub fn new(
382        elements: ArrayRef,
383        offsets: ArrayRef,
384        validity: Validity,
385        ctx: &mut ExecutionCtx,
386    ) -> Self {
387        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
388        let len = offsets.len().saturating_sub(1);
389        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
390        let data = ListData::build(elements, offsets, validity, ctx);
391        unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) }
392    }
393
394    /// Constructs a new `ListArray`.
395    pub fn try_new(
396        elements: ArrayRef,
397        offsets: ArrayRef,
398        validity: Validity,
399        ctx: &mut ExecutionCtx,
400    ) -> VortexResult<Self> {
401        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
402        let len = offsets.len().saturating_sub(1);
403        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
404        let data = ListData::try_build(elements, offsets, validity, ctx)?;
405        Ok(unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) })
406    }
407
408    /// Creates a new `ListArray` without validation.
409    ///
410    /// # Safety
411    ///
412    /// See [`ListData::new_unchecked`].
413    pub unsafe fn new_unchecked(elements: ArrayRef, offsets: ArrayRef, validity: Validity) -> Self {
414        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
415        let len = offsets.len().saturating_sub(1);
416        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
417        let data = unsafe { ListData::new_unchecked() };
418        unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) }
419    }
420
421    pub fn into_data_parts(self) -> ListDataParts {
422        let dtype = self.dtype().clone();
423        let elements = self.elements().clone();
424        let offsets = self.offsets().clone();
425        let validity = self.list_validity();
426        ListDataParts {
427            elements,
428            offsets,
429            validity,
430            dtype,
431        }
432    }
433}