Skip to main content

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//!
6//! [`Validity`] describes which rows are logically present without forcing every array to carry a
7//! materialized boolean bitmap. Constant states (`NonNullable`, `AllValid`, `AllInvalid`) are cheap
8//! to clone and inspect. [`Validity::Array`] may itself be encoded or lazy, so APIs that need exact
9//! per-row answers take an [`ExecutionCtx`] and execute the validity array as needed.
10
11use std::fmt::Debug;
12use std::ops::Range;
13
14use itertools::Itertools as _;
15use vortex_buffer::BitBuffer;
16use vortex_error::VortexExpect as _;
17use vortex_error::VortexResult;
18use vortex_error::vortex_bail;
19use vortex_error::vortex_err;
20use vortex_mask::Mask;
21use vortex_mask::MaskValues;
22
23use crate::ArrayRef;
24use crate::Canonical;
25use crate::ExecutionCtx;
26use crate::IntoArray;
27use crate::arrays::BoolArray;
28use crate::arrays::ChunkedArray;
29use crate::arrays::ConstantArray;
30use crate::builtins::ArrayBuiltins;
31use crate::dtype::DType;
32use crate::dtype::Nullability;
33use crate::patches::Patches;
34use crate::scalar::Scalar;
35use crate::scalar_fn::builtin::boolean::Boolean;
36use crate::scalar_fn::builtin::operators::BooleanOperator;
37
38/// Validity information for an array.
39#[derive(Clone)]
40pub enum Validity {
41    /// Items cannot be null because the dtype is non-nullable.
42    NonNullable,
43    /// The dtype is nullable, but every item is valid.
44    AllValid,
45    /// The dtype is nullable, and every item is null.
46    AllInvalid,
47    /// The validity of each position in the array is determined by a boolean array.
48    ///
49    /// True values are valid, false values are invalid ("null").
50    Array(ArrayRef),
51}
52
53impl Debug for Validity {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        match self {
56            Self::NonNullable => write!(f, "NonNullable"),
57            Self::AllValid => write!(f, "AllValid"),
58            Self::AllInvalid => write!(f, "AllInvalid"),
59            Self::Array(arr) => write!(f, "SomeValid({arr})"),
60        }
61    }
62}
63
64impl Validity {
65    /// Make a step towards canonicalising validity if necessary
66    pub fn execute(self, ctx: &mut ExecutionCtx) -> VortexResult<Validity> {
67        match self {
68            v @ Validity::NonNullable | v @ Validity::AllValid | v @ Validity::AllInvalid => Ok(v),
69            Validity::Array(a) => Ok(Validity::Array(a.execute::<Canonical>(ctx)?.into_array())),
70        }
71    }
72}
73
74impl Validity {
75    /// The [`DType`] of the underlying validity array (if it exists).
76    pub const DTYPE: DType = DType::Bool(Nullability::NonNullable);
77
78    /// Convert the validity to an array representation.
79    pub fn to_array(&self, len: usize) -> ArrayRef {
80        match self {
81            Self::NonNullable | Self::AllValid => ConstantArray::new(true, len).into_array(),
82            Self::AllInvalid => ConstantArray::new(false, len).into_array(),
83            Self::Array(a) => a.clone(),
84        }
85    }
86
87    /// If Validity is [`Validity::Array`], returns the array, otherwise returns `None`.
88    #[inline]
89    pub fn into_array(self) -> Option<ArrayRef> {
90        if let Self::Array(a) = self {
91            Some(a)
92        } else {
93            None
94        }
95    }
96
97    /// If Validity is [`Validity::Array`], returns a reference to the array array, otherwise returns `None`.
98    #[inline]
99    pub fn as_array(&self) -> Option<&ArrayRef> {
100        if let Self::Array(a) = self {
101            Some(a)
102        } else {
103            None
104        }
105    }
106
107    #[inline]
108    pub fn nullability(&self) -> Nullability {
109        if matches!(self, Self::NonNullable) {
110            Nullability::NonNullable
111        } else {
112            Nullability::Nullable
113        }
114    }
115
116    /// Returns `true` if this validity *definitely* contains no null values, i.e. it is either
117    /// [`Validity::NonNullable`] or [`Validity::AllValid`].
118    ///
119    /// Returning `false` does not prove the presence of nulls: a [`Validity::Array`] may still
120    /// resolve to all-valid once executed. Callers must treat `false` as "unknown without
121    /// compute" and either fall back to a null-handling path or execute the validity.
122    #[inline]
123    pub fn definitely_no_nulls(&self) -> bool {
124        matches!(self, Self::NonNullable | Self::AllValid)
125    }
126
127    /// Returns `true` if this validity is *definitely* all-null (every value is null), i.e. it
128    /// is [`Validity::AllInvalid`].
129    ///
130    /// Returning `false` does not prove that any value is valid: a [`Validity::Array`] may still
131    /// resolve to all-null once executed. Callers must treat `false` as "unknown without
132    /// compute". For a definitive answer, execute the validity with [`Self::execute_mask`] and
133    /// check whether the resulting [`Mask`] is all-false (`Mask::all_false`). This is the
134    /// all-null counterpart to [`Self::definitely_no_nulls`].
135    #[inline]
136    pub fn definitely_all_null(&self) -> bool {
137        matches!(self, Self::AllInvalid)
138    }
139
140    /// Returns whether this validity contains no null values, executing the validity array if
141    /// necessary.
142    ///
143    /// This is the exact counterpart to [`Self::definitely_no_nulls`]: use it when the caller
144    /// needs a definitive answer rather than a cheap, conservative one.
145    pub fn execute_no_nulls(&self, length: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
146        match self {
147            Self::NonNullable | Self::AllValid => Ok(true),
148            Self::AllInvalid => Ok(length == 0),
149            Self::Array(_) => Ok(self.execute_mask(length, ctx)?.all_true()),
150        }
151    }
152
153    /// The union nullability and validity.
154    #[inline]
155    pub fn union_nullability(self, nullability: Nullability) -> Self {
156        match nullability {
157            Nullability::NonNullable => self,
158            Nullability::Nullable => self.into_nullable(),
159        }
160    }
161
162    /// Returns whether the `index` item is valid, using `ctx` to execute the validity array.
163    // Todo(joe): deprecate this
164    #[inline]
165    pub fn execute_is_valid(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
166        Ok(match self {
167            Self::NonNullable | Self::AllValid => true,
168            Self::AllInvalid => false,
169            Self::Array(a) => a
170                .execute_scalar(index, ctx)?
171                .as_bool()
172                .value()
173                .ok_or_else(|| vortex_err!("validity value at index {index} is null"))?,
174        })
175    }
176
177    /// Returns whether the `index` item is null, using `ctx` to execute the validity array.
178    // Todo(joe): deprecate this
179    #[inline]
180    pub fn execute_is_null(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
181        Ok(!self.execute_is_valid(index, ctx)?)
182    }
183
184    #[inline]
185    pub fn slice(&self, range: Range<usize>) -> VortexResult<Self> {
186        match self {
187            Self::Array(a) => Ok(Self::Array(a.slice(range)?)),
188            Self::NonNullable | Self::AllValid | Self::AllInvalid => Ok(self.clone()),
189        }
190    }
191
192    pub fn take(&self, indices: &ArrayRef) -> VortexResult<Self> {
193        match self {
194            Self::NonNullable => indices.validity(),
195            Self::AllValid => Ok(match indices.validity()? {
196                Self::NonNullable => Self::AllValid,
197                v => v,
198            }),
199            Self::AllInvalid => Ok(Self::AllInvalid),
200            Self::Array(is_valid) => {
201                let maybe_is_valid = is_valid.take(indices.clone())?;
202                // Null indices invalidate that position.
203                let is_valid = maybe_is_valid.fill_null(Scalar::from(false))?;
204                Ok(Self::Array(is_valid))
205            }
206        }
207    }
208
209    // Invert the validity
210    pub fn not(&self) -> VortexResult<Self> {
211        match self {
212            Validity::NonNullable => Ok(Validity::NonNullable),
213            Validity::AllValid => Ok(Validity::AllInvalid),
214            Validity::AllInvalid => Ok(Validity::AllValid),
215            Validity::Array(arr) => Ok(Validity::Array(arr.not()?)),
216        }
217    }
218
219    /// Lazily filters a [`Validity`] with a selection mask, which keeps only the entries for which
220    /// the mask is true.
221    ///
222    /// The result has length equal to the number of true values in mask.
223    ///
224    /// If the validity is a [`Validity::Array`], then this lazily wraps it in a `FilterArray`
225    /// instead of eagerly filtering the values immediately.
226    pub fn filter(&self, mask: &Mask) -> VortexResult<Self> {
227        // NOTE(ngates): we take the mask as a reference to avoid the caller cloning unnecessarily
228        //  if we happen to be NonNullable, AllValid, or AllInvalid.
229        match self {
230            v @ (Validity::NonNullable | Validity::AllValid | Validity::AllInvalid) => {
231                Ok(v.clone())
232            }
233            Validity::Array(arr) => Ok(Validity::Array(arr.filter(mask.clone())?)),
234        }
235    }
236
237    /// Converts this validity into a [`Mask`] of the given length.
238    ///
239    /// Valid elements are `true` and invalid elements are `false`.
240    #[deprecated(note = "Use execute_mask")]
241    pub fn to_mask(&self, length: usize, ctx: &mut ExecutionCtx) -> VortexResult<Mask> {
242        match self {
243            Self::NonNullable | Self::AllValid => Ok(Mask::new_true(length)),
244            Self::AllInvalid => Ok(Mask::new_false(length)),
245            Self::Array(arr) => arr.clone().execute::<Mask>(ctx),
246        }
247    }
248
249    /// Execute this validity into a [`Mask`] of the given length.
250    ///
251    /// Resolving [`Validity::Array`] can execute and scan up to `length` values. Optimistic fast
252    /// paths that do not need the exact mask should use [`Self::definitely_no_nulls`] or
253    /// [`Self::definitely_all_null`] and delay this work until necessary.
254    #[inline]
255    pub fn execute_mask(&self, length: usize, ctx: &mut ExecutionCtx) -> VortexResult<Mask> {
256        match self {
257            Self::NonNullable | Self::AllValid => Ok(Mask::AllTrue(length)),
258            Self::AllInvalid => Ok(Mask::AllFalse(length)),
259            Self::Array(arr) => {
260                assert_eq!(
261                    arr.len(),
262                    length,
263                    "Validity::Array length must equal to_logical's argument: {}, {}.",
264                    arr.len(),
265                    length,
266                );
267                // TODO(ngates): I'm not sure execution should take arrays by ownership.
268                //  If so we should fix call sites to clone and this function takes self.
269                arr.clone().execute::<Mask>(ctx)
270            }
271        }
272    }
273
274    /// Compare the logical masks of two Validity values of the given length, executing them
275    /// into [`Mask`]s if necessary.
276    pub fn mask_eq(
277        &self,
278        other: &Validity,
279        length: usize,
280        ctx: &mut ExecutionCtx,
281    ) -> VortexResult<bool> {
282        match (self, other) {
283            // Fast paths that avoid executing: constant variants with known-equal masks.
284            (
285                Validity::NonNullable | Validity::AllValid,
286                Validity::NonNullable | Validity::AllValid,
287            )
288            | (Validity::AllInvalid, Validity::AllInvalid) => Ok(true),
289            _ => Ok(self.execute_mask(length, ctx)? == other.execute_mask(length, ctx)?),
290        }
291    }
292
293    /// Logically & two Validity values of the same length
294    #[inline]
295    pub fn and(self, rhs: Validity) -> VortexResult<Validity> {
296        Ok(match (self, rhs) {
297            // Should be pretty clear
298            (Validity::NonNullable, Validity::NonNullable) => Validity::NonNullable,
299            // Any `AllInvalid` makes the output all invalid values
300            (Validity::AllInvalid, _) | (_, Validity::AllInvalid) => Validity::AllInvalid,
301            // All truthy values on one side, which makes no effect on an `Array` variant
302            (Validity::Array(a), Validity::AllValid)
303            | (Validity::Array(a), Validity::NonNullable)
304            | (Validity::NonNullable, Validity::Array(a))
305            | (Validity::AllValid, Validity::Array(a)) => Validity::Array(a),
306            // Both sides are all valid
307            (Validity::NonNullable, Validity::AllValid)
308            | (Validity::AllValid, Validity::NonNullable)
309            | (Validity::AllValid, Validity::AllValid) => Validity::AllValid,
310            // Here we actually have to do some work
311            (Validity::Array(lhs), Validity::Array(rhs)) => {
312                Validity::Array(Boolean::try_new(lhs, rhs, BooleanOperator::And)?.into_array())
313            }
314        })
315    }
316
317    pub fn patch(
318        self,
319        len: usize,
320        indices_offset: usize,
321        indices: &ArrayRef,
322        patches: &Validity,
323        ctx: &mut ExecutionCtx,
324    ) -> VortexResult<Self> {
325        match (&self, patches) {
326            (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
327            (Validity::NonNullable, _) => {
328                vortex_bail!("Can't patch a non-nullable validity with nullable validity")
329            }
330            (_, Validity::NonNullable) => {
331                vortex_bail!("Can't patch a nullable validity with non-nullable validity")
332            }
333            (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
334            (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
335            _ => {}
336        };
337
338        if matches!(self, Validity::NonNullable) {
339            return Ok(Self::NonNullable);
340        }
341
342        // From here on we know that the validity is nullable
343        let source = match self {
344            Validity::NonNullable => BoolArray::from(BitBuffer::new_set(len)),
345            Validity::AllValid => BoolArray::from(BitBuffer::new_set(len)),
346            Validity::AllInvalid => BoolArray::from(BitBuffer::new_unset(len)),
347            Validity::Array(a) => a.execute::<BoolArray>(ctx)?,
348        };
349
350        let patch_values = match patches {
351            Validity::NonNullable => BoolArray::from(BitBuffer::new_set(indices.len())),
352            Validity::AllValid => BoolArray::from(BitBuffer::new_set(indices.len())),
353            Validity::AllInvalid => BoolArray::from(BitBuffer::new_unset(indices.len())),
354            Validity::Array(a) => a.clone().execute::<BoolArray>(ctx)?,
355        };
356
357        let patches = Patches::new(
358            len,
359            indices_offset,
360            indices.clone(),
361            patch_values.into_array(),
362            // TODO(0ax1): chunk offsets
363            None,
364            ctx,
365        )?;
366
367        Ok(Self::Array(source.patch(&patches, ctx)?.into_array()))
368    }
369
370    /// Convert into a nullable variant.
371    #[inline]
372    pub fn into_nullable(self) -> Validity {
373        match self {
374            Self::NonNullable => Self::AllValid,
375            Self::AllValid | Self::AllInvalid | Self::Array(_) => self,
376        }
377    }
378
379    /// Convert into a non-nullable variant, computing statistics if necessary.
380    ///
381    /// Returns `None` when the array contains invalid values (so the cast cannot be performed),
382    /// either because it is [`Validity::AllInvalid`] or because the validity array's minimum is
383    /// `false`.
384    ///
385    /// The result depends on the statistics of the validity array, which can come from untrusted
386    /// input. An encoding must not depend on this result for memory safety. An encoding that does
387    /// not validate the values at null rows, such as `VarBin`, must read the validity values
388    /// itself before it makes those rows valid.
389    #[inline]
390    pub fn into_non_nullable(self, len: usize, ctx: &mut ExecutionCtx) -> Option<Validity> {
391        match self {
392            _ if len == 0 => Some(Validity::NonNullable),
393            Self::NonNullable => Some(Self::NonNullable),
394            Self::AllValid => Some(Self::NonNullable),
395            Self::AllInvalid => None,
396            Self::Array(is_valid) => {
397                is_valid
398                    .statistics()
399                    .compute_min::<bool>(ctx)
400                    .vortex_expect("validity array must support min")
401                    .then(|| {
402                        // min true => all true
403                        Self::NonNullable
404                    })
405            }
406        }
407    }
408
409    /// Convert into a non-nullable variant without running execution.
410    ///
411    /// This is the cheap counterpart to [`Self::into_non_nullable`]: it inspects already-computed
412    /// statistics rather than triggering execution.
413    ///
414    /// Return values:
415    /// - `Ok(Some(NonNullable))` — the cast is provably safe.
416    /// - `Ok(None)` — We need to perform compute to determine whether cast is valid. Callers should fall back to [`Self::into_non_nullable`], typically by
417    ///   returning `Ok(None)` from a `CastReduce` rule so the corresponding `CastKernel` runs.
418    /// - `Err(_)` — we know the cast must fail (e.g. [`Validity::AllInvalid`]).
419    #[inline]
420    pub fn trivial_into_non_nullable(self, len: usize) -> VortexResult<Option<Validity>> {
421        match self {
422            _ if len == 0 => Ok(Some(Validity::NonNullable)),
423            Self::NonNullable => Ok(Some(Self::NonNullable)),
424            Self::AllValid => Ok(Some(Self::NonNullable)),
425            Self::AllInvalid => Err(vortex_err!("Cannot cast AllInvalid to NonNullable")),
426            Self::Array(_) => Ok(None),
427        }
428    }
429
430    /// Convert into a variant compatible with the given nullability.
431    ///
432    /// Unlike [`Self::trivially_cast_nullability`], this can execute the validity array, so a
433    /// [`CastKernel`] calls it. [`CastReduce`] documents when a cast rule needs the pair.
434    ///
435    /// Returns `Err` when nullability cannot be cast (for example, casting to non-nullable while
436    /// invalid values are present).
437    ///
438    /// [`CastKernel`]: crate::scalar_fn::builtin::cast::CastKernel
439    /// [`CastReduce`]: crate::scalar_fn::builtin::cast::CastReduce
440    #[inline]
441    pub fn cast_nullability(
442        self,
443        nullability: Nullability,
444        len: usize,
445        ctx: &mut ExecutionCtx,
446    ) -> VortexResult<Validity> {
447        match nullability {
448            Nullability::NonNullable => self.into_non_nullable(len, ctx).ok_or_else(|| {
449                vortex_err!("Cannot cast array with invalid values to non-nullable type.")
450            }),
451            Nullability::Nullable => Ok(self.into_nullable()),
452        }
453    }
454
455    /// Best-effort, non-executing variant of [`Self::cast_nullability`].
456    ///
457    /// A [`CastReduce`] rule that builds a new [`Validity`] calls this, because a rule cannot
458    /// execute.
459    ///
460    /// Return values:
461    /// - `Ok(Some(_))` — the cast is provably safe and the new [`Validity`] is returned.
462    /// - `Ok(None)` — the cast cannot be reduced cheaply (the `CastKernel` should be tried via
463    ///   [`Self::cast_nullability`]).
464    /// - `Err(_)` — the cast is provably impossible.
465    ///
466    /// Typical usage inside a `CastReduce`:
467    ///
468    /// ```ignore
469    /// let Some(new_validity) = array
470    ///     .validity()?
471    ///     .trivially_cast_nullability(dtype.nullability(), array.len())?
472    /// else {
473    ///     return Ok(None);
474    /// };
475    /// ```
476    ///
477    /// [`CastReduce`]: crate::scalar_fn::builtin::cast::CastReduce
478    #[inline]
479    pub fn trivially_cast_nullability(
480        self,
481        nullability: Nullability,
482        len: usize,
483    ) -> VortexResult<Option<Validity>> {
484        match nullability {
485            Nullability::NonNullable => self.trivial_into_non_nullable(len),
486            Nullability::Nullable => Ok(Some(self.into_nullable())),
487        }
488    }
489
490    /// Returns the length of the validity array, if it exists.
491    #[inline]
492    pub fn maybe_len(&self) -> Option<usize> {
493        match self {
494            Self::NonNullable | Self::AllValid | Self::AllInvalid => None,
495            Self::Array(a) => Some(a.len()),
496        }
497    }
498}
499
500impl From<BitBuffer> for Validity {
501    #[inline]
502    fn from(value: BitBuffer) -> Self {
503        let true_count = value.true_count();
504        if true_count == value.len() {
505            Self::AllValid
506        } else if true_count == 0 {
507            Self::AllInvalid
508        } else {
509            Self::Array(BoolArray::from(value).into_array())
510        }
511    }
512}
513
514impl FromIterator<Mask> for Validity {
515    #[inline]
516    fn from_iter<T: IntoIterator<Item = Mask>>(iter: T) -> Self {
517        Validity::from_mask(iter.into_iter().collect(), Nullability::Nullable)
518    }
519}
520
521impl FromIterator<bool> for Validity {
522    #[inline]
523    fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
524        Validity::from(BitBuffer::from_iter(iter))
525    }
526}
527
528impl From<Nullability> for Validity {
529    #[inline]
530    fn from(value: Nullability) -> Self {
531        Validity::from(&value)
532    }
533}
534
535impl From<&Nullability> for Validity {
536    #[inline]
537    fn from(value: &Nullability) -> Self {
538        match *value {
539            Nullability::NonNullable => Validity::NonNullable,
540            Nullability::Nullable => Validity::AllValid,
541        }
542    }
543}
544
545impl Validity {
546    /// Concatenate one or more validities together.
547    ///
548    /// Returns None if the vector is empty.
549    pub fn concat(validities: Vec<(Validity, usize)>) -> Option<Self> {
550        let mut validity_kinds = validities
551            .iter()
552            .map(|(v, _)| std::mem::discriminant(v))
553            .unique();
554        let validity_kind = validity_kinds.next()?;
555        if validity_kinds.next().is_none() {
556            // If there is only one kind of validity and its not Validity::Array, avoid constructing
557            // a Validity::Array.
558            if validity_kind == std::mem::discriminant(&Validity::AllValid) {
559                return Some(Validity::AllValid);
560            }
561            if validity_kind == std::mem::discriminant(&Validity::AllInvalid) {
562                return Some(Validity::AllInvalid);
563            }
564            if validity_kind == std::mem::discriminant(&Validity::NonNullable) {
565                return Some(Validity::NonNullable);
566            }
567        }
568
569        Some(Validity::Array(
570            unsafe {
571                ChunkedArray::new_unchecked(
572                    validities.into_iter().map(|(v, len)| v.to_array(len)),
573                    DType::Bool(Nullability::NonNullable),
574                )
575            }
576            .into_array(),
577        ))
578    }
579}
580
581impl Validity {
582    pub fn from_bit_buffer(buffer: BitBuffer, nullability: Nullability) -> Self {
583        if buffer.true_count() == buffer.len() {
584            nullability.into()
585        } else if buffer.true_count() == 0 {
586            Validity::AllInvalid
587        } else {
588            Validity::Array(BoolArray::new(buffer, Validity::NonNullable).into_array())
589        }
590    }
591
592    pub fn from_mask(mask: Mask, nullability: Nullability) -> Self {
593        assert!(
594            nullability == Nullability::Nullable || matches!(mask, Mask::AllTrue(_)),
595            "NonNullable validity must be AllValid",
596        );
597        match mask {
598            Mask::AllTrue(_) => match nullability {
599                Nullability::NonNullable => Validity::NonNullable,
600                Nullability::Nullable => Validity::AllValid,
601            },
602            Mask::AllFalse(_) => Validity::AllInvalid,
603            Mask::Values(values) => Validity::Array(values.into_array()),
604        }
605    }
606}
607
608impl IntoArray for Mask {
609    #[inline]
610    fn into_array(self) -> ArrayRef {
611        match self {
612            Self::AllTrue(len) => ConstantArray::new(true, len).into_array(),
613            Self::AllFalse(len) => ConstantArray::new(false, len).into_array(),
614            Self::Values(a) => a.into_array(),
615        }
616    }
617}
618
619impl IntoArray for &MaskValues {
620    #[inline]
621    fn into_array(self) -> ArrayRef {
622        BoolArray::new(self.bit_buffer().clone(), Validity::NonNullable).into_array()
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use std::sync::LazyLock;
629
630    use rstest::rstest;
631    use vortex_buffer::Buffer;
632    use vortex_buffer::buffer;
633    use vortex_mask::Mask;
634    use vortex_session::VortexSession;
635
636    use crate::ArrayRef;
637    use crate::IntoArray;
638    use crate::VortexSessionExecute;
639    use crate::arrays::PrimitiveArray;
640    use crate::dtype::Nullability;
641    use crate::validity::BoolArray;
642    use crate::validity::Validity;
643
644    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
645
646    #[rstest]
647    #[case(Validity::AllValid, 5, &[2, 4], Validity::AllValid, Validity::AllValid)]
648    #[case(
649        Validity::AllValid,
650        5,
651        &[2, 4],
652        Validity::AllInvalid,
653        Validity::Array(BoolArray::from_iter([true, true, false, true, false]).into_array())
654    )]
655    #[case(
656        Validity::AllValid,
657        5,
658        &[2, 4],
659        Validity::Array(BoolArray::from_iter([true, false]).into_array()),
660        Validity::Array(BoolArray::from_iter([true, true, true, true, false]).into_array())
661    )]
662    #[case(
663        Validity::AllInvalid,
664        5,
665        &[2, 4],
666        Validity::AllValid,
667        Validity::Array(BoolArray::from_iter([false, false, true, false, true]).into_array())
668    )]
669    #[case(Validity::AllInvalid, 5, &[2, 4], Validity::AllInvalid, Validity::AllInvalid)]
670    #[case(
671        Validity::AllInvalid,
672        5,
673        &[2, 4],
674        Validity::Array(BoolArray::from_iter([true, false]).into_array()),
675        Validity::Array(BoolArray::from_iter([false, false, true, false, false]).into_array())
676    )]
677    #[case(
678        Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()),
679        5,
680        &[2, 4],
681        Validity::AllValid,
682        Validity::Array(BoolArray::from_iter([false, true, true, true, true]).into_array())
683    )]
684    #[case(
685        Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()),
686        5,
687        &[2, 4],
688        Validity::AllInvalid,
689        Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array())
690    )]
691    #[case(
692        Validity::Array(BoolArray::from_iter([false, true, false, true, false]).into_array()),
693        5,
694        &[2, 4],
695        Validity::Array(BoolArray::from_iter([true, false]).into_array()),
696        Validity::Array(BoolArray::from_iter([false, true, true, true, false]).into_array())
697    )]
698
699    fn patch_validity(
700        #[case] validity: Validity,
701        #[case] len: usize,
702        #[case] positions: &[u64],
703        #[case] patches: Validity,
704        #[case] expected: Validity,
705    ) {
706        let indices =
707            PrimitiveArray::new(Buffer::copy_from(positions), Validity::NonNullable).into_array();
708
709        let mut ctx = SESSION.create_execution_ctx();
710
711        assert!(
712            validity
713                .patch(len, 0, &indices, &patches, &mut ctx,)
714                .unwrap()
715                .mask_eq(&expected, len, &mut ctx)
716                .unwrap()
717        );
718    }
719
720    #[rstest]
721    #[case(
722        Validity::NonNullable,
723        1,
724        "Can't patch a non-nullable validity with nullable validity"
725    )]
726    #[case(
727        Validity::AllValid,
728        4,
729        "Patch indices 4, offset 0 are longer than the array length 2"
730    )]
731    fn rejects_invalid_patch(
732        #[case] validity: Validity,
733        #[case] index: u64,
734        #[case] message: &str,
735    ) {
736        let mut ctx = SESSION.create_execution_ctx();
737        let error = validity
738            .patch(
739                2,
740                0,
741                &buffer![index].into_array(),
742                &Validity::AllInvalid,
743                &mut ctx,
744            )
745            .unwrap_err();
746        assert!(error.to_string().contains(message), "{error}");
747    }
748
749    #[test]
750    #[should_panic(expected = "NonNullable validity must be AllValid")]
751    fn into_validity_nullable() {
752        Validity::from_mask(Mask::AllFalse(10), Nullability::NonNullable);
753    }
754
755    #[test]
756    #[should_panic(expected = "NonNullable validity must be AllValid")]
757    fn into_validity_nullable_array() {
758        Validity::from_mask(Mask::from_iter(vec![true, false]), Nullability::NonNullable);
759    }
760
761    #[rstest]
762    #[case(
763        Validity::AllValid,
764        PrimitiveArray::new(buffer![0, 1], Validity::from_iter(vec![true, false])).into_array(),
765        Validity::from_iter(vec![true, false])
766    )]
767    #[case(Validity::AllValid, buffer![0, 1].into_array(), Validity::AllValid)]
768    #[case(
769        Validity::AllValid,
770        PrimitiveArray::new(buffer![0, 1], Validity::AllInvalid).into_array(),
771        Validity::AllInvalid
772    )]
773    #[case(
774        Validity::NonNullable,
775        PrimitiveArray::new(buffer![0, 1], Validity::from_iter(vec![true, false])).into_array(),
776        Validity::from_iter(vec![true, false])
777    )]
778    #[case(Validity::NonNullable, buffer![0, 1].into_array(), Validity::NonNullable)]
779    #[case(
780        Validity::NonNullable,
781        PrimitiveArray::new(buffer![0, 1], Validity::AllInvalid).into_array(),
782        Validity::AllInvalid
783    )]
784    fn validity_take(
785        #[case] validity: Validity,
786        #[case] indices: ArrayRef,
787        #[case] expected: Validity,
788    ) {
789        let mut ctx = SESSION.create_execution_ctx();
790        let taken = validity.take(&indices).unwrap();
791        assert_eq!(taken.nullability(), expected.nullability());
792        assert!(taken.mask_eq(&expected, indices.len(), &mut ctx).unwrap());
793    }
794
795    #[rstest]
796    // Mixed constant variants with equal masks.
797    #[case(Validity::NonNullable, Validity::AllValid, true)]
798    #[case(Validity::AllValid, Validity::NonNullable, true)]
799    #[case(Validity::AllValid, Validity::AllInvalid, false)]
800    #[case(Validity::NonNullable, Validity::AllInvalid, false)]
801    // An array that resolves to a constant mask must equal the constant variant.
802    #[case(
803        Validity::Array(BoolArray::from_iter([true, true, true]).into_array()),
804        Validity::AllValid,
805        true
806    )]
807    #[case(
808        Validity::NonNullable,
809        Validity::Array(BoolArray::from_iter([true, true, true]).into_array()),
810        true
811    )]
812    #[case(
813        Validity::Array(BoolArray::from_iter([false, false, false]).into_array()),
814        Validity::AllInvalid,
815        true
816    )]
817    #[case(
818        Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
819        Validity::AllValid,
820        false
821    )]
822    #[case(
823        Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
824        Validity::AllInvalid,
825        false
826    )]
827    fn mask_eq_mixed_variants(
828        #[case] lhs: Validity,
829        #[case] rhs: Validity,
830        #[case] expected: bool,
831    ) -> vortex_error::VortexResult<()> {
832        let mut ctx = SESSION.create_execution_ctx();
833        assert_eq!(lhs.mask_eq(&rhs, 3, &mut ctx)?, expected);
834        Ok(())
835    }
836}