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