Skip to main content

vortex_array/arrays/interleave/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`Interleave`] encoding: a lazy, random-access gather of `N` value arrays into one array,
5//! routed by a per-row `(array_index, row_index)` pair.
6//!
7//! # Specification
8//!
9//! An [`Interleave`] array has `N + 2` children: an `array_indices` selector and a `row_indices`
10//! selector followed by `N` *values*. The output has `array_indices.len()` rows, and output
11//! row `i` comes from `values[array_indices[i]][row_indices[i]]`.
12//!
13//! Unlike a `Merge`, which consumes each branch in order under a cursor, an [`Interleave`] is
14//! **random-access**: `row_indices` names an explicit position within the selected value array, so
15//! rows may be reordered, skipped, or repeated. A `Merge` is the special case where each value
16//! array is consumed front-to-back exactly once.
17//!
18//! Like a `Merge`, the value arrays are independent: each holds only its own rows, and the
19//! selectors stitch them back together. This distinguishes [`Interleave`] from an element-wise
20//! select such as `zip`, whose arguments are all full-length.
21//!
22//! ## Invariants
23//!
24//! - Both selectors are **non-nullable** and equal in length, which is the output length. They
25//!   record *where* each output row comes from, which is always a definite decision. Predicate
26//!   nullability must be resolved into definite indices by the caller *before* the interleave is
27//!   built.
28//! - `array_indices[i] < values.len()` and `row_indices[i] < values[array_indices[i]].len()` for
29//!   every `i`. These per-row bounds depend on the selector *values* and so are a runtime
30//!   precondition of the caller, checked in the execution kernels rather than at construction.
31//! - All values share a logical type up to nullability. The output type is that shared type with
32//!   the union of the values' nullabilities. This is orthogonal to the selectors: a row's *value*
33//!   may be null even though its `(array_index, row_index)` is definite.
34//! - The output length equals `array_indices.len()` (`== row_indices.len()`).
35//!
36//! ## Selector types
37//!
38//! `array_indices` encodes the value array per row as a non-nullable **unsigned integer**
39//! (`array_indices[i]` is the index into `values`). `row_indices` is likewise a non-nullable
40//! **unsigned integer** naming the position within the selected value array.
41
42mod 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/// The [`Interleave`] encoding. See the [module docs](self).
80#[derive(Clone, Debug)]
81pub struct Interleave;
82
83impl Interleave {
84    /// The single source of truth for [`InterleaveArray`] invariants.
85    ///
86    /// Validates `values`, `array_indices`, and `row_indices` against the [specification](self) and
87    /// returns the output [`DType`] (the shared value type with the union of value nullabilities).
88    /// Both the public constructor and the [`VTable::validate`] hook funnel through here.
89    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        // Both selectors are non-nullable unsigned integers: `array_indices` indexes the values and
101        // `row_indices` names a position within the selected value.
102        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        // All semantic invariants live in `check`; here we only confirm the array's cached `dtype`
181        // and `len` agree with what the children imply.
182        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        // Random-access gather: read the routing pair for `index` directly, then pull that row from
234        // the selected value array. No cursor walk is required.
235        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        // The value may be non-nullable while the interleaved output is nullable; align the dtype.
250        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        // SAFETY: `value_validity_array` yields a non-nullable boolean array per value,
272        // the selectors already validated.
273        let interleaved = unsafe {
274            InterleaveArray::new_unchecked_slots(slots, DType::Bool(Nullability::NonNullable))
275        };
276        Ok(Validity::Array(interleaved.into_array()))
277    }
278}
279
280/// Materializes a value's validity as a non-nullable boolean array of the value's length, where
281/// `true` marks a valid (non-null) row.
282fn 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    /// The value type, which picks the execution kernel.
324    #[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    /// Reference (oracle) implementation of the interleave spec, used only to validate the optimized
408    /// [execute](super::execute) path. It is intentionally simple and slow: it pulls each output
409    /// element one [`Scalar`] at a time via [`ArrayRef::execute_scalar`] and never touches raw bits.
410    ///
411    /// This is deliberately *not* wired into the array execution path — it exists purely as a
412    /// trustworthy comparison point in tests.
413    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    /// Builds the compact value arrays and the unsigned `(array_indices, row_indices)` selectors for
449    /// a gather described by per-output `(array_index, row_index)` pairs over `branches`.
450    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    /// Asserts that the optimized execute path and the reference implementation agree, exercising
484    /// `InterleaveArray` construction, `execute`, `scalar_at`, and `validity` (via
485    /// `assert_arrays_eq`).
486    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        // Random access: rows are pulled out of order and branch 0 row 0 is repeated.
503        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        // Branch 0 row 1 and branch 1 row 0 are never gathered.
512        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        // Exercises a two-value gather across more than one 64-bit packing word, with out-of-order
524        // routing into both branches so neither buffer is consumed contiguously.
525        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        // Same two-value gather, now with nulls so the validity packing is exercised too.
534        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        // An unsigned `array_indices` routes among three values with full random access.
547        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}