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::Hasher;
5
6use num_traits::AsPrimitive;
7use vortex_error::VortexResult;
8use vortex_error::vortex_ensure_eq;
9use vortex_error::vortex_panic;
10use vortex_mask::AllOr;
11use vortex_mask::Mask;
12use vortex_session::VortexSession;
13use vortex_session::registry::CachedId;
14
15use super::DictData;
16use super::DictOwnedExt;
17use super::DictParts;
18use super::array::DictSlots;
19use super::array::DictSlotsView;
20use crate::AnyCanonical;
21use crate::ArrayEq;
22use crate::ArrayHash;
23use crate::ArrayRef;
24use crate::Canonical;
25use crate::CanonicalView;
26use crate::EqMode;
27use crate::IntoArray;
28use crate::array::Array;
29use crate::array::ArrayId;
30use crate::array::ArrayParts;
31use crate::array::ArrayView;
32use crate::array::VTable;
33use crate::array::with_empty_buffers;
34use crate::arrays::ConstantArray;
35use crate::arrays::Primitive;
36use crate::arrays::PrimitiveArray;
37use crate::arrays::VarBinView;
38use crate::arrays::dict::DictArraySlotsExt;
39use crate::arrays::dict::compute::rules::RULES;
40use crate::arrays::dict::execute::take_canonical;
41use crate::buffer::BufferHandle;
42use crate::builders::ArrayBuilder;
43use crate::builders::VarBinBuilder;
44use crate::builders::VarBinViewBuilder;
45use crate::dtype::DType;
46use crate::dtype::OffsetBuilderPType;
47use crate::executor::ExecutionCtx;
48use crate::executor::ExecutionResult;
49use crate::match_each_integer_ptype;
50use crate::match_each_varbin_builder;
51use crate::require_child;
52use crate::scalar::Scalar;
53
54mod kernel;
55mod operations;
56mod plugin;
57mod validity;
58
59/// A [`Dict`]-encoded Vortex array.
60pub type DictArray = Array<Dict>;
61
62pub(crate) fn initialize(session: &VortexSession) {
63    kernel::initialize(session);
64}
65
66#[derive(Clone, Debug)]
67pub struct Dict;
68
69impl ArrayHash for DictData {
70    fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {}
71}
72
73impl ArrayEq for DictData {
74    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
75        true
76    }
77}
78
79impl VTable for Dict {
80    type TypedArrayData = DictData;
81
82    type OperationsVTable = Self;
83    type ValidityVTable = Self;
84
85    fn id(&self) -> ArrayId {
86        static ID: CachedId = CachedId::new("vortex.dict");
87        *ID
88    }
89
90    fn validate(
91        &self,
92        _data: &DictData,
93        dtype: &DType,
94        len: usize,
95        slots: &[Option<ArrayRef>],
96    ) -> VortexResult<()> {
97        let view = DictSlotsView::from_slots(slots);
98        let codes = view.codes;
99        let values = view.values;
100        vortex_ensure_eq!(codes.len(), len, "DictArray codes length mismatch");
101        vortex_ensure_eq!(
102            values
103                .dtype()
104                .union_nullability(codes.dtype().nullability()),
105            *dtype,
106            "DictArray dtype does not match codes/values dtype",
107        );
108        Ok(())
109    }
110
111    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
112        0
113    }
114
115    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
116        vortex_panic!("DictArray buffer index {idx} out of bounds")
117    }
118
119    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
120        None
121    }
122
123    fn with_buffers(
124        &self,
125        array: ArrayView<'_, Self>,
126        buffers: &[BufferHandle],
127    ) -> VortexResult<ArrayParts<Self>> {
128        with_empty_buffers(self, array, buffers)
129    }
130
131    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
132        DictSlots::NAMES[idx].to_string()
133    }
134
135    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
136        if array.is_empty() {
137            let result_dtype = array
138                .dtype()
139                .union_nullability(array.codes().dtype().nullability());
140            return Ok(ExecutionResult::done(Canonical::empty(&result_dtype)));
141        }
142
143        let array = require_child!(array, array.codes(), DictSlots::CODES => Primitive);
144
145        if array.codes().validity()?.definitely_all_null() {
146            return Ok(ExecutionResult::done(ConstantArray::new(
147                Scalar::null(array.dtype().as_nullable()),
148                array.codes().len(),
149            )));
150        }
151
152        let array = require_child!(array, array.values(), DictSlots::VALUES => AnyCanonical);
153
154        let DictParts { values, codes, .. } = array.into_parts();
155
156        Ok(ExecutionResult::done(take_canonical(
157            values.as_::<AnyCanonical>(),
158            codes.as_::<Primitive>(),
159            ctx,
160        )?))
161    }
162
163    fn append_to_builder(
164        array: ArrayView<'_, Self>,
165        builder: &mut dyn ArrayBuilder,
166        ctx: &mut ExecutionCtx,
167    ) -> VortexResult<()> {
168        if !array.is_empty() && !array.codes().validity()?.definitely_all_null() {
169            let values = array.values();
170
171            if array.len() <= values.len() / sparse_take_ratio(array.dtype())
172                && !values.is::<AnyCanonical>()
173            {
174                // A Dict with few codes over encoded values is usually a lazy `take`. Execute it
175                // so the take kernel of the values (ALP-RD, BitPacked, the OnPair token-run
176                // gather, ...) decodes only the selected rows, rather than decoding every value
177                // and then gathering. The codes stay as they are: a kernel can take a structured
178                // index array, such as the runs of a `PiecewiseSequenceArray`, faster than the
179                // same indices expanded one by one.
180                let canonical = array
181                    .array()
182                    .clone()
183                    .execute::<Canonical>(ctx)?
184                    .into_array();
185                return canonical.append_to_builder(builder, ctx);
186            }
187
188            let codes = array.codes().clone().execute::<PrimitiveArray>(ctx)?;
189
190            // Decode the children without taking values to the full row count. The
191            // variable-binary builders gather directly through these dictionary codes.
192            let values = if array.values().is::<AnyCanonical>() {
193                array.values().clone()
194            } else {
195                array
196                    .values()
197                    .clone()
198                    .execute::<Canonical>(ctx)?
199                    .into_array()
200            };
201            let values = values.as_::<AnyCanonical>();
202            let codes = codes.as_view();
203            if let CanonicalView::VarBinView(values) = values
204                && let Some(result) = match_each_varbin_builder!(builder, |builder| {
205                    let validity = array.validity()?.execute_mask(array.len(), ctx)?;
206                    append_dict_to_varbin(codes, values, validity, builder)
207                })
208            {
209                return result;
210            }
211            if let CanonicalView::VarBinView(values) = values
212                && let Some(builder) = builder.as_any_mut().downcast_mut::<VarBinViewBuilder>()
213            {
214                let validity = array.validity()?.execute_mask(array.len(), ctx)?;
215                return append_dict_to_varbinview(codes, values, validity, builder);
216            }
217            let canonical = take_canonical(values, codes, ctx)?.into_array();
218            canonical.append_to_builder(builder, ctx)?;
219            return Ok(());
220        }
221
222        let canonical = array
223            .array()
224            .clone()
225            .execute::<Canonical>(ctx)?
226            .into_array();
227        canonical.append_to_builder(builder, ctx)?;
228        Ok(())
229    }
230
231    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
232        RULES.evaluate(array)
233    }
234}
235
236/// The values-to-codes ratio at or above which `Dict::append_to_builder` runs the take kernel of
237/// encoded values instead of decoding all of them.
238///
239/// Fixed-width encodings decode in bulk for under a nanosecond per value, while their take kernels
240/// cost over ten times that per row: taking rows of an ALP-RD `f32` segment breaks even at about
241/// one row in eleven (see the `alp_rd_take_chunked` benchmark in `vortex-alp`). The ratio for
242/// variable-width values was chosen for their take kernels, such as the OnPair token-run gather.
243fn sparse_take_ratio(dtype: &DType) -> usize {
244    match dtype {
245        DType::Utf8(_) | DType::Binary(_) => 4,
246        _ => 16,
247    }
248}
249
250/// Gathers the dictionary values straight into `builder` as views.
251///
252/// The canonical route first takes the values to full logical length — allocating an intermediate
253/// views buffer proportional to the row count — and then `append_varbinview_array` walks all
254/// those views a second time to rebase their buffer indices onto the builder's. Gathering through
255/// the codes directly instead adopts the dictionary's buffers once (deduplicated across chunks
256/// sharing the dictionary, when the builder deduplicates) and writes each row's rebased view in a
257/// single pass, with no byte copy at all.
258fn append_dict_to_varbinview(
259    codes: ArrayView<'_, Primitive>,
260    values: ArrayView<'_, VarBinView>,
261    validity: Mask,
262    builder: &mut VarBinViewBuilder,
263) -> VortexResult<()> {
264    let views = values.views();
265    let buffers = values
266        .data_buffers()
267        .iter()
268        .map(|buffer| buffer.as_host().clone())
269        .collect::<Vec<_>>();
270
271    match_each_integer_ptype!(codes.ptype(), |C| {
272        let codes = codes.as_slice::<C>();
273        builder.append_views_gathered(buffers, views, &validity, |row| {
274            AsPrimitive::<usize>::as_(codes[row])
275        });
276    });
277    Ok(())
278}
279
280/// Gathers the dictionary values straight into `builder`.
281///
282/// The canonical route first takes the values to full logical length, which allocates and then
283/// re-reads a views buffer proportional to the row count. The dictionary is usually far smaller
284/// than the column, so resolving each code against it in place skips that intermediate entirely
285/// and leaves one `memcpy` per row as the only work.
286fn append_dict_to_varbin<O: OffsetBuilderPType>(
287    codes: ArrayView<'_, Primitive>,
288    values: ArrayView<'_, VarBinView>,
289    validity: Mask,
290    builder: &mut VarBinBuilder<O>,
291) -> VortexResult<()>
292where
293    usize: AsPrimitive<O>,
294{
295    let len = codes.as_ref().len();
296    vortex_ensure_eq!(
297        validity.len(),
298        len,
299        "Dictionary gather validity length mismatch"
300    );
301
302    // Resolve the dictionary's storage once so that looking up a code is an O(1) read.
303    let views = values.views();
304    let buffers = values
305        .data_buffers()
306        .iter()
307        .map(|buffer| buffer.as_host().as_slice())
308        .collect::<Vec<_>>();
309
310    match_each_integer_ptype!(codes.ptype(), |C| {
311        let codes = codes.as_slice::<C>();
312        let view = |row: usize| &views[AsPrimitive::<usize>::as_(codes[row])];
313
314        // Both passes below resolve a row through its code, so the byte total comes from the same
315        // walk over the valid rows that the copy will make.
316        let num_bytes = match validity.bit_buffer() {
317            AllOr::All => (0..len).map(|row| view(row).len() as usize).sum(),
318            AllOr::None => {
319                builder.push_nulls(len);
320                return Ok(());
321            }
322            AllOr::Some(bits) => {
323                let mut total = 0;
324                bits.for_each_set_index(|row| total += view(row).len() as usize);
325                total
326            }
327        };
328
329        builder.append_valid_slices(num_bytes, &validity, |row| {
330            // SAFETY: the byte-count pass checked every selected code against `views`, and
331            // append_valid_slices visits exactly those same rows. The slices and validity are
332            // immutable, and the length check above bounds every visited row within `codes`.
333            let value = unsafe {
334                views.get_unchecked(AsPrimitive::<usize>::as_(*codes.get_unchecked(row)))
335            };
336            value.bytes(&buffers)
337        })
338    })
339}
340
341#[cfg(test)]
342mod tests {
343    use std::sync::LazyLock;
344
345    use vortex_session::VortexSession;
346
347    use super::*;
348    use crate::VortexSessionExecute;
349    use crate::arrays::ChunkedArray;
350    use crate::arrays::PrimitiveArray;
351    use crate::arrays::VarBinViewArray;
352    use crate::arrays::dict::DictArray;
353    use crate::assert_arrays_eq;
354    use crate::builders::builder_with_capacity_in;
355    use crate::dtype::Nullability::NonNullable;
356    use crate::dtype::Nullability::Nullable;
357    use crate::dtype::PType;
358
359    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
360
361    const LONG: &str = "a string that is far too long to be inlined in a view";
362
363    #[test]
364    fn dictionary_gather_rejects_mismatched_validity() -> VortexResult<()> {
365        let ctx = SESSION.create_execution_ctx();
366        let codes = PrimitiveArray::from_iter([0u8, 1]);
367        let values = VarBinViewArray::from_iter([Some("one"), Some("two")], DType::Utf8(Nullable));
368        let mut builder = VarBinBuilder::<i32>::new_in(DType::Utf8(Nullable), ctx.allocator());
369        let result = append_dict_to_varbin(
370            codes.as_view(),
371            values.as_view(),
372            Mask::new_true(3),
373            &mut builder,
374        );
375        assert!(result.is_err());
376        assert_eq!(builder.len(), 0);
377        Ok(())
378    }
379
380    #[test]
381    fn dictionary_gather_does_not_read_null_row_codes() -> VortexResult<()> {
382        let mut ctx = SESSION.create_execution_ctx();
383        let codes = PrimitiveArray::from_iter([0u8, 255, 1]);
384        let values = VarBinViewArray::from_iter([Some("one"), Some("two")], DType::Utf8(Nullable));
385        let mut builder = VarBinBuilder::<i32>::new_in(DType::Utf8(Nullable), ctx.allocator());
386        append_dict_to_varbin(
387            codes.as_view(),
388            values.as_view(),
389            Mask::from_iter([true, false, true]),
390            &mut builder,
391        )?;
392        let expected =
393            VarBinViewArray::from_iter([Some("one"), None, Some("two")], DType::Utf8(Nullable));
394        assert_arrays_eq!(builder.finish_into_varbin(), expected, &mut ctx);
395        Ok(())
396    }
397
398    #[test]
399    #[should_panic(expected = "index out of bounds")]
400    fn dictionary_gather_checks_selected_codes_before_copy() {
401        let ctx = SESSION.create_execution_ctx();
402        let codes = PrimitiveArray::from_iter([0u8, 255]);
403        let values = VarBinViewArray::from_iter([Some("one")], DType::Utf8(Nullable));
404        let mut builder = VarBinBuilder::<i32>::new_in(DType::Utf8(Nullable), ctx.allocator());
405        drop(append_dict_to_varbin(
406            codes.as_view(),
407            values.as_view(),
408            Mask::new_true(2),
409            &mut builder,
410        ));
411    }
412
413    #[test]
414    fn append_to_builder_gathers_through_the_dictionary() -> VortexResult<()> {
415        let mut ctx = SESSION.create_execution_ctx();
416        let dict = DictArray::try_new(
417            PrimitiveArray::from_option_iter([Some(0u32), Some(2), None, Some(1), Some(0)])
418                .into_array(),
419            VarBinViewArray::from_iter([Some(LONG), None, Some("short")], DType::Utf8(Nullable))
420                .into_array(),
421        )?;
422
423        let mut builder = VarBinBuilder::<i32>::new_in(DType::Utf8(Nullable), ctx.allocator());
424        dict.append_to_builder(&mut builder, &mut ctx)?;
425
426        let expected = VarBinViewArray::from_iter(
427            [Some(LONG), Some("short"), None, None, Some(LONG)],
428            DType::Utf8(Nullable),
429        );
430        assert_arrays_eq!(builder.finish_into_varbin(), expected, &mut ctx);
431        Ok(())
432    }
433
434    /// A few codes over encoded values are appended through the take of the values, which must
435    /// match the gather through the decoded values, including null codes.
436    #[test]
437    fn append_to_builder_takes_few_rows_of_encoded_values() -> VortexResult<()> {
438        let mut ctx = SESSION.create_execution_ctx();
439        let values = ChunkedArray::try_new(
440            [
441                PrimitiveArray::from_iter(0i32..32).into_array(),
442                PrimitiveArray::from_iter(32i32..64).into_array(),
443            ],
444            DType::Primitive(PType::I32, NonNullable),
445        )?;
446        let dict = DictArray::try_new(
447            PrimitiveArray::from_option_iter([Some(40u32), None, Some(3)]).into_array(),
448            values.into_array(),
449        )?;
450        assert!(dict.len() <= dict.values().len() / sparse_take_ratio(dict.dtype()));
451
452        let mut builder = builder_with_capacity_in(dict.dtype(), 4, ctx.allocator());
453        builder.append_scalar(&Scalar::primitive(-1i32, Nullable))?;
454        dict.append_to_builder(builder.as_mut(), &mut ctx)?;
455
456        let expected = PrimitiveArray::from_option_iter([Some(-1i32), Some(40), None, Some(3)]);
457        assert_arrays_eq!(builder.finish(), expected, &mut ctx);
458        Ok(())
459    }
460
461    /// The view-builder path gathers views through the codes without materializing the taken
462    /// array, so the result must still match the canonical take — including rows whose code is
463    /// null and rows whose dictionary value is null.
464    #[test]
465    fn append_to_view_builder_gathers_through_the_dictionary() -> VortexResult<()> {
466        let mut ctx = SESSION.create_execution_ctx();
467        let dict = DictArray::try_new(
468            PrimitiveArray::from_option_iter([Some(0u32), Some(2), None, Some(1), Some(0)])
469                .into_array(),
470            VarBinViewArray::from_iter([Some(LONG), None, Some("short")], DType::Utf8(Nullable))
471                .into_array(),
472        )?;
473
474        let mut builder = VarBinViewBuilder::with_capacity_in(
475            DType::Utf8(Nullable),
476            8,
477            vortex_buffer::BufferAllocatorRef::statically_allocated(),
478        );
479        builder.append_value(LONG);
480        dict.append_to_builder(&mut builder, &mut ctx)?;
481
482        let expected = VarBinViewArray::from_iter(
483            [
484                Some(LONG),
485                Some(LONG),
486                Some("short"),
487                None,
488                None,
489                Some(LONG),
490            ],
491            DType::Utf8(Nullable),
492        );
493        assert_arrays_eq!(builder.finish_into_varbinview(), expected, &mut ctx);
494        Ok(())
495    }
496
497    /// Two chunks gathered through the same dictionary into a deduplicating builder must adopt
498    /// the dictionary's data buffers once.
499    #[test]
500    fn append_to_dedup_view_builder_adopts_the_dictionary_once() -> VortexResult<()> {
501        let mut ctx = SESSION.create_execution_ctx();
502        let values = VarBinViewArray::from_iter([Some(LONG), Some("short")], DType::Utf8(Nullable));
503        assert_eq!(values.data_buffers().len(), 1);
504
505        let first = DictArray::try_new(
506            PrimitiveArray::from_option_iter([Some(0u32), Some(1)]).into_array(),
507            values.clone().into_array(),
508        )?;
509        let second = DictArray::try_new(
510            PrimitiveArray::from_option_iter([Some(1u32), Some(0)]).into_array(),
511            values.into_array(),
512        )?;
513
514        let mut builder = VarBinViewBuilder::with_buffer_deduplication_in(
515            DType::Utf8(Nullable),
516            8,
517            vortex_buffer::BufferAllocatorRef::statically_allocated(),
518        );
519        first.append_to_builder(&mut builder, &mut ctx)?;
520        second.append_to_builder(&mut builder, &mut ctx)?;
521        assert_eq!(builder.completed_block_count(), 1);
522
523        let expected = VarBinViewArray::from_iter(
524            [Some(LONG), Some("short"), Some("short"), Some(LONG)],
525            DType::Utf8(Nullable),
526        );
527        assert_arrays_eq!(builder.finish_into_varbinview(), expected, &mut ctx);
528        Ok(())
529    }
530}