Skip to main content

vortex_array/arrays/dict/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use num_traits::AsPrimitive;
8use smallvec::smallvec;
9use vortex_buffer::BitBuffer;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_err;
15use vortex_mask::AllOr;
16
17use crate::ArrayRef;
18use crate::ArraySlots;
19use crate::ExecutionCtx;
20use crate::array::Array;
21use crate::array::ArrayParts;
22use crate::array::TypedArrayRef;
23use crate::array_slots;
24use crate::arrays::Dict;
25use crate::arrays::PrimitiveArray;
26use crate::dtype::DType;
27use crate::dtype::PType;
28use crate::match_each_integer_ptype;
29
30#[derive(Clone, prost::Message)]
31pub struct DictMetadata {
32    #[prost(uint32, tag = "1")]
33    pub(super) values_len: u32,
34    #[prost(int32, tag = "2")]
35    pub(super) codes_ptype: i32,
36    // nullable codes are optional since they were added after stabilisation.
37    #[prost(optional, bool, tag = "3")]
38    pub(super) is_nullable_codes: Option<bool>,
39    // all_values_referenced is optional for backward compatibility.
40    // true = all dictionary values are definitely referenced by at least one code.
41    // false/None = unknown whether all values are referenced (conservative default).
42    #[prost(optional, bool, tag = "4")]
43    pub(super) all_values_referenced: Option<bool>,
44}
45
46impl DictMetadata {
47    pub(super) fn get_codes_ptype(&self) -> VortexResult<PType> {
48        PType::try_from(self.codes_ptype).map_err(|_| {
49            vortex_err!(
50                "DictMetadata codes_ptype must be a known PType, got {}",
51                self.codes_ptype
52            )
53        })
54    }
55}
56
57#[array_slots(Dict)]
58pub struct DictSlots {
59    /// The codes array mapping each element to a dictionary entry.
60    #[slot(0)]
61    pub codes: ArrayRef,
62    /// The dictionary values array containing the unique values.
63    #[slot(1)]
64    pub values: ArrayRef,
65}
66
67#[derive(Debug, Clone)]
68pub struct DictData {
69    /// Indicates whether all dictionary values are definitely referenced by at least one code.
70    /// `true` = all values are referenced (computed during encoding).
71    /// `false` = unknown/might have unreferenced values.
72    /// In case this is incorrect never use this to enable memory unsafe behaviour just semantically
73    /// incorrect behaviour.
74    pub(super) all_values_referenced: bool,
75}
76
77impl Display for DictData {
78    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79        write!(f, "all_values_referenced: {}", self.all_values_referenced)
80    }
81}
82
83impl DictData {
84    /// Build a new `DictArray` without validating the codes or values.
85    ///
86    /// # Safety
87    /// This should be called only when you can guarantee the invariants checked
88    /// by the safe `DictArray::try_new` constructor are valid, for example when
89    /// you are filtering or slicing an existing valid `DictArray`.
90    pub unsafe fn new_unchecked() -> Self {
91        Self {
92            all_values_referenced: false,
93        }
94    }
95
96    /// Set whether all dictionary values are definitely referenced.
97    ///
98    /// # Safety
99    /// The caller must ensure that when setting `all_values_referenced = true`, ALL dictionary
100    /// values are actually referenced by at least one valid code. Setting this incorrectly can
101    /// lead to incorrect query results in operations like min/max.
102    ///
103    /// This is typically only set to `true` during dictionary encoding when we know for certain
104    /// that all values are referenced.
105    pub unsafe fn set_all_values_referenced(mut self, all_values_referenced: bool) -> Self {
106        self.all_values_referenced = all_values_referenced;
107        self
108    }
109
110    /// Build a new `DictArray` from its components, `codes` and `values`.
111    ///
112    /// This constructor will panic if `codes` or `values` do not pass validation for building
113    /// a new `DictArray`. See `DictArray::try_new` for a description of the error conditions.
114    pub fn new(codes_dtype: &DType) -> Self {
115        Self::try_new(codes_dtype).vortex_expect("DictArray new")
116    }
117
118    /// Build a new `DictArray` from its components, `codes` and `values`.
119    ///
120    /// The codes must be integers, and may be nullable. Values can be any
121    /// type, and may also be nullable. This mirrors the nullability of the Arrow `DictionaryArray`.
122    ///
123    /// # Errors
124    ///
125    /// The `codes` **must** be integers. Otherwise, this constructor returns an error.
126    ///
127    /// It is an error to provide a nullable `codes` with non-nullable `values`.
128    ///
129    /// This constructor does not read the codes. Each operation that uses a code as an index
130    /// into `values` must do its own bounds check, because the codes can come from a file.
131    pub(crate) fn try_new(codes_dtype: &DType) -> VortexResult<Self> {
132        if !codes_dtype.is_int() {
133            vortex_bail!("expected type: int but instead got {}", codes_dtype);
134        }
135
136        Ok(unsafe { Self::new_unchecked() })
137    }
138}
139
140pub trait DictArrayExt: TypedArrayRef<Dict> {
141    #[inline]
142    fn has_all_values_referenced(&self) -> bool {
143        self.all_values_referenced
144    }
145
146    fn validate_all_values_referenced(&self, ctx: &mut ExecutionCtx) -> VortexResult<()> {
147        if self.has_all_values_referenced() {
148            if !self.codes().is_host() {
149                return Ok(());
150            }
151
152            let referenced_mask = self.compute_referenced_values_mask(true, ctx)?;
153            let all_referenced = referenced_mask.true_count() == referenced_mask.len();
154
155            vortex_ensure!(all_referenced, "value in dict not referenced");
156        }
157
158        Ok(())
159    }
160
161    fn compute_referenced_values_mask(
162        &self,
163        referenced: bool,
164        ctx: &mut ExecutionCtx,
165    ) -> VortexResult<BitBuffer> {
166        let codes = self.codes();
167        let codes_validity = codes.validity()?.execute_mask(codes.len(), ctx)?;
168        let codes_primitive = codes.clone().execute::<PrimitiveArray>(ctx)?;
169        let values_len = self.values().len();
170
171        let mut values_vec = vec![!referenced; values_len];
172        let saturated = match codes_validity.bit_buffer() {
173            AllOr::All => match_each_integer_ptype!(codes_primitive.ptype(), |P| {
174                mark_codes(&mut values_vec, referenced, codes_primitive.as_slice::<P>())
175            }),
176            AllOr::None => false,
177            AllOr::Some(mask) => match_each_integer_ptype!(codes_primitive.ptype(), |P| {
178                mark_masked_codes(
179                    &mut values_vec,
180                    referenced,
181                    codes_primitive.as_slice::<P>(),
182                    mask,
183                    codes_validity.true_count(),
184                )
185            }),
186        };
187        if saturated {
188            return Ok(BitBuffer::full(referenced, values_len));
189        }
190
191        Ok(BitBuffer::from(values_vec))
192    }
193}
194impl<T: TypedArrayRef<Dict>> DictArrayExt for T {}
195
196/// Number of codes visited between checks for whether every dictionary value is referenced.
197const EARLY_EXIT_CHUNK: usize = 2048;
198
199/// Sets `values[code]` to `referenced` for every code, returning `true` early once every entry
200/// of `values` is `referenced`, since further codes cannot change the result.
201///
202/// With fewer codes than values not every value can be referenced, so the saturation checks are
203/// skipped entirely.
204fn mark_codes<P: AsPrimitive<usize>>(values: &mut [bool], referenced: bool, codes: &[P]) -> bool {
205    if codes.len() < values.len() {
206        for code in codes {
207            values[code.as_()] = referenced;
208        }
209        return false;
210    }
211
212    let mut cursor = 0;
213    for chunk in codes.chunks(EARLY_EXIT_CHUNK) {
214        for code in chunk {
215            values[code.as_()] = referenced;
216        }
217        if is_saturated(values, &mut cursor, referenced) {
218            return true;
219        }
220    }
221    false
222}
223
224/// Like [`mark_codes`], but only for the codes at the `valid_count` set positions of `mask`.
225fn mark_masked_codes<P: AsPrimitive<usize>>(
226    values: &mut [bool],
227    referenced: bool,
228    codes: &[P],
229    mask: &BitBuffer,
230    valid_count: usize,
231) -> bool {
232    if valid_count < values.len() {
233        mask.set_indices().for_each(|idx| {
234            values[codes[idx].as_()] = referenced;
235        });
236        return false;
237    }
238
239    let mut cursor = 0;
240    for start in (0..codes.len()).step_by(EARLY_EXIT_CHUNK) {
241        let end = (start + EARLY_EXIT_CHUNK).min(codes.len());
242        let codes = &codes[start..end];
243        mask.slice(start..end).set_indices().for_each(|idx| {
244            values[codes[idx].as_()] = referenced;
245        });
246        if is_saturated(values, &mut cursor, referenced) {
247            return true;
248        }
249    }
250    false
251}
252
253/// Advances `cursor` past the entries of `values` equal to `referenced` and returns whether that
254/// is all of them. Callers share one cursor that only moves forward, so repeated checks cost
255/// `O(values.len())` in total.
256#[inline]
257fn is_saturated(values: &[bool], cursor: &mut usize, referenced: bool) -> bool {
258    // Skip whole blocks with a branch-free comparison the compiler can vectorize, then find the
259    // exact stopping point within the first block that is not fully marked.
260    const BLOCK: usize = 32;
261    let rest = &values[*cursor..];
262    let full_blocks = rest
263        .as_chunks::<BLOCK>()
264        .0
265        .iter()
266        .take_while(|block| block.iter().fold(true, |acc, &v| acc & (v == referenced)))
267        .count();
268    *cursor += full_blocks * BLOCK;
269    *cursor += values[*cursor..]
270        .iter()
271        .take_while(|&&v| v == referenced)
272        .count();
273    *cursor == values.len()
274}
275
276/// Concrete parts of a [`DictArray`](super::DictArray) after iterative execution.
277pub struct DictParts {
278    pub dtype: DType,
279    pub codes: ArrayRef,
280    pub values: ArrayRef,
281}
282
283pub trait DictOwnedExt {
284    fn into_parts(self) -> DictParts;
285}
286
287impl DictOwnedExt for Array<Dict> {
288    fn into_parts(self) -> DictParts {
289        match self.try_into_parts() {
290            Ok(array_parts) => {
291                let slots = DictSlots::from_slots(array_parts.slots);
292                DictParts {
293                    dtype: array_parts.dtype,
294                    codes: slots.codes,
295                    values: slots.values,
296                }
297            }
298            Err(array) => {
299                let slots = array.slots_view();
300                DictParts {
301                    dtype: array.dtype().clone(),
302                    codes: slots.codes.clone(),
303                    values: slots.values.clone(),
304                }
305            }
306        }
307    }
308}
309
310impl Array<Dict> {
311    /// Build a new `DictArray` from its components, `codes` and `values`.
312    pub fn new(codes: ArrayRef, values: ArrayRef) -> Self {
313        Self::try_new(codes, values).vortex_expect("DictArray new")
314    }
315
316    /// Build a new `DictArray` from its components, `codes` and `values`.
317    pub fn try_new(codes: ArrayRef, values: ArrayRef) -> VortexResult<Self> {
318        let dtype = values
319            .dtype()
320            .union_nullability(codes.dtype().nullability());
321        let len = codes.len();
322        let data = DictData::try_new(codes.dtype())?;
323        Array::try_from_parts(ArrayParts::new(
324            Dict,
325            dtype,
326            len,
327            data,
328            smallvec![Some(codes), Some(values)],
329        ))
330    }
331
332    /// Build a new `DictArray` without validating the codes or values.
333    ///
334    /// # Safety
335    ///
336    /// See [`DictData::new_unchecked`].
337    pub unsafe fn new_unchecked(codes: ArrayRef, values: ArrayRef) -> Self {
338        let dtype = values
339            .dtype()
340            .union_nullability(codes.dtype().nullability());
341        let len = codes.len();
342        let data = unsafe { DictData::new_unchecked() };
343        unsafe {
344            Array::from_parts_unchecked(ArrayParts::new(
345                Dict,
346                dtype,
347                len,
348                data,
349                smallvec![Some(codes), Some(values)],
350            ))
351        }
352    }
353
354    /// Set whether all values in the dictionary are referenced by at least one code.
355    ///
356    /// # Safety
357    ///
358    /// See [`DictData::set_all_values_referenced`].
359    pub unsafe fn set_all_values_referenced(self, all_values_referenced: bool) -> Self {
360        let dtype = self.dtype().clone();
361        let len = self.len();
362        let slots: ArraySlots = self.slots().iter().cloned().collect();
363        let data = unsafe {
364            self.into_data()
365                .set_all_values_referenced(all_values_referenced)
366        };
367        unsafe { Array::from_parts_unchecked(ArrayParts::new(Dict, dtype, len, data, slots)) }
368    }
369}
370
371#[cfg(test)]
372mod test {
373    use std::sync::LazyLock;
374
375    use prost::Message;
376    use rand::RngExt;
377    use rand::SeedableRng;
378    use rand::distr::Distribution;
379    use rand::distr::StandardUniform;
380    use rand::prelude::StdRng;
381    use vortex_buffer::BitBuffer;
382    use vortex_buffer::buffer;
383    use vortex_error::VortexExpect;
384    use vortex_error::VortexResult;
385    use vortex_error::vortex_panic;
386    use vortex_mask::AllOr;
387    use vortex_session::VortexSession;
388
389    use super::DictMetadata;
390    use crate::ArrayRef;
391    use crate::IntoArray;
392    use crate::VortexSessionExecute;
393    use crate::array::ArrayDeserialization;
394    use crate::array::ArrayPlugin;
395    use crate::array::VTable;
396    use crate::arrays::ChunkedArray;
397    use crate::arrays::Dict;
398    use crate::arrays::DictArray;
399    use crate::arrays::PrimitiveArray;
400    use crate::arrays::VarBinViewArray;
401    use crate::arrays::dict::DictArrayExt;
402    use crate::assert_arrays_eq;
403    use crate::builders::VarBinBuilder;
404    use crate::builders::builder_with_capacity_in;
405    use crate::dtype::DType;
406    use crate::dtype::NativePType;
407    use crate::dtype::Nullability::NonNullable;
408    use crate::dtype::PType;
409    use crate::dtype::UnsignedPType;
410    use crate::validity::Validity;
411
412    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
413
414    #[test]
415    fn nullable_codes_validity() {
416        let dict = DictArray::try_new(
417            PrimitiveArray::new(
418                buffer![0u32, 1, 2, 2, 1],
419                Validity::from(BitBuffer::from(vec![true, false, true, false, true])),
420            )
421            .into_array(),
422            PrimitiveArray::new(buffer![3, 6, 9], Validity::AllValid).into_array(),
423        )
424        .unwrap();
425        let mask = dict
426            .as_ref()
427            .validity()
428            .unwrap()
429            .execute_mask(dict.as_ref().len(), &mut SESSION.create_execution_ctx())
430            .unwrap();
431        let AllOr::Some(indices) = mask.indices() else {
432            vortex_panic!("Expected indices from mask")
433        };
434        assert_eq!(indices, [0, 2, 4]);
435    }
436
437    #[test]
438    fn nullable_values_validity() {
439        let dict = DictArray::try_new(
440            buffer![0u32, 1, 2, 2, 1].into_array(),
441            PrimitiveArray::new(
442                buffer![3, 6, 9],
443                Validity::from(BitBuffer::from(vec![true, false, false])),
444            )
445            .into_array(),
446        )
447        .unwrap();
448        let mask = dict
449            .as_ref()
450            .validity()
451            .unwrap()
452            .execute_mask(dict.as_ref().len(), &mut SESSION.create_execution_ctx())
453            .unwrap();
454        let AllOr::Some(indices) = mask.indices() else {
455            vortex_panic!("Expected indices from mask")
456        };
457        assert_eq!(indices, [0]);
458    }
459
460    #[test]
461    fn nullable_codes_and_values() {
462        let dict = DictArray::try_new(
463            PrimitiveArray::new(
464                buffer![0u32, 1, 2, 2, 1],
465                Validity::from(BitBuffer::from(vec![true, false, true, false, true])),
466            )
467            .into_array(),
468            PrimitiveArray::new(
469                buffer![3, 6, 9],
470                Validity::from(BitBuffer::from(vec![false, true, true])),
471            )
472            .into_array(),
473        )
474        .unwrap();
475        let mask = dict
476            .as_ref()
477            .validity()
478            .unwrap()
479            .execute_mask(dict.as_ref().len(), &mut SESSION.create_execution_ctx())
480            .unwrap();
481        let AllOr::Some(indices) = mask.indices() else {
482            vortex_panic!("Expected indices from mask")
483        };
484        assert_eq!(indices, [2, 4]);
485    }
486
487    #[test]
488    fn nullable_codes_and_non_null_values() {
489        let dict = DictArray::try_new(
490            PrimitiveArray::new(
491                buffer![0u32, 1, 2, 2, 1],
492                Validity::from(BitBuffer::from(vec![true, false, true, false, true])),
493            )
494            .into_array(),
495            PrimitiveArray::new(buffer![3, 6, 9], Validity::NonNullable).into_array(),
496        )
497        .unwrap();
498        let mask = dict
499            .as_ref()
500            .validity()
501            .unwrap()
502            .execute_mask(dict.as_ref().len(), &mut SESSION.create_execution_ctx())
503            .unwrap();
504        let AllOr::Some(indices) = mask.indices() else {
505            vortex_panic!("Expected indices from mask")
506        };
507        assert_eq!(indices, [0, 2, 4]);
508    }
509
510    fn make_dict_primitive_chunks<T: NativePType, Code: UnsignedPType>(
511        len: usize,
512        unique_values: usize,
513        chunk_count: usize,
514    ) -> (ArrayRef, Vec<T>)
515    where
516        StandardUniform: Distribution<T>,
517    {
518        let mut rng = StdRng::seed_from_u64(0);
519
520        let mut expected = Vec::with_capacity(len * chunk_count);
521        let array = (0..chunk_count)
522            .map(|_| {
523                let values = (0..unique_values)
524                    .map(|_| rng.random::<T>())
525                    .collect::<PrimitiveArray>();
526                let codes = (0..len)
527                    .map(|_| {
528                        Code::from(rng.random_range(0..unique_values)).vortex_expect("valid value")
529                    })
530                    .collect::<PrimitiveArray>();
531
532                expected.extend(codes.as_slice::<Code>().iter().map(|code| {
533                    values.as_slice::<T>()[<Code as num_traits::AsPrimitive<usize>>::as_(*code)]
534                }));
535                DictArray::try_new(codes.into_array(), values.into_array())
536                    .vortex_expect("DictArray creation should succeed in arbitrary impl")
537                    .into_array()
538            })
539            .collect::<ChunkedArray>()
540            .into_array();
541        (array, expected)
542    }
543
544    #[test]
545    fn test_dict_utf8_append_to_varbin_builder() -> VortexResult<()> {
546        let values = VarBinViewArray::from_iter_str(["zero", "one", "two"]);
547        let dict = DictArray::try_new(buffer![2u8, 0, 2, 1].into_array(), values.into_array())?;
548        let expected = VarBinViewArray::from_iter_str(["two", "zero", "two", "one"]);
549        let mut ctx = SESSION.create_execution_ctx();
550        let mut builder = VarBinBuilder::<i32>::with_capacity_in(
551            dict.dtype().clone(),
552            dict.len(),
553            ctx.allocator(),
554        );
555
556        dict.into_array()
557            .append_to_builder(&mut builder, &mut ctx)?;
558
559        assert_arrays_eq!(builder.finish_into_varbin(), expected, &mut ctx);
560        Ok(())
561    }
562
563    #[test]
564    fn test_dict_array_from_primitive_chunks() -> VortexResult<()> {
565        let mut ctx = SESSION.create_execution_ctx();
566        let len = 2;
567        let chunk_count = 2;
568        let (array, expected) = make_dict_primitive_chunks::<u64, u64>(len, 2, chunk_count);
569
570        let mut builder = builder_with_capacity_in(
571            &DType::Primitive(PType::U64, NonNullable),
572            len * chunk_count,
573            ctx.allocator(),
574        );
575        array.append_to_builder(builder.as_mut(), &mut SESSION.create_execution_ctx())?;
576
577        let prim_into = builder.finish_into_canonical(&mut ctx).into_primitive();
578
579        let expected = PrimitiveArray::from_iter(expected);
580        assert_arrays_eq!(array, expected, &mut ctx);
581        assert_arrays_eq!(prim_into, expected, &mut ctx);
582        Ok(())
583    }
584
585    #[cfg_attr(miri, ignore)]
586    #[test]
587    fn test_dict_metadata() {
588        use prost::Message;
589
590        use super::DictMetadata;
591        use crate::test_harness::check_metadata;
592
593        check_metadata(
594            "dict.metadata",
595            &DictMetadata {
596                codes_ptype: PType::U64 as i32,
597                values_len: u32::MAX,
598                is_nullable_codes: None,
599                all_values_referenced: None,
600            }
601            .encode_to_vec(),
602        );
603    }
604
605    #[test]
606    fn test_deserialize_rejects_unknown_codes_ptype() -> VortexResult<()> {
607        let metadata = DictMetadata {
608            codes_ptype: 11,
609            ..Default::default()
610        }
611        .encode_to_vec();
612        let children: Vec<ArrayRef> = Vec::new();
613        let result = ArrayPlugin::deserialize(
614            &Dict,
615            ArrayDeserialization::new(
616                VTable::id(&Dict),
617                &DType::Primitive(PType::I32, NonNullable),
618                0,
619                &metadata,
620                &[],
621                &children,
622            ),
623            &SESSION,
624        );
625        assert!(result.is_err_and(|err| {
626            err.to_string()
627                .contains("DictMetadata codes_ptype must be a known PType, got 11")
628        }));
629
630        let known = DictMetadata {
631            codes_ptype: PType::U32 as i32,
632            ..Default::default()
633        };
634        assert_eq!(known.get_codes_ptype()?, PType::U32);
635
636        Ok(())
637    }
638
639    /// Covers the early exit taken once every value is referenced, including when that happens
640    /// after the first chunk, alongside cases that never saturate.
641    #[rstest::rstest]
642    #[case::saturates_in_first_chunk(16, 5000, 16, None)]
643    #[case::saturates_in_later_chunk(4096, 60_000, 4096, None)]
644    #[case::saturates_unaligned_to_scan_block(4001, 60_000, 4001, None)]
645    #[case::never_saturates(1024, 10_000, 1000, None)]
646    #[case::fewer_codes_than_values(1024, 1000, 1024, None)]
647    #[case::fewer_valid_codes_than_values(1024, 1500, 1024, Some(0.5))]
648    #[case::saturates_with_nulls(64, 10_000, 64, Some(0.5))]
649    #[case::never_saturates_with_nulls(64, 10_000, 63, Some(0.5))]
650    fn referenced_values_mask_matches_reference(
651        #[case] num_values: u32,
652        #[case] num_codes: usize,
653        #[case] referenced_range: u32,
654        #[case] valid_fraction: Option<f64>,
655        #[values(true, false)] referenced: bool,
656    ) -> VortexResult<()> {
657        let mut rng = StdRng::seed_from_u64(0);
658        let codes: Vec<Option<u32>> = (0..num_codes)
659            .map(|_| {
660                valid_fraction
661                    .is_none_or(|f| rng.random_bool(f))
662                    .then(|| rng.random_range(0..referenced_range))
663            })
664            .collect();
665
666        let mut expected = vec![!referenced; num_values as usize];
667        for code in codes.iter().flatten() {
668            expected[*code as usize] = referenced;
669        }
670
671        let codes = match valid_fraction {
672            Some(_) => PrimitiveArray::from_option_iter(codes).into_array(),
673            None => PrimitiveArray::from_iter(codes.into_iter().flatten()).into_array(),
674        };
675        let dict =
676            DictArray::try_new(codes, PrimitiveArray::from_iter(0..num_values).into_array())?;
677        let mut ctx = SESSION.create_execution_ctx();
678        let mask = dict.compute_referenced_values_mask(referenced, &mut ctx)?;
679
680        assert_eq!(mask, BitBuffer::from(expected));
681        Ok(())
682    }
683}