vortex-array 0.94.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use num_traits::AsPrimitive;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_err;

use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::ExecutionResult;
use crate::IntoArray;
use crate::array::ArrayView;
use crate::arrays::ChunkedArray;
use crate::arrays::FixedSizeList;
use crate::arrays::FixedSizeListArray;
use crate::arrays::List;
use crate::arrays::ListView;
use crate::arrays::ListViewArray;
use crate::arrays::PrimitiveArray;
use crate::arrays::Struct;
use crate::arrays::StructArray;
use crate::arrays::Variant;
use crate::arrays::chunked::ChunkedArrayExt;
use crate::arrays::chunked::array::ChunkedSlots;
use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
use crate::arrays::list::ListArraySlotsExt;
use crate::arrays::listview::ListViewArraySlotsExt;
use crate::arrays::struct_::StructArrayExt;
use crate::builders::ArrayBuilder;
use crate::builders::VariantBuilder;
use crate::dtype::DType;
use crate::match_each_integer_ptype;
use crate::matcher::Matcher;
use crate::validity::Validity;

pub(super) struct ListChunks;

impl Matcher for ListChunks {
    type Match<'a> = ();

    fn try_match(array: &ArrayRef) -> Option<()> {
        (array.is::<List>() || array.is::<ListView>()).then_some(())
    }
}

/// Executes chunks into the required encoding one at a time, then transposes their children.
pub(super) fn swizzle<V: Matcher + 'static>(
    array: ChunkedArray,
    finish: impl FnOnce(ChunkedArray) -> VortexResult<ArrayRef>,
) -> VortexResult<ExecutionResult> {
    let next_chunk = array
        .next_child_slot
        .saturating_sub(ChunkedSlots::CHUNKS_OFFSET);
    let needs_execution = array
        .iter_chunks()
        .enumerate()
        .skip(next_chunk)
        .find(|(_, chunk)| !V::matches(chunk))
        .map(|(idx, _)| idx + ChunkedSlots::CHUNKS_OFFSET);
    if let Some(slot) = needs_execution {
        return Ok(ExecutionResult::execute_slot::<V>(
            array.with_next_child_slot(slot + 1),
            slot,
        ));
    }

    Ok(ExecutionResult::done(finish(array)?))
}

pub(super) fn swizzle_fixed_size_list(array: ChunkedArray) -> VortexResult<ArrayRef> {
    let DType::FixedSizeList(element_dtype, list_size, _) = array.dtype() else {
        unreachable!("called only for a fixed-size list dtype")
    };
    // Canonical FSL children are trimmed to list_size * len; their elements concatenate directly.
    let element_chunks: Vec<_> = array
        .iter_chunks()
        .map(|chunk| chunk.as_::<FixedSizeList>().elements().clone())
        .collect();
    let validity = array.validity()?;
    // SAFETY: all chunks share the parent's FSL dtype, so their elements share element_dtype
    // and their lengths sum to list_size * array.len(). The parent supplies the combined validity.
    Ok(unsafe {
        let elements = ChunkedArray::new_unchecked(element_chunks, element_dtype.as_ref().clone())
            .into_array();
        FixedSizeListArray::new_unchecked(elements, *list_size, validity, array.len()).into_array()
    })
}

pub(super) fn swizzle_struct(array: ChunkedArray) -> VortexResult<ArrayRef> {
    let struct_fields = array.dtype().as_struct_fields();
    let chunks: Vec<_> = array
        .iter_chunks()
        .map(|chunk| chunk.as_::<Struct>())
        .collect();
    let fields = struct_fields.fields().enumerate().map(|(idx, dtype)| {
        let children = chunks.iter().map(|chunk| chunk.unmasked_field(idx).clone());
        // SAFETY: each chunk has the parent's struct dtype, which fixes each field's dtype.
        unsafe { ChunkedArray::new_unchecked(children, dtype) }.into_array()
    });
    let validity = array.validity()?;
    // SAFETY: each field concatenates the same chunk lengths, summing to array.len(). Their
    // dtypes come from the parent and its validity applies to exactly those rows, including nulls.
    Ok(unsafe {
        StructArray::new_unchecked(fields, struct_fields.clone(), array.len(), validity)
            .into_array()
    })
}

