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 smallvec::SmallVec;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_err;
13use vortex_error::vortex_panic;
14use vortex_session::VortexSession;
15use vortex_session::registry::CachedId;
16
17use crate::ArrayEq;
18use crate::ArrayHash;
19use crate::ArrayRef;
20use crate::Canonical;
21use crate::EqMode;
22use crate::ExecutionCtx;
23use crate::ExecutionResult;
24use crate::IntoArray;
25use crate::VortexSessionExecute;
26use crate::array::Array;
27use crate::array::ArrayId;
28use crate::array::ArrayParts;
29use crate::array::ArrayView;
30use crate::array::VTable;
31use crate::array::with_empty_buffers;
32use crate::arrays::PrimitiveArray;
33use crate::arrays::chunked::ChunkedArrayExt;
34use crate::arrays::chunked::ChunkedData;
35use crate::arrays::chunked::array::CHUNK_OFFSETS_SLOT;
36use crate::arrays::chunked::array::CHUNKS_OFFSET;
37use crate::arrays::chunked::compute::rules::PARENT_RULES;
38use crate::arrays::chunked::vtable::canonical::_canonicalize;
39use crate::buffer::BufferHandle;
40use crate::builders::ArrayBuilder;
41use crate::dtype::DType;
42use crate::dtype::Nullability;
43use crate::dtype::PType;
44use crate::serde::ArrayChildren;
45mod canonical;
46mod operations;
47mod validity;
48
49/// A [`Chunked`]-encoded Vortex array.
50pub type ChunkedArray = Array<Chunked>;
51
52#[derive(Clone, Debug)]
53pub struct Chunked;
54
55impl ArrayHash for ChunkedData {
56    fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {
57        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
58        // and ArrayData hashing includes every slot before TypedArrayData.
59    }
60}
61
62impl ArrayEq for ChunkedData {
63    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
64        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
65        // and ArrayData equality compares every slot before TypedArrayData.
66        true
67    }
68}
69
70impl VTable for Chunked {
71    type TypedArrayData = ChunkedData;
72
73    type OperationsVTable = Self;
74    type ValidityVTable = Self;
75    fn id(&self) -> ArrayId {
76        static ID: CachedId = CachedId::new("vortex.chunked");
77        *ID
78    }
79
80    fn validate(
81        &self,
82        data: &ChunkedData,
83        dtype: &DType,
84        len: usize,
85        slots: &[Option<ArrayRef>],
86    ) -> VortexResult<()> {
87        vortex_ensure!(
88            !slots.is_empty(),
89            "ChunkedArray must have at least a chunk offsets slot"
90        );
91        let chunk_offsets = slots[CHUNK_OFFSETS_SLOT]
92            .as_ref()
93            .vortex_expect("validated chunk offsets slot");
94        vortex_ensure!(
95            chunk_offsets.dtype() == &DType::Primitive(PType::U64, Nullability::NonNullable),
96            "ChunkedArray chunk offsets must be non-nullable u64, found {}",
97            chunk_offsets.dtype()
98        );
99        vortex_ensure!(
100            chunk_offsets.len() == data.chunk_offsets.len(),
101            "ChunkedArray chunk offsets slot length {} does not match cached offsets length {}",
102            chunk_offsets.len(),
103            data.chunk_offsets.len()
104        );
105        vortex_ensure!(
106            data.chunk_offsets.len() == slots.len() - CHUNKS_OFFSET + 1,
107            "ChunkedArray chunk offsets length {} does not match {} chunks",
108            data.chunk_offsets.len(),
109            slots.len() - CHUNKS_OFFSET
110        );
111        vortex_ensure!(
112            data.chunk_offsets
113                .last()
114                .copied()
115                .vortex_expect("chunked arrays always have a leading 0 offset")
116                == len,
117            "ChunkedArray length {} does not match outer length {}",
118            data.chunk_offsets.last().copied().unwrap_or_default(),
119            len
120        );
121        for (idx, (start, end)) in data
122            .chunk_offsets
123            .iter()
124            .copied()
125            .tuple_windows()
126            .enumerate()
127        {
128            let chunk = slots[CHUNKS_OFFSET + idx]
129                .as_ref()
130                .vortex_expect("validated chunk slot");
131            vortex_ensure!(
132                chunk.dtype() == dtype,
133                "ChunkedArray chunk dtype {} does not match outer dtype {}",
134                chunk.dtype(),
135                dtype
136            );
137            vortex_ensure!(
138                chunk.len() == end - start,
139                "ChunkedArray chunk {} len {} does not match offsets span {}",
140                idx,
141                chunk.len(),
142                end - start
143            );
144        }
145        Ok(())
146    }
147
148    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
149        0
150    }
151
152    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
153        vortex_panic!("ChunkedArray buffer index {idx} out of bounds")
154    }
155
156    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
157        vortex_panic!("ChunkedArray buffer_name index {idx} out of bounds")
158    }
159
160    fn with_buffers(
161        &self,
162        array: ArrayView<'_, Self>,
163        buffers: &[BufferHandle],
164    ) -> VortexResult<ArrayParts<Self>> {
165        with_empty_buffers(self, array, buffers)
166    }
167
168    fn serialize(
169        _array: ArrayView<'_, Self>,
170        _session: &VortexSession,
171    ) -> VortexResult<Option<Vec<u8>>> {
172        Ok(Some(vec![]))
173    }
174
175    fn deserialize(
176        &self,
177        dtype: &DType,
178        len: usize,
179        metadata: &[u8],
180        _buffers: &[BufferHandle],
181        children: &dyn ArrayChildren,
182        session: &VortexSession,
183    ) -> VortexResult<ArrayParts<Self>> {
184        if !metadata.is_empty() {
185            vortex_bail!(
186                "ChunkedArray expects empty metadata, got {} bytes",
187                metadata.len()
188            );
189        }
190        if children.is_empty() {
191            vortex_bail!("Chunked array needs at least one child");
192        }
193
194        let nchunks = children.len() - 1;
195        let chunk_offsets = children.get(
196            CHUNK_OFFSETS_SLOT,
197            &DType::Primitive(PType::U64, Nullability::NonNullable),
198            nchunks + 1,
199        )?;
200        let mut ctx = session.create_execution_ctx();
201        let chunk_offsets_buf = chunk_offsets
202            .clone()
203            .execute::<PrimitiveArray>(&mut ctx)?
204            .to_buffer::<u64>();
205        let chunk_offsets_usize = chunk_offsets_buf
206            .iter()
207            .copied()
208            .map(|offset| {
209                usize::try_from(offset)
210                    .map_err(|_| vortex_err!("chunk offset {offset} exceeds usize range"))
211            })
212            .collect::<VortexResult<Vec<_>>>()?;
213        let mut slots = SmallVec::with_capacity(children.len());
214        slots.push(Some(chunk_offsets));
215        for (idx, (start, end)) in chunk_offsets_usize
216            .iter()
217            .copied()
218            .tuple_windows()
219            .enumerate()
220        {
221            let chunk_len = end - start;
222            slots.push(Some(children.get(idx + CHUNKS_OFFSET, dtype, chunk_len)?));
223        }
224
225        Ok(ArrayParts::new(
226            self.clone(),
227            dtype.clone(),
228            len,
229            ChunkedData::new(chunk_offsets_usize),
230        )
231        .with_slots(slots))
232    }
233
234    fn append_to_builder(
235        array: ArrayView<'_, Self>,
236        builder: &mut dyn ArrayBuilder,
237        ctx: &mut ExecutionCtx,
238    ) -> VortexResult<()> {
239        for chunk in array.iter_chunks() {
240            chunk.append_to_builder(builder, ctx)?;
241        }
242        Ok(())
243    }
244
245    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
246        match idx {
247            CHUNK_OFFSETS_SLOT => "chunk_offsets".to_string(),
248            n => format!("chunks[{}]", n - CHUNKS_OFFSET),
249        }
250    }
251
252    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
253        match array.dtype() {
254            // Struct, List, FixedSizeList, and Variant need child swizzling that the builder path
255            // cannot express.
256            DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) | DType::Variant(..) => {
257                // TODO(joe)[#7674]: iterative execution here too
258                Ok(ExecutionResult::done(_canonicalize(array.as_view(), ctx)?))
259            }
260            // For all other types, use the builder path via AppendChild.
261            _ => {
262                let slot_idx = array.next_builder_slot.max(CHUNKS_OFFSET);
263                if slot_idx < array.slots().len() {
264                    Ok(ExecutionResult::append_child(
265                        array.with_next_builder_slot(slot_idx + 1),
266                        slot_idx,
267                    ))
268                } else {
269                    Ok(ExecutionResult::done(
270                        Canonical::empty(array.dtype()).into_array(),
271                    ))
272                }
273            }
274        }
275    }
276
277    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
278        Ok(match array.nchunks() {
279            0 => Some(Canonical::empty(array.dtype()).into_array()),
280            1 => Some(array.chunk(0).clone()),
281            _ => None,
282        })
283    }
284
285    fn reduce_parent(
286        array: ArrayView<'_, Self>,
287        parent: &ArrayRef,
288        child_idx: usize,
289    ) -> VortexResult<Option<ArrayRef>> {
290        PARENT_RULES.evaluate(array, parent, child_idx)
291    }
292}