Skip to main content

vortex_scan/arrays/shared/
vtable.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hasher;
5
6use vortex_array::Array;
7use vortex_array::ArrayEq;
8use vortex_array::ArrayHash;
9use vortex_array::ArrayId;
10use vortex_array::ArrayParts;
11use vortex_array::ArrayRef;
12use vortex_array::ArrayView;
13use vortex_array::Canonical;
14use vortex_array::EqMode;
15use vortex_array::ExecutionCtx;
16use vortex_array::ExecutionResult;
17use vortex_array::OperationsVTable;
18use vortex_array::ProbeState;
19use vortex_array::RepeatedArrayProbe;
20use vortex_array::VTable;
21use vortex_array::ValidityVTable;
22use vortex_array::buffer::BufferHandle;
23use vortex_array::dtype::DType;
24use vortex_array::scalar::Scalar;
25use vortex_array::validity::Validity;
26use vortex_array::with_empty_buffers;
27use vortex_error::VortexExpect;
28use vortex_error::VortexResult;
29use vortex_error::vortex_panic;
30use vortex_session::registry::CachedId;
31
32use crate::arrays::shared::SharedArrayExt;
33use crate::arrays::shared::SharedData;
34use crate::arrays::shared::SharedSlots;
35
36/// A [`Shared`]-encoded Vortex array.
37pub type SharedArray = Array<Shared>;
38
39// TODO(ngates): consider hooking Shared into the iterative execution model. Cache either the
40//  most executed, or after each iteration, and return a shared cache for each execution.
41#[derive(Clone, Debug)]
42/// An array encoding that caches execution of its source.
43pub struct Shared;
44
45impl ArrayHash for SharedData {
46    fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {}
47}
48
49impl ArrayEq for SharedData {
50    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
51        true
52    }
53}
54
55impl VTable for Shared {
56    type TypedArrayData = SharedData;
57    type OperationsVTable = Self;
58    type ValidityVTable = Self;
59    fn id(&self) -> ArrayId {
60        static ID: CachedId = CachedId::new("vortex.shared");
61        *ID
62    }
63
64    fn validate(
65        &self,
66        _data: &SharedData,
67        dtype: &DType,
68        len: usize,
69        slots: &[Option<ArrayRef>],
70    ) -> VortexResult<()> {
71        let source = slots[SharedSlots::SOURCE]
72            .as_ref()
73            .vortex_expect("SharedArray source slot must be present");
74        vortex_error::vortex_ensure_eq!(source.dtype(), dtype, "SharedArray dtype mismatch");
75        vortex_error::vortex_ensure_eq!(source.len(), len, "SharedArray len mismatch");
76        Ok(())
77    }
78
79    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
80        0
81    }
82
83    fn buffer(_array: ArrayView<'_, Self>, _idx: usize) -> BufferHandle {
84        vortex_panic!("SharedArray has no buffers")
85    }
86
87    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
88        None
89    }
90
91    fn with_buffers(
92        &self,
93        array: ArrayView<'_, Self>,
94        buffers: &[BufferHandle],
95    ) -> VortexResult<ArrayParts<Self>> {
96        with_empty_buffers(self, array, buffers)
97    }
98
99    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
100        SharedSlots::NAMES[idx].to_string()
101    }
102
103    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
104        array
105            .get_or_compute(|source| source.clone().execute::<Canonical>(ctx))
106            .map(ExecutionResult::done)
107    }
108}
109
110/// A probe over whichever array [`SharedArrayExt::current_array_ref`] resolves to. The source
111/// can be replaced by the computed result between reads, so the retained probe is rebuilt when
112/// the array it was built over is no longer the current one.
113#[derive(Default)]
114pub struct SharedProbeState {
115    current: Option<RepeatedArrayProbe>,
116}
117
118impl OperationsVTable<Shared> for Shared {
119    type ProbeState = SharedProbeState;
120
121    fn probe_scalar(
122        state: &mut ProbeState<'_, Shared>,
123        index: usize,
124        ctx: &mut ExecutionCtx,
125    ) -> VortexResult<Scalar> {
126        let array = state.array();
127        let current = array.current_array_ref();
128        let Some(retained) = state.retained() else {
129            return current.probe().execute_scalar(index, ctx);
130        };
131        let probe = match &mut retained.current {
132            Some(probe) if ArrayRef::ptr_eq(probe.array(), current) => probe,
133            slot => slot.insert(RepeatedArrayProbe::new(current.clone())),
134        };
135        probe.execute_scalar(index, ctx)
136    }
137
138    fn scalar_at(
139        array: ArrayView<'_, Shared>,
140        index: usize,
141        ctx: &mut ExecutionCtx,
142    ) -> VortexResult<Scalar> {
143        Self::probe_scalar(&mut ProbeState::once(array), index, ctx)
144    }
145}
146
147impl ValidityVTable<Shared> for Shared {
148    fn validity(array: ArrayView<'_, Shared>) -> VortexResult<Validity> {
149        array.current_array_ref().validity()
150    }
151}