vortex_array/arrays/chunked/vtable/
mod.rs1use 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_err;
12use vortex_error::vortex_panic;
13use vortex_session::VortexSession;
14
15use crate::ArrayEq;
16use crate::ArrayHash;
17use crate::ArrayRef;
18use crate::Canonical;
19use crate::ExecutionCtx;
20use crate::ExecutionResult;
21use crate::IntoArray;
22use crate::Precision;
23use crate::ToCanonical;
24use crate::array::Array;
25use crate::array::ArrayId;
26use crate::array::ArrayParts;
27use crate::array::ArrayView;
28use crate::array::VTable;
29use crate::arrays::chunked::ChunkedArrayExt;
30use crate::arrays::chunked::ChunkedData;
31use crate::arrays::chunked::array::CHUNK_OFFSETS_SLOT;
32use crate::arrays::chunked::array::CHUNKS_OFFSET;
33use crate::arrays::chunked::compute::kernel::PARENT_KERNELS;
34use crate::arrays::chunked::compute::rules::PARENT_RULES;
35use crate::arrays::chunked::vtable::canonical::_canonicalize;
36use crate::buffer::BufferHandle;
37use crate::builders::ArrayBuilder;
38use crate::dtype::DType;
39use crate::dtype::Nullability;
40use crate::dtype::PType;
41use crate::serde::ArrayChildren;
42mod canonical;
43mod operations;
44mod validity;
45pub type ChunkedArray = Array<Chunked>;
47
48#[derive(Clone, Debug)]
49pub struct Chunked;
50
51impl Chunked {
52 pub const ID: ArrayId = ArrayId::new_ref("vortex.chunked");
53}
54
55impl ArrayHash for ChunkedData {
56 fn array_hash<H: Hasher>(&self, _state: &mut H, _precision: Precision) {
57 }
60}
61
62impl ArrayEq for ChunkedData {
63 fn array_eq(&self, _other: &Self, _precision: Precision) -> bool {
64 true
67 }
68}
69
70impl VTable for Chunked {
71 type ArrayData = ChunkedData;
72
73 type OperationsVTable = Self;
74 type ValidityVTable = Self;
75
76 fn id(&self) -> ArrayId {
77 Self::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 serialize(
161 _array: ArrayView<'_, Self>,
162 _session: &VortexSession,
163 ) -> VortexResult<Option<Vec<u8>>> {
164 Ok(Some(vec![]))
165 }
166
167 fn deserialize(
168 &self,
169 dtype: &DType,
170 len: usize,
171 metadata: &[u8],
172 _buffers: &[BufferHandle],
173 children: &dyn ArrayChildren,
174 _session: &VortexSession,
175 ) -> VortexResult<ArrayParts<Self>> {
176 if !metadata.is_empty() {
177 vortex_bail!(
178 "ChunkedArray expects empty metadata, got {} bytes",
179 metadata.len()
180 );
181 }
182 if children.is_empty() {
183 vortex_bail!("Chunked array needs at least one child");
184 }
185
186 let nchunks = children.len() - 1;
187 let chunk_offsets = children.get(
188 CHUNK_OFFSETS_SLOT,
189 &DType::Primitive(PType::U64, Nullability::NonNullable),
190 nchunks + 1,
191 )?;
192 let chunk_offsets_buf = chunk_offsets.to_primitive().to_buffer::<u64>();
193 let chunk_offsets_usize = chunk_offsets_buf
194 .iter()
195 .copied()
196 .map(|offset| {
197 usize::try_from(offset)
198 .map_err(|_| vortex_err!("chunk offset {offset} exceeds usize range"))
199 })
200 .collect::<VortexResult<Vec<_>>>()?;
201 let mut slots = Vec::with_capacity(children.len());
202 slots.push(Some(chunk_offsets));
203 for (idx, (start, end)) in chunk_offsets_usize
204 .iter()
205 .copied()
206 .tuple_windows()
207 .enumerate()
208 {
209 let chunk_len = end - start;
210 slots.push(Some(children.get(idx + CHUNKS_OFFSET, dtype, chunk_len)?));
211 }
212
213 Ok(ArrayParts::new(
214 self.clone(),
215 dtype.clone(),
216 len,
217 ChunkedData {
218 chunk_offsets: chunk_offsets_usize,
219 },
220 )
221 .with_slots(slots))
222 }
223
224 fn append_to_builder(
225 array: ArrayView<'_, Self>,
226 builder: &mut dyn ArrayBuilder,
227 ctx: &mut ExecutionCtx,
228 ) -> VortexResult<()> {
229 for chunk in array.iter_chunks() {
230 chunk.append_to_builder(builder, ctx)?;
231 }
232 Ok(())
233 }
234
235 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
236 match idx {
237 CHUNK_OFFSETS_SLOT => "chunk_offsets".to_string(),
238 n => format!("chunks[{}]", n - CHUNKS_OFFSET),
239 }
240 }
241
242 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
243 Ok(ExecutionResult::done(_canonicalize(array.as_view(), ctx)?))
244 }
245
246 fn execute_parent(
247 array: ArrayView<'_, Self>,
248 parent: &ArrayRef,
249 child_idx: usize,
250 ctx: &mut ExecutionCtx,
251 ) -> VortexResult<Option<ArrayRef>> {
252 PARENT_KERNELS.execute(array, parent, child_idx, ctx)
253 }
254
255 fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
256 Ok(match array.nchunks() {
257 0 => Some(Canonical::empty(array.dtype()).into_array()),
258 1 => Some(array.chunk(0).clone()),
259 _ => None,
260 })
261 }
262
263 fn reduce_parent(
264 array: ArrayView<'_, Self>,
265 parent: &ArrayRef,
266 child_idx: usize,
267 ) -> VortexResult<Option<ArrayRef>> {
268 PARENT_RULES.evaluate(array, parent, child_idx)
269 }
270}