vortex_array/array/vtable/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! This module contains the VTable definitions for a Vortex encoding.
5//!
6//! A Vortex array encoding is implemented by a small static vtable type plus an associated
7//! `TypedArrayData` value stored in each array instance. The vtable owns behavior such as
8//! validation, execution, child traversal, scalar access, and validity access.
9//!
10//! The public [`ArrayRef`] API performs common precondition checks before calling
11//! into these traits. Implementations should focus on encoding-specific work and uphold the
12//! documented postconditions.
13
14mod operations;
15mod validity;
16
17use std::fmt::Debug;
18use std::fmt::Display;
19use std::fmt::Formatter;
20use std::hash::Hasher;
21
22pub use operations::*;
23pub use validity::*;
24use vortex_error::VortexExpect;
25use vortex_error::VortexResult;
26use vortex_error::vortex_bail;
27use vortex_error::vortex_ensure;
28use vortex_error::vortex_panic;
29
30use crate::Array;
31use crate::ArrayRef;
32use crate::ArrayView;
33use crate::Canonical;
34use crate::EqMode;
35use crate::ExecutionResult;
36use crate::IntoArray;
37pub use crate::array::plugin::*;
38use crate::arrays::ConstantArray;
39use crate::arrays::constant::Constant;
40use crate::buffer::BufferHandle;
41use crate::builders::ArrayBuilder;
42use crate::dtype::DType;
43use crate::dtype::Nullability;
44use crate::executor::ExecutionCtx;
45use crate::hash::ArrayEq;
46use crate::hash::ArrayHash;
47use crate::patches::Patches;
48use crate::scalar::ScalarValue;
49use crate::validity::Validity;
50
51/// The array [`VTable`] encapsulates logic for an Array type within Vortex.
52///
53/// The logic is split across several "VTable" traits to enable easier code organization than
54/// simply lumping everything into a single trait.
55///
56/// From this [`VTable`] trait, we derive implementations for the sealed `DynArrayData` trait.
57/// Serialization is not part of the vtable: encodings that support serde implement
58/// [`ArrayPlugin`] separately and register it with the session.
59///
60/// The functions defined in these vtable traits will typically document their pre- and
61/// post-conditions. The pre-conditions are validated inside the `DynArrayData` and [`ArrayRef`]
62/// implementations so do not need to be checked in the vtable implementations (for example, index
63/// out of bounds). Post-conditions are validated after invocation of the vtable function and will
64/// panic if violated.
65pub trait VTable: 'static + Clone + Sized + Send + Sync + Debug {
66 /// Per-array data owned by this encoding, excluding child arrays.
67 ///
68 /// Child arrays belong in [`ArrayParts::slots`](crate::ArrayParts::slots) so traversal,
69 /// serialization, and layout writers can discover them generically.
70 type TypedArrayData: 'static + Send + Sync + Clone + Debug + Display + ArrayHash + ArrayEq;
71
72 /// Scalar and element-wise operation hooks for this encoding.
73 type OperationsVTable: OperationsVTable<Self>;
74 /// Validity hook for nullable instances of this encoding.
75 type ValidityVTable: ValidityVTable<Self>;
76
77 /// Returns the ID of the array.
78 fn id(&self) -> ArrayId;
79
80 /// Validates that externally supplied logical metadata matches the array data.
81 ///
82 /// This is called by [`Array::try_from_parts`](crate::Array::try_from_parts) before the array
83 /// is published. Implementations should check dtype, length, slot count, child dtypes/lengths,
84 /// metadata bounds, and any buffer shape invariants that unsafe accessors depend on.
85 ///
86 /// Do not read the statistics of the array or its children here. Statistics can come from
87 /// untrusted input, such as a serialized file, so an invariant must be checked on the data.
88 fn validate(
89 &self,
90 data: &Self::TypedArrayData,
91 dtype: &DType,
92 len: usize,
93 slots: &[Option<ArrayRef>],
94 ) -> VortexResult<()>;
95
96 /// Returns the number of top-level buffers in the array.
97 fn nbuffers(array: ArrayView<'_, Self>) -> usize;
98
99 /// Returns the buffer at the given index.
100 ///
101 /// # Panics
102 /// Panics if `idx >= nbuffers(array)`.
103 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle;
104
105 /// Returns the name of the buffer at the given index, or `None` if unnamed.
106 fn buffer_name(array: ArrayView<'_, Self>, idx: usize) -> Option<String>;
107
108 /// Rebuild this array with replacement top-level buffers.
109 ///
110 /// This is for physical rewrites that preserve `dtype`, `len`, child slots, buffer count, and
111 /// buffer lengths. The caller checks the generic invariants before dispatching here;
112 /// implementations should interpret the replacement buffers for their encoding-specific
113 /// in-memory representation.
114 fn with_buffers(
115 &self,
116 array: ArrayView<'_, Self>,
117 buffers: &[BufferHandle],
118 ) -> VortexResult<ArrayParts<Self>>;
119
120 /// Writes the array's logical values into a canonical builder.
121 ///
122 /// The default implementation executes the full array to [`Canonical`] and appends that result.
123 /// Encodings may override this to avoid materializing an intermediate canonical array.
124 fn append_to_builder(
125 array: ArrayView<'_, Self>,
126 builder: &mut dyn ArrayBuilder,
127 ctx: &mut ExecutionCtx,
128 ) -> VortexResult<()> {
129 let canonical = array
130 .array()
131 .clone()
132 .execute::<Canonical>(ctx)?
133 .into_array();
134 canonical.append_to_builder(builder, ctx)
135 }
136
137 /// Returns the name of the slot at the given index.
138 ///
139 /// # Panics
140 /// Panics if `idx >= slots(array).len()`.
141 fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String;
142
143 /// Execute this array by returning an [`ExecutionResult`].
144 ///
145 /// Execution is **iterative**, not recursive. Instead of recursively executing children,
146 /// implementations should return [`ExecutionResult::execute_slot`] to request that the
147 /// scheduler execute a slot first, or [`ExecutionResult::done`] when the encoding can
148 /// produce a result directly.
149 ///
150 /// For good examples of this pattern, see:
151 /// - [`Dict::execute`](crate::arrays::dict::vtable::Dict::execute) — demonstrates
152 /// requiring children via `require_child!` and producing a result once they are canonical.
153 /// - `BitPacked::execute` (in `vortex-fastlanes`) — demonstrates requiring patches and
154 /// validity via `require_patches!`/`require_validity!`.
155 ///
156 /// Array execution is designed such that repeated execution of an array will eventually
157 /// converge to a canonical representation. Implementations of this function should therefore
158 /// ensure they make progress towards that goal.
159 ///
160 /// The returned array (in `Done`) must be logically equivalent to the input array. In other
161 /// words, the recursively canonicalized forms of both arrays must be equal.
162 ///
163 /// Debug builds will panic if the returned array is of the wrong type, wrong length, or
164 /// incorrectly contains null values.
165 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult>;
166
167 /// Attempt to reduce the array to a simpler representation without changing logical values.
168 ///
169 /// Reductions are opportunistic and may return `Ok(None)` when no cheaper representation is
170 /// known.
171 fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
172 _ = array;
173 Ok(None)
174 }
175}
176
177/// Alias for migration — downstream code can start using `ArrayVTable`.
178pub use VTable as ArrayVTable;
179
180use crate::array::ArrayId;
181use crate::array::ArrayParts;
182
183/// Empty array metadata struct for encodings with no per-array metadata.
184#[derive(Clone, Debug, Default)]
185pub struct EmptyArrayData;
186
187impl ArrayEq for EmptyArrayData {
188 fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
189 true
190 }
191}
192impl ArrayHash for EmptyArrayData {
193 fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {}
194}
195
196impl Display for EmptyArrayData {
197 fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
198 Ok(())
199 }
200}
201
202/// Rebuild an array that has no top-level buffers.
203#[inline]
204pub fn with_empty_buffers<V: VTable>(
205 vtable: &V,
206 array: ArrayView<'_, V>,
207 buffers: &[BufferHandle],
208) -> VortexResult<ArrayParts<V>> {
209 vortex_ensure!(
210 buffers.is_empty(),
211 "Array {} expects 0 buffers, got {}",
212 array.encoding_id(),
213 buffers.len()
214 );
215 Ok(ArrayParts::new(
216 vtable.clone(),
217 array.dtype().clone(),
218 array.len(),
219 array.data().clone(),
220 array.slots().iter().cloned().collect(),
221 ))
222}
223
224/// Reject buffer replacement for encodings whose exposed buffers are not runtime backing buffers.
225#[inline]
226pub fn unsupported_buffer_replacement<V: VTable>(
227 array: ArrayView<'_, V>,
228 _buffers: &[BufferHandle],
229) -> VortexResult<ArrayParts<V>> {
230 vortex_bail!(
231 "Array {} does not support in-memory buffer replacement",
232 array.encoding_id()
233 )
234}
235
236/// Placeholder type used to indicate when a particular vtable is not supported by the encoding.
237pub struct NotSupported;
238
239/// Returns the validity as a child array if it produces one.
240#[inline]
241pub fn validity_to_child(validity: &Validity, len: usize) -> Option<ArrayRef> {
242 match validity {
243 Validity::NonNullable | Validity::AllValid => None,
244 Validity::AllInvalid => Some(ConstantArray::new(false, len).into_array()),
245 Validity::Array(array) => Some(array.clone()),
246 }
247}
248
249/// Reconstruct a [`Validity`] from an optional child array and nullability.
250///
251/// This is the inverse of [`validity_to_child`].
252#[inline]
253pub fn child_to_validity(child: Option<&ArrayRef>, nullability: Nullability) -> Validity {
254 match child {
255 Some(arr) => {
256 // Detect constant bool arrays created by validity_to_child.
257 // Use direct ScalarValue matching to avoid expensive scalar conversion.
258 if let Some(c) = arr.as_opt::<Constant>()
259 && let Some(ScalarValue::Bool(val)) = c.scalar().value()
260 {
261 return if *val {
262 Validity::AllValid
263 } else {
264 Validity::AllInvalid
265 };
266 }
267 Validity::Array(arr.clone())
268 }
269 None => Validity::from(nullability),
270 }
271}
272
273/// Returns 1 if validity produces a child, 0 otherwise.
274#[inline]
275pub fn validity_nchildren(validity: &Validity) -> usize {
276 match validity {
277 Validity::NonNullable | Validity::AllValid => 0,
278 Validity::AllInvalid | Validity::Array(_) => 1,
279 }
280}
281
282/// Returns the number of children produced by patches.
283#[inline]
284pub fn patches_nchildren(patches: &Patches) -> usize {
285 2 + patches.chunk_offsets().is_some() as usize
286}
287
288/// Returns the child at the given index within a patches component.
289#[inline]
290pub fn patches_child(patches: &Patches, idx: usize) -> ArrayRef {
291 match idx {
292 0 => patches.indices().clone(),
293 1 => patches.values().clone(),
294 2 => patches
295 .chunk_offsets()
296 .as_ref()
297 .vortex_expect("patch_chunk_offsets child out of bounds")
298 .clone(),
299 _ => vortex_panic!("patches child index {idx} out of bounds"),
300 }
301}
302
303/// Returns the name of the child at the given index within a patches component.
304#[inline]
305pub fn patches_child_name(idx: usize) -> &'static str {
306 match idx {
307 0 => "patch_indices",
308 1 => "patch_values",
309 2 => "patch_chunk_offsets",
310 _ => vortex_panic!("patches child name index {idx} out of bounds"),
311 }
312}