Skip to main content

vortex_array/arrays/chunked/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! First-class chunked arrays.
5//!
6//! Vortex is a chunked array library that's able to
7
8use std::fmt::Debug;
9use std::fmt::Display;
10use std::fmt::Formatter;
11
12use futures::stream;
13use vortex_buffer::Buffer;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_bail;
17
18use crate::ArrayRef;
19use crate::ArraySlots;
20use crate::Canonical;
21use crate::ExecutionCtx;
22use crate::IntoArray;
23use crate::array::Array;
24use crate::array::ArrayParts;
25use crate::array::TypedArrayRef;
26use crate::array_slots;
27use crate::arrays::Chunked;
28use crate::arrays::PrimitiveArray;
29use crate::dtype::DType;
30use crate::iter::ArrayIterator;
31use crate::iter::ArrayIteratorAdapter;
32use crate::search_sorted::SearchSorted;
33use crate::search_sorted::SearchSortedSide;
34use crate::stream::ArrayStream;
35use crate::stream::ArrayStreamAdapter;
36use crate::validity::Validity;
37
38/// Slot layout of a [`Chunked`] array: `[chunk_offsets, chunks...]`.
39#[array_slots(Chunked)]
40pub struct ChunkedSlots {
41    /// The non-nullable `u64` array of cumulative chunk offsets.
42    #[slot(0)]
43    pub chunk_offsets: ArrayRef,
44    /// The chunk arrays, each sharing the outer dtype.
45    #[slot(1..)]
46    pub chunks: Vec<ArrayRef>,
47}
48
49#[derive(Clone, Debug)]
50pub struct ChunkedData {
51    pub(super) chunk_offsets: Vec<usize>,
52    /// The next child to visit while executing slots or appending into a builder.
53    pub(super) next_child_slot: usize,
54}
55
56impl Display for ChunkedData {
57    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
58        write!(f, "nchunks: {}", self.chunk_offsets.len().saturating_sub(1))
59    }
60}
61
62pub trait ChunkedArrayExt: TypedArrayRef<Chunked> {
63    fn nchunks(&self) -> usize {
64        ChunkedArraySlotsExt::chunks(self).len()
65    }
66
67    fn chunk(&self, idx: usize) -> &ArrayRef {
68        ChunkedArraySlotsExt::chunks(self)
69            .get(idx)
70            .vortex_expect("chunk index out of bounds")
71    }
72
73    fn iter_chunks(&self) -> impl Iterator<Item = &ArrayRef> {
74        ChunkedArraySlotsExt::chunks(self).iter()
75    }
76
77    fn chunks(&self) -> Vec<ArrayRef> {
78        self.iter_chunks().cloned().collect()
79    }
80
81    fn non_empty_chunks(&self) -> impl Iterator<Item = &ArrayRef> {
82        self.iter_chunks().filter(|chunk| !chunk.is_empty())
83    }
84
85    /// Returns the cached chunk boundary offsets.
86    fn chunk_offset_values(&self) -> &[usize] {
87        &self.chunk_offsets
88    }
89
90    fn find_chunk_idx(&self, index: usize) -> VortexResult<(usize, usize)> {
91        assert!(index <= self.len(), "Index out of bounds of the array");
92        let chunk_offset_values = self.chunk_offset_values();
93        let index_chunk = chunk_offset_values
94            .search_sorted(&index, SearchSortedSide::Right)?
95            .to_ends_index(self.nchunks() + 1)
96            .saturating_sub(1);
97        let chunk_start = chunk_offset_values[index_chunk];
98        let index_in_chunk = index - chunk_start;
99        Ok((index_chunk, index_in_chunk))
100    }
101
102    fn array_iterator(&self) -> impl ArrayIterator + '_ {
103        ArrayIteratorAdapter::new(
104            self.dtype().clone(),
105            self.iter_chunks().map(|chunk| Ok(chunk.clone())),
106        )
107    }
108
109    fn array_stream(&self) -> impl ArrayStream + '_ {
110        ArrayStreamAdapter::new(
111            self.dtype().clone(),
112            stream::iter(self.iter_chunks().map(|chunk| Ok(chunk.clone()))),
113        )
114    }
115}
116impl<T: TypedArrayRef<Chunked>> ChunkedArrayExt for T {}
117
118impl ChunkedData {
119    pub(super) fn new(chunk_offsets: Vec<usize>) -> Self {
120        Self {
121            chunk_offsets,
122            next_child_slot: ChunkedSlots::CHUNKS_OFFSET,
123        }
124    }
125
126    pub(super) fn make_chunk_offsets_array(chunk_offsets: &[usize]) -> ArrayRef {
127        let chunk_offsets_buf =
128            Buffer::from_trusted_len_iter(chunk_offsets.iter().copied().map(|offset| {
129                u64::try_from(offset)
130                    .vortex_expect("chunk offset must fit in u64 for serialization")
131            }));
132
133        unsafe { PrimitiveArray::new_unchecked(chunk_offsets_buf, Validity::NonNullable) }
134            .into_array()
135    }
136
137    /// Validates the components that would be used to create a `ChunkedArray`.
138    ///
139    /// This function checks all the invariants required by `ChunkedArray::new_unchecked`.
140    pub fn validate(chunks: &[ArrayRef], dtype: &DType) -> VortexResult<()> {
141        for chunk in chunks {
142            if chunk.dtype() != dtype {
143                vortex_bail!("expected type: {} but instead got {}", dtype, chunk.dtype());
144            }
145        }
146
147        Ok(())
148    }
149}
150
151impl Array<Chunked> {
152    fn parts_from_chunks<const VALIDATE: bool>(
153        chunks: impl IntoIterator<Item = ArrayRef>,
154        dtype: DType,
155    ) -> VortexResult<ArrayParts<Chunked>> {
156        let chunks = chunks.into_iter();
157        let (lower, _) = chunks.size_hint();
158        Self::parts_from_chunks_with_capacity::<VALIDATE>(chunks, dtype, lower)
159    }
160
161    fn parts_from_chunks_with_capacity<const VALIDATE: bool>(
162        chunks: impl IntoIterator<Item = ArrayRef>,
163        dtype: DType,
164        capacity: usize,
165    ) -> VortexResult<ArrayParts<Chunked>> {
166        let mut slots = ArraySlots::with_capacity(ChunkedSlots::CHUNKS_OFFSET + capacity);
167        slots.push(None);
168        let mut chunk_offsets = Vec::with_capacity(capacity + 1);
169        chunk_offsets.push(0);
170        let mut len = 0usize;
171
172        for chunk in chunks {
173            if VALIDATE {
174                Self::validate_chunk_dtype(&chunk, &dtype)?;
175            }
176            len += chunk.len();
177            chunk_offsets.push(len);
178            slots.push(Some(chunk));
179        }
180
181        Ok(Self::parts_from_slots(dtype, len, chunk_offsets, slots))
182    }
183
184    /// Checks that the chunk has the dtype of the array.
185    ///
186    /// This function is not generic, so each iterator type does not compile its own copy of the
187    /// error message.
188    fn validate_chunk_dtype(chunk: &ArrayRef, dtype: &DType) -> VortexResult<()> {
189        if chunk.dtype() != dtype {
190            vortex_bail!("expected type: {} but instead got {}", dtype, chunk.dtype());
191        }
192        Ok(())
193    }
194
195    /// Creates the parts from the collected chunk slots and offsets.
196    ///
197    /// This function is not generic, so each iterator type that `parts_from_chunks_with_capacity`
198    /// gets compiled for does not compile its own copy.
199    fn parts_from_slots(
200        dtype: DType,
201        len: usize,
202        chunk_offsets: Vec<usize>,
203        mut slots: ArraySlots,
204    ) -> ArrayParts<Chunked> {
205        slots[ChunkedSlots::CHUNK_OFFSETS] =
206            Some(ChunkedData::make_chunk_offsets_array(&chunk_offsets));
207        ArrayParts::new(Chunked, dtype, len, ChunkedData::new(chunk_offsets), slots)
208    }
209
210    pub(super) fn with_next_child_slot(self, next_child_slot: usize) -> Self {
211        self.with_data_mut(|data| data.next_child_slot = next_child_slot)
212    }
213
214    /// Constructs a new `ChunkedArray`.
215    pub fn try_new(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> VortexResult<Self> {
216        Self::try_from_chunked_parts(Self::parts_from_chunks::<true>(chunks, dtype)?)
217    }
218
219    pub fn rechunk(
220        &self,
221        target_bytesize: u64,
222        target_rowsize: usize,
223        ctx: &mut ExecutionCtx,
224    ) -> VortexResult<Self> {
225        let mut new_chunks = Vec::new();
226        let mut chunks_to_combine = Vec::new();
227        let mut new_chunk_n_bytes = 0;
228        let mut new_chunk_n_elements = 0;
229        for chunk in self.iter_chunks() {
230            let n_bytes = chunk.nbytes();
231            let n_elements = chunk.len();
232
233            if (new_chunk_n_bytes + n_bytes > target_bytesize
234                || new_chunk_n_elements + n_elements > target_rowsize)
235                && !chunks_to_combine.is_empty()
236            {
237                let canonical = unsafe {
238                    Array::<Chunked>::new_unchecked(
239                        chunks_to_combine.drain(..),
240                        self.dtype().clone(),
241                    )
242                }
243                .into_array()
244                .execute::<Canonical>(ctx)?
245                .into_array();
246                new_chunks.push(canonical);
247
248                new_chunk_n_bytes = 0;
249                new_chunk_n_elements = 0;
250            }
251
252            if n_bytes > target_bytesize || n_elements > target_rowsize {
253                new_chunks.push(chunk.clone());
254            } else {
255                new_chunk_n_bytes += n_bytes;
256                new_chunk_n_elements += n_elements;
257                chunks_to_combine.push(chunk.clone());
258            }
259        }
260
261        if !chunks_to_combine.is_empty() {
262            let canonical =
263                unsafe { Array::<Chunked>::new_unchecked(chunks_to_combine, self.dtype().clone()) }
264                    .into_array()
265                    .execute::<Canonical>(ctx)?
266                    .into_array();
267            new_chunks.push(canonical);
268        }
269
270        unsafe { Ok(Self::new_unchecked(new_chunks, self.dtype().clone())) }
271    }
272
273    /// Creates a new `ChunkedArray` without validation.
274    ///
275    /// # Safety
276    ///
277    /// All chunks must have exactly the same [`DType`] as the provided `dtype`.
278    pub unsafe fn new_unchecked(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> Self {
279        let chunks = chunks.into_iter();
280        let (expected_nchunks, _) = chunks.size_hint();
281        // SAFETY: the caller guarantees the dtype of every chunk.
282        unsafe { Self::new_unchecked_sized(chunks, dtype, expected_nchunks) }
283    }
284
285    /// Creates a chunked array without validation, reserving space for `expected_nchunks` chunks.
286    ///
287    /// The expected count is only an allocation hint: fewer or more chunks are allowed.
288    /// This is useful when iterator adapters such as `process_results` lose the source size hint.
289    ///
290    /// # Safety
291    ///
292    /// All chunks must have exactly the same [`DType`] as the provided `dtype`.
293    pub unsafe fn new_unchecked_sized(
294        chunks: impl IntoIterator<Item = ArrayRef>,
295        dtype: DType,
296        expected_nchunks: usize,
297    ) -> Self {
298        let parts = Self::parts_from_chunks_with_capacity::<false>(chunks, dtype, expected_nchunks)
299            .vortex_expect("unchecked chunked construction cannot fail");
300        // SAFETY: the caller guarantees the dtype of every chunk.
301        unsafe { Self::from_chunked_parts_unchecked(parts) }
302    }
303
304    /// Creates the array from parts after validation.
305    ///
306    /// The generic constructors call this function. It is not generic, so crates that call those
307    /// constructors do not each compile the `Chunked` array vtable.
308    fn try_from_chunked_parts(parts: ArrayParts<Chunked>) -> VortexResult<Self> {
309        Array::try_from_parts(parts)
310    }
311
312    /// Creates the array from parts without validation.
313    ///
314    /// The generic constructors call this function. It is not generic, so crates that call those
315    /// constructors do not each compile the `Chunked` array vtable.
316    ///
317    /// # Safety
318    ///
319    /// The parts must be logically consistent.
320    unsafe fn from_chunked_parts_unchecked(parts: ArrayParts<Chunked>) -> Self {
321        unsafe { Array::from_parts_unchecked(parts) }
322    }
323}
324
325impl FromIterator<ArrayRef> for Array<Chunked> {
326    fn from_iter<T: IntoIterator<Item = ArrayRef>>(iter: T) -> Self {
327        let mut chunks = iter.into_iter().peekable();
328        let dtype = chunks
329            .peek()
330            .map(|c| c.dtype().clone())
331            .vortex_expect("Cannot infer DType from an empty iterator");
332        Array::<Chunked>::try_new(chunks, dtype)
333            .vortex_expect("Failed to create chunked array from iterator")
334    }
335}
336
337#[cfg(test)]
338mod test {
339    use std::sync::LazyLock;
340
341    use itertools::Itertools;
342    use rstest::rstest;
343    use vortex_buffer::buffer;
344    use vortex_error::VortexResult;
345    use vortex_error::vortex_err;
346    use vortex_session::VortexSession;
347
348    use crate::IntoArray;
349    use crate::VortexSessionExecute;
350    use crate::arrays::ChunkedArray;
351    use crate::arrays::PrimitiveArray;
352    use crate::arrays::chunked::ChunkedArrayExt;
353    use crate::assert_arrays_eq;
354    use crate::dtype::DType;
355    use crate::dtype::Nullability;
356    use crate::dtype::PType;
357    use crate::validity::Validity;
358
359    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
360
361    #[rstest]
362    fn sized_chunks(
363        #[values(0, 1, 17)] nchunks: usize,
364        #[values(0, 1, 17)] expected_nchunks: usize,
365    ) -> VortexResult<()> {
366        let dtype = DType::from(PType::U64);
367        let chunks = (0..nchunks as u64).map(|i| buffer![i].into_array());
368        // SAFETY: every chunk contains non-nullable u64 values.
369        let array =
370            unsafe { ChunkedArray::new_unchecked_sized(chunks, dtype.clone(), expected_nchunks) };
371
372        assert_eq!(array.dtype(), &dtype);
373        assert_eq!(array.nchunks(), nchunks);
374        assert_eq!(
375            array.chunk_offset_values(),
376            (0..=nchunks).collect::<Vec<_>>()
377        );
378        let mut ctx = SESSION.create_execution_ctx();
379        assert_arrays_eq!(
380            array,
381            PrimitiveArray::from_iter(0..nchunks as u64),
382            &mut ctx
383        );
384        Ok(())
385    }
386
387    #[rstest]
388    fn sized_chunks_with_process_results(#[values(0, 1)] error_at: usize) {
389        let mut visited = 0;
390        let chunks = (0..3).map(|i| {
391            visited += 1;
392            if i == error_at {
393                Err(vortex_err!("chunk source failed"))
394            } else {
395                Ok(buffer![1u64].into_array())
396            }
397        });
398        let dtype = DType::from(PType::U64);
399        let result = chunks.process_results(|chunks| {
400            // SAFETY: every successfully yielded chunk contains non-nullable u64 values.
401            unsafe { ChunkedArray::new_unchecked_sized(chunks, dtype, 3) }
402        });
403
404        assert!(
405            result
406                .unwrap_err()
407                .to_string()
408                .contains("chunk source failed")
409        );
410        assert_eq!(visited, error_at + 1);
411    }
412
413    #[test]
414    fn test_rechunk_one_chunk() {
415        let mut ctx = SESSION.create_execution_ctx();
416        let chunked = ChunkedArray::try_new(
417            vec![buffer![0u64].into_array()],
418            DType::Primitive(PType::U64, Nullability::NonNullable),
419        )
420        .unwrap();
421
422        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();
423
424        assert_arrays_eq!(chunked, rechunked, &mut ctx);
425    }
426
427    #[test]
428    fn test_rechunk_two_chunks() {
429        let mut ctx = SESSION.create_execution_ctx();
430        let chunked = ChunkedArray::try_new(
431            vec![buffer![0u64].into_array(), buffer![5u64].into_array()],
432            DType::Primitive(PType::U64, Nullability::NonNullable),
433        )
434        .unwrap();
435
436        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();
437
438        assert_eq!(rechunked.nchunks(), 1);
439        assert_arrays_eq!(chunked, rechunked, &mut ctx);
440    }
441
442    #[test]
443    fn test_rechunk_tiny_target_chunks() {
444        let mut ctx = SESSION.create_execution_ctx();
445        let chunked = ChunkedArray::try_new(
446            vec![
447                buffer![0u64, 1, 2, 3].into_array(),
448                buffer![4u64, 5].into_array(),
449            ],
450            DType::Primitive(PType::U64, Nullability::NonNullable),
451        )
452        .unwrap();
453
454        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();
455
456        assert_eq!(rechunked.nchunks(), 2);
457        assert!(rechunked.iter_chunks().all(|c| c.len() < 5));
458        assert_arrays_eq!(chunked, rechunked, &mut ctx);
459    }
460
461    #[test]
462    fn test_rechunk_with_too_big_chunk() {
463        let mut ctx = SESSION.create_execution_ctx();
464        let chunked = ChunkedArray::try_new(
465            vec![
466                buffer![0u64, 1, 2].into_array(),
467                buffer![42_u64; 6].into_array(),
468                buffer![4u64, 5].into_array(),
469                buffer![6u64, 7].into_array(),
470                buffer![8u64, 9].into_array(),
471            ],
472            DType::Primitive(PType::U64, Nullability::NonNullable),
473        )
474        .unwrap();
475
476        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();
477        // greedy so should be: [0, 1, 2] [42, 42, 42, 42, 42, 42] [4, 5, 6, 7] [8, 9]
478
479        assert_eq!(rechunked.nchunks(), 4);
480        assert_arrays_eq!(chunked, rechunked, &mut ctx);
481    }
482
483    #[test]
484    fn test_empty_chunks_all_valid() -> VortexResult<()> {
485        let mut ctx = SESSION.create_execution_ctx();
486        // Create chunks where some are empty but all non-empty chunks have all valid values
487        let chunks = vec![
488            PrimitiveArray::new(buffer![1u64, 2, 3], Validity::AllValid).into_array(),
489            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
490            PrimitiveArray::new(buffer![4u64, 5], Validity::AllValid).into_array(),
491            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
492        ];
493
494        let chunked =
495            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
496
497        // Should be all_valid since all non-empty chunks are all_valid
498        assert!(chunked.all_valid(&mut ctx)?);
499        assert!(!chunked.into_array().all_invalid(&mut ctx)?);
500
501        Ok(())
502    }
503
504    #[test]
505    fn test_empty_chunks_all_invalid() -> VortexResult<()> {
506        let mut ctx = SESSION.create_execution_ctx();
507        // Create chunks where some are empty but all non-empty chunks have all invalid values
508        let chunks = vec![
509            PrimitiveArray::new(buffer![1u64, 2], Validity::AllInvalid).into_array(),
510            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
511            PrimitiveArray::new(buffer![3u64, 4, 5], Validity::AllInvalid).into_array(),
512            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
513        ];
514
515        let chunked =
516            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
517
518        // Should be all_invalid since all non-empty chunks are all_invalid
519        assert!(!chunked.all_valid(&mut ctx)?);
520        assert!(chunked.into_array().all_invalid(&mut ctx)?);
521
522        Ok(())
523    }
524
525    #[test]
526    fn test_empty_chunks_mixed_validity() -> VortexResult<()> {
527        let mut ctx = SESSION.create_execution_ctx();
528        // Create chunks with mixed validity including empty chunks
529        let chunks = vec![
530            PrimitiveArray::new(buffer![1u64, 2], Validity::AllValid).into_array(),
531            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
532            PrimitiveArray::new(buffer![3u64, 4], Validity::AllInvalid).into_array(),
533            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
534        ];
535
536        let chunked =
537            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
538
539        // Should be neither all_valid nor all_invalid
540        assert!(!chunked.all_valid(&mut ctx)?);
541        assert!(!chunked.into_array().all_invalid(&mut ctx)?);
542
543        Ok(())
544    }
545}