Skip to main content

vortex_array/arrays/chunked/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hasher;
5
6use itertools::Itertools;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_ensure;
11use vortex_error::vortex_ensure_eq;
12use vortex_error::vortex_panic;
13use vortex_session::registry::CachedId;
14
15use crate::ArrayEq;
16use crate::ArrayHash;
17use crate::ArrayRef;
18use crate::Canonical;
19use crate::EqMode;
20use crate::ExecutionCtx;
21use crate::ExecutionResult;
22use crate::IntoArray;
23use crate::array::Array;
24use crate::array::ArrayId;
25use crate::array::ArrayParts;
26use crate::array::ArrayView;
27use crate::array::VTable;
28use crate::array::with_empty_buffers;
29use crate::arrays::FixedSizeList;
30use crate::arrays::Struct;
31use crate::arrays::Variant;
32use crate::arrays::chunked::ChunkedArrayExt;
33use crate::arrays::chunked::ChunkedData;
34use crate::arrays::chunked::array::ChunkedSlots;
35use crate::arrays::chunked::compute::rules::RULES;
36use crate::arrays::chunked::vtable::canonical::ListChunks;
37use crate::arrays::chunked::vtable::canonical::swizzle;
38use crate::arrays::chunked::vtable::canonical::swizzle_fixed_size_list;
39use crate::arrays::chunked::vtable::canonical::swizzle_list;
40use crate::arrays::chunked::vtable::canonical::swizzle_struct;
41use crate::arrays::chunked::vtable::canonical::swizzle_variant;
42use crate::buffer::BufferHandle;
43use crate::builders::ArrayBuilder;
44use crate::dtype::DType;
45use crate::dtype::Nullability;
46use crate::dtype::PType;
47mod canonical;
48mod operations;
49mod plugin;
50mod validity;
51
52/// A [`Chunked`]-encoded Vortex array.
53pub type ChunkedArray = Array<Chunked>;
54
55#[derive(Clone, Debug)]
56pub struct Chunked;
57
58impl ArrayHash for ChunkedData {
59    fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {
60        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
61        // and ArrayData hashing includes every slot before TypedArrayData.
62    }
63}
64
65impl ArrayEq for ChunkedData {
66    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
67        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
68        // and ArrayData equality compares every slot before TypedArrayData.
69        true
70    }
71}
72
73impl VTable for Chunked {
74    type TypedArrayData = ChunkedData;
75
76    type OperationsVTable = Self;
77    type ValidityVTable = Self;
78    fn id(&self) -> ArrayId {
79        static ID: CachedId = CachedId::new("vortex.chunked");
80        *ID
81    }
82
83    fn validate(
84        &self,
85        data: &ChunkedData,
86        dtype: &DType,
87        len: usize,
88        slots: &[Option<ArrayRef>],
89    ) -> VortexResult<()> {
90        vortex_ensure!(
91            !slots.is_empty(),
92            "ChunkedArray must have at least a chunk offsets slot"
93        );
94        let chunk_offsets = slots[ChunkedSlots::CHUNK_OFFSETS]
95            .as_ref()
96            .vortex_expect("validated chunk offsets slot");
97        vortex_ensure_eq!(
98            chunk_offsets.dtype(),
99            &DType::Primitive(PType::U64, Nullability::NonNullable),
100            "ChunkedArray chunk offsets must be non-nullable u64",
101        );
102        vortex_ensure_eq!(
103            chunk_offsets.len(),
104            data.chunk_offsets.len(),
105            "ChunkedArray chunk offsets slot length does not match cached offsets length",
106        );
107        vortex_ensure_eq!(
108            data.chunk_offsets.len(),
109            slots.len() - ChunkedSlots::CHUNKS_OFFSET + 1,
110            "ChunkedArray must have one more chunk offset than chunks",
111        );
112        vortex_ensure_eq!(
113            data.chunk_offsets
114                .last()
115                .copied()
116                .vortex_expect("chunked arrays always have a leading 0 offset"),
117            len,
118            "ChunkedArray length does not match outer length",
119        );
120        for (idx, (start, end)) in data
121            .chunk_offsets
122            .iter()
123            .copied()
124            .tuple_windows()
125            .enumerate()
126        {
127            let chunk = slots[ChunkedSlots::CHUNKS_OFFSET + idx]
128                .as_ref()
129                .vortex_expect("validated chunk slot");
130            vortex_ensure_eq!(
131                chunk.dtype(),
132                dtype,
133                "ChunkedArray chunk dtype does not match outer dtype",
134            );
135            vortex_ensure_eq!(
136                chunk.len(),
137                end - start,
138                "ChunkedArray chunk {idx} len does not match offsets span",
139            );
140        }
141        Ok(())
142    }
143
144    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
145        0
146    }
147
148    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
149        vortex_panic!("ChunkedArray buffer index {idx} out of bounds")
150    }
151
152    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
153        vortex_panic!("ChunkedArray buffer_name index {idx} out of bounds")
154    }
155
156    fn with_buffers(
157        &self,
158        array: ArrayView<'_, Self>,
159        buffers: &[BufferHandle],
160    ) -> VortexResult<ArrayParts<Self>> {
161        with_empty_buffers(self, array, buffers)
162    }
163
164    fn append_to_builder(
165        array: ArrayView<'_, Self>,
166        builder: &mut dyn ArrayBuilder,
167        ctx: &mut ExecutionCtx,
168    ) -> VortexResult<()> {
169        // The builder is about to receive one array per chunk, so let any chunk lists it keeps
170        // grow once rather than on the way through.
171        builder.reserve_chunks(array.nchunks());
172        for chunk in array.iter_chunks() {
173            chunk.append_to_builder(builder, ctx)?;
174        }
175        Ok(())
176    }
177
178    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
179        match idx {
180            ChunkedSlots::CHUNK_OFFSETS => "chunk_offsets".to_string(),
181            n => format!("chunks[{}]", n - ChunkedSlots::CHUNKS_OFFSET),
182        }
183    }
184
185    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
186        match array.dtype() {
187            DType::Union(..) => {
188                vortex_bail!(
189                    "TODO(connor)[Union]: canonicalize chunked Union arrays by packing type IDs \
190                     and every sparse child along identical chunk boundaries"
191                )
192            }
193            DType::FixedSizeList(..) => swizzle::<FixedSizeList>(array, swizzle_fixed_size_list),
194            DType::Struct(..) => swizzle::<Struct>(array, swizzle_struct),
195            DType::List(..) => swizzle::<ListChunks>(array, |array| swizzle_list(array, ctx)),
196            DType::Variant(..) => swizzle::<Variant>(array, |array| swizzle_variant(array, ctx)),
197            // For all other types, use the builder path via AppendChild.
198            _ => {
199                let slot_idx = array.next_child_slot.max(ChunkedSlots::CHUNKS_OFFSET);
200                if slot_idx < array.slots().len() {
201                    Ok(ExecutionResult::append_child(
202                        array.with_next_child_slot(slot_idx + 1),
203                        slot_idx,
204                    ))
205                } else if slot_idx == ChunkedSlots::CHUNKS_OFFSET {
206                    // No chunks at all, so nothing was ever appended and the executor holds no
207                    // builder to finish. This array really is empty.
208                    Ok(ExecutionResult::done(
209                        Canonical::empty(array.dtype()).into_array(),
210                    ))
211                } else {
212                    // Every chunk has gone to the builder, which is what the executor will finish.
213                    Ok(ExecutionResult::done_into_builder(array))
214                }
215            }
216        }
217    }
218
219    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
220        Ok(match array.nchunks() {
221            // Variant has no empty canonical form; canonicalization handles empty variant chunks.
222            0 if matches!(array.dtype(), DType::Variant(_)) => None,
223            0 => Some(Canonical::empty(array.dtype()).into_array()),
224            1 => Some(array.chunk(0).clone()),
225            _ => return RULES.evaluate(array),
226        })
227    }
228}