vortex-array 0.93.0

Vortex in memory columnar data format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! First-class chunked arrays.
//!
//! Vortex is a chunked array library that's able to

use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;

use futures::stream;
use vortex_buffer::BufferMut;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;

use crate::ArrayRef;
use crate::ArraySlots;
use crate::Canonical;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::array::Array;
use crate::array::ArrayParts;
use crate::array::TypedArrayRef;
use crate::array_slots;
use crate::arrays::Chunked;
use crate::arrays::PrimitiveArray;
use crate::dtype::DType;
use crate::iter::ArrayIterator;
use crate::iter::ArrayIteratorAdapter;
use crate::search_sorted::SearchSorted;
use crate::search_sorted::SearchSortedSide;
use crate::stream::ArrayStream;
use crate::stream::ArrayStreamAdapter;
use crate::validity::Validity;

/// Slot layout of a [`Chunked`] array: `[chunk_offsets, chunks...]`.
#[array_slots(Chunked)]
pub struct ChunkedSlots {
    /// The non-nullable `u64` array of cumulative chunk offsets.
    #[slot(0)]
    pub chunk_offsets: ArrayRef,
    /// The chunk arrays, each sharing the outer dtype.
    #[slot(1..)]
    pub chunks: Vec<ArrayRef>,
}

#[derive(Clone, Debug)]
pub struct ChunkedData {
    pub(super) chunk_offsets: Vec<usize>,
    /// This is used to find the next child to execute when in executing into a builder.
    pub(super) next_builder_slot: usize,
}

impl Display for ChunkedData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "nchunks: {}", self.chunk_offsets.len().saturating_sub(1))
    }
}

pub trait ChunkedArrayExt: TypedArrayRef<Chunked> {
    fn chunk_offsets_array(&self) -> &ArrayRef {
        self.slots()[ChunkedSlots::CHUNK_OFFSETS]
            .as_ref()
            .vortex_expect("validated chunk offsets slot")
    }

    fn nchunks(&self) -> usize {
        self.slots()
            .len()
            .saturating_sub(ChunkedSlots::CHUNKS_OFFSET)
    }

    fn chunk(&self, idx: usize) -> &ArrayRef {
        self.slots()[ChunkedSlots::CHUNKS_OFFSET + idx]
            .as_ref()
            .vortex_expect("validated chunk slot")
    }

    fn iter_chunks(&self) -> impl Iterator<Item = &ArrayRef> {
        self.slots()[ChunkedSlots::CHUNKS_OFFSET..]
            .iter()
            .map(|slot| slot.as_ref().vortex_expect("validated chunk slot"))
    }

    fn chunks(&self) -> Vec<ArrayRef> {
        self.iter_chunks().cloned().collect()
    }

    fn non_empty_chunks(&self) -> impl Iterator<Item = &ArrayRef> {
        self.iter_chunks().filter(|chunk| !chunk.is_empty())
    }

    /// Returns the cached chunk boundary offsets.
    fn chunk_offset_values(&self) -> &[usize] {
        &self.chunk_offsets
    }

    fn find_chunk_idx(&self, index: usize) -> VortexResult<(usize, usize)> {
        assert!(index <= self.len(), "Index out of bounds of the array");
        let chunk_offset_values = self.chunk_offset_values();
        let index_chunk = chunk_offset_values
            .search_sorted(&index, SearchSortedSide::Right)?
            .to_ends_index(self.nchunks() + 1)
            .saturating_sub(1);
        let chunk_start = chunk_offset_values[index_chunk];
        let index_in_chunk = index - chunk_start;
        Ok((index_chunk, index_in_chunk))
    }

    fn array_iterator(&self) -> impl ArrayIterator + '_ {
        ArrayIteratorAdapter::new(
            self.dtype().clone(),
            self.iter_chunks().map(|chunk| Ok(chunk.clone())),
        )
    }

    fn array_stream(&self) -> impl ArrayStream + '_ {
        ArrayStreamAdapter::new(
            self.dtype().clone(),
            stream::iter(self.iter_chunks().map(|chunk| Ok(chunk.clone()))),
        )
    }
}
impl<T: TypedArrayRef<Chunked>> ChunkedArrayExt for T {}

