Skip to main content

vortex_array/array/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::fmt::Debug;
6use std::fmt::Formatter;
7use std::hash::Hasher;
8use std::sync::Arc;
9
10use vortex_buffer::ByteBuffer;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_ensure_eq;
15use vortex_error::vortex_err;
16use vortex_error::vortex_panic;
17use vortex_session::registry::Id;
18
19use crate::ExecutionCtx;
20use crate::buffer::BufferHandle;
21use crate::builders::ArrayBuilder;
22use crate::canonical::CanonicalKind;
23use crate::dtype::DType;
24use crate::dtype::Nullability;
25use crate::executor::ExecutionResult;
26use crate::scalar::Scalar;
27use crate::validity::Validity;
28
29mod erased;
30pub use erased::*;
31
32mod plugin;
33pub use plugin::*;
34mod probe;
35pub use probe::*;
36
37mod foreign;
38pub(crate) use foreign::*;
39
40mod typed;
41pub use typed::*;
42
43pub mod vtable;
44pub use vtable::*;
45
46mod view;
47use smallvec::SmallVec;
48pub use view::*;
49
50use crate::hash::ArrayEq;
51use crate::hash::ArrayHash;
52
53/// The slots of an array: a collection of optional child arrays.
54///
55/// Most encodings have 4 or fewer slots, so we use a `SmallVec` to avoid
56/// heap allocation in the common case.
57pub type ArraySlots = SmallVec<[Option<ArrayRef>; 4]>;
58
59/// A borrowed run of required slots, e.g. the variadic tail of a slot layout.
60///
61/// Wraps a `&[Option<ArrayRef>]` whose entries are guaranteed present by encoding
62/// validation, exposing them as `&ArrayRef` without per-call-site unwrapping.
63#[derive(Clone, Copy, Debug)]
64pub struct SlotSlice<'a> {
65    slots: &'a [Option<ArrayRef>],
66    expect: &'static str,
67}
68
69impl<'a> SlotSlice<'a> {
70    /// Wrap a slice of slots that validation guarantees are all present.
71    ///
72    /// `expect` names the slot run in the panic message if a slot is unexpectedly absent.
73    pub fn new(slots: &'a [Option<ArrayRef>], expect: &'static str) -> Self {
74        Self { slots, expect }
75    }
76
77    /// The number of slots in the run.
78    pub fn len(&self) -> usize {
79        self.slots.len()
80    }
81
82    /// Returns `true` if the run contains no slots.
83    pub fn is_empty(&self) -> bool {
84        self.slots.is_empty()
85    }
86
87    /// Returns the slot at `idx`, or `None` if out of bounds.
88    pub fn get(&self, idx: usize) -> Option<&'a ArrayRef> {
89        self.slots
90            .get(idx)
91            .map(|slot| slot.as_ref().vortex_expect(self.expect))
92    }
93
94    /// Iterate the slots in order.
95    pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a ArrayRef> + use<'a> {
96        let expect = self.expect;
97        self.slots
98            .iter()
99            .map(move |slot| slot.as_ref().vortex_expect(expect))
100    }
101
102    /// Clone every slot into an owned `Vec`.
103    pub fn to_vec(&self) -> Vec<ArrayRef> {
104        self.iter().cloned().collect()
105    }
106}
107
108impl std::ops::Index<usize> for SlotSlice<'_> {
109    type Output = ArrayRef;
110
111    fn index(&self, idx: usize) -> &Self::Output {
112        self.slots[idx].as_ref().vortex_expect(self.expect)
113    }
114}
115
116/// The public API trait for all Vortex arrays.
117///
118/// This trait is sealed and cannot be implemented outside of `vortex-array`.
119/// Use [`ArrayRef`] as the primary handle for working with arrays.
120#[doc(hidden)]
121pub(crate) trait DynArrayData: 'static + private::Sealed + Send + Sync + Debug {
122    /// Returns the array as a reference to a generic [`Any`] trait object.
123    fn as_any(&self) -> &dyn Any;
124
125    /// Classifies the concrete vtable independently of its logical dtype or encoding ID.
126    fn canonical_kind(&self) -> Option<CanonicalKind>;
127
128    /// Returns the [`Validity`] of the array.
129    fn validity(&self, this: &ArrayRef) -> VortexResult<Validity>;
130
131    /// Writes the array into the canonical builder.
132    ///
133    /// The [`DType`] of the builder must match that of the array.
134    fn append_to_builder(
135        &self,
136        this: &ArrayRef,
137        builder: &mut dyn ArrayBuilder,
138        ctx: &mut ExecutionCtx,
139    ) -> VortexResult<()>;
140
141    // --- Visitor methods (formerly in ArrayVisitor) ---
142
143    /// Returns the buffers of the array.
144    fn buffers(&self, this: &ArrayRef) -> Vec<ByteBuffer>;
145
146    /// Returns the buffer handles of the array.
147    fn buffer_handles(&self, this: &ArrayRef) -> Vec<BufferHandle>;
148
149    /// Returns the names of the buffers of the array.
150    fn buffer_names(&self, this: &ArrayRef) -> Vec<String>;
151
152    /// Returns the array's buffers with their names.
153    fn named_buffers(&self, this: &ArrayRef) -> Vec<(String, BufferHandle)>;
154
155    /// Returns the number of buffers of the array.
156    fn nbuffers(&self, this: &ArrayRef) -> usize;
157
158    /// Returns the name of the slot at the given index.
159    fn slot_name(&self, this: &ArrayRef, idx: usize) -> String;
160
161    /// Formats a human-readable metadata description.
162    fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result;
163
164    /// Hashes the array contents including len, dtype, and encoding id.
165    fn dyn_array_hash(&self, state: &mut dyn Hasher, accuracy: crate::EqMode);
166
167    /// Compares two arrays of the same concrete type for equality.
168    fn dyn_array_eq(&self, other: &ArrayRef, accuracy: crate::EqMode) -> bool;
169
170    /// Returns a new array with the given slots.
171    fn with_slots(&self, this: &ArrayRef, slots: ArraySlots) -> VortexResult<ArrayRef>;
172
173    /// Returns a new array with the given buffers.
174    fn with_buffers(&self, this: &ArrayRef, buffers: Vec<BufferHandle>) -> VortexResult<ArrayRef>;
175
176    /// Returns a new array with the given slots, bypassing encoding-level validation.
177    ///
178    /// Used by the executor to temporarily carry an array that has had one of its child slots
179    /// taken out (leaving `None`) without panicking `V::validate`. The caller must ensure the
180    /// missing slot is filled back in (via `put_slot_unchecked`) or driven to completion by the
181    /// builder path before the array becomes externally observable.
182    ///
183    /// # Safety
184    ///
185    /// The array returned may have slots whose content does not match the encoding's normal
186    /// invariants. Callers must re-establish those invariants before handing the array to
187    /// anything outside the executor.
188    unsafe fn with_slots_unchecked(&self, this: &ArrayRef, slots: ArraySlots) -> ArrayRef;
189
190    /// Attempt to reduce the array to a simpler representation.
191    fn reduce(&self, this: &ArrayRef) -> VortexResult<Option<ArrayRef>>;
192
193    /// The encoding's execute step, as a function taking the array by value.
194    ///
195    /// The executor calls it after this borrow of the array's data has ended: the step may drop
196    /// the last reference to the array, which must not happen while a reference into it is still
197    /// a live argument.
198    fn execute_fn(&self) -> ExecuteFn;
199
200    /// Read the scalar at `index`, including its nullness, retaining nothing.
201    ///
202    /// Caller must guarantee `index < len`.
203    ///
204    /// Kept apart from [`Self::probe_scalar_retained`] so this entry is a bare trampoline into
205    /// the encoding: sharing one function made the one-off path pay the retained branch's
206    /// register saves before its tail call.
207    fn probe_scalar_once(
208        &self,
209        this: &ArrayRef,
210        index: usize,
211        ctx: &mut ExecutionCtx,
212    ) -> VortexResult<Scalar>;
213
214    /// Read the scalar at `index`, including its nullness, keeping preparation in `state`.
215    ///
216    /// Caller must guarantee `index < len`.
217    fn probe_scalar_retained(
218        &self,
219        this: &ArrayRef,
220        index: usize,
221        state: &mut Option<Box<dyn Any>>,
222        ctx: &mut ExecutionCtx,
223    ) -> VortexResult<Scalar>;
224
225    /// Whether the row at `index` is valid, using the validity kept in `state`.
226    ///
227    /// Caller must guarantee `index < len`.
228    fn probe_is_valid_retained(
229        &self,
230        this: &ArrayRef,
231        index: usize,
232        state: &mut Option<Box<dyn Any>>,
233        ctx: &mut ExecutionCtx,
234    ) -> VortexResult<bool>;
235}
236
237/// An encoding's execute step: see [`DynArrayData::execute_fn`].
238pub(crate) type ExecuteFn = fn(ArrayRef, &mut ExecutionCtx) -> VortexResult<ExecutionResult>;
239
240/// Run `V`'s execute step on `this`, which must be an array of `V`.
241fn execute_encoding<V: VTable>(
242    this: ArrayRef,
243    ctx: &mut ExecutionCtx,
244) -> VortexResult<ExecutionResult> {
245    let typed = Array::<V>::try_from_array_ref(this)
246        .map_err(|_| vortex_err!("Failed to downcast array for execute"))
247        .vortex_expect("Failed to downcast array for execute");
248    V::execute(typed, ctx)
249}
250
251/// Trait for converting a type into a Vortex [`ArrayRef`].
252pub trait IntoArray {
253    /// Convert this value into the erased array handle used by generic APIs.
254    fn into_array(self) -> ArrayRef;
255}
256
257mod private {
258    use super::*;
259
260    pub trait Sealed {}
261
262    impl<V: VTable> Sealed for ArrayData<V> {}
263}
264
265// =============================================================================
266// New path: DynArrayData and supporting trait impls for ArrayData<V>
267// =============================================================================
268
269/// DynArrayData implementation for [`ArrayData<V>`].
270///
271/// This is self-contained: identity methods use `ArrayData<V>`'s own fields (dtype, len, stats),
272/// while data-access methods delegate to VTable methods on the inner `V::TypedArrayData`.
273impl<V: VTable> DynArrayData for ArrayData<V> {
274    fn canonical_kind(&self) -> Option<CanonicalKind> {
275        CanonicalKind::of::<V>()
276    }
277
278    fn as_any(&self) -> &dyn Any {
279        self
280    }
281
282    fn validity(&self, this: &ArrayRef) -> VortexResult<Validity> {
283        if this.dtype().is_nullable() {
284            let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
285            let validity = <V::ValidityVTable as ValidityVTable<V>>::validity(view)?;
286            if let Validity::Array(array) = &validity {
287                vortex_ensure_eq!(array.len(), this.len(), "Validity array length mismatch");
288                vortex_ensure!(
289                    matches!(array.dtype(), DType::Bool(Nullability::NonNullable)),
290                    "Validity array is not non-nullable boolean: {}",
291                    this.encoding_id(),
292                );
293            }
294            Ok(validity)
295        } else {
296            Ok(Validity::NonNullable)
297        }
298    }
299
300    fn append_to_builder(
301        &self,
302        this: &ArrayRef,
303        builder: &mut dyn ArrayBuilder,
304        ctx: &mut ExecutionCtx,
305    ) -> VortexResult<()> {
306        if builder.dtype() != this.dtype() {
307            vortex_panic!(
308                "Builder dtype mismatch: expected {}, got {}",
309                this.dtype(),
310                builder.dtype(),
311            );
312        }
313        let len = builder.len();
314
315        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
316        V::append_to_builder(view, builder, ctx)?;
317
318        assert_eq!(
319            len + this.len(),
320            builder.len(),
321            "Builder length mismatch after writing array for encoding {}",
322            this.encoding_id(),
323        );
324        Ok(())
325    }
326
327    fn buffers(&self, this: &ArrayRef) -> Vec<ByteBuffer> {
328        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
329        (0..V::nbuffers(view))
330            .map(|i| V::buffer(view, i).to_host_sync())
331            .collect()
332    }
333
334    fn buffer_handles(&self, this: &ArrayRef) -> Vec<BufferHandle> {
335        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
336        (0..V::nbuffers(view)).map(|i| V::buffer(view, i)).collect()
337    }
338
339    fn buffer_names(&self, this: &ArrayRef) -> Vec<String> {
340        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
341        (0..V::nbuffers(view))
342            .filter_map(|i| V::buffer_name(view, i))
343            .collect()
344    }
345
346    fn named_buffers(&self, this: &ArrayRef) -> Vec<(String, BufferHandle)> {
347        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
348        (0..V::nbuffers(view))
349            .filter_map(|i| V::buffer_name(view, i).map(|name| (name, V::buffer(view, i))))
350            .collect()
351    }
352
353    fn nbuffers(&self, this: &ArrayRef) -> usize {
354        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
355        V::nbuffers(view)
356    }
357
358    fn slot_name(&self, this: &ArrayRef, idx: usize) -> String {
359        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
360        V::slot_name(view, idx)
361    }
362
363    fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
364        std::fmt::Display::fmt(&self.data, f)
365    }
366
367    fn dyn_array_hash(&self, state: &mut dyn Hasher, accuracy: crate::EqMode) {
368        let mut wrapper = HasherWrapper(state);
369        // Note: metadata (len, dtype, encoding_id) and slots are hashed by ArrayRef.
370        self.data.array_hash(&mut wrapper, accuracy);
371    }
372
373    fn dyn_array_eq(&self, other: &ArrayRef, accuracy: crate::EqMode) -> bool {
374        // Note: metadata (len, dtype, encoding_id) and slots are compared by ArrayRef.
375        other
376            .dyn_array()
377            .as_any()
378            .downcast_ref::<Self>()
379            .is_some_and(|other_inner| self.data.array_eq(&other_inner.data, accuracy))
380    }
381
382    fn with_slots(&self, this: &ArrayRef, slots: ArraySlots) -> VortexResult<ArrayRef> {
383        let stats = this.statistics().to_owned();
384        Ok(Array::<V>::try_from_parts(ArrayParts::new(
385            self.vtable.clone(),
386            this.dtype().clone(),
387            this.len(),
388            self.data.clone(),
389            slots,
390        ))?
391        .with_stats_set(stats)
392        .into_array())
393    }
394
395    fn with_buffers(&self, this: &ArrayRef, buffers: Vec<BufferHandle>) -> VortexResult<ArrayRef> {
396        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
397        let stats = this.statistics().to_owned();
398        Ok(
399            Array::<V>::try_from_parts(V::with_buffers(&self.vtable, view, &buffers)?)?
400                .with_stats_set(stats)
401                .into_array(),
402        )
403    }
404
405    unsafe fn with_slots_unchecked(&self, this: &ArrayRef, slots: ArraySlots) -> ArrayRef {
406        // SAFETY: we intentionally skip `V::validate` here. Caller guarantees that the resulting
407        // array is either repaired or not externally observed.
408        let parts = ArrayParts::new(
409            self.vtable.clone(),
410            this.dtype().clone(),
411            this.len(),
412            self.data.clone(),
413            slots,
414        );
415        let encoding_id = self.vtable.id();
416        let stats = this.statistics().share_existing();
417        let uninit = Arc::new_uninit();
418
419        // SAFETY: `uninit` is new.
420        let store = unsafe { ArrayInner::init_arc(uninit, parts, encoding_id, stats) };
421
422        ArrayRef::from_inner(store)
423    }
424
425    fn reduce(&self, this: &ArrayRef) -> VortexResult<Option<ArrayRef>> {
426        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
427        let Some(reduced) = V::reduce(view)? else {
428            return Ok(None);
429        };
430        vortex_ensure_eq!(
431            reduced.len(),
432            this.len(),
433            "Reduced array length mismatch from {} to {}",
434            this.encoding_id(),
435            reduced.encoding_id()
436        );
437        // Rules may reduce to a non-nullable constant
438        vortex_ensure!(
439            reduced.dtype() == this.dtype()
440                || (reduced.dtype().eq_ignore_nullability(this.dtype())
441                    && !reduced.dtype().is_nullable()),
442            "Reduced array dtype mismatch from {} ({}) to {} ({})",
443            this.encoding_id(),
444            this.dtype(),
445            reduced.encoding_id(),
446            reduced.dtype()
447        );
448        Ok(Some(reduced))
449    }
450
451    fn execute_fn(&self) -> ExecuteFn {
452        execute_encoding::<V>
453    }
454
455    fn probe_scalar_once(
456        &self,
457        this: &ArrayRef,
458        index: usize,
459        ctx: &mut ExecutionCtx,
460    ) -> VortexResult<Scalar> {
461        // SAFETY: this adapter belongs to the ArrayData<V> stored in `this`.
462        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
463        <V::OperationsVTable as OperationsVTable<V>>::probe_scalar(
464            &mut ProbeState::once(view),
465            index,
466            ctx,
467        )
468    }
469
470    fn probe_scalar_retained(
471        &self,
472        this: &ArrayRef,
473        index: usize,
474        state: &mut Option<Box<dyn Any>>,
475        ctx: &mut ExecutionCtx,
476    ) -> VortexResult<Scalar> {
477        // SAFETY: this adapter belongs to the ArrayData<V> stored in `this`.
478        let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
479        let mut state = ProbeState::repeated(view, repeated_state(state)?);
480        <V::OperationsVTable as OperationsVTable<V>>::probe_scalar(&mut state, index, ctx)
481    }
482
483    fn probe_is_valid_retained(
484        &self,
485        this: &ArrayRef,
486        index: usize,
487        state: &mut Option<Box<dyn Any>>,
488        ctx: &mut ExecutionCtx,
489    ) -> VortexResult<bool> {
490        repeated_state::<EncodingProbeState<V>>(state)?.is_valid(this, index, ctx)
491    }
492}
493
494/// Wrapper around `&mut dyn Hasher` that implements `Hasher` (and is `Sized`).
495struct HasherWrapper<'a>(&'a mut dyn Hasher);
496
497impl Hasher for HasherWrapper<'_> {
498    fn finish(&self) -> u64 {
499        self.0.finish()
500    }
501
502    fn write(&mut self, bytes: &[u8]) {
503        self.0.write(bytes);
504    }
505}
506
507/// ArrayId is a globally unique name for the array's vtable.
508pub type ArrayId = Id;