Skip to main content

vortex_array/arrays/dict/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5use std::sync::Arc;
6
7use kernel::PARENT_KERNELS;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_err;
13use vortex_error::vortex_panic;
14use vortex_session::VortexSession;
15
16use super::DictArray;
17use super::DictArrayParts;
18use super::DictMetadata;
19use super::take_canonical;
20use crate::AnyCanonical;
21use crate::ArrayRef;
22use crate::Canonical;
23use crate::DeserializeMetadata;
24use crate::DynArray;
25use crate::IntoArray;
26use crate::Precision;
27use crate::ProstMetadata;
28use crate::SerializeMetadata;
29use crate::arrays::ConstantArray;
30use crate::arrays::Primitive;
31use crate::arrays::dict::compute::rules::PARENT_RULES;
32use crate::buffer::BufferHandle;
33use crate::dtype::DType;
34use crate::dtype::Nullability;
35use crate::dtype::PType;
36use crate::executor::ExecutionCtx;
37use crate::executor::ExecutionResult;
38use crate::hash::ArrayEq;
39use crate::hash::ArrayHash;
40use crate::require_child;
41use crate::scalar::Scalar;
42use crate::serde::ArrayChildren;
43use crate::stats::StatsSetRef;
44use crate::vtable;
45use crate::vtable::ArrayId;
46use crate::vtable::VTable;
47mod kernel;
48mod operations;
49mod validity;
50
51vtable!(Dict);
52
53#[derive(Clone, Debug)]
54pub struct Dict;
55
56impl Dict {
57    pub const ID: ArrayId = ArrayId::new_ref("vortex.dict");
58}
59
60impl VTable for Dict {
61    type Array = DictArray;
62
63    type Metadata = ProstMetadata<DictMetadata>;
64    type OperationsVTable = Self;
65    type ValidityVTable = Self;
66
67    fn vtable(_array: &Self::Array) -> &Self {
68        &Dict
69    }
70
71    fn id(&self) -> ArrayId {
72        Self::ID
73    }
74
75    fn len(array: &DictArray) -> usize {
76        array.codes.len()
77    }
78
79    fn dtype(array: &DictArray) -> &DType {
80        &array.dtype
81    }
82
83    fn stats(array: &DictArray) -> StatsSetRef<'_> {
84        array.stats_set.to_ref(array.as_ref())
85    }
86
87    fn array_hash<H: std::hash::Hasher>(array: &DictArray, state: &mut H, precision: Precision) {
88        array.dtype.hash(state);
89        array.codes.array_hash(state, precision);
90        array.values.array_hash(state, precision);
91    }
92
93    fn array_eq(array: &DictArray, other: &DictArray, precision: Precision) -> bool {
94        array.dtype == other.dtype
95            && array.codes.array_eq(&other.codes, precision)
96            && array.values.array_eq(&other.values, precision)
97    }
98
99    fn nbuffers(_array: &DictArray) -> usize {
100        0
101    }
102
103    fn buffer(_array: &DictArray, idx: usize) -> BufferHandle {
104        vortex_panic!("DictArray buffer index {idx} out of bounds")
105    }
106
107    fn buffer_name(_array: &DictArray, _idx: usize) -> Option<String> {
108        None
109    }
110
111    fn nchildren(_array: &DictArray) -> usize {
112        2
113    }
114
115    fn child(array: &DictArray, idx: usize) -> ArrayRef {
116        match idx {
117            0 => array.codes().clone(),
118            1 => array.values().clone(),
119            _ => vortex_panic!("DictArray child index {idx} out of bounds"),
120        }
121    }
122
123    fn child_name(_array: &DictArray, idx: usize) -> String {
124        match idx {
125            0 => "codes".to_string(),
126            1 => "values".to_string(),
127            _ => vortex_panic!("DictArray child_name index {idx} out of bounds"),
128        }
129    }
130
131    fn metadata(array: &DictArray) -> VortexResult<Self::Metadata> {
132        Ok(ProstMetadata(DictMetadata {
133            codes_ptype: PType::try_from(array.codes().dtype())? as i32,
134            values_len: u32::try_from(array.values().len()).map_err(|_| {
135                vortex_err!(
136                    "Dictionary values size {} overflowed u32",
137                    array.values().len()
138                )
139            })?,
140            is_nullable_codes: Some(array.codes().dtype().is_nullable()),
141            all_values_referenced: Some(array.all_values_referenced),
142        }))
143    }
144
145    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
146        Ok(Some(metadata.serialize()))
147    }
148
149    fn deserialize(
150        bytes: &[u8],
151        _dtype: &DType,
152        _len: usize,
153        _buffers: &[BufferHandle],
154        _session: &VortexSession,
155    ) -> VortexResult<Self::Metadata> {
156        let metadata = <Self::Metadata as DeserializeMetadata>::deserialize(bytes)?;
157        Ok(ProstMetadata(metadata))
158    }
159
160    fn build(
161        dtype: &DType,
162        len: usize,
163        metadata: &Self::Metadata,
164        _buffers: &[BufferHandle],
165        children: &dyn ArrayChildren,
166    ) -> VortexResult<DictArray> {
167        if children.len() != 2 {
168            vortex_bail!(
169                "Expected 2 children for dict encoding, found {}",
170                children.len()
171            )
172        }
173        let codes_nullable = metadata
174            .is_nullable_codes
175            .map(Nullability::from)
176            // If no `is_nullable_codes` metadata use the nullability of the values
177            // (and whole array) as before.
178            .unwrap_or_else(|| dtype.nullability());
179        let codes_dtype = DType::Primitive(metadata.codes_ptype(), codes_nullable);
180        let codes = children.get(0, &codes_dtype, len)?;
181        let values = children.get(1, dtype, metadata.values_len as usize)?;
182        let all_values_referenced = metadata.all_values_referenced.unwrap_or(false);
183
184        // SAFETY: We've validated the metadata and children.
185        Ok(unsafe {
186            DictArray::new_unchecked(codes, values).set_all_values_referenced(all_values_referenced)
187        })
188    }
189
190    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
191        vortex_ensure!(
192            children.len() == 2,
193            "DictArray expects exactly 2 children (codes, values), got {}",
194            children.len()
195        );
196        let [codes, values]: [ArrayRef; 2] = children
197            .try_into()
198            .map_err(|_| vortex_err!("Failed to convert children to array"))?;
199        array.codes = codes;
200        array.values = values;
201        Ok(())
202    }
203
204    fn execute(array: Arc<Self::Array>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
205        if array.is_empty() {
206            let result_dtype = array
207                .dtype()
208                .union_nullability(array.codes().dtype().nullability());
209            return Ok(ExecutionResult::done(Canonical::empty(&result_dtype)));
210        }
211
212        let array = require_child!(Self, array, array.codes(), 0 => Primitive);
213
214        // TODO(joe): use stat get instead computing.
215        // Also not the check to do here it take value validity using code validity, but this approx
216        // is correct.
217        if array.codes().all_invalid()? {
218            return Ok(ExecutionResult::done(
219                ConstantArray::new(Scalar::null(array.dtype().as_nullable()), array.codes.len())
220                    .into_array(),
221            ));
222        }
223
224        let array = require_child!(Self, array, array.values(), 1 => AnyCanonical);
225
226        let DictArrayParts { codes, values, .. } = Arc::unwrap_or_clone(array).into_parts();
227
228        let codes = codes
229            .try_into::<Primitive>()
230            .ok()
231            .vortex_expect("must be primitive");
232        debug_assert!(values.is_canonical());
233        // TODO: add canonical owned cast.
234        let values = values.to_canonical()?;
235
236        Ok(ExecutionResult::done(
237            take_canonical(values, &codes, ctx)?.into_array(),
238        ))
239    }
240
241    fn reduce_parent(
242        array: &Self::Array,
243        parent: &ArrayRef,
244        child_idx: usize,
245    ) -> VortexResult<Option<ArrayRef>> {
246        PARENT_RULES.evaluate(array, parent, child_idx)
247    }
248
249    fn execute_parent(
250        array: &Self::Array,
251        parent: &ArrayRef,
252        child_idx: usize,
253        ctx: &mut ExecutionCtx,
254    ) -> VortexResult<Option<ArrayRef>> {
255        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
256    }
257}