pub(super) fn swizzle_list(array: ChunkedArray, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
    let DType::List(element_dtype, _) = array.dtype() else {
        unreachable!("called only for a list dtype")
    };
    let mut elements = Vec::with_capacity(array.nchunks());
    let mut offsets = ctx.allocator().zeroed::<u64>(array.len());
    let mut sizes = ctx.allocator().zeroed::<u64>(array.len());
    let mut element_base = 0usize;
    let mut row = 0;
    let mut zero_copy_to_list = true;

    for chunk in array.iter_chunks() {
        if chunk.is_empty() {
            continue;
        }
        let offsets_out = &mut offsets.as_mut_slice()[row..row + chunk.len()];
        let sizes_out = &mut sizes.as_mut_slice()[row..row + chunk.len()];
        let window = if let Some(list) = chunk.as_opt::<List>() {
            list_window(list, offsets_out, sizes_out, ctx)?
        } else {
            list_view_window(chunk.as_::<ListView>(), offsets_out, sizes_out, ctx)?
        };

        let start =
            usize::try_from(window.start).vortex_expect("offset is bounded by elements.len()");
        let end =
            usize::try_from(window.end).vortex_expect("view end is bounded by elements.len()");
        let next_base = element_base
            .checked_add(end - start)
            .ok_or_else(|| vortex_err!("combined list elements length overflow"))?;
        for offset in offsets_out {
            *offset = (*offset - start as u64) + element_base as u64;
        }
        elements.push(window.elements.slice(start..end)?);
        zero_copy_to_list &= window.zero_copy_to_list;
        element_base = next_base;
        row += chunk.len();
    }
    let validity = array.validity()?;
    // SAFETY: element dtypes come from the common list dtype. Offsets/sizes are non-nullable u64
    // arrays with one entry per row. Trimming and rebasing preserve each validated view's bounds,
    // and the checked combined length prevents overflow. Validity comes from the parent. If every
    // chunk is zero-copyable, trimming makes adjacent chunks meet without gaps or overlaps.
    Ok(unsafe {
        let elements =
            ChunkedArray::new_unchecked(elements, element_dtype.as_ref().clone()).into_array();
        let offsets =
            PrimitiveArray::new_unchecked(offsets.freeze(), Validity::NonNullable).into_array();
        let sizes =
            PrimitiveArray::new_unchecked(sizes.freeze(), Validity::NonNullable).into_array();
        ListViewArray::new_unchecked(elements, offsets, sizes, validity)
            .with_zero_copy_to_list(zero_copy_to_list)
            .into_array()
    })
}

/// The range of child elements that one list chunk references.
struct ElementWindow {
    elements: ArrayRef,
    start: u64,
    end: u64,
    zero_copy_to_list: bool,
}

/// Writes the `u64` offsets and sizes of a [`List`] chunk and returns its element window.
fn list_window(
    list: ArrayView<'_, List>,
    offsets_out: &mut [u64],
    sizes_out: &mut [u64],
    ctx: &mut ExecutionCtx,
) -> VortexResult<ElementWindow> {
    let chunk_offsets = list.offsets().clone().execute::<PrimitiveArray>(ctx)?;
    match_each_integer_ptype!(chunk_offsets.ptype(), |O| {
        for ((out, size), pair) in offsets_out
            .iter_mut()
            .zip(sizes_out.iter_mut())
            .zip(chunk_offsets.as_slice::<O>().windows(2))
        {
            let start: u64 = pair[0].as_();
            let end: u64 = pair[1].as_();
            *out = start;
            *size = end - start;
        }
    });

    let last = offsets_out.len() - 1;
    Ok(ElementWindow {
        elements: list.elements().clone(),
        start: offsets_out[0],
        end: offsets_out[last] + sizes_out[last],
        zero_copy_to_list: true,
    })
}

