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