1mod array;
43mod execute;
44
45use vortex_error::VortexExpect;
46use vortex_error::VortexResult;
47use vortex_error::vortex_bail;
48use vortex_error::vortex_ensure;
49use vortex_error::vortex_ensure_eq;
50use vortex_error::vortex_panic;
51use vortex_session::registry::CachedId;
52
53pub use self::array::InterleaveArray;
54pub use self::array::InterleaveArrayExt;
55pub use self::array::InterleaveArraySlotsExt;
56pub use self::array::InterleaveData;
57pub use self::array::InterleaveSlots;
58pub use self::array::InterleaveSlotsView;
59use crate::ArrayRef;
60use crate::ExecutionCtx;
61use crate::IntoArray;
62use crate::array::Array;
63use crate::array::ArrayId;
64use crate::array::ArrayParts;
65use crate::array::ArraySlots;
66use crate::array::ArrayView;
67use crate::array::OperationsVTable;
68use crate::array::VTable;
69use crate::array::ValidityVTable;
70use crate::array::with_empty_buffers;
71use crate::arrays::ConstantArray;
72use crate::buffer::BufferHandle;
73use crate::dtype::DType;
74use crate::dtype::Nullability;
75use crate::executor::ExecutionResult;
76use crate::scalar::Scalar;
77use crate::validity::Validity;
78
79#[derive(Clone, Debug)]
81pub struct Interleave;
82
83impl Interleave {
84 fn check(
90 values: &[ArrayRef],
91 array_indices: &ArrayRef,
92 row_indices: &ArrayRef,
93 ) -> VortexResult<DType> {
94 vortex_ensure!(
95 values.len() >= 2,
96 "interleave requires at least 2 values, got {}",
97 values.len()
98 );
99
100 for (name, selector) in [
103 ("array_indices", array_indices),
104 ("row_indices", row_indices),
105 ] {
106 match selector.dtype() {
107 DType::Primitive(ptype, nullability) if ptype.is_unsigned_int() => {
108 vortex_ensure!(
109 !nullability.is_nullable(),
110 "interleave {name} must be non-nullable, got {}",
111 selector.dtype()
112 );
113 }
114 other => vortex_bail!(
115 "interleave {name} must be a non-nullable unsigned integer, got {other}"
116 ),
117 }
118 }
119
120 vortex_ensure_eq!(
121 array_indices.len(),
122 row_indices.len(),
123 "interleave selectors must have equal length",
124 );
125
126 let base_dtype = values[0].dtype();
127 let mut nullability = Nullability::NonNullable;
128 for value in values {
129 vortex_ensure!(
130 value.dtype().eq_ignore_nullability(base_dtype),
131 "interleave values must share a dtype up to nullability: {} vs {}",
132 base_dtype,
133 value.dtype()
134 );
135 nullability |= value.dtype().nullability();
136 }
137
138 Ok(base_dtype.with_nullability(nullability))
139 }
140}
141
142impl VTable for Interleave {
143 type TypedArrayData = InterleaveData;
144 type OperationsVTable = Self;
145 type ValidityVTable = Self;
146
147 fn id(&self) -> ArrayId {
148 static ID: CachedId = CachedId::new("vortex.interleave");
149 *ID
150 }
151
152 fn validate(
153 &self,
154 data: &Self::TypedArrayData,
155 dtype: &DType,
156 len: usize,
157 slots: &[Option<ArrayRef>],
158 ) -> VortexResult<()> {
159 vortex_ensure_eq!(
160 slots.len(),
161 data.num_values + InterleaveSlots::FIXED_COUNT,
162 "InterleaveArray expects values + array_indices + row_indices slots",
163 );
164 vortex_ensure!(
165 slots.iter().all(|s| s.is_some()),
166 "InterleaveArray slots must all be present"
167 );
168
169 let array_indices = slots[InterleaveSlots::ARRAY_INDICES]
170 .clone()
171 .vortex_expect("validated array_indices slot");
172 let row_indices = slots[InterleaveSlots::ROW_INDICES]
173 .clone()
174 .vortex_expect("validated row_indices slot");
175 let values: Vec<ArrayRef> = slots[InterleaveSlots::VALUES_OFFSET..]
176 .iter()
177 .map(|s| s.clone().vortex_expect("validated value slot"))
178 .collect();
179
180 let expected_dtype = Interleave::check(&values, &array_indices, &row_indices)?;
183 vortex_ensure_eq!(
184 dtype,
185 &expected_dtype,
186 "InterleaveArray dtype does not match the dtype implied by its children",
187 );
188 vortex_ensure_eq!(
189 len,
190 array_indices.len(),
191 "InterleaveArray length does not match array_indices length",
192 );
193 Ok(())
194 }
195
196 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
197 0
198 }
199
200 fn buffer(_array: ArrayView<'_, Self>, _idx: usize) -> BufferHandle {
201 vortex_panic!("InterleaveArray has no buffers")
202 }
203
204 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
205 None
206 }
207
208 fn with_buffers(
209 &self,
210 array: ArrayView<'_, Self>,
211 buffers: &[BufferHandle],
212 ) -> VortexResult<ArrayParts<Self>> {
213 with_empty_buffers(self, array, buffers)
214 }
215
216 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
217 InterleaveSlots::slot_name(idx)
218 }
219
220 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
221 execute::execute(array, ctx)
222 }
223}
224
225impl OperationsVTable<Interleave> for Interleave {
226 type ProbeState = ();
227
228 fn scalar_at(
229 array: ArrayView<'_, Interleave>,
230 index: usize,
231 ctx: &mut ExecutionCtx,
232 ) -> VortexResult<Scalar> {
233 let branch_idx = array
236 .array_indices()
237 .execute_scalar(index, ctx)?
238 .as_primitive()
239 .as_::<usize>()
240 .vortex_expect("interleave array_indices is non-nullable");
241 let row = array
242 .row_indices()
243 .execute_scalar(index, ctx)?
244 .as_primitive()
245 .as_::<usize>()
246 .vortex_expect("interleave row_indices is non-nullable");
247
248 let scalar = array.value(branch_idx).execute_scalar(row, ctx)?;
249 Ok(if array.as_ref().dtype().is_nullable() {
251 scalar.into_nullable()
252 } else {
253 scalar
254 })
255 }
256}
257
258impl ValidityVTable<Interleave> for Interleave {
259 fn validity(array: ArrayView<'_, Interleave>) -> VortexResult<Validity> {
260 if !array.as_ref().dtype().is_nullable() {
261 return Ok(Validity::NonNullable);
262 }
263 let num_values = array.num_values();
264 let mut slots: ArraySlots =
265 ArraySlots::with_capacity(num_values + InterleaveSlots::FIXED_COUNT);
266 slots.push(Some(array.array_indices().clone()));
267 slots.push(Some(array.row_indices().clone()));
268 for i in 0..num_values {
269 slots.push(Some(value_validity_array(array.value(i))?));
270 }
271 let interleaved = unsafe {
274 InterleaveArray::new_unchecked_slots(slots, DType::Bool(Nullability::NonNullable))
275 };
276 Ok(Validity::Array(interleaved.into_array()))
277 }
278}
279
280fn value_validity_array(value: &ArrayRef) -> VortexResult<ArrayRef> {
283 Ok(match value.validity()? {
284 Validity::NonNullable | Validity::AllValid => {
285 ConstantArray::new(true, value.len()).into_array()
286 }
287 Validity::AllInvalid => ConstantArray::new(false, value.len()).into_array(),
288 Validity::Array(array) => array,
289 })
290}
291
292#[cfg(test)]
293mod tests {
294 use std::sync::LazyLock;
295
296 use rstest::rstest;
297 use vortex_error::VortexResult;
298 use vortex_session::VortexSession;
299
300 use super::*;
301 use crate::AnyColumnar;
302 use crate::Canonical;
303 use crate::VortexSessionExecute;
304 use crate::arrays::Bool;
305 use crate::arrays::BoolArray;
306 use crate::arrays::DecimalArray;
307 use crate::arrays::Primitive;
308 use crate::arrays::PrimitiveArray;
309 use crate::arrays::SliceArray;
310 use crate::assert_arrays_eq;
311 use crate::dtype::DecimalDType;
312 use crate::dtype::PType;
313
314 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
315
316 #[derive(Clone, Copy)]
317 enum LazyChild {
318 ArraySelector,
319 RowSelector,
320 ThirdValue,
321 }
322
323 #[derive(Clone, Copy)]
325 enum ValueKind {
326 Bool,
327 Primitive,
328 Decimal,
329 }
330
331 #[rstest]
332 #[case::array_selector(LazyChild::ArraySelector)]
333 #[case::row_selector(LazyChild::RowSelector)]
334 #[case::third_value(LazyChild::ThirdValue)]
335 fn executes_lazy_children(
336 #[case] lazy_child: LazyChild,
337 #[values(ValueKind::Bool, ValueKind::Primitive, ValueKind::Decimal)] value_kind: ValueKind,
338 ) -> VortexResult<()> {
339 let decimal_dtype = DecimalDType::new(9, 2);
340 let (mut values, expected) = match value_kind {
341 ValueKind::Bool => (
342 vec![
343 BoolArray::from_iter([true, false]).into_array(),
344 BoolArray::from_iter([false, true]).into_array(),
345 BoolArray::from_iter([Some(false), None]).into_array(),
346 ],
347 BoolArray::from_iter([None, Some(true), Some(true), Some(false), Some(false)])
348 .into_array(),
349 ),
350 ValueKind::Primitive => (
351 vec![
352 PrimitiveArray::from_iter([10i32, 11]).into_array(),
353 PrimitiveArray::from_iter([20i32, 21]).into_array(),
354 PrimitiveArray::from_option_iter([Some(30i32), None]).into_array(),
355 ],
356 PrimitiveArray::from_option_iter([None, Some(10i32), Some(21), Some(30), Some(11)])
357 .into_array(),
358 ),
359 ValueKind::Decimal => (
360 vec![
361 DecimalArray::from_iter([10i32, 11], decimal_dtype).into_array(),
362 DecimalArray::from_iter([20i32, 21], decimal_dtype).into_array(),
363 DecimalArray::from_option_iter([Some(30i32), None], decimal_dtype).into_array(),
364 ],
365 DecimalArray::from_option_iter(
366 [None, Some(10i32), Some(21), Some(30), Some(11)],
367 decimal_dtype,
368 )
369 .into_array(),
370 ),
371 };
372 let mut array_indices = PrimitiveArray::from_iter([2u8, 0, 1, 2, 0]).into_array();
373 let mut row_indices = PrimitiveArray::from_iter([1u32, 0, 1, 0, 1]).into_array();
374 let child = match lazy_child {
375 LazyChild::ArraySelector => &mut array_indices,
376 LazyChild::RowSelector => &mut row_indices,
377 LazyChild::ThirdValue => &mut values[2],
378 };
379 *child = SliceArray::try_new(child.clone(), 0..child.len())?.into_array();
380
381 assert_eq!(
382 array_indices.is::<Primitive>(),
383 !matches!(lazy_child, LazyChild::ArraySelector)
384 );
385 assert_eq!(
386 row_indices.is::<Primitive>(),
387 !matches!(lazy_child, LazyChild::RowSelector)
388 );
389 for (i, value) in values.iter().enumerate() {
390 let matches = match value_kind {
391 ValueKind::Bool => value.is::<Bool>(),
392 ValueKind::Primitive | ValueKind::Decimal => value.is::<AnyColumnar>(),
393 };
394 assert_eq!(
395 matches,
396 !(matches!(lazy_child, LazyChild::ThirdValue) && i == 2)
397 );
398 }
399
400 let interleaved =
401 InterleaveArray::try_new(values, array_indices, row_indices)?.into_array();
402 let mut ctx = SESSION.create_execution_ctx();
403 assert_arrays_eq!(interleaved, expected, &mut ctx);
404 Ok(())
405 }
406
407 fn interleave_reference(
414 values: &[ArrayRef],
415 array_indices: &ArrayRef,
416 row_indices: &ArrayRef,
417 ctx: &mut ExecutionCtx,
418 ) -> VortexResult<ArrayRef> {
419 let len = array_indices.len();
420 let nullable = values.iter().any(|v| v.dtype().is_nullable());
421 let mut out: Vec<Option<bool>> = Vec::with_capacity(len);
422
423 for i in 0..len {
424 let j = array_indices
425 .execute_scalar(i, ctx)?
426 .as_primitive()
427 .as_::<usize>()
428 .vortex_expect("array_indices is non-nullable");
429 let row = row_indices
430 .execute_scalar(i, ctx)?
431 .as_primitive()
432 .as_::<usize>()
433 .vortex_expect("row_indices is non-nullable");
434 out.push(values[j].execute_scalar(row, ctx)?.as_bool().value());
435 }
436
437 Ok(if nullable {
438 BoolArray::from_iter(out).into_array()
439 } else {
440 BoolArray::from_iter(
441 out.into_iter()
442 .map(|v| v.vortex_expect("non-nullable value produced a null")),
443 )
444 .into_array()
445 })
446 }
447
448 fn build(
451 branches: &[&[Option<bool>]],
452 indices: &[(usize, usize)],
453 ) -> (Vec<ArrayRef>, ArrayRef, ArrayRef) {
454 let nullable = branches.iter().flat_map(|b| b.iter()).any(Option::is_none);
455 let to_value = |vals: &[Option<bool>]| -> ArrayRef {
456 if nullable {
457 BoolArray::from_iter(vals.iter().copied()).into_array()
458 } else {
459 BoolArray::from_iter(
460 vals.iter()
461 .map(|v| v.vortex_expect("non-nullable value produced a null")),
462 )
463 .into_array()
464 }
465 };
466
467 let values = branches.iter().map(|b| to_value(b)).collect();
468 let array_indices = PrimitiveArray::from_iter(
469 indices
470 .iter()
471 .map(|&(a, _)| u32::try_from(a).vortex_expect("array index fits in u32")),
472 )
473 .into_array();
474 let row_indices = PrimitiveArray::from_iter(
475 indices
476 .iter()
477 .map(|&(_, r)| u32::try_from(r).vortex_expect("row index fits in u32")),
478 )
479 .into_array();
480 (values, array_indices, row_indices)
481 }
482
483 fn check(branches: &[&[Option<bool>]], indices: &[(usize, usize)]) -> VortexResult<()> {
487 let (values, array_indices, row_indices) = build(branches, indices);
488
489 let interleaved =
490 InterleaveArray::try_new(values.clone(), array_indices.clone(), row_indices.clone())?
491 .into_array();
492
493 let mut ctx = SESSION.create_execution_ctx();
494 let reference = interleave_reference(&values, &array_indices, &row_indices, &mut ctx)?;
495
496 assert_arrays_eq!(interleaved, reference, &mut ctx);
497 Ok(())
498 }
499
500 #[test]
501 fn interleave_reorders_and_repeats() -> VortexResult<()> {
502 check(
504 &[&[Some(true), Some(false)], &[Some(false), Some(true)]],
505 &[(0, 1), (1, 0), (0, 0), (1, 1), (0, 0)],
506 )
507 }
508
509 #[test]
510 fn interleave_skips_rows() -> VortexResult<()> {
511 check(
513 &[
514 &[Some(true), Some(false), Some(true)],
515 &[Some(false), Some(true)],
516 ],
517 &[(0, 0), (1, 1), (0, 2)],
518 )
519 }
520
521 #[test]
522 fn interleave_binary_spans_word_boundary() -> VortexResult<()> {
523 let branch0: Vec<Option<bool>> = (0..100).map(|i| Some(i % 3 == 0)).collect();
526 let branch1: Vec<Option<bool>> = (0..100).map(|i| Some(i % 5 == 0)).collect();
527 let indices: Vec<(usize, usize)> = (0..200).map(|i| (i % 2, (i * 7) % 100)).collect();
528 check(&[&branch0, &branch1], &indices)
529 }
530
531 #[test]
532 fn interleave_binary_nullable_spans_word_boundary() -> VortexResult<()> {
533 let branch0: Vec<Option<bool>> = (0..70)
535 .map(|i| (i % 4 != 0).then_some(i % 2 == 0))
536 .collect();
537 let branch1: Vec<Option<bool>> = (0..70)
538 .map(|i| (i % 3 != 0).then_some(i % 2 == 1))
539 .collect();
540 let indices: Vec<(usize, usize)> = (0..150).map(|i| (i % 2, (i * 11) % 70)).collect();
541 check(&[&branch0, &branch1], &indices)
542 }
543
544 #[test]
545 fn interleave_three_values() -> VortexResult<()> {
546 check(
548 &[
549 &[Some(true), Some(false)],
550 &[Some(false)],
551 &[Some(true), Some(true), Some(false)],
552 ],
553 &[(2, 1), (0, 0), (1, 0), (2, 2), (0, 1), (2, 0)],
554 )
555 }
556
557 #[test]
558 fn interleave_only_one_branch() -> VortexResult<()> {
559 check(
560 &[&[Some(true), Some(false), Some(true)], &[Some(false)]],
561 &[(0, 2), (0, 0), (0, 1)],
562 )
563 }
564
565 #[test]
566 fn interleave_nullable_with_nulls_in_values() -> VortexResult<()> {
567 check(
568 &[&[None, Some(true), None], &[Some(false), None]],
569 &[(1, 1), (0, 0), (1, 0), (0, 2), (0, 1)],
570 )
571 }
572
573 #[test]
574 fn interleave_empty() -> VortexResult<()> {
575 check(&[&[Some(true)], &[Some(false)]], &[])
576 }
577
578 #[test]
579 fn rejects_boolean_array_indices() {
580 let value = BoolArray::from_iter([true, false]).into_array();
581 let array_indices = BoolArray::from_iter([true, false]).into_array();
582 let row_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
583 let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
584 .err()
585 .vortex_expect("expected interleave to reject a boolean array_indices");
586 assert!(err.to_string().contains("unsigned integer"), "{err}");
587 }
588
589 #[test]
590 fn rejects_signed_integer_array_indices() {
591 let value = BoolArray::from_iter([true]).into_array();
592 let array_indices = PrimitiveArray::from_iter([0i32, 1]).into_array();
593 let row_indices = PrimitiveArray::from_iter([0u32, 0]).into_array();
594 let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
595 .err()
596 .vortex_expect("expected interleave to reject a signed integer array_indices");
597 assert!(err.to_string().contains("unsigned integer"), "{err}");
598 }
599
600 #[test]
601 fn rejects_nullable_row_indices() {
602 let value = BoolArray::from_iter([true, false]).into_array();
603 let array_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
604 let row_indices = PrimitiveArray::from_option_iter([Some(0u32), Some(1)]).into_array();
605 let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
606 .err()
607 .vortex_expect("expected interleave to reject nullable row_indices");
608 assert!(err.to_string().contains("non-nullable"), "{err}");
609 }
610
611 #[test]
612 fn rejects_mismatched_selector_lengths() {
613 let value = BoolArray::from_iter([true, false]).into_array();
614 let array_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
615 let row_indices = PrimitiveArray::from_iter([0u32]).into_array();
616 let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
617 .err()
618 .vortex_expect("expected interleave to reject mismatched selector lengths");
619 assert!(err.to_string().contains("equal length"), "{err}");
620 }
621
622 #[test]
623 fn execute_rejects_out_of_bounds_array_index() -> VortexResult<()> {
624 let value = BoolArray::from_iter([true]).into_array();
625 let array_indices = PrimitiveArray::from_iter([2u32]).into_array();
626 let row_indices = PrimitiveArray::from_iter([0u32]).into_array();
627 let interleaved =
628 InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)?
629 .into_array();
630
631 let mut ctx = SESSION.create_execution_ctx();
632 let err = interleaved
633 .execute::<Canonical>(&mut ctx)
634 .err()
635 .vortex_expect("expected execution to reject out-of-bounds array index");
636 assert!(
637 err.to_string().contains("array index out of bounds"),
638 "{err}"
639 );
640 Ok(())
641 }
642
643 #[test]
644 fn execute_rejects_out_of_bounds_row_index() -> VortexResult<()> {
645 let value = BoolArray::from_iter([true]).into_array();
646 let array_indices = PrimitiveArray::from_iter([0u32]).into_array();
647 let row_indices = PrimitiveArray::from_iter([1u32]).into_array();
648 let interleaved =
649 InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)?
650 .into_array();
651
652 let mut ctx = SESSION.create_execution_ctx();
653 let err = interleaved
654 .execute::<Canonical>(&mut ctx)
655 .err()
656 .vortex_expect("expected execution to reject out-of-bounds row index");
657 assert!(err.to_string().contains("row index out of bounds"), "{err}");
658 Ok(())
659 }
660
661 #[test]
662 fn executes_primitive_values() -> VortexResult<()> {
663 let v0 = PrimitiveArray::from_iter([1.0f64, 2.0]).into_array();
664 let v1 = PrimitiveArray::from_option_iter([Some(10.0f64), None]).into_array();
665 let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
666 let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
667 let interleaved =
668 InterleaveArray::try_new(vec![v0, v1], array_indices, row_indices)?.into_array();
669 let expected =
670 PrimitiveArray::from_option_iter([Some(1.0f64), Some(10.0), Some(2.0), None])
671 .into_array();
672 let mut ctx = SESSION.create_execution_ctx();
673 assert_arrays_eq!(interleaved, expected, &mut ctx);
674 Ok(())
675 }
676
677 #[test]
678 fn executes_primitive_constant_values() -> VortexResult<()> {
679 let constant = ConstantArray::new(1.0f64, 2).into_array();
680 let column = PrimitiveArray::from_iter([10.0f64, 20.0]).into_array();
681 let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
682 let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
683 let interleaved =
684 InterleaveArray::try_new(vec![constant, column], array_indices, row_indices)?
685 .into_array();
686 let expected = PrimitiveArray::from_iter([1.0f64, 10.0, 1.0, 20.0]).into_array();
687 let mut ctx = SESSION.create_execution_ctx();
688
689 assert_arrays_eq!(interleaved, expected, &mut ctx);
690 Ok(())
691 }
692
693 #[test]
694 fn executes_null_primitive_constant_values() -> VortexResult<()> {
695 let constant = ConstantArray::new(
696 Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)),
697 2,
698 )
699 .into_array();
700 let column = PrimitiveArray::from_iter([10.0f64, 20.0]).into_array();
701 let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
702 let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
703 let interleaved =
704 InterleaveArray::try_new(vec![constant, column], array_indices, row_indices)?
705 .into_array();
706 let expected =
707 PrimitiveArray::from_option_iter([None, Some(10.0f64), None, Some(20.0)]).into_array();
708 let mut ctx = SESSION.create_execution_ctx();
709
710 assert_arrays_eq!(interleaved, expected, &mut ctx);
711 Ok(())
712 }
713}