vortex_array/arrays/variant/
mod.rs1mod vtable;
5
6pub(crate) mod compute;
7
8use vortex_error::VortexResult;
9use vortex_error::vortex_ensure;
10
11pub use self::vtable::Variant;
12pub use self::vtable::VariantArray;
13
14pub(crate) fn initialize(session: &vortex_session::VortexSession) {
15 compute::rules::register_parent_rules(session);
16}
17
18pub use self::vtable::merge_typed_scalar_as_variant;
19use crate::ArrayRef;
20use crate::array::Array;
21use crate::array::ArrayParts;
22use crate::array::EmptyArrayData;
23use crate::array_slots;
24use crate::dtype::DType;
25
26#[array_slots(Variant)]
36pub struct VariantSlots {
37 #[slot(0)]
39 pub core_storage: ArrayRef,
40 #[slot(1)]
44 pub shredded: Option<ArrayRef>,
45}
46
47impl Array<Variant> {
48 pub fn try_new(core_storage: ArrayRef, shredded: Option<ArrayRef>) -> VortexResult<Self> {
56 let dtype = core_storage.dtype().clone();
57 vortex_ensure!(
58 matches!(dtype, DType::Variant(_)),
59 "VariantArray core_storage dtype must be Variant, found {dtype}"
60 );
61 let len = core_storage.len();
62 let stats = core_storage.statistics().to_owned();
63 Ok(Array::try_from_parts(ArrayParts::new(
64 Variant,
65 dtype,
66 len,
67 EmptyArrayData,
68 VariantSlots {
69 core_storage,
70 shredded,
71 }
72 .into_slots(),
73 ))?
74 .with_stats_set(stats))
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use std::sync::LazyLock;
81
82 use vortex_buffer::buffer;
83 use vortex_error::VortexResult;
84 use vortex_error::vortex_err;
85 use vortex_mask::Mask;
86 use vortex_session::VortexSession;
87
88 use crate::ArrayRef;
89 use crate::Canonical;
90 use crate::IntoArray;
91 use crate::VortexSessionExecute;
92 use crate::arrays::BoolArray;
93 use crate::arrays::ChunkedArray;
94 use crate::arrays::ConstantArray;
95 use crate::arrays::PrimitiveArray;
96 use crate::arrays::VariantArray;
97 use crate::arrays::variant::VariantArraySlotsExt;
98 use crate::assert_arrays_eq;
99 use crate::builtins::ArrayBuiltins;
100 use crate::compute::conformance::consistency::test_scalar_probe_consistency;
101 use crate::dtype::DType;
102 use crate::dtype::Nullability;
103 use crate::scalar::Scalar;
104
105 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
106
107 fn core_storage(len: usize) -> ArrayRef {
108 ConstantArray::new(
109 Scalar::variant(Scalar::primitive(1i32, Nullability::NonNullable)),
110 len,
111 )
112 .into_array()
113 }
114
115 fn row_storage(values: impl IntoIterator<Item = i32>) -> VortexResult<ArrayRef> {
116 Ok(ChunkedArray::try_new(
117 values.into_iter().map(|value| {
118 ConstantArray::new(
119 Scalar::variant(Scalar::primitive(value, Nullability::NonNullable)),
120 1,
121 )
122 .into_array()
123 }),
124 DType::Variant(Nullability::NonNullable),
125 )?
126 .into_array())
127 }
128
129 fn variant_with_shredded(
130 core_values: impl IntoIterator<Item = i32>,
131 shredded_values: impl IntoIterator<Item = i32>,
132 ) -> VortexResult<VariantArray> {
133 VariantArray::try_new(
134 row_storage(core_values)?,
135 Some(PrimitiveArray::from_iter(shredded_values).into_array()),
136 )
137 }
138
139 fn execute_variant(array: ArrayRef) -> VortexResult<VariantArray> {
140 let mut ctx = SESSION.create_execution_ctx();
141 let Canonical::Variant(variant) = array.execute::<Canonical>(&mut ctx)? else {
142 return Err(vortex_err!("expected canonical variant array"));
143 };
144 Ok(variant)
145 }
146
147 fn assert_variant_rows(
148 array: &VariantArray,
149 expected_core: &[Option<i32>],
150 expected_shredded: &[Option<i32>],
151 ) -> VortexResult<()> {
152 assert_variant_core_rows(array, expected_core)?;
153 assert_eq!(array.len(), expected_shredded.len());
154
155 let shredded = array
156 .shredded()
157 .ok_or_else(|| vortex_err!("expected shredded child"))?;
158 let mut ctx = SESSION.create_execution_ctx();
159 let expected_shredded_array = if let Some(values) = expected_shredded
160 .iter()
161 .copied()
162 .collect::<Option<Vec<_>>>()
163 {
164 PrimitiveArray::from_iter(values)
165 } else {
166 PrimitiveArray::from_option_iter(expected_shredded.iter().copied())
167 };
168 assert_arrays_eq!(shredded, expected_shredded_array, &mut ctx);
169
170 Ok(())
171 }
172
173 fn assert_variant_core_rows(
174 array: &VariantArray,
175 expected_core: &[Option<i32>],
176 ) -> VortexResult<()> {
177 assert_eq!(array.len(), expected_core.len());
178
179 let mut ctx = SESSION.create_execution_ctx();
180 for (idx, expected) in expected_core.iter().enumerate() {
181 let scalar = array.core_storage().execute_scalar(idx, &mut ctx)?;
182 let variant = scalar.as_variant();
183 match expected {
184 Some(expected) => {
185 let value = variant
186 .value()
187 .ok_or_else(|| vortex_err!("expected non-null variant row"))?;
188 assert_eq!(value.as_primitive().typed_value::<i32>(), Some(*expected));
189 }
190 None => assert!(variant.is_null()),
191 }
192 }
193
194 Ok(())
195 }
196
197 #[test]
198 fn try_new_exposes_core_storage_without_shredded() -> VortexResult<()> {
199 let core_storage = core_storage(2);
200
201 let variant = VariantArray::try_new(core_storage.clone(), None)?;
202
203 assert_eq!(variant.dtype(), core_storage.dtype());
204 assert_eq!(variant.len(), 2);
205 assert_eq!(variant.core_storage().dtype(), core_storage.dtype());
206 assert!(variant.shredded().is_none());
207 assert_variant_core_rows(&variant, &[Some(1), Some(1)])?;
208
209 Ok(())
210 }
211
212 #[test]
213 fn try_new_exposes_core_storage_and_shredded() -> VortexResult<()> {
214 let core_storage = core_storage(3);
215 let shredded = buffer![10i32, 20, 30].into_array();
216
217 let variant = VariantArray::try_new(core_storage.clone(), Some(shredded.clone()))?;
218
219 assert_eq!(variant.dtype(), &DType::Variant(Nullability::NonNullable));
220 assert_eq!(variant.len(), 3);
221 assert_eq!(variant.core_storage().dtype(), core_storage.dtype());
222 assert_eq!(variant.core_storage().len(), core_storage.len());
223 assert_eq!(
224 variant.shredded().map(|child| child.dtype()),
225 Some(shredded.dtype())
226 );
227 assert_eq!(
228 variant.shredded().map(|child| child.len()),
229 Some(shredded.len())
230 );
231 assert_eq!(variant.as_ref().slot_name(0), "core_storage");
232 assert_eq!(variant.as_ref().slot_name(1), "shredded");
233 assert_variant_rows(&variant, &[Some(1); 3], &[Some(10), Some(20), Some(30)])?;
234
235 Ok(())
236 }
237
238 #[test]
239 fn try_new_rejects_non_variant_core_storage() {
240 let core_storage = PrimitiveArray::from_iter([1i32, 2, 3]).into_array();
241
242 assert!(VariantArray::try_new(core_storage, None).is_err());
243 }
244
245 #[test]
246 fn try_new_rejects_shredded_length_mismatch() {
247 let core_storage = core_storage(3);
248 let shredded = buffer![10i32, 20].into_array();
249
250 assert!(VariantArray::try_new(core_storage, Some(shredded)).is_err());
251 }
252
253 #[test]
254 fn scalar_at_merges_shredded_with_core_storage() -> VortexResult<()> {
255 let dtype = DType::Variant(Nullability::Nullable);
256 let core_chunks = [Some(1i32), None, Some(3)]
257 .into_iter()
258 .map(|value| {
259 let scalar = match value {
260 Some(value) => {
261 Scalar::variant(Scalar::primitive(value, Nullability::NonNullable))
262 .cast(&dtype)?
263 }
264 None => Scalar::null(dtype.clone()),
265 };
266 Ok(ConstantArray::new(scalar, 1).into_array())
267 })
268 .collect::<VortexResult<Vec<_>>>()?;
269 let core_storage = ChunkedArray::try_new(core_chunks, dtype)?.into_array();
270 let shredded = PrimitiveArray::from_option_iter([Some(10i32), Some(20), None]).into_array();
271 let variant = VariantArray::try_new(core_storage, Some(shredded))?;
272
273 let mut ctx = SESSION.create_execution_ctx();
274 for (idx, expected) in [Some(10i32), None, Some(3)].into_iter().enumerate() {
275 let scalar = variant.execute_scalar(idx, &mut ctx)?;
276 let variant = scalar.as_variant();
277 match expected {
278 Some(expected) => {
279 let value = variant
280 .value()
281 .ok_or_else(|| vortex_err!("expected non-null variant row"))?;
282 assert_eq!(value.as_primitive().typed_value::<i32>(), Some(expected));
283 }
284 None => assert!(variant.is_null()),
285 }
286 }
287
288 test_scalar_probe_consistency(&variant.into_array(), &mut ctx);
289
290 Ok(())
291 }
292
293 #[test]
294 fn scalar_probe_without_shredded_storage() -> VortexResult<()> {
295 let variant = VariantArray::try_new(core_storage(5), None)?.into_array();
296 test_scalar_probe_consistency(&variant, &mut SESSION.create_execution_ctx());
297 Ok(())
298 }
299
300 #[test]
301 fn slice_preserves_core_storage_and_shredded_rows() -> VortexResult<()> {
302 let variant = variant_with_shredded(0..5, 10..15)?;
303
304 let sliced = execute_variant(variant.into_array().slice(1..4)?)?;
305
306 assert_variant_rows(
307 &sliced,
308 &[Some(1), Some(2), Some(3)],
309 &[Some(11), Some(12), Some(13)],
310 )
311 }
312
313 #[test]
314 fn filter_preserves_core_storage_and_shredded_rows() -> VortexResult<()> {
315 let variant = variant_with_shredded(0..5, 10..15)?;
316
317 let filtered = execute_variant(
318 variant
319 .into_array()
320 .filter(Mask::from_iter([true, false, true, false, true]))?,
321 )?;
322
323 assert_variant_rows(
324 &filtered,
325 &[Some(0), Some(2), Some(4)],
326 &[Some(10), Some(12), Some(14)],
327 )
328 }
329
330 #[test]
331 fn take_preserves_core_storage_and_shredded_rows() -> VortexResult<()> {
332 let variant = variant_with_shredded(0..5, 10..15)?;
333
334 let taken = execute_variant(
335 variant
336 .into_array()
337 .take(buffer![4u64, 1, 3].into_array())?,
338 )?;
339
340 assert_variant_rows(
341 &taken,
342 &[Some(4), Some(1), Some(3)],
343 &[Some(14), Some(11), Some(13)],
344 )
345 }
346
347 #[test]
348 fn mask_preserves_core_storage_and_shredded_rows() -> VortexResult<()> {
349 let variant = variant_with_shredded(0..5, 10..15)?;
350 let mask = BoolArray::from_iter([true, false, true, false, true]).into_array();
351
352 let masked = execute_variant(variant.into_array().mask(mask)?)?;
353
354 assert_variant_rows(
355 &masked,
356 &[Some(0), None, Some(2), None, Some(4)],
357 &[Some(10), None, Some(12), None, Some(14)],
358 )
359 }
360
361 #[test]
362 fn mask_preserves_chunked_core_storage_validity() -> VortexResult<()> {
363 let dtype = DType::Variant(Nullability::Nullable);
364 let core_chunks = [Some(1i32), None, Some(3), Some(4)]
365 .into_iter()
366 .map(|value| {
367 let scalar = match value {
368 Some(value) => {
369 Scalar::variant(Scalar::primitive(value, Nullability::NonNullable))
370 .cast(&dtype)?
371 }
372 None => Scalar::null(dtype.clone()),
373 };
374 Ok(ConstantArray::new(scalar, 1).into_array())
375 })
376 .collect::<VortexResult<Vec<_>>>()?;
377 let core_storage = ChunkedArray::try_new(core_chunks, dtype)?.into_array();
378 let variant = VariantArray::try_new(core_storage, None)?;
379 let mask = BoolArray::from_iter([true, true, false, true]).into_array();
380
381 let masked = execute_variant(variant.into_array().mask(mask)?)?;
382
383 assert_variant_core_rows(&masked, &[Some(1), None, None, Some(4)])
384 }
385}