/// Writes the `u64` offsets and sizes of a [`ListView`] chunk and returns its element window.
fn list_view_window(
    list: ArrayView<'_, ListView>,
    offsets_out: &mut [u64],
    sizes_out: &mut [u64],
    ctx: &mut ExecutionCtx,
) -> VortexResult<ElementWindow> {
    let chunk_offsets = list.offsets().clone().execute::<PrimitiveArray>(ctx)?;
    let chunk_sizes = list.sizes().clone().execute::<PrimitiveArray>(ctx)?;
    match_each_integer_ptype!(chunk_offsets.ptype(), |O| {
        for (out, &offset) in offsets_out.iter_mut().zip(chunk_offsets.as_slice::<O>()) {
            *out = offset.as_();
        }
    });
    match_each_integer_ptype!(chunk_sizes.ptype(), |S| {
        for (out, &size) in sizes_out.iter_mut().zip(chunk_sizes.as_slice::<S>()) {
            *out = size.as_();
        }
    });

    // Exact views bound their window with the first and last row. Other layouts need
    // both extrema so that overlaps and interior gaps remain unchanged.
    let (start, end) = if list.is_zero_copy_to_list() {
        let last = offsets_out.len() - 1;
        (offsets_out[0], offsets_out[last] + sizes_out[last])
    } else {
        offsets_out
            .iter()
            .zip(sizes_out.iter())
            .fold((u64::MAX, 0), |(start, end), (&offset, &size)| {
                (start.min(offset), end.max(offset + size))
            })
    };

    Ok(ElementWindow {
        elements: list.elements().clone(),
        start,
        end,
        zero_copy_to_list: list.is_zero_copy_to_list(),
    })
}

