vortex_array/
validity.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Array validity and nullability behavior, used by arrays and compute functions.
5
6use std::fmt::Debug;
7use std::ops::{BitAnd, Range};
8
9use vortex_buffer::BitBuffer;
10use vortex_dtype::{DType, Nullability};
11use vortex_error::{VortexExpect as _, VortexResult, vortex_err, vortex_panic};
12use vortex_mask::{AllOr, Mask, MaskValues};
13use vortex_scalar::Scalar;
14
15use crate::arrays::{BoolArray, ConstantArray};
16use crate::compute::{fill_null, filter, sum, take};
17use crate::patches::Patches;
18use crate::{Array, ArrayRef, IntoArray, ToCanonical};
19
20/// Validity information for an array
21#[derive(Clone, Debug)]
22pub enum Validity {
23    /// Items *can't* be null
24    NonNullable,
25    /// All items are valid
26    AllValid,
27    /// All items are null
28    AllInvalid,
29    /// The validity of each position in the array is determined by a boolean array.
30    ///
31    /// True values are valid, false values are invalid ("null").
32    Array(ArrayRef),
33}
34
35impl Validity {
36    /// The [`DType`] of the underlying validity array (if it exists).
37    pub const DTYPE: DType = DType::Bool(Nullability::NonNullable);
38
39    /// If Validity is [`Validity::Array`], returns the array, otherwise returns `None`.
40    #[inline]
41    pub fn into_array(self) -> Option<ArrayRef> {
42        if let Self::Array(a) = self {
43            Some(a)
44        } else {
45            None
46        }
47    }
48
49    /// If Validity is [`Validity::Array`], returns a reference to the array array, otherwise returns `None`.
50    #[inline]
51    pub fn as_array(&self) -> Option<&ArrayRef> {
52        if let Self::Array(a) = self {
53            Some(a)
54        } else {
55            None
56        }
57    }
58
59    #[inline]
60    pub fn nullability(&self) -> Nullability {
61        if matches!(self, Self::NonNullable) {
62            Nullability::NonNullable
63        } else {
64            Nullability::Nullable
65        }
66    }
67
68    /// The union nullability and validity.
69    #[inline]
70    pub fn union_nullability(self, nullability: Nullability) -> Self {
71        match nullability {
72            Nullability::NonNullable => self,
73            Nullability::Nullable => self.into_nullable(),
74        }
75    }
76
77    #[inline]
78    pub fn all_valid(&self, len: usize) -> bool {
79        match self {
80            _ if len == 0 => true,
81            Validity::NonNullable | Validity::AllValid => true,
82            Validity::AllInvalid => false,
83            Validity::Array(array) => {
84                usize::try_from(&sum(array).vortex_expect("must have sum for bool array"))
85                    .vortex_expect("sum must be a usize")
86                    == array.len()
87            }
88        }
89    }
90
91    #[inline]
92    pub fn all_invalid(&self, len: usize) -> bool {
93        match self {
94            _ if len == 0 => true,
95            Validity::NonNullable | Validity::AllValid => false,
96            Validity::AllInvalid => true,
97            Validity::Array(array) => {
98                usize::try_from(&sum(array).vortex_expect("must have sum for bool array"))
99                    .vortex_expect("sum must be a usize")
100                    == 0
101            }
102        }
103    }
104
105    /// Returns whether the `index` item is valid.
106    #[inline]
107    pub fn is_valid(&self, index: usize) -> bool {
108        match self {
109            Self::NonNullable | Self::AllValid => true,
110            Self::AllInvalid => false,
111            Self::Array(a) => {
112                let scalar = a.scalar_at(index);
113                scalar
114                    .as_bool()
115                    .value()
116                    .vortex_expect("Validity must be non-nullable")
117            }
118        }
119    }
120
121    #[inline]
122    pub fn is_null(&self, index: usize) -> bool {
123        !self.is_valid(index)
124    }
125
126    #[inline]
127    pub fn slice(&self, range: Range<usize>) -> Self {
128        match self {
129            Self::Array(a) => Self::Array(a.slice(range)),
130            Self::NonNullable | Self::AllValid | Self::AllInvalid => self.clone(),
131        }
132    }
133
134    pub fn take(&self, indices: &dyn Array) -> VortexResult<Self> {
135        match self {
136            Self::NonNullable => match indices.validity_mask().bit_buffer() {
137                AllOr::All => {
138                    if indices.dtype().is_nullable() {
139                        Ok(Self::AllValid)
140                    } else {
141                        Ok(Self::NonNullable)
142                    }
143                }
144                AllOr::None => Ok(Self::AllInvalid),
145                AllOr::Some(buf) => Ok(Validity::from(buf.clone())),
146            },
147            Self::AllValid => match indices.validity_mask().bit_buffer() {
148                AllOr::All => Ok(Self::AllValid),
149                AllOr::None => Ok(Self::AllInvalid),
150                AllOr::Some(buf) => Ok(Validity::from(buf.clone())),
151            },
152            Self::AllInvalid => Ok(Self::AllInvalid),
153            Self::Array(is_valid) => {
154                let maybe_is_valid = take(is_valid, indices)?;
155                // Null indices invalidate that position.
156                let is_valid = fill_null(&maybe_is_valid, &Scalar::from(false))?;
157                Ok(Self::Array(is_valid))
158            }
159        }
160    }
161
162    /// Keep only the entries for which the mask is true.
163    ///
164    /// The result has length equal to the number of true values in mask.
165    pub fn filter(&self, mask: &Mask) -> VortexResult<Self> {
166        // NOTE(ngates): we take the mask as a reference to avoid the caller cloning unnecessarily
167        //  if we happen to be NonNullable, AllValid, or AllInvalid.
168        match self {
169            v @ (Validity::NonNullable | Validity::AllValid | Validity::AllInvalid) => {
170                Ok(v.clone())
171            }
172            Validity::Array(arr) => Ok(Validity::Array(filter(arr, mask)?)),
173        }
174    }
175
176    /// Set to false any entries for which the mask is true.
177    ///
178    /// The result is always nullable. The result has the same length as self.
179    #[inline]
180    pub fn mask(&self, mask: &Mask) -> Self {
181        match mask.bit_buffer() {
182            AllOr::All => Validity::AllInvalid,
183            AllOr::None => self.clone().into_nullable(),
184            AllOr::Some(make_invalid) => match self {
185                Validity::NonNullable | Validity::AllValid => {
186                    Validity::Array(BoolArray::from(!make_invalid).into_array())
187                }
188                Validity::AllInvalid => Validity::AllInvalid,
189                Validity::Array(is_valid) => {
190                    let is_valid = is_valid.to_bool();
191                    Validity::from(is_valid.bit_buffer() & !make_invalid)
192                }
193            },
194        }
195    }
196
197    #[inline]
198    pub fn to_mask(&self, length: usize) -> Mask {
199        match self {
200            Self::NonNullable | Self::AllValid => Mask::AllTrue(length),
201            Self::AllInvalid => Mask::AllFalse(length),
202            Self::Array(is_valid) => {
203                assert_eq!(
204                    is_valid.len(),
205                    length,
206                    "Validity::Array length must equal to_logical's argument: {}, {}.",
207                    is_valid.len(),
208                    length,
209                );
210                is_valid.to_bool().to_mask()
211            }
212        }
213    }
214
215    /// Logically & two Validity values of the same length
216    #[inline]
217    pub fn and(self, rhs: Validity) -> Validity {
218        match (self, rhs) {
219            // Should be pretty clear
220            (Validity::NonNullable, Validity::NonNullable) => Validity::NonNullable,
221            // Any `AllInvalid` makes the output all invalid values
222            (Validity::AllInvalid, _) | (_, Validity::AllInvalid) => Validity::AllInvalid,
223            // All truthy values on one side, which makes no effect on an `Array` variant
224            (Validity::Array(a), Validity::AllValid)
225            | (Validity::Array(a), Validity::NonNullable)
226            | (Validity::NonNullable, Validity::Array(a))
227            | (Validity::AllValid, Validity::Array(a)) => Validity::Array(a),
228            // Both sides are all valid
229            (Validity::NonNullable, Validity::AllValid)
230            | (Validity::AllValid, Validity::NonNullable)
231            | (Validity::AllValid, Validity::AllValid) => Validity::AllValid,
232            // Here we actually have to do some work
233            (Validity::Array(lhs), Validity::Array(rhs)) => {
234                let lhs = lhs.to_bool();
235                let rhs = rhs.to_bool();
236
237                let lhs = lhs.bit_buffer();
238                let rhs = rhs.bit_buffer();
239
240                Validity::from(lhs.bitand(rhs))
241            }
242        }
243    }
244
245    pub fn patch(
246        self,
247        len: usize,
248        indices_offset: usize,
249        indices: &dyn Array,
250        patches: &Validity,
251    ) -> Self {
252        match (&self, patches) {
253            (Validity::NonNullable, Validity::NonNullable) => return Validity::NonNullable,
254            (Validity::NonNullable, _) => {
255                vortex_panic!("Can't patch a non-nullable validity with nullable validity")
256            }
257            (_, Validity::NonNullable) => {
258                vortex_panic!("Can't patch a nullable validity with non-nullable validity")
259            }
260            (Validity::AllValid, Validity::AllValid) => return Validity::AllValid,
261            (Validity::AllInvalid, Validity::AllInvalid) => return Validity::AllInvalid,
262            _ => {}
263        };
264
265        let own_nullability = if self == Validity::NonNullable {
266            Nullability::NonNullable
267        } else {
268            Nullability::Nullable
269        };
270
271        let source = match self {
272            Validity::NonNullable => BoolArray::from(BitBuffer::new_set(len)),
273            Validity::AllValid => BoolArray::from(BitBuffer::new_set(len)),
274            Validity::AllInvalid => BoolArray::from(BitBuffer::new_unset(len)),
275            Validity::Array(a) => a.to_bool(),
276        };
277
278        let patch_values = match patches {
279            Validity::NonNullable => BoolArray::from(BitBuffer::new_set(indices.len())),
280            Validity::AllValid => BoolArray::from(BitBuffer::new_set(indices.len())),
281            Validity::AllInvalid => BoolArray::from(BitBuffer::new_unset(indices.len())),
282            Validity::Array(a) => a.to_bool(),
283        };
284
285        let patches = Patches::new(
286            len,
287            indices_offset,
288            indices.to_array(),
289            patch_values.into_array(),
290            // TODO(0ax1): chunk offsets
291            None,
292        );
293
294        Self::from_array(source.patch(&patches).into_array(), own_nullability)
295    }
296
297    /// Convert into a nullable variant
298    #[inline]
299    pub fn into_nullable(self) -> Validity {
300        match self {
301            Self::NonNullable => Self::AllValid,
302            Self::AllValid | Self::AllInvalid | Self::Array(_) => self,
303        }
304    }
305
306    /// Convert into a non-nullable variant
307    #[inline]
308    pub fn into_non_nullable(self, len: usize) -> Option<Validity> {
309        match self {
310            _ if len == 0 => Some(Validity::NonNullable),
311            Self::NonNullable => Some(Self::NonNullable),
312            Self::AllValid => Some(Self::NonNullable),
313            Self::AllInvalid => None,
314            Self::Array(is_valid) => {
315                is_valid
316                    .statistics()
317                    .compute_min::<bool>()
318                    .vortex_expect("validity array must support min")
319                    .then(|| {
320                        // min true => all true
321                        Self::NonNullable
322                    })
323            }
324        }
325    }
326
327    /// Convert into a variant compatible with the given nullability, if possible.
328    #[inline]
329    pub fn cast_nullability(self, nullability: Nullability, len: usize) -> VortexResult<Validity> {
330        match nullability {
331            Nullability::NonNullable => self.into_non_nullable(len).ok_or_else(|| {
332                vortex_err!("Cannot cast array with invalid values to non-nullable type.")
333            }),
334            Nullability::Nullable => Ok(self.into_nullable()),
335        }
336    }
337
338    /// Create Validity by copying the given array's validity.
339    #[inline]
340    pub fn copy_from_array(array: &dyn Array) -> Self {
341        Validity::from_mask(array.validity_mask(), array.dtype().nullability())
342    }
343
344    /// Create Validity from boolean array with given nullability of the array.
345    ///
346    /// Note: You want to pass the nullability of parent array and not the nullability of the validity array itself
347    ///     as that is always nonnullable
348    #[inline]
349    fn from_array(value: ArrayRef, nullability: Nullability) -> Self {
350        if !matches!(value.dtype(), DType::Bool(Nullability::NonNullable)) {
351            vortex_panic!("Expected a non-nullable boolean array")
352        }
353        match nullability {
354            Nullability::NonNullable => Self::NonNullable,
355            Nullability::Nullable => Self::Array(value),
356        }
357    }
358
359    /// Returns the length of the validity array, if it exists.
360    #[inline]
361    pub fn maybe_len(&self) -> Option<usize> {
362        match self {
363            Self::NonNullable | Self::AllValid | Self::AllInvalid => None,
364            Self::Array(a) => Some(a.len()),
365        }
366    }
367
368    #[inline]
369    pub fn uncompressed_size(&self) -> usize {
370        if let Validity::Array(a) = self {
371            a.len().div_ceil(8)
372        } else {
373            0
374        }
375    }
376}
377
378impl PartialEq for Validity {
379    #[inline]
380    fn eq(&self, other: &Self) -> bool {
381        match (self, other) {
382            (Self::NonNullable, Self::NonNullable) => true,
383            (Self::AllValid, Self::AllValid) => true,
384            (Self::AllInvalid, Self::AllInvalid) => true,
385            (Self::Array(a), Self::Array(b)) => {
386                let a = a.to_bool();
387                let b = b.to_bool();
388                a.bit_buffer() == b.bit_buffer()
389            }
390            _ => false,
391        }
392    }
393}
394
395impl From<BitBuffer> for Validity {
396    #[inline]
397    fn from(value: BitBuffer) -> Self {
398        let true_count = value.true_count();
399        if true_count == value.len() {
400            Self::AllValid
401        } else if true_count == 0 {
402            Self::AllInvalid
403        } else {
404            Self::Array(BoolArray::from(value).into_array())
405        }
406    }
407}
408
409impl FromIterator<Mask> for Validity {
410    #[inline]
411    fn from_iter<T: IntoIterator<Item = Mask>>(iter: T) -> Self {
412        Validity::from_mask(iter.into_iter().collect(), Nullability::Nullable)
413    }
414}
415
416impl FromIterator<bool> for Validity {
417    #[inline]
418    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
419        Validity::from(BitBuffer::from_iter(iter))
420    }
421}
422
423impl From<Nullability> for Validity {
424    #[inline]
425    fn from(value: Nullability) -> Self {
426        match value {
427            Nullability::NonNullable => Validity::NonNullable,
428            Nullability::Nullable => Validity::AllValid,
429        }
430    }
431}
432
433impl Validity {
434    pub fn from_bit_buffer(buffer: BitBuffer, nullability: Nullability) -> Self {
435        if buffer.true_count() == buffer.len() {
436            nullability.into()
437        } else if buffer.true_count() == 0 {
438            Validity::AllInvalid
439        } else {
440            Validity::Array(BoolArray::from_bit_buffer(buffer, Validity::NonNullable).into_array())
441        }
442    }
443
444    pub fn from_mask(mask: Mask, nullability: Nullability) -> Self {
445        assert!(
446            nullability == Nullability::Nullable || matches!(mask, Mask::AllTrue(_)),
447            "NonNullable validity must be AllValid",
448        );
449        match mask {
450            Mask::AllTrue(_) => match nullability {
451                Nullability::NonNullable => Validity::NonNullable,
452                Nullability::Nullable => Validity::AllValid,
453            },
454            Mask::AllFalse(_) => Validity::AllInvalid,
455            Mask::Values(values) => Validity::Array(values.into_array()),
456        }
457    }
458}
459
460impl IntoArray for Mask {
461    #[inline]
462    fn into_array(self) -> ArrayRef {
463        match self {
464            Self::AllTrue(len) => ConstantArray::new(true, len).into_array(),
465            Self::AllFalse(len) => ConstantArray::new(false, len).into_array(),
466            Self::Values(a) => a.into_array(),
467        }
468    }
469}
470
471impl IntoArray for &MaskValues {
472    #[inline]
473    fn into_array(self) -> ArrayRef {
474        BoolArray::from_bit_buffer(self.bit_buffer().clone(), Validity::NonNullable).into_array()
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use rstest::rstest;
481    use vortex_buffer::{Buffer, buffer};
482    use vortex_dtype::Nullability;
483    use vortex_mask::Mask;
484
485    use crate::arrays::{BoolArray, PrimitiveArray};
486    use crate::validity::Validity;
487    use crate::{ArrayRef, IntoArray};
488
489    #[rstest]
490    #[case(Validity::AllValid, 5, &[2, 4], Validity::AllValid, Validity::AllValid)]
491    #[case(Validity::AllValid, 5, &[2, 4], Validity::AllInvalid, Validity::Array(BoolArray::from_iter([true, true, false, true, false]).into_array())
492    )]
493    #[case(Validity::AllValid, 5, &[2, 4], Validity::Array(BoolArray::from_iter([true, false]).into_array()), Validity::Array(BoolArray::from_iter([true, true, true, true, false]).into_array())
494    )]
495    #[case(Validity::AllInvalid, 5, &[2, 4], Validity::AllValid, Validity::Array(BoolArray::from_iter([false, false, true, false, true]).into_array())
496    )]
497    #[case(Validity::AllInvalid, 5, &[2, 4], Validity::AllInvalid, Validity::AllInvalid)]
498    #[case(Validity::AllInvalid, 5, &[2, 4], Validity::Array(BoolArray::from_iter([true, false]).into_array()), Validity::Array(BoolArray::from_iter([false, false, true, false, false]).into_array())
499    )]
500    #[case(Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()), 5, &[2, 4], Validity::AllValid, Validity::Array(BoolArray::from_iter([false, true, true, true, true]).into_array())
501    )]
502    #[case(Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()), 5, &[2, 4], Validity::AllInvalid, Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array())
503    )]
504    #[case(Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()), 5, &[2, 4], Validity::Array(BoolArray::from_iter([true, false]).into_array()), Validity::Array(BoolArray::from_iter([false, true, true, true, false]).into_array())
505    )]
506    fn patch_validity(
507        #[case] validity: Validity,
508        #[case] len: usize,
509        #[case] positions: &[u64],
510        #[case] patches: Validity,
511        #[case] expected: Validity,
512    ) {
513        let indices =
514            PrimitiveArray::new(Buffer::copy_from(positions), Validity::NonNullable).into_array();
515        assert_eq!(validity.patch(len, 0, &indices, &patches), expected);
516    }
517
518    #[test]
519    #[should_panic]
520    fn out_of_bounds_patch() {
521        Validity::NonNullable.patch(2, 0, &buffer![4].into_array(), &Validity::AllInvalid);
522    }
523
524    #[test]
525    #[should_panic]
526    fn into_validity_nullable() {
527        Validity::from_mask(Mask::AllFalse(10), Nullability::NonNullable);
528    }
529
530    #[test]
531    #[should_panic]
532    fn into_validity_nullable_array() {
533        Validity::from_mask(Mask::from_iter(vec![true, false]), Nullability::NonNullable);
534    }
535
536    #[rstest]
537    #[case(Validity::AllValid, PrimitiveArray::new(buffer![0, 1], Validity::from_iter(vec![true, false])).into_array(), Validity::from_iter(vec![true, false])
538    )]
539    #[case(Validity::AllValid, buffer![0, 1].into_array(), Validity::AllValid)]
540    #[case(Validity::AllValid, PrimitiveArray::new(buffer![0, 1], Validity::AllInvalid).into_array(), Validity::AllInvalid
541    )]
542    #[case(Validity::NonNullable, PrimitiveArray::new(buffer![0, 1], Validity::from_iter(vec![true, false])).into_array(), Validity::from_iter(vec![true, false])
543    )]
544    #[case(Validity::NonNullable, buffer![0, 1].into_array(), Validity::NonNullable)]
545    #[case(Validity::NonNullable, PrimitiveArray::new(buffer![0, 1], Validity::AllInvalid).into_array(), Validity::AllInvalid
546    )]
547    fn validity_take(
548        #[case] validity: Validity,
549        #[case] indices: ArrayRef,
550        #[case] expected: Validity,
551    ) {
552        assert_eq!(validity.take(&indices).unwrap(), expected);
553    }
554
555    #[test]
556    fn mask_non_nullable() {
557        assert_eq!(
558            Validity::AllValid,
559            Validity::NonNullable.mask(&Mask::AllFalse(2))
560        )
561    }
562}