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::BufferMut;
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    /// This is used to find the next child to execute when in executing into a builder.
53    pub(super) next_builder_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 chunk_offsets_array(&self) -> &ArrayRef {
64        self.as_ref().slots()[ChunkedSlots::CHUNK_OFFSETS]
65            .as_ref()
66            .vortex_expect("validated chunk offsets slot")
67    }
68
69    fn nchunks(&self) -> usize {
70        self.as_ref()
71            .slots()
72            .len()
73            .saturating_sub(ChunkedSlots::CHUNKS_OFFSET)
74    }
75
76    fn chunk(&self, idx: usize) -> &ArrayRef {
77        self.as_ref().slots()[ChunkedSlots::CHUNKS_OFFSET + idx]
78            .as_ref()
79            .vortex_expect("validated chunk slot")
80    }
81
82    fn iter_chunks<'a>(&'a self) -> Box<dyn Iterator<Item = &'a ArrayRef> + 'a> {
83        Box::new(
84            self.as_ref().slots()[ChunkedSlots::CHUNKS_OFFSET..]
85                .iter()
86                .map(|slot| slot.as_ref().vortex_expect("validated chunk slot")),
87        )
88    }
89
90    fn chunks(&self) -> Vec<ArrayRef> {
91        self.iter_chunks().cloned().collect()
92    }
93
94    fn non_empty_chunks<'a>(&'a self) -> Box<dyn Iterator<Item = &'a ArrayRef> + 'a> {
95        Box::new(self.iter_chunks().filter(|chunk| !chunk.is_empty()))
96    }
97
98    /// Returns the cached chunk boundary offsets.
99    fn chunk_offset_values(&self) -> &[usize] {
100        &self.chunk_offsets
101    }
102
103    fn find_chunk_idx(&self, index: usize) -> VortexResult<(usize, usize)> {
104        assert!(
105            index <= self.as_ref().len(),
106            "Index out of bounds of the array"
107        );
108        let chunk_offset_values = self.chunk_offset_values();
109        let index_chunk = chunk_offset_values
110            .search_sorted(&index, SearchSortedSide::Right)?
111            .to_ends_index(self.nchunks() + 1)
112            .saturating_sub(1);
113        let chunk_start = chunk_offset_values[index_chunk];
114        let index_in_chunk = index - chunk_start;
115        Ok((index_chunk, index_in_chunk))
116    }
117
118    fn array_iterator(&self) -> impl ArrayIterator + '_ {
119        ArrayIteratorAdapter::new(
120            self.as_ref().dtype().clone(),
121            self.iter_chunks().map(|chunk| Ok(chunk.clone())),
122        )
123    }
124
125    fn array_stream(&self) -> impl ArrayStream + '_ {
126        ArrayStreamAdapter::new(
127            self.as_ref().dtype().clone(),
128            stream::iter(self.iter_chunks().map(|chunk| Ok(chunk.clone()))),
129        )
130    }
131}
132impl<T: TypedArrayRef<Chunked>> ChunkedArrayExt for T {}
133
134impl ChunkedData {
135    pub(super) fn new(chunk_offsets: Vec<usize>) -> Self {
136        Self {
137            chunk_offsets,
138            next_builder_slot: ChunkedSlots::CHUNKS_OFFSET,
139        }
140    }
141
142    pub(super) fn make_chunk_offsets_array(chunk_offsets: &[usize]) -> ArrayRef {
143        let mut chunk_offsets_buf = BufferMut::<u64>::with_capacity(chunk_offsets.len());
144        for &offset in chunk_offsets {
145            let offset = u64::try_from(offset)
146                .vortex_expect("chunk offset must fit in u64 for serialization");
147            unsafe { chunk_offsets_buf.push_unchecked(offset) }
148        }
149        PrimitiveArray::new(chunk_offsets_buf.freeze(), Validity::NonNullable).into_array()
150    }
151
152    /// Validates the components that would be used to create a `ChunkedArray`.
153    ///
154    /// This function checks all the invariants required by `ChunkedArray::new_unchecked`.
155    pub fn validate(chunks: &[ArrayRef], dtype: &DType) -> VortexResult<()> {
156        for chunk in chunks {
157            if chunk.dtype() != dtype {
158                vortex_bail!(MismatchedTypes: dtype, chunk.dtype());
159            }
160        }
161
162        Ok(())
163    }
164}
165
166impl Array<Chunked> {
167    fn parts_from_chunks<const VALIDATE: bool>(
168        chunks: impl IntoIterator<Item = ArrayRef>,
169        dtype: DType,
170    ) -> VortexResult<ArrayParts<Chunked>> {
171        let chunks = chunks.into_iter();
172        let (lower, _) = chunks.size_hint();
173        let mut slots = ArraySlots::with_capacity(ChunkedSlots::CHUNKS_OFFSET + lower);
174        slots.push(None);
175        let mut chunk_offsets = Vec::with_capacity(lower + 1);
176        chunk_offsets.push(0);
177        let mut len = 0usize;
178
179        for chunk in chunks {
180            if VALIDATE && chunk.dtype() != &dtype {
181                vortex_bail!(MismatchedTypes: &dtype, chunk.dtype());
182            }
183            len += chunk.len();
184            chunk_offsets.push(len);
185            slots.push(Some(chunk));
186        }
187
188        slots[ChunkedSlots::CHUNK_OFFSETS] =
189            Some(ChunkedData::make_chunk_offsets_array(&chunk_offsets));
190        Ok(ArrayParts::new(Chunked, dtype, len, ChunkedData::new(chunk_offsets)).with_slots(slots))
191    }
192
193    pub(super) fn with_next_builder_slot(mut self, next_builder_slot: usize) -> Self {
194        if let Some(data) = self.data_mut() {
195            data.next_builder_slot = next_builder_slot;
196            return self;
197        }
198        // This is the slow path that will be hit at most once per execution since the second one
199        // *MUST* have execlusive access due to this copy.
200        let stats = self.statistics().to_owned();
201        let mut data = self.data().clone();
202        data.next_builder_slot = next_builder_slot;
203        // SAFETY: we only modified next_builder_slot which doesn't affect array invariants.
204        unsafe {
205            Array::from_parts_unchecked(
206                ArrayParts::new(Chunked, self.dtype().clone(), self.len(), data)
207                    .with_slots(self.slots().iter().cloned().collect::<ArraySlots>()),
208            )
209        }
210        .with_stats_set(stats)
211    }
212
213    /// Constructs a new `ChunkedArray`.
214    pub fn try_new(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> VortexResult<Self> {
215        Array::try_from_parts(Self::parts_from_chunks::<true>(chunks, dtype)?)
216    }
217
218    pub fn rechunk(
219        &self,
220        target_bytesize: u64,
221        target_rowsize: usize,
222        ctx: &mut ExecutionCtx,
223    ) -> VortexResult<Self> {
224        let mut new_chunks = Vec::new();
225        let mut chunks_to_combine = Vec::new();
226        let mut new_chunk_n_bytes = 0;
227        let mut new_chunk_n_elements = 0;
228        for chunk in self.iter_chunks() {
229            let n_bytes = chunk.nbytes();
230            let n_elements = chunk.len();
231
232            if (new_chunk_n_bytes + n_bytes > target_bytesize
233                || new_chunk_n_elements + n_elements > target_rowsize)
234                && !chunks_to_combine.is_empty()
235            {
236                let canonical = unsafe {
237                    Array::<Chunked>::new_unchecked(chunks_to_combine, self.dtype().clone())
238                }
239                .into_array()
240                .execute::<Canonical>(ctx)?
241                .into_array();
242                new_chunks.push(canonical);
243
244                new_chunk_n_bytes = 0;
245                new_chunk_n_elements = 0;
246                chunks_to_combine = Vec::new();
247            }
248
249            if n_bytes > target_bytesize || n_elements > target_rowsize {
250                new_chunks.push(chunk.clone());
251            } else {
252                new_chunk_n_bytes += n_bytes;
253                new_chunk_n_elements += n_elements;
254                chunks_to_combine.push(chunk.clone());
255            }
256        }
257
258        if !chunks_to_combine.is_empty() {
259            let canonical =
260                unsafe { Array::<Chunked>::new_unchecked(chunks_to_combine, self.dtype().clone()) }
261                    .into_array()
262                    .execute::<Canonical>(ctx)?
263                    .into_array();
264            new_chunks.push(canonical);
265        }
266
267        unsafe { Ok(Self::new_unchecked(new_chunks, self.dtype().clone())) }
268    }
269
270    /// Creates a new `ChunkedArray` without validation.
271    ///
272    /// # Safety
273    ///
274    /// All chunks must have exactly the same [`DType`] as the provided `dtype`.
275    pub unsafe fn new_unchecked(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> Self {
276        let parts = Self::parts_from_chunks::<false>(chunks, dtype)
277            .vortex_expect("unchecked chunked construction cannot fail");
278        unsafe { Array::from_parts_unchecked(parts) }
279    }
280}
281
282impl FromIterator<ArrayRef> for Array<Chunked> {
283    fn from_iter<T: IntoIterator<Item = ArrayRef>>(iter: T) -> Self {
284        let chunks: Vec<ArrayRef> = iter.into_iter().collect();
285        let dtype = chunks
286            .first()
287            .map(|c| c.dtype().clone())
288            .vortex_expect("Cannot infer DType from an empty iterator");
289        Array::<Chunked>::try_new(chunks, dtype)
290            .vortex_expect("Failed to create chunked array from iterator")
291    }
292}
293
294#[cfg(test)]
295mod test {
296    use vortex_buffer::buffer;
297    use vortex_error::VortexResult;
298
299    use crate::IntoArray;
300    use crate::VortexSessionExecute;
301    use crate::array_session;
302    use crate::arrays::ChunkedArray;
303    use crate::arrays::PrimitiveArray;
304    use crate::arrays::chunked::ChunkedArrayExt;
305    use crate::assert_arrays_eq;
306    use crate::dtype::DType;
307    use crate::dtype::Nullability;
308    use crate::dtype::PType;
309    use crate::validity::Validity;
310
311    #[test]
312    fn test_rechunk_one_chunk() {
313        let mut ctx = array_session().create_execution_ctx();
314        let chunked = ChunkedArray::try_new(
315            vec![buffer![0u64].into_array()],
316            DType::Primitive(PType::U64, Nullability::NonNullable),
317        )
318        .unwrap();
319
320        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();
321
322        assert_arrays_eq!(chunked, rechunked, &mut ctx);
323    }
324
325    #[test]
326    fn test_rechunk_two_chunks() {
327        let mut ctx = array_session().create_execution_ctx();
328        let chunked = ChunkedArray::try_new(
329            vec![buffer![0u64].into_array(), buffer![5u64].into_array()],
330            DType::Primitive(PType::U64, Nullability::NonNullable),
331        )
332        .unwrap();
333
334        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();
335
336        assert_eq!(rechunked.nchunks(), 1);
337        assert_arrays_eq!(chunked, rechunked, &mut ctx);
338    }
339
340    #[test]
341    fn test_rechunk_tiny_target_chunks() {
342        let mut ctx = array_session().create_execution_ctx();
343        let chunked = ChunkedArray::try_new(
344            vec![
345                buffer![0u64, 1, 2, 3].into_array(),
346                buffer![4u64, 5].into_array(),
347            ],
348            DType::Primitive(PType::U64, Nullability::NonNullable),
349        )
350        .unwrap();
351
352        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();
353
354        assert_eq!(rechunked.nchunks(), 2);
355        assert!(rechunked.iter_chunks().all(|c| c.len() < 5));
356        assert_arrays_eq!(chunked, rechunked, &mut ctx);
357    }
358
359    #[test]
360    fn test_rechunk_with_too_big_chunk() {
361        let mut ctx = array_session().create_execution_ctx();
362        let chunked = ChunkedArray::try_new(
363            vec![
364                buffer![0u64, 1, 2].into_array(),
365                buffer![42_u64; 6].into_array(),
366                buffer![4u64, 5].into_array(),
367                buffer![6u64, 7].into_array(),
368                buffer![8u64, 9].into_array(),
369            ],
370            DType::Primitive(PType::U64, Nullability::NonNullable),
371        )
372        .unwrap();
373
374        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();
375        // greedy so should be: [0, 1, 2] [42, 42, 42, 42, 42, 42] [4, 5, 6, 7] [8, 9]
376
377        assert_eq!(rechunked.nchunks(), 4);
378        assert_arrays_eq!(chunked, rechunked, &mut ctx);
379    }
380
381    #[test]
382    fn test_empty_chunks_all_valid() -> VortexResult<()> {
383        let mut ctx = array_session().create_execution_ctx();
384        // Create chunks where some are empty but all non-empty chunks have all valid values
385        let chunks = vec![
386            PrimitiveArray::new(buffer![1u64, 2, 3], Validity::AllValid).into_array(),
387            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
388            PrimitiveArray::new(buffer![4u64, 5], Validity::AllValid).into_array(),
389            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
390        ];
391
392        let chunked =
393            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
394
395        // Should be all_valid since all non-empty chunks are all_valid
396        assert!(chunked.all_valid(&mut ctx)?);
397        assert!(!chunked.into_array().all_invalid(&mut ctx)?);
398
399        Ok(())
400    }
401
402    #[test]
403    fn test_empty_chunks_all_invalid() -> VortexResult<()> {
404        let mut ctx = array_session().create_execution_ctx();
405        // Create chunks where some are empty but all non-empty chunks have all invalid values
406        let chunks = vec![
407            PrimitiveArray::new(buffer![1u64, 2], Validity::AllInvalid).into_array(),
408            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
409            PrimitiveArray::new(buffer![3u64, 4, 5], Validity::AllInvalid).into_array(),
410            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
411        ];
412
413        let chunked =
414            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
415
416        // Should be all_invalid since all non-empty chunks are all_invalid
417        assert!(!chunked.all_valid(&mut ctx)?);
418        assert!(chunked.into_array().all_invalid(&mut ctx)?);
419
420        Ok(())
421    }
422
423    #[test]
424    fn test_empty_chunks_mixed_validity() -> VortexResult<()> {
425        let mut ctx = array_session().create_execution_ctx();
426        // Create chunks with mixed validity including empty chunks
427        let chunks = vec![
428            PrimitiveArray::new(buffer![1u64, 2], Validity::AllValid).into_array(),
429            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
430            PrimitiveArray::new(buffer![3u64, 4], Validity::AllInvalid).into_array(),
431            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
432        ];
433
434        let chunked =
435            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;
436
437        // Should be neither all_valid nor all_invalid
438        assert!(!chunked.all_valid(&mut ctx)?);
439        assert!(!chunked.into_array().all_invalid(&mut ctx)?);
440
441        Ok(())
442    }
443}