pub(super) fn swizzle_variant(
    array: ChunkedArray,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
    // The builder merges consecutive chunks of storage whose encoding has a storage builder, and
    // pads the shredded child with nulls for chunks that have none.
    let mut builder = VariantBuilder::new(array.dtype().nullability());
    builder.reserve_chunks(array.nchunks());
    for chunk in array.iter_chunks() {
        builder.append_variant_array(&chunk.as_::<Variant>().into_owned(), ctx)?;
    }
    builder.finish_into_variant().map(IntoArray::into_array)
}

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

    use vortex_buffer::buffer;
    use vortex_error::VortexResult;
    use vortex_error::vortex_bail;
    use vortex_error::vortex_err;
    use vortex_session::VortexSession;

    use crate::ArrayRef;
    use crate::Canonical;
    use crate::ExecutionCtx;
    use crate::IntoArray;
    use crate::VortexSessionExecute;
    use crate::arrays::ChunkedArray;
    use crate::arrays::ConstantArray;
    use crate::arrays::ListArray;
    use crate::arrays::ListViewArray;
    use crate::arrays::PrimitiveArray;
    use crate::arrays::VariantArray;
    use crate::arrays::listview::list_from_list_view;
    use crate::arrays::variant::VariantArraySlotsExt;
    use crate::assert_arrays_eq;
    use crate::dtype::DType::Variant as VariantDType;
    use crate::dtype::Nullability::NonNullable;
    use crate::scalar::Scalar;
    use crate::validity::Validity;

    /// A shared session for these chunked-array tests, used to create execution contexts.
    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

    fn variant_scalar(value: i32) -> Scalar {
        Scalar::variant(Scalar::primitive(value, NonNullable))
    }

    fn variant_core(values: impl IntoIterator<Item = i32>) -> VortexResult<ArrayRef> {
        Ok(ChunkedArray::try_new(
            values
                .into_iter()
                .map(|value| ConstantArray::new(variant_scalar(value), 1).into_array()),
            VariantDType(NonNullable),
        )?
        .into_array())
    }

    fn variant_chunk(values: impl IntoIterator<Item = i32>) -> VortexResult<VariantArray> {
        VariantArray::try_new(variant_core(values)?, None)
    }

    fn variant_chunk_with_shredded(
        values: impl IntoIterator<Item = i32>,
        shredded: ArrayRef,
    ) -> VortexResult<VariantArray> {
        VariantArray::try_new(variant_core(values)?, Some(shredded))
    }

    fn into_variant(canonical: Canonical) -> VortexResult<VariantArray> {
        match canonical {
            Canonical::Variant(array) => Ok(array),
            other => {
                vortex_bail!("expected Variant canonical array, got {other:?}")
            }
        }
    }

    fn assert_variant_values(array: &VariantArray, expected: &[i32]) -> VortexResult<()> {
        assert_eq!(array.dtype(), &VariantDType(NonNullable));
        assert_eq!(array.len(), expected.len());
        let mut ctx = SESSION.create_execution_ctx();

        for (idx, expected) in expected.iter().copied().enumerate() {
            let scalar = array.execute_scalar(idx, &mut ctx)?;
            let actual = scalar
                .as_variant()
                .value()
                .and_then(|value| value.as_primitive().as_::<i32>());
            assert_eq!(actual, Some(expected), "row {idx}");
        }

        Ok(())
    }

    /// Each chunk executes to a Variant before the builder joins them, and the rows of a chunk
    /// without a shredded child are null in the shredded child.
    #[test]
    fn canonicalize_variant_chunks() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(
            vec![
                variant_chunk_with_shredded([1], PrimitiveArray::from_iter([10i32]).into_array())?
                    .into_array(),
                variant_chunk([2])?.into_array(),
                variant_chunk_with_shredded([3], PrimitiveArray::from_iter([30i32]).into_array())?
                    .into_array(),
            ],
            VariantDType(NonNullable),
        )?
        .into_array();

        let variant = into_variant(chunked.execute::<Canonical>(&mut ctx)?)?;
        let shredded = variant
            .shredded()
            .ok_or_else(|| vortex_err!("expected shredded child"))?;

        assert_arrays_eq!(
            shredded,
            PrimitiveArray::from_option_iter([Some(10i32), None, Some(30)]),
            &mut ctx
        );
        assert_variant_values(&variant, &[10, 2, 30])
    }

    #[test]
    fn canonicalize_variant_chunks_empty() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let chunked = ChunkedArray::try_new(vec![], VariantDType(NonNullable))?.into_array();

        let variant = into_variant(chunked.execute::<Canonical>(&mut ctx)?)?;

        assert_eq!(variant.len(), 0);
        assert!(variant.shredded().is_none());
        Ok(())
    }

    fn list_view(
        elements: ArrayRef,
        offsets: &[u32],
        sizes: &[u32],
        ctx: &mut ExecutionCtx,
    ) -> ArrayRef {
        ListViewArray::new(
            elements,
            PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
            PrimitiveArray::from_iter(sizes.iter().copied()).into_array(),
            Validity::NonNullable,
            ctx,
        )
        .into_array()
    }

    #[test]
    fn list_chunks_drop_an_empty_chunks_elements() -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let chunks = vec![
            list_view(buffer![1i32, 2].into_array(), &[0], &[2], &mut ctx),
            // No lists, but still an element.
            list_view(buffer![99i32].into_array(), &[], &[], &mut ctx),
            list_view(buffer![3i32].into_array(), &[0], &[1], &mut ctx),
        ];
        let dtype = chunks[0].dtype().clone();
        let chunked = ChunkedArray::try_new(chunks, dtype)?.into_array();

        // Converting to a list reads the elements back to back, so a leftover 99 would land in
        // the first list.
        let list = list_from_list_view(chunked.execute::<ListViewArray>(&mut ctx)?, &mut ctx)?;
        let expected = ListArray::try_new(
            buffer![1i32, 2, 3].into_array(),
            buffer![0u32, 2, 3].into_array(),
            Validity::NonNullable,
            &mut ctx,
        )?;
        assert_arrays_eq!(list, expected, &mut ctx);
        Ok(())
    }
}