impl ChunkedData {
    pub(super) fn new(chunk_offsets: Vec<usize>) -> Self {
        Self {
            chunk_offsets,
            next_builder_slot: ChunkedSlots::CHUNKS_OFFSET,
        }
    }

    pub(super) fn make_chunk_offsets_array(chunk_offsets: &[usize]) -> ArrayRef {
        let mut chunk_offsets_buf = BufferMut::<u64>::with_capacity(chunk_offsets.len());
        for &offset in chunk_offsets {
            let offset = u64::try_from(offset)
                .vortex_expect("chunk offset must fit in u64 for serialization");
            unsafe { chunk_offsets_buf.push_unchecked(offset) }
        }
        PrimitiveArray::new(chunk_offsets_buf.freeze(), Validity::NonNullable).into_array()
    }

    /// Validates the components that would be used to create a `ChunkedArray`.
    ///
    /// This function checks all the invariants required by `ChunkedArray::new_unchecked`.
    pub fn validate(chunks: &[ArrayRef], dtype: &DType) -> VortexResult<()> {
        for chunk in chunks {
            if chunk.dtype() != dtype {
                vortex_bail!("expected type: {} but instead got {}", dtype, chunk.dtype());
            }
        }

        Ok(())
    }
}

impl Array<Chunked> {
    fn parts_from_chunks<const VALIDATE: bool>(
        chunks: impl IntoIterator<Item = ArrayRef>,
        dtype: DType,
    ) -> VortexResult<ArrayParts<Chunked>> {
        let chunks = chunks.into_iter();
        let (lower, _) = chunks.size_hint();
        Self::parts_from_chunks_with_capacity::<VALIDATE>(chunks, dtype, lower)
    }

    fn parts_from_chunks_with_capacity<const VALIDATE: bool>(
        chunks: impl IntoIterator<Item = ArrayRef>,
        dtype: DType,
        capacity: usize,
    ) -> VortexResult<ArrayParts<Chunked>> {
        let mut slots = ArraySlots::with_capacity(ChunkedSlots::CHUNKS_OFFSET + capacity);
        slots.push(None);
        let mut chunk_offsets = Vec::with_capacity(capacity + 1);
        chunk_offsets.push(0);
        let mut len = 0usize;

        for chunk in chunks {
            if VALIDATE {
                Self::validate_chunk_dtype(&chunk, &dtype)?;
            }
            len += chunk.len();
            chunk_offsets.push(len);
            slots.push(Some(chunk));
        }

        Ok(Self::parts_from_slots(dtype, len, chunk_offsets, slots))
    }

    /// Checks that the chunk has the dtype of the array.
    ///
    /// This function is not generic, so each iterator type does not compile its own copy of the
    /// error message.
    fn validate_chunk_dtype(chunk: &ArrayRef, dtype: &DType) -> VortexResult<()> {
        if chunk.dtype() != dtype {
            vortex_bail!("expected type: {} but instead got {}", dtype, chunk.dtype());
        }
        Ok(())
    }

    /// Creates the parts from the collected chunk slots and offsets.
    ///
    /// This function is not generic, so each iterator type that `parts_from_chunks_with_capacity`
    /// gets compiled for does not compile its own copy.
    fn parts_from_slots(
        dtype: DType,
        len: usize,
        chunk_offsets: Vec<usize>,
        mut slots: ArraySlots,
    ) -> ArrayParts<Chunked> {
        slots[ChunkedSlots::CHUNK_OFFSETS] =
            Some(ChunkedData::make_chunk_offsets_array(&chunk_offsets));
        ArrayParts::new(Chunked, dtype, len, ChunkedData::new(chunk_offsets), slots)
    }

