vortex_array/arrays/masked/vtable/
mod.rs1mod 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;
49pub 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 #[expect(clippy::disallowed_methods)]
77 fn validate(
78 &self,
79 _data: &MaskedData,
80 dtype: &DType,
81 len: usize,
82 slots: &[Option<ArrayRef>],
83 ) -> VortexResult<()> {
84 vortex_ensure!(
85 slots[MaskedSlots::CHILD].is_some(),
86 "MaskedArray child slot must be present"
87 );
88 let child = slots[MaskedSlots::CHILD]
89 .as_ref()
90 .vortex_expect("validated child slot");
91 vortex_ensure!(child.len() == len, "MaskedArray child length mismatch");
92 vortex_ensure!(
93 child.dtype().as_nullable() == *dtype,
94 "MaskedArray dtype does not match child and validity"
95 );
96 vortex_ensure!(
97 child.all_valid(&mut legacy_session().create_execution_ctx())?,
98 "MaskedArray children must not have nulls",
99 );
100 Ok(())
101 }
102
103 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
104 0
105 }
106
107 fn buffer(_array: ArrayView<'_, Self>, _idx: usize) -> BufferHandle {
108 vortex_panic!("MaskedArray has no buffers")
109 }
110
111 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
112 None
113 }
114
115 fn with_buffers(
116 &self,
117 array: ArrayView<'_, Self>,
118 buffers: &[BufferHandle],
119 ) -> VortexResult<ArrayParts<Self>> {
120 with_empty_buffers(self, array, buffers)
121 }
122
123 fn serialize(
124 _array: ArrayView<'_, Self>,
125 _session: &VortexSession,
126 ) -> VortexResult<Option<Vec<u8>>> {
127 Ok(Some(vec![]))
128 }
129
130 #[allow(clippy::disallowed_methods)]
131 fn deserialize(
132 &self,
133 dtype: &DType,
134 len: usize,
135 metadata: &[u8],
136
137 buffers: &[BufferHandle],
138 children: &dyn ArrayChildren,
139 _session: &VortexSession,
140 ) -> VortexResult<ArrayParts<Self>> {
141 if !metadata.is_empty() {
142 vortex_bail!(
143 "MaskedArray expects empty metadata, got {} bytes",
144 metadata.len()
145 );
146 }
147 if !buffers.is_empty() {
148 vortex_bail!("Expected 0 buffer, got {}", buffers.len());
149 }
150
151 vortex_ensure!(
152 children.len() == 1 || children.len() == 2,
153 "`MaskedArray::build` expects 1 or 2 children, got {}",
154 children.len()
155 );
156
157 let child = children.get(0, &dtype.as_nonnullable(), len)?;
158
159 let validity = if children.len() == 2 {
160 let validity = children.get(1, &Validity::DTYPE, len)?;
161 Validity::Array(validity)
162 } else {
163 Validity::from(dtype.nullability())
164 };
165
166 let validity_slot = validity_to_child(&validity, len);
167 let data = MaskedData::try_new(
168 len,
169 child.all_valid(&mut legacy_session().create_execution_ctx())?,
170 validity,
171 )?;
172 Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data)
173 .with_slots(smallvec![Some(child), validity_slot]))
174 }
175
176 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
177 let array = require_child!(array, array.child(), MaskedSlots::CHILD => AnyCanonical);
178
179 let validity = array.masked_validity();
180
181 if validity.definitely_all_null() {
183 return Ok(ExecutionResult::done(
184 ConstantArray::new(Scalar::null(array.dtype().as_nullable()), array.len())
185 .into_array(),
186 ));
187 }
188
189 let child = Canonical::from(array.child().as_::<AnyCanonical>());
196 Ok(ExecutionResult::done(
197 mask_validity_canonical(child, validity, ctx)?.into_array(),
198 ))
199 }
200
201 fn reduce_parent(
202 array: ArrayView<'_, Self>,
203 parent: &ArrayRef,
204 child_idx: usize,
205 ) -> VortexResult<Option<ArrayRef>> {
206 PARENT_RULES.evaluate(array, parent, child_idx)
207 }
208 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
209 MaskedSlots::NAMES[idx].to_string()
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use rstest::rstest;
216 use vortex_buffer::ByteBufferMut;
217 use vortex_error::VortexError;
218 use vortex_session::registry::ReadContext;
219
220 use crate::ArrayContext;
221 use crate::Canonical;
222 use crate::IntoArray;
223 use crate::VortexSessionExecute;
224 use crate::array_session;
225 use crate::arrays::Masked;
226 use crate::arrays::MaskedArray;
227 use crate::arrays::PrimitiveArray;
228 use crate::dtype::Nullability;
229 use crate::serde::SerializeOptions;
230 use crate::serde::SerializedArray;
231 use crate::validity::Validity;
232
233 #[rstest]
234 #[case(
235 MaskedArray::try_new(
236 PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
237 Validity::AllValid
238 ).unwrap()
239 )]
240 #[case(
241 MaskedArray::try_new(
242 PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]).into_array(),
243 Validity::from_iter([true, true, false, true, false])
244 ).unwrap()
245 )]
246 #[case(
247 MaskedArray::try_new(
248 PrimitiveArray::from_iter(0..100).into_array(),
249 Validity::from_iter((0..100).map(|i| i % 3 != 0))
250 ).unwrap()
251 )]
252 fn test_serde_roundtrip(#[case] array: MaskedArray) {
253 let dtype = array.dtype().clone();
254 let len = array.len();
255
256 let ctx = ArrayContext::empty();
257 let serialized = array
258 .clone()
259 .into_array()
260 .serialize(&ctx, &array_session(), &SerializeOptions::default())
261 .unwrap();
262
263 let mut concat = ByteBufferMut::empty();
265 for buf in serialized {
266 concat.extend_from_slice(buf.as_ref());
267 }
268 let concat = concat.freeze();
269
270 let parts = SerializedArray::try_from(concat).unwrap();
271 let decoded = parts
272 .decode(
273 &dtype,
274 len,
275 &ReadContext::new(ctx.to_ids()),
276 &array_session(),
277 )
278 .unwrap();
279
280 assert!(decoded.is::<Masked>());
281 assert_eq!(
282 array.as_ref().display_values().to_string(),
283 decoded.display_values().to_string()
284 );
285 }
286
287 #[test]
293 fn test_execute_with_all_valid_preserves_nullable_dtype() -> Result<(), VortexError> {
294 let child = PrimitiveArray::from_iter([1i32, 2, 3]).into_array();
298 assert_eq!(child.dtype().nullability(), Nullability::NonNullable);
299
300 let array = MaskedArray::try_new(child, Validity::AllValid)?;
301 assert_eq!(array.dtype().nullability(), Nullability::Nullable);
302
303 let mut ctx = array_session().create_execution_ctx();
305 let result: Canonical = array.into_array().execute(&mut ctx)?;
306
307 assert_eq!(
308 result.dtype().nullability(),
309 Nullability::Nullable,
310 "MaskedArray execute should produce Nullable dtype"
311 );
312
313 Ok(())
314 }
315}