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::ProbeState;
69use crate::array::VTable;
70use crate::array::ValidityVTable;
71use crate::array::with_empty_buffers;
72use crate::arrays::ConstantArray;
73use crate::buffer::BufferHandle;
74use crate::dtype::DType;
75use crate::dtype::Nullability;
76use crate::executor::ExecutionResult;
77use crate::scalar::Scalar;
78use crate::validity::Validity;
79
80/// The [`Interleave`] encoding. See the [module docs](self).
81#[derive(Clone, Debug)]
82pub struct Interleave;
83
84impl Interleave {
85    /// The single source of truth for [`InterleaveArray`] invariants.
86    ///
87    /// Validates `values`, `array_indices`, and `row_indices` against the [specification](self) and
88    /// returns the output [`DType`] (the shared value type with the union of value nullabilities).
89    /// Both the public constructor and the [`VTable::validate`] hook funnel through here.
90    fn check(
91        values: &[ArrayRef],
92        array_indices: &ArrayRef,
93        row_indices: &ArrayRef,
94    ) -> VortexResult<DType> {
95        vortex_ensure!(
96            values.len() >= 2,
97            "interleave requires at least 2 values, got {}",
98            values.len()
99        );
100
101        // Both selectors are non-nullable unsigned integers: `array_indices` indexes the values and
102        // `row_indices` names a position within the selected value.
103        for (name, selector) in [
104            ("array_indices", array_indices),
105            ("row_indices", row_indices),
106        ] {
107            match selector.dtype() {
108                DType::Primitive(ptype, nullability) if ptype.is_unsigned_int() => {
109                    vortex_ensure!(
110                        !nullability.is_nullable(),
111                        "interleave {name} must be non-nullable, got {}",
112                        selector.dtype()
113                    );
114                }
115                other => vortex_bail!(
116                    "interleave {name} must be a non-nullable unsigned integer, got {other}"
117                ),
118            }
119        }
120
121        vortex_ensure_eq!(
122            array_indices.len(),
123            row_indices.len(),
124            "interleave selectors must have equal length",
125        );
126
127        let base_dtype = values[0].dtype();
128        let mut nullability = Nullability::NonNullable;
129        for value in values {
130            vortex_ensure!(
131                value.dtype().eq_ignore_nullability(base_dtype),
132                "interleave values must share a dtype up to nullability: {} vs {}",
133                base_dtype,
134                value.dtype()
135            );
136            nullability |= value.dtype().nullability();
137        }
138
139        Ok(base_dtype.with_nullability(nullability))
140    }
141}
142
143impl VTable for Interleave {
144    type TypedArrayData = InterleaveData;
145    type OperationsVTable = Self;
146    type ValidityVTable = Self;
147
148    fn id(&self) -> ArrayId {
149        static ID: CachedId = CachedId::new("vortex.interleave");
150        *ID
151    }
152
153    fn validate(
154        &self,
155        data: &Self::TypedArrayData,
156        dtype: &DType,
157        len: usize,
158        slots: &[Option<ArrayRef>],
159    ) -> VortexResult<()> {
160        vortex_ensure_eq!(
161            slots.len(),
162            data.num_values + InterleaveSlots::FIXED_COUNT,
163            "InterleaveArray expects values + array_indices + row_indices slots",
164        );
165        vortex_ensure!(
166            slots.iter().all(|s| s.is_some()),
167            "InterleaveArray slots must all be present"
168        );
169
170        let array_indices = slots[InterleaveSlots::ARRAY_INDICES]
171            .clone()
172            .vortex_expect("validated array_indices slot");
173        let row_indices = slots[InterleaveSlots::ROW_INDICES]
174            .clone()
175            .vortex_expect("validated row_indices slot");
176        let values: Vec<ArrayRef> = slots[InterleaveSlots::VALUES_OFFSET..]
177            .iter()
178            .map(|s| s.clone().vortex_expect("validated value slot"))
179            .collect();
180
181        // All semantic invariants live in `check`; here we only confirm the array's cached `dtype`
182        // and `len` agree with what the children imply.
183        let expected_dtype = Interleave::check(&values, &array_indices, &row_indices)?;
184        vortex_ensure_eq!(
185            dtype,
186            &expected_dtype,
187            "InterleaveArray dtype does not match the dtype implied by its children",
188        );
189        vortex_ensure_eq!(
190            len,
191            array_indices.len(),
192            "InterleaveArray length does not match array_indices length",
193        );
194        Ok(())
195    }
196
197    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
198        0
199    }
200
201    fn buffer(_array: ArrayView<'_, Self>, _idx: usize) -> BufferHandle {
202        vortex_panic!("InterleaveArray has no buffers")
203    }
204
205    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
206        None
207    }
208
209    fn with_buffers(
210        &self,
211        array: ArrayView<'_, Self>,
212        buffers: &[BufferHandle],
213    ) -> VortexResult<ArrayParts<Self>> {
214        with_empty_buffers(self, array, buffers)
215    }
216
217    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
218        InterleaveSlots::slot_name(idx)
219    }
220
221    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
222        execute::execute(array, ctx)
223    }
224}
225
226impl OperationsVTable<Interleave> for Interleave {
227    type ProbeState = ();
228
229    fn probe_scalar(
230        state: &mut ProbeState<'_, Interleave>,
231        index: usize,
232        ctx: &mut ExecutionCtx,
233    ) -> VortexResult<Scalar> {
234        // Random-access gather: read the routing pair for `index` directly, then pull that row from
235        // the selected value array. No cursor walk is required.
236        let branch_idx = state
237            .slot(InterleaveSlots::ARRAY_INDICES)?
238            .vortex_expect("validated interleave array_indices slot")
239            .execute_scalar(index, ctx)?
240            .as_primitive()
241            .as_::<usize>()
242            .vortex_expect("interleave array_indices is non-nullable");
243        let row = state
244            .slot(InterleaveSlots::ROW_INDICES)?
245            .vortex_expect("validated interleave row_indices slot")
246            .execute_scalar(index, ctx)?
247            .as_primitive()
248            .as_::<usize>()
249            .vortex_expect("interleave row_indices is non-nullable");
250
251        let scalar = state
252            .slot(InterleaveSlots::VALUES_OFFSET + branch_idx)?
253            .vortex_expect("validated interleave value slot")
254            .execute_scalar(row, ctx)?;
255        // The value may be non-nullable while the interleaved output is nullable; align the dtype.
256        Ok(if state.array().as_ref().dtype().is_nullable() {
257            scalar.into_nullable()
258        } else {
259            scalar
260        })
261    }
262
263    fn scalar_at(
264        array: ArrayView<'_, Interleave>,
265        index: usize,
266        ctx: &mut ExecutionCtx,
267    ) -> VortexResult<Scalar> {
268        Self::probe_scalar(&mut ProbeState::once(array), index, ctx)
269    }
270}
271
272impl ValidityVTable<Interleave> for Interleave {
273    fn validity(array: ArrayView<'_, Interleave>) -> VortexResult<Validity> {
274        if !array.as_ref().dtype().is_nullable() {
275            return Ok(Validity::NonNullable);
276        }
277        let num_values = array.num_values();
278        let mut slots: ArraySlots =
279            ArraySlots::with_capacity(num_values + InterleaveSlots::FIXED_COUNT);
280        slots.push(Some(array.array_indices().clone()));
281        slots.push(Some(array.row_indices().clone()));
282        for i in 0..num_values {
283            slots.push(Some(value_validity_array(array.value(i))?));
284        }
285        // SAFETY: `value_validity_array` yields a non-nullable boolean array per value,
286        // the selectors already validated.
287        let interleaved = unsafe {
288            InterleaveArray::new_unchecked_slots(slots, DType::Bool(Nullability::NonNullable))
289        };
290        Ok(Validity::Array(interleaved.into_array()))
291    }
292}
293
294/// Materializes a value's validity as a non-nullable boolean array of the value's length, where
295/// `true` marks a valid (non-null) row.
296fn value_validity_array(value: &ArrayRef) -> VortexResult<ArrayRef> {
297    Ok(match value.validity()? {
298        Validity::NonNullable | Validity::AllValid => {
299            ConstantArray::new(true, value.len()).into_array()
300        }
301        Validity::AllInvalid => ConstantArray::new(false, value.len()).into_array(),
302        Validity::Array(array) => array,
303    })
304}
305
306#[cfg(test)]
307mod tests {
308    use std::sync::LazyLock;
309
310    use rstest::rstest;
311    use vortex_error::VortexResult;
312    use vortex_session::VortexSession;
313
314    use super::*;
315    use crate::AnyColumnar;
316    use crate::Canonical;
317    use crate::VortexSessionExecute;
318    use crate::arrays::Bool;
319    use crate::arrays::BoolArray;
320    use crate::arrays::DecimalArray;
321    use crate::arrays::Primitive;
322    use crate::arrays::PrimitiveArray;
323    use crate::arrays::SliceArray;
324    use crate::assert_arrays_eq;
325    use crate::compute::conformance::consistency::test_scalar_probe_consistency;
326    use crate::dtype::DecimalDType;
327    use crate::dtype::PType;
328
329    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
330
331    #[derive(Clone, Copy)]
332    enum LazyChild {
333        ArraySelector,
334        RowSelector,
335        ThirdValue,
336    }
337
338    /// The value type, which picks the execution kernel.
339    #[derive(Clone, Copy)]
340    enum ValueKind {
341        Bool,
342        Primitive,
343        Decimal,
344    }
345
346    #[rstest]
347    #[case::array_selector(LazyChild::ArraySelector)]
348    #[case::row_selector(LazyChild::RowSelector)]
349    #[case::third_value(LazyChild::ThirdValue)]
350    fn executes_lazy_children(
351        #[case] lazy_child: LazyChild,
352        #[values(ValueKind::Bool, ValueKind::Primitive, ValueKind::Decimal)] value_kind: ValueKind,
353    ) -> VortexResult<()> {
354        let decimal_dtype = DecimalDType::new(9, 2);
355        let (mut values, expected) = match value_kind {
356            ValueKind::Bool => (
357                vec![
358                    BoolArray::from_iter([true, false]).into_array(),
359                    BoolArray::from_iter([false, true]).into_array(),
360                    BoolArray::from_iter([Some(false), None]).into_array(),
361                ],
362                BoolArray::from_iter([None, Some(true), Some(true), Some(false), Some(false)])
363                    .into_array(),
364            ),
365            ValueKind::Primitive => (
366                vec![
367                    PrimitiveArray::from_iter([10i32, 11]).into_array(),
368                    PrimitiveArray::from_iter([20i32, 21]).into_array(),
369                    PrimitiveArray::from_option_iter([Some(30i32), None]).into_array(),
370                ],
371                PrimitiveArray::from_option_iter([None, Some(10i32), Some(21), Some(30), Some(11)])
372                    .into_array(),
373            ),
374            ValueKind::Decimal => (
375                vec![
376                    DecimalArray::from_iter([10i32, 11], decimal_dtype).into_array(),
377                    DecimalArray::from_iter([20i32, 21], decimal_dtype).into_array(),
378                    DecimalArray::from_option_iter([Some(30i32), None], decimal_dtype).into_array(),
379                ],
380                DecimalArray::from_option_iter(
381                    [None, Some(10i32), Some(21), Some(30), Some(11)],
382                    decimal_dtype,
383                )
384                .into_array(),
385            ),
386        };
387        let mut array_indices = PrimitiveArray::from_iter([2u8, 0, 1, 2, 0]).into_array();
388        let mut row_indices = PrimitiveArray::from_iter([1u32, 0, 1, 0, 1]).into_array();
389        let child = match lazy_child {
390            LazyChild::ArraySelector => &mut array_indices,
391            LazyChild::RowSelector => &mut row_indices,
392            LazyChild::ThirdValue => &mut values[2],
393        };
394        *child = SliceArray::try_new(child.clone(), 0..child.len())?.into_array();
395
396        assert_eq!(
397            array_indices.is::<Primitive>(),
398            !matches!(lazy_child, LazyChild::ArraySelector)
399        );
400        assert_eq!(
401            row_indices.is::<Primitive>(),
402            !matches!(lazy_child, LazyChild::RowSelector)
403        );
404        for (i, value) in values.iter().enumerate() {
405            let matches = match value_kind {
406                ValueKind::Bool => value.is::<Bool>(),
407                ValueKind::Primitive | ValueKind::Decimal => value.is::<AnyColumnar>(),
408            };
409            assert_eq!(
410                matches,
411                !(matches!(lazy_child, LazyChild::ThirdValue) && i == 2)
412            );
413        }
414
415        let interleaved =
416            InterleaveArray::try_new(values, array_indices, row_indices)?.into_array();
417        let mut ctx = SESSION.create_execution_ctx();
418        assert_arrays_eq!(interleaved, expected, &mut ctx);
419        Ok(())
420    }
421
422    /// Reference (oracle) implementation of the interleave spec, used only to validate the optimized
423    /// [execute](super::execute) path. It is intentionally simple and slow: it pulls each output
424    /// element one [`Scalar`] at a time via [`ArrayRef::execute_scalar`] and never touches raw bits.
425    ///
426    /// This is deliberately *not* wired into the array execution path — it exists purely as a
427    /// trustworthy comparison point in tests.
428    fn interleave_reference(
429        values: &[ArrayRef],
430        array_indices: &ArrayRef,
431        row_indices: &ArrayRef,
432        ctx: &mut ExecutionCtx,
433    ) -> VortexResult<ArrayRef> {
434        let len = array_indices.len();
435        let nullable = values.iter().any(|v| v.dtype().is_nullable());
436        let mut out: Vec<Option<bool>> = Vec::with_capacity(len);
437
438        for i in 0..len {
439            let j = array_indices
440                .execute_scalar(i, ctx)?
441                .as_primitive()
442                .as_::<usize>()
443                .vortex_expect("array_indices is non-nullable");
444            let row = row_indices
445                .execute_scalar(i, ctx)?
446                .as_primitive()
447                .as_::<usize>()
448                .vortex_expect("row_indices is non-nullable");
449            out.push(values[j].execute_scalar(row, ctx)?.as_bool().value());
450        }
451
452        Ok(if nullable {
453            BoolArray::from_iter(out).into_array()
454        } else {
455            BoolArray::from_iter(
456                out.into_iter()
457                    .map(|v| v.vortex_expect("non-nullable value produced a null")),
458            )
459            .into_array()
460        })
461    }
462
463    /// Builds the compact value arrays and the unsigned `(array_indices, row_indices)` selectors for
464    /// a gather described by per-output `(array_index, row_index)` pairs over `branches`.
465    fn build(
466        branches: &[&[Option<bool>]],
467        indices: &[(usize, usize)],
468    ) -> (Vec<ArrayRef>, ArrayRef, ArrayRef) {
469        let nullable = branches.iter().flat_map(|b| b.iter()).any(Option::is_none);
470        let to_value = |vals: &[Option<bool>]| -> ArrayRef {
471            if nullable {
472                BoolArray::from_iter(vals.iter().copied()).into_array()
473            } else {
474                BoolArray::from_iter(
475                    vals.iter()
476                        .map(|v| v.vortex_expect("non-nullable value produced a null")),
477                )
478                .into_array()
479            }
480        };
481
482        let values = branches.iter().map(|b| to_value(b)).collect();
483        let array_indices = PrimitiveArray::from_iter(
484            indices
485                .iter()
486                .map(|&(a, _)| u32::try_from(a).vortex_expect("array index fits in u32")),
487        )
488        .into_array();
489        let row_indices = PrimitiveArray::from_iter(
490            indices
491                .iter()
492                .map(|&(_, r)| u32::try_from(r).vortex_expect("row index fits in u32")),
493        )
494        .into_array();
495        (values, array_indices, row_indices)
496    }
497
498    /// Asserts that the optimized execute path and the reference implementation agree, exercising
499    /// `InterleaveArray` construction, `execute`, `scalar_at`, and `validity` (via
500    /// `assert_arrays_eq`).
501    fn check(branches: &[&[Option<bool>]], indices: &[(usize, usize)]) -> VortexResult<()> {
502        let (values, array_indices, row_indices) = build(branches, indices);
503
504        let interleaved =
505            InterleaveArray::try_new(values.clone(), array_indices.clone(), row_indices.clone())?
506                .into_array();
507
508        let mut ctx = SESSION.create_execution_ctx();
509        let reference = interleave_reference(&values, &array_indices, &row_indices, &mut ctx)?;
510
511        assert_arrays_eq!(interleaved, reference, &mut ctx);
512        Ok(())
513    }
514
515    #[test]
516    fn interleave_reorders_and_repeats() -> VortexResult<()> {
517        // Random access: rows are pulled out of order and branch 0 row 0 is repeated.
518        check(
519            &[&[Some(true), Some(false)], &[Some(false), Some(true)]],
520            &[(0, 1), (1, 0), (0, 0), (1, 1), (0, 0)],
521        )
522    }
523
524    #[test]
525    fn interleave_skips_rows() -> VortexResult<()> {
526        // Branch 0 row 1 and branch 1 row 0 are never gathered.
527        check(
528            &[
529                &[Some(true), Some(false), Some(true)],
530                &[Some(false), Some(true)],
531            ],
532            &[(0, 0), (1, 1), (0, 2)],
533        )
534    }
535
536    #[test]
537    fn interleave_binary_spans_word_boundary() -> VortexResult<()> {
538        // Exercises a two-value gather across more than one 64-bit packing word, with out-of-order
539        // routing into both branches so neither buffer is consumed contiguously.
540        let branch0: Vec<Option<bool>> = (0..100).map(|i| Some(i % 3 == 0)).collect();
541        let branch1: Vec<Option<bool>> = (0..100).map(|i| Some(i % 5 == 0)).collect();
542        let indices: Vec<(usize, usize)> = (0..200).map(|i| (i % 2, (i * 7) % 100)).collect();
543        check(&[&branch0, &branch1], &indices)
544    }
545
546    #[test]
547    fn interleave_binary_nullable_spans_word_boundary() -> VortexResult<()> {
548        // Same two-value gather, now with nulls so the validity packing is exercised too.
549        let branch0: Vec<Option<bool>> = (0..70)
550            .map(|i| (i % 4 != 0).then_some(i % 2 == 0))
551            .collect();
552        let branch1: Vec<Option<bool>> = (0..70)
553            .map(|i| (i % 3 != 0).then_some(i % 2 == 1))
554            .collect();
555        let indices: Vec<(usize, usize)> = (0..150).map(|i| (i % 2, (i * 11) % 70)).collect();
556        check(&[&branch0, &branch1], &indices)
557    }
558
559    #[test]
560    fn interleave_three_values() -> VortexResult<()> {
561        // An unsigned `array_indices` routes among three values with full random access.
562        check(
563            &[
564                &[Some(true), Some(false)],
565                &[Some(false)],
566                &[Some(true), Some(true), Some(false)],
567            ],
568            &[(2, 1), (0, 0), (1, 0), (2, 2), (0, 1), (2, 0)],
569        )
570    }
571
572    #[test]
573    fn interleave_only_one_branch() -> VortexResult<()> {
574        check(
575            &[&[Some(true), Some(false), Some(true)], &[Some(false)]],
576            &[(0, 2), (0, 0), (0, 1)],
577        )
578    }
579
580    #[test]
581    fn interleave_nullable_with_nulls_in_values() -> VortexResult<()> {
582        check(
583            &[&[None, Some(true), None], &[Some(false), None]],
584            &[(1, 1), (0, 0), (1, 0), (0, 2), (0, 1)],
585        )
586    }
587
588    #[test]
589    fn interleave_scalar_probe_with_nulls() -> VortexResult<()> {
590        let (values, array_indices, row_indices) = build(
591            &[&[None, Some(true), Some(false)], &[Some(false), None]],
592            &[(1, 1), (0, 0), (1, 0), (0, 2), (0, 1), (1, 1)],
593        );
594        let array = InterleaveArray::try_new(values, array_indices, row_indices)?.into_array();
595
596        test_scalar_probe_consistency(&array, &mut SESSION.create_execution_ctx());
597        Ok(())
598    }
599
600    #[test]
601    fn interleave_empty() -> VortexResult<()> {
602        check(&[&[Some(true)], &[Some(false)]], &[])
603    }
604
605    #[test]
606    fn rejects_boolean_array_indices() {
607        let value = BoolArray::from_iter([true, false]).into_array();
608        let array_indices = BoolArray::from_iter([true, false]).into_array();
609        let row_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
610        let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
611            .err()
612            .vortex_expect("expected interleave to reject a boolean array_indices");
613        assert!(err.to_string().contains("unsigned integer"), "{err}");
614    }
615
616    #[test]
617    fn rejects_signed_integer_array_indices() {
618        let value = BoolArray::from_iter([true]).into_array();
619        let array_indices = PrimitiveArray::from_iter([0i32, 1]).into_array();
620        let row_indices = PrimitiveArray::from_iter([0u32, 0]).into_array();
621        let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
622            .err()
623            .vortex_expect("expected interleave to reject a signed integer array_indices");
624        assert!(err.to_string().contains("unsigned integer"), "{err}");
625    }
626
627    #[test]
628    fn rejects_nullable_row_indices() {
629        let value = BoolArray::from_iter([true, false]).into_array();
630        let array_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
631        let row_indices = PrimitiveArray::from_option_iter([Some(0u32), Some(1)]).into_array();
632        let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
633            .err()
634            .vortex_expect("expected interleave to reject nullable row_indices");
635        assert!(err.to_string().contains("non-nullable"), "{err}");
636    }
637
638    #[test]
639    fn rejects_mismatched_selector_lengths() {
640        let value = BoolArray::from_iter([true, false]).into_array();
641        let array_indices = PrimitiveArray::from_iter([0u32, 1]).into_array();
642        let row_indices = PrimitiveArray::from_iter([0u32]).into_array();
643        let err = InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)
644            .err()
645            .vortex_expect("expected interleave to reject mismatched selector lengths");
646        assert!(err.to_string().contains("equal length"), "{err}");
647    }
648
649    #[test]
650    fn execute_rejects_out_of_bounds_array_index() -> VortexResult<()> {
651        let value = BoolArray::from_iter([true]).into_array();
652        let array_indices = PrimitiveArray::from_iter([2u32]).into_array();
653        let row_indices = PrimitiveArray::from_iter([0u32]).into_array();
654        let interleaved =
655            InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)?
656                .into_array();
657
658        let mut ctx = SESSION.create_execution_ctx();
659        let err = interleaved
660            .execute::<Canonical>(&mut ctx)
661            .err()
662            .vortex_expect("expected execution to reject out-of-bounds array index");
663        assert!(
664            err.to_string().contains("array index out of bounds"),
665            "{err}"
666        );
667        Ok(())
668    }
669
670    #[test]
671    fn execute_rejects_out_of_bounds_row_index() -> VortexResult<()> {
672        let value = BoolArray::from_iter([true]).into_array();
673        let array_indices = PrimitiveArray::from_iter([0u32]).into_array();
674        let row_indices = PrimitiveArray::from_iter([1u32]).into_array();
675        let interleaved =
676            InterleaveArray::try_new(vec![value.clone(), value], array_indices, row_indices)?
677                .into_array();
678
679        let mut ctx = SESSION.create_execution_ctx();
680        let err = interleaved
681            .execute::<Canonical>(&mut ctx)
682            .err()
683            .vortex_expect("expected execution to reject out-of-bounds row index");
684        assert!(err.to_string().contains("row index out of bounds"), "{err}");
685        Ok(())
686    }
687
688    #[test]
689    fn executes_primitive_values() -> VortexResult<()> {
690        let v0 = PrimitiveArray::from_iter([1.0f64, 2.0]).into_array();
691        let v1 = PrimitiveArray::from_option_iter([Some(10.0f64), None]).into_array();
692        let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
693        let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
694        let interleaved =
695            InterleaveArray::try_new(vec![v0, v1], array_indices, row_indices)?.into_array();
696        let expected =
697            PrimitiveArray::from_option_iter([Some(1.0f64), Some(10.0), Some(2.0), None])
698                .into_array();
699        let mut ctx = SESSION.create_execution_ctx();
700        assert_arrays_eq!(interleaved, expected, &mut ctx);
701        Ok(())
702    }
703
704    #[test]
705    fn executes_primitive_constant_values() -> VortexResult<()> {
706        let constant = ConstantArray::new(1.0f64, 2).into_array();
707        let column = PrimitiveArray::from_iter([10.0f64, 20.0]).into_array();
708        let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
709        let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
710        let interleaved =
711            InterleaveArray::try_new(vec![constant, column], array_indices, row_indices)?
712                .into_array();
713        let expected = PrimitiveArray::from_iter([1.0f64, 10.0, 1.0, 20.0]).into_array();
714        let mut ctx = SESSION.create_execution_ctx();
715
716        assert_arrays_eq!(interleaved, expected, &mut ctx);
717        Ok(())
718    }
719
720    #[test]
721    fn executes_null_primitive_constant_values() -> VortexResult<()> {
722        let constant = ConstantArray::new(
723            Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)),
724            2,
725        )
726        .into_array();
727        let column = PrimitiveArray::from_iter([10.0f64, 20.0]).into_array();
728        let array_indices = PrimitiveArray::from_iter([0u8, 1, 0, 1]).into_array();
729        let row_indices = PrimitiveArray::from_iter([0u32, 0, 1, 1]).into_array();
730        let interleaved =
731            InterleaveArray::try_new(vec![constant, column], array_indices, row_indices)?
732                .into_array();
733        let expected =
734            PrimitiveArray::from_option_iter([None, Some(10.0f64), None, Some(20.0)]).into_array();
735        let mut ctx = SESSION.create_execution_ctx();
736
737        assert_arrays_eq!(interleaved, expected, &mut ctx);
738        Ok(())
739    }
740}