    pub(super) fn with_next_builder_slot(mut self, next_builder_slot: usize) -> Self {
        if let Some(data) = self.data_mut() {
            data.next_builder_slot = next_builder_slot;
            return self;
        }
        // This is the slow path that will be hit at most once per execution since the second one
        // *MUST* have execlusive access due to this copy.
        let stats = self.statistics().to_owned();
        let mut data = self.data().clone();
        data.next_builder_slot = next_builder_slot;
        // SAFETY: we only modified next_builder_slot which doesn't affect array invariants.
        unsafe {
            Array::from_parts_unchecked(ArrayParts::new(
                Chunked,
                self.dtype().clone(),
                self.len(),
                data,
                self.slots().iter().cloned().collect::<ArraySlots>(),
            ))
        }
        .with_stats_set(stats)
    }

    /// Constructs a new `ChunkedArray`.
    pub fn try_new(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> VortexResult<Self> {
        Self::try_from_chunked_parts(Self::parts_from_chunks::<true>(chunks, dtype)?)
    }

    pub fn rechunk(
        &self,
        target_bytesize: u64,
        target_rowsize: usize,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<Self> {
        let mut new_chunks = Vec::new();
        let mut chunks_to_combine = Vec::new();
        let mut new_chunk_n_bytes = 0;
        let mut new_chunk_n_elements = 0;
        for chunk in self.iter_chunks() {
            let n_bytes = chunk.nbytes();
            let n_elements = chunk.len();

            if (new_chunk_n_bytes + n_bytes > target_bytesize
                || new_chunk_n_elements + n_elements > target_rowsize)
                && !chunks_to_combine.is_empty()
            {
                let canonical = unsafe {
                    Array::<Chunked>::new_unchecked(
                        chunks_to_combine.drain(..),
                        self.dtype().clone(),
                    )
                }
                .into_array()
                .execute::<Canonical>(ctx)?
                .into_array();
                new_chunks.push(canonical);

                new_chunk_n_bytes = 0;
                new_chunk_n_elements = 0;
            }

            if n_bytes > target_bytesize || n_elements > target_rowsize {
                new_chunks.push(chunk.clone());
            } else {
                new_chunk_n_bytes += n_bytes;
                new_chunk_n_elements += n_elements;
                chunks_to_combine.push(chunk.clone());
            }
        }

        if !chunks_to_combine.is_empty() {
            let canonical =
                unsafe { Array::<Chunked>::new_unchecked(chunks_to_combine, self.dtype().clone()) }
                    .into_array()
                    .execute::<Canonical>(ctx)?
                    .into_array();
            new_chunks.push(canonical);
        }

        unsafe { Ok(Self::new_unchecked(new_chunks, self.dtype().clone())) }
    }

    /// Creates a new `ChunkedArray` without validation.
    ///
    /// # Safety
    ///
    /// All chunks must have exactly the same [`DType`] as the provided `dtype`.
    pub unsafe fn new_unchecked(chunks: impl IntoIterator<Item = ArrayRef>, dtype: DType) -> Self {
        let chunks = chunks.into_iter();
        let (expected_nchunks, _) = chunks.size_hint();
        // SAFETY: the caller guarantees the dtype of every chunk.
        unsafe { Self::new_unchecked_sized(chunks, dtype, expected_nchunks) }
    }

    /// Creates a chunked array without validation, reserving space for `expected_nchunks` chunks.
    ///
    /// The expected count is only an allocation hint: fewer or more chunks are allowed.
    /// This is useful when iterator adapters such as `process_results` lose the source size hint.
    ///
    /// # Safety
    ///
    /// All chunks must have exactly the same [`DType`] as the provided `dtype`.
    pub unsafe fn new_unchecked_sized(
        chunks: impl IntoIterator<Item = ArrayRef>,
        dtype: DType,
        expected_nchunks: usize,
    ) -> Self {
        let parts = Self::parts_from_chunks_with_capacity::<false>(chunks, dtype, expected_nchunks)
            .vortex_expect("unchecked chunked construction cannot fail");
        // SAFETY: the caller guarantees the dtype of every chunk.
        unsafe { Self::from_chunked_parts_unchecked(parts) }
    }

    /// Creates the array from parts after validation.
    ///
    /// The generic constructors call this function. It is not generic, so crates that call those
    /// constructors do not each compile the `Chunked` array vtable.
    fn try_from_chunked_parts(parts: ArrayParts<Chunked>) -> VortexResult<Self> {
        Array::try_from_parts(parts)
    }

    /// Creates the array from parts without validation.
    ///
    /// The generic constructors call this function. It is not generic, so crates that call those
    /// constructors do not each compile the `Chunked` array vtable.
    ///
    /// # Safety
    ///
    /// The parts must be logically consistent.
    unsafe fn from_chunked_parts_unchecked(parts: ArrayParts<Chunked>) -> Self {
        unsafe { Array::from_parts_unchecked(parts) }
    }
}

impl FromIterator<ArrayRef> for Array<Chunked> {
    fn from_iter<T: IntoIterator<Item = ArrayRef>>(iter: T) -> Self {
        let mut chunks = iter.into_iter().peekable();
        let dtype = chunks
            .peek()
            .map(|c| c.dtype().clone())
            .vortex_expect("Cannot infer DType from an empty iterator");
        Array::<Chunked>::try_new(chunks, dtype)
            .vortex_expect("Failed to create chunked array from iterator")
    }
}

#[cfg(test)]
mod test {
    use std::sync::LazyLock;

    use itertools::Itertools;
    use rstest::rstest;
    use vortex_buffer::buffer;
    use vortex_error::VortexResult;
    use vortex_error::vortex_err;
    use vortex_session::VortexSession;

    use crate::IntoArray;
    use crate::VortexSessionExecute;
    use crate::arrays::ChunkedArray;
    use crate::arrays::PrimitiveArray;
    use crate::arrays::chunked::ChunkedArrayExt;
    use crate::assert_arrays_eq;
    use crate::dtype::DType;
    use crate::dtype::Nullability;
    use crate::dtype::PType;
    use crate::validity::Validity;

    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

    #[rstest]
    fn sized_chunks(
        #[values(0, 1, 17)] nchunks: usize,
        #[values(0, 1, 17)] expected_nchunks: usize,
    ) -> VortexResult<()> {
        let dtype = DType::from(PType::U64);
        let chunks = (0..nchunks as u64).map(|i| buffer![i].into_array());
        // SAFETY: every chunk contains non-nullable u64 values.
        let array =
            unsafe { ChunkedArray::new_unchecked_sized(chunks, dtype.clone(), expected_nchunks) };

        assert_eq!(array.dtype(), &dtype);
        assert_eq!(array.nchunks(), nchunks);
        assert_eq!(
            array.chunk_offset_values(),
            (0..=nchunks).collect::<Vec<_>>()
        );
        let mut ctx = SESSION.create_execution_ctx();
        assert_arrays_eq!(
            array,
            PrimitiveArray::from_iter(0..nchunks as u64),
            &mut ctx
        );
        Ok(())
    }

    #[rstest]
    fn sized_chunks_with_process_results(#[values(0, 1)] error_at: usize) {
        let mut visited = 0;
        let chunks = (0..3).map(|i| {
            visited += 1;
            if i == error_at {
                Err(vortex_err!("chunk source failed"))
            } else {
                Ok(buffer![1u64].into_array())
            }
        });
        let dtype = DType::from(PType::U64);
        let result = chunks.process_results(|chunks| {
            // SAFETY: every successfully yielded chunk contains non-nullable u64 values.
            unsafe { ChunkedArray::new_unchecked_sized(chunks, dtype, 3) }
        });

        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("chunk source failed")
        );
        assert_eq!(visited, error_at + 1);
    }

    #[test]
    fn test_rechunk_one_chunk() {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(
            vec![buffer![0u64].into_array()],
            DType::Primitive(PType::U64, Nullability::NonNullable),
        )
        .unwrap();

        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();

        assert_arrays_eq!(chunked, rechunked, &mut ctx);
    }

    #[test]
    fn test_rechunk_two_chunks() {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(
            vec![buffer![0u64].into_array(), buffer![5u64].into_array()],
            DType::Primitive(PType::U64, Nullability::NonNullable),
        )
        .unwrap();

        let rechunked = chunked.rechunk(1 << 16, 1 << 16, &mut ctx).unwrap();

        assert_eq!(rechunked.nchunks(), 1);
        assert_arrays_eq!(chunked, rechunked, &mut ctx);
    }

    #[test]
    fn test_rechunk_tiny_target_chunks() {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(
            vec![
                buffer![0u64, 1, 2, 3].into_array(),
                buffer![4u64, 5].into_array(),
            ],
            DType::Primitive(PType::U64, Nullability::NonNullable),
        )
        .unwrap();

        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();

        assert_eq!(rechunked.nchunks(), 2);
        assert!(rechunked.iter_chunks().all(|c| c.len() < 5));
        assert_arrays_eq!(chunked, rechunked, &mut ctx);
    }

    #[test]
    fn test_rechunk_with_too_big_chunk() {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(
            vec![
                buffer![0u64, 1, 2].into_array(),
                buffer![42_u64; 6].into_array(),
                buffer![4u64, 5].into_array(),
                buffer![6u64, 7].into_array(),
                buffer![8u64, 9].into_array(),
            ],
            DType::Primitive(PType::U64, Nullability::NonNullable),
        )
        .unwrap();

        let rechunked = chunked.rechunk(1 << 16, 5, &mut ctx).unwrap();
        // greedy so should be: [0, 1, 2] [42, 42, 42, 42, 42, 42] [4, 5, 6, 7] [8, 9]

        assert_eq!(rechunked.nchunks(), 4);
        assert_arrays_eq!(chunked, rechunked, &mut ctx);
    }

    #[test]
    fn test_empty_chunks_all_valid() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        // Create chunks where some are empty but all non-empty chunks have all valid values
        let chunks = vec![
            PrimitiveArray::new(buffer![1u64, 2, 3], Validity::AllValid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
            PrimitiveArray::new(buffer![4u64, 5], Validity::AllValid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
        ];

        let chunked =
            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;

        // Should be all_valid since all non-empty chunks are all_valid
        assert!(chunked.all_valid(&mut ctx)?);
        assert!(!chunked.into_array().all_invalid(&mut ctx)?);

        Ok(())
    }

    #[test]
    fn test_empty_chunks_all_invalid() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        // Create chunks where some are empty but all non-empty chunks have all invalid values
        let chunks = vec![
            PrimitiveArray::new(buffer![1u64, 2], Validity::AllInvalid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
            PrimitiveArray::new(buffer![3u64, 4, 5], Validity::AllInvalid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
        ];

        let chunked =
            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;

        // Should be all_invalid since all non-empty chunks are all_invalid
        assert!(!chunked.all_valid(&mut ctx)?);
        assert!(chunked.into_array().all_invalid(&mut ctx)?);

        Ok(())
    }

    #[test]
    fn test_empty_chunks_mixed_validity() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        // Create chunks with mixed validity including empty chunks
        let chunks = vec![
            PrimitiveArray::new(buffer![1u64, 2], Validity::AllValid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllValid).into_array(), // empty chunk
            PrimitiveArray::new(buffer![3u64, 4], Validity::AllInvalid).into_array(),
            PrimitiveArray::new(buffer![0u64; 0], Validity::AllInvalid).into_array(), /* empty chunk */
        ];

        let chunked =
            ChunkedArray::try_new(chunks, DType::Primitive(PType::U64, Nullability::Nullable))?;

        // Should be neither all_valid nor all_invalid
        assert!(!chunked.all_valid(&mut ctx)?);
        assert!(!chunked.into_array().all_invalid(&mut ctx)?);

        Ok(())
    }
}