Skip to main content

vortex_array/arrays/masked/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3mod canonical;
4mod operations;
5mod validity;
6
7use std::hash::Hash;
8use std::sync::Arc;
9
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_panic;
15use vortex_session::VortexSession;
16
17use crate::ArrayRef;
18use crate::Canonical;
19use crate::EmptyMetadata;
20use crate::IntoArray;
21use crate::Precision;
22use crate::arrays::ConstantArray;
23use crate::arrays::MaskedArray;
24use crate::arrays::masked::compute::rules::PARENT_RULES;
25use crate::arrays::masked::mask_validity_canonical;
26use crate::buffer::BufferHandle;
27use crate::dtype::DType;
28use crate::executor::ExecutionCtx;
29use crate::executor::ExecutionResult;
30use crate::hash::ArrayEq;
31use crate::hash::ArrayHash;
32use crate::scalar::Scalar;
33use crate::serde::ArrayChildren;
34use crate::stats::StatsSetRef;
35use crate::validity::Validity;
36use crate::vtable;
37use crate::vtable::ArrayId;
38use crate::vtable::VTable;
39use crate::vtable::ValidityVTableFromValidityHelper;
40use crate::vtable::validity_nchildren;
41use crate::vtable::validity_to_child;
42vtable!(Masked);
43
44#[derive(Clone, Debug)]
45pub struct Masked;
46
47impl Masked {
48    pub const ID: ArrayId = ArrayId::new_ref("vortex.masked");
49}
50
51impl VTable for Masked {
52    type Array = MaskedArray;
53
54    type Metadata = EmptyMetadata;
55    type OperationsVTable = Self;
56    type ValidityVTable = ValidityVTableFromValidityHelper;
57
58    fn vtable(_array: &Self::Array) -> &Self {
59        &Masked
60    }
61
62    fn id(&self) -> ArrayId {
63        Self::ID
64    }
65
66    fn len(array: &MaskedArray) -> usize {
67        array.child.len()
68    }
69
70    fn dtype(array: &MaskedArray) -> &DType {
71        &array.dtype
72    }
73
74    fn stats(array: &MaskedArray) -> StatsSetRef<'_> {
75        array.stats.to_ref(array.as_ref())
76    }
77
78    fn array_hash<H: std::hash::Hasher>(array: &MaskedArray, state: &mut H, precision: Precision) {
79        array.child.array_hash(state, precision);
80        array.validity.array_hash(state, precision);
81        array.dtype.hash(state);
82    }
83
84    fn array_eq(array: &MaskedArray, other: &MaskedArray, precision: Precision) -> bool {
85        array.child.array_eq(&other.child, precision)
86            && array.validity.array_eq(&other.validity, precision)
87            && array.dtype == other.dtype
88    }
89
90    fn nbuffers(_array: &Self::Array) -> usize {
91        0
92    }
93
94    fn buffer(_array: &Self::Array, _idx: usize) -> BufferHandle {
95        vortex_panic!("MaskedArray has no buffers")
96    }
97
98    fn buffer_name(_array: &Self::Array, _idx: usize) -> Option<String> {
99        None
100    }
101
102    fn nchildren(array: &Self::Array) -> usize {
103        1 + validity_nchildren(&array.validity)
104    }
105
106    fn child(array: &Self::Array, idx: usize) -> ArrayRef {
107        match idx {
108            0 => array.child.clone(),
109            1 => validity_to_child(&array.validity, array.child.len())
110                .vortex_expect("MaskedArray validity child out of bounds"),
111            _ => vortex_panic!("MaskedArray child index {idx} out of bounds"),
112        }
113    }
114
115    fn child_name(_array: &Self::Array, idx: usize) -> String {
116        match idx {
117            0 => "child".to_string(),
118            1 => "validity".to_string(),
119            _ => vortex_panic!("MaskedArray child_name index {idx} out of bounds"),
120        }
121    }
122
123    fn metadata(_array: &MaskedArray) -> VortexResult<Self::Metadata> {
124        Ok(EmptyMetadata)
125    }
126
127    fn serialize(_metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
128        Ok(Some(vec![]))
129    }
130
131    fn deserialize(
132        _bytes: &[u8],
133        _dtype: &DType,
134        _len: usize,
135        _buffers: &[BufferHandle],
136        _session: &VortexSession,
137    ) -> VortexResult<Self::Metadata> {
138        Ok(EmptyMetadata)
139    }
140
141    fn build(
142        dtype: &DType,
143        len: usize,
144        _metadata: &Self::Metadata,
145        buffers: &[BufferHandle],
146        children: &dyn ArrayChildren,
147    ) -> VortexResult<MaskedArray> {
148        if !buffers.is_empty() {
149            vortex_bail!("Expected 0 buffer, got {}", buffers.len());
150        }
151
152        let child = children.get(0, &dtype.as_nonnullable(), len)?;
153
154        let validity = if children.len() == 1 {
155            Validity::from(dtype.nullability())
156        } else if children.len() == 2 {
157            let validity = children.get(1, &Validity::DTYPE, len)?;
158            Validity::Array(validity)
159        } else {
160            vortex_bail!(
161                "`MaskedArray::build` expects 1 or 2 children, got {}",
162                children.len()
163            );
164        };
165
166        MaskedArray::try_new(child, validity)
167    }
168
169    fn execute(array: Arc<Self::Array>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
170        let validity_mask = array.validity_mask()?;
171
172        // Fast path: all masked means result is all nulls.
173        if validity_mask.all_false() {
174            return Ok(ExecutionResult::done(
175                ConstantArray::new(Scalar::null(array.dtype().as_nullable()), array.len())
176                    .into_array(),
177            ));
178        }
179
180        // NB: We intentionally do NOT have a fast path for `validity_mask.all_true()`.
181        // `MaskedArray`'s dtype is always `Nullable`, but the child has `NonNullable` `DType` (by
182        // invariant). Simply returning the child's canonical would cause a dtype mismatch.
183        // While we could manually convert the dtype, `mask_validity_canonical` is already O(1) for
184        // `AllTrue` masks (no data copying), so there's no benefit.
185
186        let child = array.child().clone().execute::<Canonical>(ctx)?;
187        Ok(ExecutionResult::done(
188            mask_validity_canonical(child, &validity_mask, ctx)?.into_array(),
189        ))
190    }
191
192    fn reduce_parent(
193        array: &Self::Array,
194        parent: &ArrayRef,
195        child_idx: usize,
196    ) -> VortexResult<Option<ArrayRef>> {
197        PARENT_RULES.evaluate(array, parent, child_idx)
198    }
199
200    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
201        vortex_ensure!(
202            children.len() == 1 || children.len() == 2,
203            "MaskedArray expects 1 or 2 children, got {}",
204            children.len()
205        );
206
207        let mut iter = children.into_iter();
208        let child = iter
209            .next()
210            .vortex_expect("children length already validated");
211        let validity = if let Some(validity_array) = iter.next() {
212            Validity::Array(validity_array)
213        } else {
214            Validity::from(array.dtype.nullability())
215        };
216
217        let new_array = MaskedArray::try_new(child, validity)?;
218        *array = new_array;
219        Ok(())
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use rstest::rstest;
226    use vortex_buffer::ByteBufferMut;
227    use vortex_error::VortexError;
228    use vortex_session::registry::ReadContext;
229
230    use crate::ArrayContext;
231    use crate::Canonical;
232    use crate::IntoArray;
233    use crate::LEGACY_SESSION;
234    use crate::VortexSessionExecute;
235    use crate::arrays::Masked;
236    use crate::arrays::MaskedArray;
237    use crate::arrays::PrimitiveArray;
238    use crate::dtype::Nullability;
239    use crate::serde::ArrayParts;
240    use crate::serde::SerializeOptions;
241    use crate::validity::Validity;
242
243    #[rstest]
244    #[case(
245        MaskedArray::try_new(
246            PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
247            Validity::AllValid
248        ).unwrap()
249    )]
250    #[case(
251        MaskedArray::try_new(
252            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
253            Validity::from_iter([true, true, false, true, false])
254        ).unwrap()
255    )]
256    #[case(
257        MaskedArray::try_new(
258            PrimitiveArray::from_iter(0..100).into_array(),
259            Validity::from_iter((0..100).map(|i| i % 3 != 0))
260        ).unwrap()
261    )]
262    fn test_serde_roundtrip(#[case] array: MaskedArray) {
263        let dtype = array.dtype().clone();
264        let len = array.len();
265
266        let ctx = ArrayContext::empty();
267        let serialized = array
268            .clone()
269            .into_array()
270            .serialize(&ctx, &SerializeOptions::default())
271            .unwrap();
272
273        // Concat into a single buffer.
274        let mut concat = ByteBufferMut::empty();
275        for buf in serialized {
276            concat.extend_from_slice(buf.as_ref());
277        }
278        let concat = concat.freeze();
279
280        let parts = ArrayParts::try_from(concat).unwrap();
281        let decoded = parts
282            .decode(
283                &dtype,
284                len,
285                &ReadContext::new(ctx.to_ids()),
286                &LEGACY_SESSION,
287            )
288            .unwrap();
289
290        assert!(decoded.is::<Masked>());
291        assert_eq!(
292            array.as_ref().display_values().to_string(),
293            decoded.display_values().to_string()
294        );
295    }
296
297    /// Regression test for issue #5989: execute_fast_path returns child with wrong dtype.
298    ///
299    /// When MaskedArray's validity mask is all true, returning the child's canonical form
300    /// directly would cause a dtype mismatch because the child has NonNullable dtype while
301    /// MaskedArray always has Nullable dtype.
302    #[test]
303    fn test_execute_with_all_valid_preserves_nullable_dtype() -> Result<(), VortexError> {
304        // Create a MaskedArray with AllValid validity.
305
306        // Child has NonNullable dtype, but MaskedArray's dtype is Nullable.
307        let child = PrimitiveArray::from_iter([1i32, 2, 3]).into_array();
308        assert_eq!(child.dtype().nullability(), Nullability::NonNullable);
309
310        let array = MaskedArray::try_new(child, Validity::AllValid)?;
311        assert_eq!(array.dtype().nullability(), Nullability::Nullable);
312
313        // Execute the array. This should produce a Canonical with Nullable dtype.
314        let mut ctx = LEGACY_SESSION.create_execution_ctx();
315        let result: Canonical = array.into_array().execute(&mut ctx)?;
316
317        assert_eq!(
318            result.as_ref().dtype().nullability(),
319            Nullability::Nullable,
320            "MaskedArray execute should produce Nullable dtype"
321        );
322
323        Ok(())
324    }
325}