vortex_array/arrays/chunked/vtable/
mod.rs1use 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_ensure_eq;
13use vortex_error::vortex_err;
14use vortex_error::vortex_panic;
15use vortex_session::VortexSession;
16use vortex_session::registry::CachedId;
17
18use crate::ArrayEq;
19use crate::ArrayHash;
20use crate::ArrayRef;
21use crate::Canonical;
22use crate::EqMode;
23use crate::ExecutionCtx;
24use crate::ExecutionResult;
25use crate::IntoArray;
26use crate::VortexSessionExecute;
27use crate::array::Array;
28use crate::array::ArrayId;
29use crate::array::ArrayParts;
30use crate::array::ArrayView;
31use crate::array::VTable;
32use crate::array::with_empty_buffers;
33use crate::arrays::PrimitiveArray;
34use crate::arrays::chunked::ChunkedArrayExt;
35use crate::arrays::chunked::ChunkedData;
36use crate::arrays::chunked::array::ChunkedSlots;
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
49pub 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 }
60}
61
62impl ArrayEq for ChunkedData {
63 fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
64 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[ChunkedSlots::CHUNK_OFFSETS]
92 .as_ref()
93 .vortex_expect("validated chunk offsets slot");
94 vortex_ensure_eq!(
95 chunk_offsets.dtype(),
96 &DType::Primitive(PType::U64, Nullability::NonNullable),
97 "ChunkedArray chunk offsets must be non-nullable u64",
98 );
99 vortex_ensure_eq!(
100 chunk_offsets.len(),
101 data.chunk_offsets.len(),
102 "ChunkedArray chunk offsets slot length does not match cached offsets length",
103 );
104 vortex_ensure_eq!(
105 data.chunk_offsets.len(),
106 slots.len() - ChunkedSlots::CHUNKS_OFFSET + 1,
107 "ChunkedArray must have one more chunk offset than chunks",
108 );
109 vortex_ensure_eq!(
110 data.chunk_offsets
111 .last()
112 .copied()
113 .vortex_expect("chunked arrays always have a leading 0 offset"),
114 len,
115 "ChunkedArray length does not match outer length",
116 );
117 for (idx, (start, end)) in data
118 .chunk_offsets
119 .iter()
120 .copied()
121 .tuple_windows()
122 .enumerate()
123 {
124 let chunk = slots[ChunkedSlots::CHUNKS_OFFSET + idx]
125 .as_ref()
126 .vortex_expect("validated chunk slot");
127 vortex_ensure_eq!(
128 chunk.dtype(),
129 dtype,
130 "ChunkedArray chunk dtype does not match outer dtype",
131 );
132 vortex_ensure_eq!(
133 chunk.len(),
134 end - start,
135 "ChunkedArray chunk {idx} len does not match offsets span",
136 );
137 }
138 Ok(())
139 }
140
141 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
142 0
143 }
144
145 fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
146 vortex_panic!("ChunkedArray buffer index {idx} out of bounds")
147 }
148
149 fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
150 vortex_panic!("ChunkedArray buffer_name index {idx} out of bounds")
151 }
152
153 fn with_buffers(
154 &self,
155 array: ArrayView<'_, Self>,
156 buffers: &[BufferHandle],
157 ) -> VortexResult<ArrayParts<Self>> {
158 with_empty_buffers(self, array, buffers)
159 }
160
161 fn serialize(
162 _array: ArrayView<'_, Self>,
163 _session: &VortexSession,
164 ) -> VortexResult<Option<Vec<u8>>> {
165 Ok(Some(vec![]))
166 }
167
168 fn deserialize(
169 &self,
170 dtype: &DType,
171 len: usize,
172 metadata: &[u8],
173 _buffers: &[BufferHandle],
174 children: &dyn ArrayChildren,
175 session: &VortexSession,
176 ) -> VortexResult<ArrayParts<Self>> {
177 if !metadata.is_empty() {
178 vortex_bail!(
179 "ChunkedArray expects empty metadata, got {} bytes",
180 metadata.len()
181 );
182 }
183 if children.is_empty() {
184 vortex_bail!("Chunked array needs at least one child");
185 }
186
187 let nchunks = children.len() - 1;
188 let chunk_offsets = children.get(
189 ChunkedSlots::CHUNK_OFFSETS,
190 &DType::Primitive(PType::U64, Nullability::NonNullable),
191 nchunks + 1,
192 )?;
193 let mut ctx = session.create_execution_ctx();
194 let chunk_offsets_buf = chunk_offsets
195 .clone()
196 .execute::<PrimitiveArray>(&mut ctx)?
197 .to_buffer::<u64>();
198 let chunk_offsets_usize = chunk_offsets_buf
199 .iter()
200 .copied()
201 .map(|offset| {
202 usize::try_from(offset)
203 .map_err(|_| vortex_err!("chunk offset {offset} exceeds usize range"))
204 })
205 .collect::<VortexResult<Vec<_>>>()?;
206 let mut slots = SmallVec::with_capacity(children.len());
207 slots.push(Some(chunk_offsets));
208 for (idx, (start, end)) in chunk_offsets_usize
209 .iter()
210 .copied()
211 .tuple_windows()
212 .enumerate()
213 {
214 let chunk_len = end - start;
215 slots.push(Some(children.get(
216 idx + ChunkedSlots::CHUNKS_OFFSET,
217 dtype,
218 chunk_len,
219 )?));
220 }
221
222 Ok(ArrayParts::new(
223 self.clone(),
224 dtype.clone(),
225 len,
226 ChunkedData::new(chunk_offsets_usize),
227 slots,
228 ))
229 }
230
231 fn append_to_builder(
232 array: ArrayView<'_, Self>,
233 builder: &mut dyn ArrayBuilder,
234 ctx: &mut ExecutionCtx,
235 ) -> VortexResult<()> {
236 for chunk in array.iter_chunks() {
237 chunk.append_to_builder(builder, ctx)?;
238 }
239 Ok(())
240 }
241
242 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
243 match idx {
244 ChunkedSlots::CHUNK_OFFSETS => "chunk_offsets".to_string(),
245 n => format!("chunks[{}]", n - ChunkedSlots::CHUNKS_OFFSET),
246 }
247 }
248
249 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
250 match array.dtype() {
251 DType::Union(..) => {
252 vortex_bail!(
253 "TODO(connor)[Union]: canonicalize chunked Union arrays by packing type IDs \
254 and every sparse child along identical chunk boundaries"
255 )
256 }
257 DType::Struct(..) | DType::List(..) | DType::FixedSizeList(..) | DType::Variant(..) => {
260 Ok(ExecutionResult::done(_canonicalize(array.as_view(), ctx)?))
262 }
263 _ => {
265 let slot_idx = array.next_builder_slot.max(ChunkedSlots::CHUNKS_OFFSET);
266 if slot_idx < array.slots().len() {
267 Ok(ExecutionResult::append_child(
268 array.with_next_builder_slot(slot_idx + 1),
269 slot_idx,
270 ))
271 } else {
272 Ok(ExecutionResult::done(
273 Canonical::empty(array.dtype()).into_array(),
274 ))
275 }
276 }
277 }
278 }
279
280 fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
281 Ok(match array.nchunks() {
282 0 => Some(Canonical::empty(array.dtype()).into_array()),
283 1 => Some(array.chunk(0).clone()),
284 _ => None,
285 })
286 }
287
288 fn reduce_parent(
289 array: ArrayView<'_, Self>,
290 parent: &ArrayRef,
291 child_idx: usize,
292 ) -> VortexResult<Option<ArrayRef>> {
293 PARENT_RULES.evaluate(array, parent, child_idx)
294 }
295}