Skip to main content

vortex_functions/zip/
listview.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::mem::MaybeUninit;
5use std::ops::BitAnd;
6use std::ops::BitOr;
7use std::ops::Not;
8
9use itertools::Either;
10use vortex_array::ArrayRef;
11use vortex_array::ArrayView;
12use vortex_array::ExecutionCtx;
13use vortex_array::IntoArray;
14use vortex_array::arrays::Chunked;
15use vortex_array::arrays::ChunkedArray;
16use vortex_array::arrays::ListView;
17use vortex_array::arrays::ListViewArray;
18use vortex_array::arrays::chunked::ChunkedArrayExt;
19use vortex_array::arrays::listview::ListViewArraySlotsExt;
20use vortex_array::builtins::ArrayBuiltins;
21use vortex_array::dtype::DType;
22use vortex_array::dtype::Nullability;
23use vortex_array::dtype::PType;
24use vortex_array::optimizer::ArrayOptimizer;
25use vortex_array::validity::Validity;
26use vortex_buffer::Buffer;
27use vortex_buffer::BufferMut;
28use vortex_compute::lane_kernels::for_each_mask_word;
29use vortex_error::VortexExpect;
30use vortex_error::VortexResult;
31use vortex_mask::Mask;
32
33use crate::zip::ZipKernel;
34
35/// Zip two [`ListViewArray`]s by selecting whole list views per row.
36///
37/// A [`ListViewArray`] addresses each list by an `(offset, size)` pair into a shared `elements`
38/// array, and unlike [`ListArray`](vortex_array::arrays::ListArray) it does not require lists to be stored
39/// contiguously or in order. Zipping two list views is therefore a metadata-only operation over the
40/// `offsets`, `sizes` and `validity` child arrays: we concatenate the two `elements` arrays
41/// (without rewriting them) and, for each row, select the `(offset, size)` pair from `if_true` or
42/// `if_false` per the mask. `if_false` views are shifted past the end of `if_true`'s elements so
43/// they continue to address the correct half of the concatenated elements array.
44impl ZipKernel for ListView {
45    fn zip(
46        if_true: ArrayView<'_, ListView>,
47        if_false: &ArrayRef,
48        mask: &ArrayRef,
49        ctx: &mut ExecutionCtx,
50    ) -> VortexResult<Option<ArrayRef>> {
51        let Some(if_false) = if_false.as_opt::<ListView>() else {
52            return Ok(None);
53        };
54
55        // Null mask entries select `if_false`, matching `Zip`'s SQL ELSE semantics.
56        let mask = mask.clone().fill_null(false)?.execute::<Mask>(ctx)?;
57        match &mask {
58            // Defer the trivial masks to the generic zip, which just casts one side.
59            Mask::AllTrue(_) | Mask::AllFalse(_) => return Ok(None),
60            Mask::Values(_) => {}
61        }
62
63        let len = if_true.len();
64
65        let result_elements_dtype = if_true
66            .elements()
67            .dtype()
68            .union_nullability(if_false.elements().dtype().nullability());
69
70        // `if_false`'s elements share the element dtype up to nullability; normalize so both chunks
71        // of the concatenated elements array have an identical dtype.
72        let true_elements = if_true
73            .elements()
74            .cast(result_elements_dtype.clone())?
75            .optimize_ctx(ctx)?;
76        let false_elements = if_false
77            .elements()
78            .cast(result_elements_dtype.clone())?
79            .optimize_ctx(ctx)?;
80
81        // `if_false` views index into the second half of the concatenated elements.
82        let false_shift = true_elements.len() as u64;
83
84        // Concatenate the two `elements` arrays without copying. If either side is already a
85        // `ChunkedArray` (e.g. the result of a previous list-view zip), splice its chunks in
86        // directly rather than nesting chunked arrays.
87        let chunks = element_chunks(&true_elements).chain(element_chunks(&false_elements));
88        let elements = ChunkedArray::try_new(chunks, result_elements_dtype)?.into_array();
89
90        let true_offsets = to_u64(if_true.offsets(), ctx)?;
91        let true_sizes = to_u64(if_true.sizes(), ctx)?;
92        let false_offsets = to_u64(if_false.offsets(), ctx)?;
93        let false_sizes = to_u64(if_false.sizes(), ctx)?;
94
95        let mut offsets = BufferMut::<u64>::with_capacity(len);
96        let mut sizes = BufferMut::<u64>::with_capacity(len);
97        {
98            let true_offsets = true_offsets.as_slice();
99            let true_sizes = true_sizes.as_slice();
100            let false_offsets = false_offsets.as_slice();
101            let false_sizes = false_sizes.as_slice();
102
103            let offsets_out = offsets.spare_capacity_mut();
104            let sizes_out = sizes.spare_capacity_mut();
105
106            // We matched `Mask::Values` above, so the bit buffer is materialized. We blend both
107            // sides branchlessly per row so the compiler vectorizes the inner select instead of
108            // mispredicting a data-dependent branch.
109            let mask_bits = mask
110                .values()
111                .vortex_expect("mask is Mask::Values")
112                .bit_buffer();
113
114            for_each_mask_word(mask_bits, |word, base, n| {
115                let end = base + n;
116                // `if_false` views address the second half of the concatenated elements, so shift
117                // their offsets by `false_shift`; sizes are taken verbatim from the chosen side.
118                select_column(
119                    word,
120                    &true_offsets[base..end],
121                    &false_offsets[base..end],
122                    false_shift,
123                    &mut offsets_out[base..end],
124                );
125                select_column(
126                    word,
127                    &true_sizes[base..end],
128                    &false_sizes[base..end],
129                    0,
130                    &mut sizes_out[base..end],
131                );
132            });
133        }
134
135        // SAFETY: `select_column` initialized exactly `len` slots in both buffers.
136        unsafe {
137            offsets.set_len(len);
138            sizes.set_len(len);
139        }
140
141        let validity = zip_validity(if_true.validity()?, if_false.validity()?, &mask, ctx)?;
142
143        Ok(Some(
144            ListViewArray::try_new(
145                elements,
146                offsets.freeze().into_array(),
147                sizes.freeze().into_array(),
148                validity,
149                ctx,
150            )?
151            .into_array(),
152        ))
153    }
154}
155
156/// Branchlessly select one `u64` column per row from `if_true` or `if_false`.
157///
158/// `word` holds the mask bits for this block, bit `j` (LSB-first) selecting row `j`: a set bit keeps
159/// `true_vals[j]`, an unset bit keeps `false_vals[j] + false_add`. The bit is expanded to a
160/// full-width lane mask and blended, so the inner loop is branch-free and auto-vectorizable. Inputs
161/// are sliced to the output length up front so the compiler can elide bounds checks across the block.
162#[inline]
163fn select_column(
164    word: u64,
165    true_vals: &[u64],
166    false_vals: &[u64],
167    false_add: u64,
168    out: &mut [MaybeUninit<u64>],
169) {
170    let n = out.len();
171    let true_vals = &true_vals[..n];
172    let false_vals = &false_vals[..n];
173    for j in 0..n {
174        // 0 for an unset bit, `u64::MAX` for a set bit.
175        let lane = 0u64.wrapping_sub((word >> j) & 1);
176        out[j].write((true_vals[j] & lane) | ((false_vals[j] + false_add) & !lane));
177    }
178}
179
180/// Iterates over `array`'s element chunks, flattening a top-level [`ChunkedArray`] so the
181/// concatenated elements never nest chunked arrays.
182fn element_chunks(array: &ArrayRef) -> impl Iterator<Item = ArrayRef> + '_ {
183    match array.as_opt::<Chunked>() {
184        Some(chunked) => {
185            Either::Left((0..chunked.nchunks()).map(move |i| chunked.chunk(i).clone()))
186        }
187        None => Either::Right(std::iter::once(array.clone())),
188    }
189}
190
191/// Read a non-nullable integer array into a `u64` buffer.
192fn to_u64(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Buffer<u64>> {
193    array
194        .clone()
195        .cast(DType::Primitive(PType::U64, Nullability::NonNullable))?
196        .execute::<Buffer<u64>>(ctx)
197}
198
199/// Combine the two list-level validities, taking `if_true`'s validity where `mask` is set and
200/// `if_false`'s where it is not.
201fn zip_validity(
202    if_true: Validity,
203    if_false: Validity,
204    mask: &Mask,
205    ctx: &mut ExecutionCtx,
206) -> VortexResult<Validity> {
207    Ok(match (&if_true, &if_false) {
208        (Validity::NonNullable, Validity::NonNullable) => Validity::NonNullable,
209        (Validity::AllValid, Validity::AllValid) => Validity::AllValid,
210        (Validity::AllInvalid, Validity::AllInvalid) => Validity::AllInvalid,
211        _ => {
212            let true_mask = if_true.execute_mask(mask.len(), ctx)?;
213            let false_mask = if_false.execute_mask(mask.len(), ctx)?;
214            let combined = true_mask
215                .bitand(mask)
216                .bitor(&false_mask.bitand(&mask.not()));
217            Validity::from_mask(combined, if_true.nullability() | if_false.nullability())
218        }
219    })
220}
221
222#[cfg(test)]
223mod tests {
224    #![allow(
225        clippy::cast_possible_truncation,
226        reason = "test fixtures use small indices that fit the target widths"
227    )]
228    use std::sync::Arc;
229    use std::sync::LazyLock;
230
231    use vortex_array::ArrayRef;
232    use vortex_array::IntoArray;
233    use vortex_array::VortexSessionExecute;
234    use vortex_array::arrays::BoolArray;
235    use vortex_array::arrays::Chunked;
236    use vortex_array::arrays::ChunkedArray;
237    use vortex_array::arrays::ListView;
238    use vortex_array::arrays::ListViewArray;
239    use vortex_array::arrays::PrimitiveArray;
240    use vortex_array::arrays::chunked::ChunkedArrayExt;
241    use vortex_array::arrays::listview::ListViewArraySlotsExt;
242    use vortex_array::assert_arrays_eq;
243    use vortex_array::dtype::DType;
244    use vortex_array::dtype::Nullability;
245    use vortex_array::dtype::PType;
246    use vortex_array::optimizer::ArrayOptimizer;
247    use vortex_array::validity::Validity;
248    use vortex_buffer::Buffer;
249    use vortex_buffer::buffer;
250    use vortex_error::VortexResult;
251    use vortex_mask::Mask;
252    use vortex_session::VortexSession;
253
254    use crate::builtins::ArrayFunctions;
255
256    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
257        let session = VortexSession::empty();
258
259        vortex_array::initialize(&session);
260
261        crate::initialize(&session);
262
263        session
264    });
265
266    fn list_view(
267        elements: ArrayRef,
268        offsets: ArrayRef,
269        sizes: ArrayRef,
270        validity: Validity,
271    ) -> ArrayRef {
272        let mut ctx = SESSION.create_execution_ctx();
273        ListViewArray::try_new(elements, offsets, sizes, validity, &mut ctx)
274            .unwrap()
275            .into_array()
276    }
277
278    /// `zip` of two list views selects whole lists per the mask and keeps the list encoding.
279    #[test]
280    fn zip_selects_lists() -> VortexResult<()> {
281        let mut ctx = SESSION.create_execution_ctx();
282        // [[1, 2], [3], [4, 5, 6]]
283        let if_true = list_view(
284            buffer![1i32, 2, 3, 4, 5, 6].into_array(),
285            buffer![0u32, 2, 3].into_array(),
286            buffer![2u32, 1, 3].into_array(),
287            Validity::NonNullable,
288        );
289        // [[10], [20, 21], [30]]
290        let if_false = list_view(
291            buffer![10i32, 20, 21, 30].into_array(),
292            buffer![0u32, 1, 3].into_array(),
293            buffer![1u32, 2, 1].into_array(),
294            Validity::NonNullable,
295        );
296        let mask = Mask::from_iter([true, false, true]);
297
298        let result = mask
299            .into_array()
300            .zip(if_true, if_false)?
301            .execute::<ArrayRef>(&mut ctx)?;
302
303        // The kernel should keep the list-view encoding rather than canonicalizing.
304        assert!(result.is::<ListView>());
305
306        // Expected: [[1, 2], [20, 21], [4, 5, 6]]
307        let expected = list_view(
308            buffer![1i32, 2, 20, 21, 4, 5, 6].into_array(),
309            buffer![0u32, 2, 4].into_array(),
310            buffer![2u32, 2, 3].into_array(),
311            Validity::NonNullable,
312        );
313        assert_arrays_eq!(result, expected, &mut ctx);
314        Ok(())
315    }
316
317    /// `zip` selects list-level validity from the chosen side and widens nullability.
318    #[test]
319    fn zip_selects_validity() -> VortexResult<()> {
320        let mut ctx = SESSION.create_execution_ctx();
321        // [[1], null, [2]] (list-level nulls)
322        let if_true = list_view(
323            buffer![1i32, 2].into_array(),
324            buffer![0u32, 1, 1].into_array(),
325            buffer![1u32, 0, 1].into_array(),
326            Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
327        );
328        // [[10], [20], null]
329        let if_false = list_view(
330            buffer![10i32, 20].into_array(),
331            buffer![0u32, 1, 2].into_array(),
332            buffer![1u32, 1, 0].into_array(),
333            Validity::Array(BoolArray::from_iter([true, true, false]).into_array()),
334        );
335        // true -> if_true, false -> if_false
336        let mask = Mask::from_iter([false, true, true]);
337
338        let result = mask.into_array().zip(if_true, if_false)?;
339
340        // Row 0 -> if_false[0] = [10]; row 1 -> if_true[1] = null; row 2 -> if_true[2] = [2]
341        let expected = list_view(
342            buffer![10i32, 2].into_array(),
343            buffer![0u32, 1, 1].into_array(),
344            buffer![1u32, 0, 1].into_array(),
345            Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
346        );
347        assert_arrays_eq!(result, expected, &mut ctx);
348        Ok(())
349    }
350
351    /// `zip` handles out-of-order/non-contiguous offsets and widens nullability when only one side
352    /// is nullable.
353    #[test]
354    fn zip_out_of_order_offsets_and_widening() -> VortexResult<()> {
355        let mut ctx = SESSION.create_execution_ctx();
356        // [[5, 6], [7], [8, 9]] expressed with out-of-order offsets.
357        let if_true = list_view(
358            buffer![7i32, 8, 9, 5, 6].into_array(),
359            buffer![3u32, 0, 1].into_array(),
360            buffer![2u32, 1, 2].into_array(),
361            Validity::NonNullable,
362        );
363        // [[100], null, [200, 201]]
364        let if_false = list_view(
365            buffer![100i32, 200, 201].into_array(),
366            buffer![0u32, 1, 1].into_array(),
367            buffer![1u32, 0, 2].into_array(),
368            Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
369        );
370        let mask = Mask::from_iter([true, true, false]);
371
372        let result = mask
373            .into_array()
374            .zip(if_true, if_false)?
375            .execute::<ArrayRef>(&mut ctx)?;
376        assert!(result.is::<ListView>());
377
378        // [[5, 6], [7], [200, 201]], all valid but nullable (widened by if_false).
379        let expected = list_view(
380            buffer![5i32, 6, 7, 200, 201].into_array(),
381            buffer![0u32, 2, 3].into_array(),
382            buffer![2u32, 1, 2].into_array(),
383            Validity::AllValid,
384        );
385        assert_arrays_eq!(result, expected, &mut ctx);
386        Ok(())
387    }
388
389    /// Zipping more rows than fit in a single 64-bit mask chunk exercises both the chunked select
390    /// loop and the trailing remainder, including the `false_shift` applied to `if_false` views.
391    #[test]
392    fn zip_spans_multiple_mask_chunks() -> VortexResult<()> {
393        let mut ctx = SESSION.create_execution_ctx();
394        // 130 single-element lists per side: `if_true[i] = [i]`, `if_false[i] = [1000 + i]`.
395        let len = 130usize;
396        let true_elements: Vec<i32> = (0..len as i32).collect();
397        let false_elements: Vec<i32> = (0..len as i32).map(|i| 1000 + i).collect();
398        let offsets: Vec<u64> = (0..len as u64).collect();
399        let sizes: Vec<u64> = vec![1; len];
400
401        let if_true = list_view(
402            true_elements
403                .iter()
404                .copied()
405                .collect::<Buffer<i32>>()
406                .into_array(),
407            offsets
408                .iter()
409                .copied()
410                .collect::<Buffer<u64>>()
411                .into_array(),
412            sizes.iter().copied().collect::<Buffer<u64>>().into_array(),
413            Validity::NonNullable,
414        );
415        let if_false = list_view(
416            false_elements
417                .iter()
418                .copied()
419                .collect::<Buffer<i32>>()
420                .into_array(),
421            offsets
422                .iter()
423                .copied()
424                .collect::<Buffer<u64>>()
425                .into_array(),
426            sizes.iter().copied().collect::<Buffer<u64>>().into_array(),
427            Validity::NonNullable,
428        );
429
430        // A non-trivial pattern that straddles the chunk boundary (index 63/64) and the remainder.
431        let mask_bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(3) || i == 64).collect();
432        let mask = Mask::from_iter(mask_bits.iter().copied());
433
434        let result = mask
435            .into_array()
436            .zip(if_true, if_false)?
437            .execute::<ArrayRef>(&mut ctx)?;
438        assert!(result.is::<ListView>());
439
440        // Each row collapses to a single element: `i` when the mask is set, else `1000 + i`.
441        let expected_elements: Vec<i32> = (0..len)
442            .map(|i| {
443                if mask_bits[i] {
444                    i as i32
445                } else {
446                    1000 + i as i32
447                }
448            })
449            .collect();
450        let expected = list_view(
451            expected_elements
452                .iter()
453                .copied()
454                .collect::<Buffer<i32>>()
455                .into_array(),
456            offsets
457                .iter()
458                .copied()
459                .collect::<Buffer<u64>>()
460                .into_array(),
461            sizes.iter().copied().collect::<Buffer<u64>>().into_array(),
462            Validity::NonNullable,
463        );
464        assert_arrays_eq!(result, expected, &mut ctx);
465        Ok(())
466    }
467
468    /// A mask whose bit buffer starts at a non-byte-aligned offset (here from slicing a bool array)
469    /// has non-zero `unaligned_chunks` lead padding, exercising the prefix word alongside the
470    /// aligned chunk body and the suffix.
471    #[test]
472    fn zip_handles_offset_mask() -> VortexResult<()> {
473        let mut ctx = SESSION.create_execution_ctx();
474        // 200 single-element lists per side: `if_true[i] = [i]`, `if_false[i] = [1000 + i]`. With a
475        // 3-bit lead offset the mask spans more than 16 bytes, so `unaligned_chunks` exposes a
476        // non-empty aligned `chunks` body between the prefix and suffix words.
477        let len = 200usize;
478        let true_elements: Vec<i32> = (0..len as i32).collect();
479        let false_elements: Vec<i32> = (0..len as i32).map(|i| 1000 + i).collect();
480        let offsets: Vec<u64> = (0..len as u64).collect();
481        let sizes: Vec<u64> = vec![1; len];
482
483        let single_element_view = |elements: &[i32]| {
484            list_view(
485                elements
486                    .iter()
487                    .copied()
488                    .collect::<Buffer<i32>>()
489                    .into_array(),
490                offsets
491                    .iter()
492                    .copied()
493                    .collect::<Buffer<u64>>()
494                    .into_array(),
495                sizes.iter().copied().collect::<Buffer<u64>>().into_array(),
496                Validity::NonNullable,
497            )
498        };
499        let if_true = single_element_view(&true_elements);
500        let if_false = single_element_view(&false_elements);
501
502        // Slice off the first `offset` bits so the mask's bit buffer keeps a sub-byte offset while
503        // remaining `len` rows long. A non-trivial pattern straddles the prefix/body and chunk
504        // boundaries within the sliced window.
505        let offset = 3usize;
506        let mask_bits: Vec<bool> = (0..offset + len)
507            .map(|i| i.is_multiple_of(3) || i == offset + 64)
508            .collect();
509        let mask = BoolArray::from_iter(mask_bits.iter().copied())
510            .into_array()
511            .slice(offset..offset + len)?
512            .optimize_ctx(&SESSION)?;
513
514        let result = mask.zip(if_true, if_false)?.execute::<ArrayRef>(&mut ctx)?;
515        assert!(result.is::<ListView>());
516
517        // Each row collapses to a single element: `i` when the sliced mask is set, else `1000 + i`.
518        let expected_elements: Vec<i32> = (0..len)
519            .map(|i| {
520                if mask_bits[offset + i] {
521                    i as i32
522                } else {
523                    1000 + i as i32
524                }
525            })
526            .collect();
527        let expected = single_element_view(&expected_elements);
528        assert_arrays_eq!(result, expected, &mut ctx);
529        Ok(())
530    }
531
532    /// When an input's `elements` is already a [`ChunkedArray`], its chunks are spliced in rather
533    /// than nesting a chunked array inside the concatenated elements.
534    #[test]
535    fn zip_flattens_chunked_elements() -> VortexResult<()> {
536        let mut ctx = SESSION.create_execution_ctx();
537        // elements [1, 2, 3] stored as two chunks; lists [[1, 2], [3]].
538        let chunked_elements = ChunkedArray::try_new(
539            vec![buffer![1i32, 2].into_array(), buffer![3i32].into_array()],
540            DType::Primitive(PType::I32, Nullability::NonNullable),
541        )?
542        .into_array();
543        let if_true = list_view(
544            chunked_elements,
545            buffer![0u32, 2].into_array(),
546            buffer![2u32, 1].into_array(),
547            Validity::NonNullable,
548        );
549        // [[10], [20]]
550        let if_false = list_view(
551            buffer![10i32, 20].into_array(),
552            buffer![0u32, 1].into_array(),
553            buffer![1u32, 1].into_array(),
554            Validity::NonNullable,
555        );
556        let mask = Mask::from_iter([true, false]);
557
558        let result = mask
559            .into_array()
560            .zip(if_true, if_false)?
561            .execute::<ArrayRef>(&mut ctx)?;
562
563        // The concatenated elements are chunked, but no chunk is itself a `ChunkedArray`.
564        let result_lv = result
565            .as_opt::<ListView>()
566            .expect("zip keeps the list-view encoding");
567        let chunked = result_lv
568            .elements()
569            .as_opt::<Chunked>()
570            .expect("zip concatenates elements into a chunked array");
571        assert!(
572            chunked.iter_chunks().all(|chunk| !chunk.is::<Chunked>()),
573            "chunked elements must be flattened, not nested",
574        );
575
576        // [[1, 2], [20]]
577        let expected = list_view(
578            buffer![1i32, 2, 20].into_array(),
579            buffer![0u32, 2].into_array(),
580            buffer![2u32, 1].into_array(),
581            Validity::NonNullable,
582        );
583        assert_arrays_eq!(result, expected, &mut ctx);
584        Ok(())
585    }
586
587    #[test]
588    fn test_zip_widens_false_element_nullability() -> VortexResult<()> {
589        let mut ctx = SESSION.create_execution_ctx();
590        // [[1, 2], [3], [4]]
591        let if_true = ListViewArray::new(
592            buffer![1i32, 2, 3, 4].into_array(),
593            buffer![0u32, 2, 3].into_array(),
594            buffer![2u32, 1, 1].into_array(),
595            Validity::NonNullable,
596            &mut ctx,
597        )
598        .into_array();
599        // [[10, null], [30], [40]]
600        let if_false = ListViewArray::new(
601            PrimitiveArray::from_option_iter([Some(10i32), None, Some(30), Some(40)]).into_array(),
602            buffer![0u32, 2, 3].into_array(),
603            buffer![2u32, 1, 1].into_array(),
604            Validity::NonNullable,
605            &mut ctx,
606        )
607        .into_array();
608        let mask = Mask::from_iter([false, true, false]);
609
610        let result = mask
611            .into_array()
612            .zip(if_true, if_false)?
613            .execute::<ArrayRef>(&mut SESSION.create_execution_ctx())?;
614        assert!(result.is::<ListView>());
615        assert_eq!(
616            result.dtype(),
617            &DType::List(
618                Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)),
619                Nullability::NonNullable,
620            )
621        );
622
623        // [[10, null], [3], [40]]
624        let expected = ListViewArray::new(
625            PrimitiveArray::from_option_iter([Some(10i32), None, Some(3), Some(40)]).into_array(),
626            buffer![0u32, 2, 3].into_array(),
627            buffer![2u32, 1, 1].into_array(),
628            Validity::NonNullable,
629            &mut ctx,
630        )
631        .into_array();
632        assert_arrays_eq!(result, expected, &mut ctx);
633        Ok(())
634    }
635
636    #[test]
637    fn test_zip_widens_true_element_nullability() -> VortexResult<()> {
638        let mut ctx = SESSION.create_execution_ctx();
639        // [[1, null], [3], [4]]
640        let if_true = ListViewArray::new(
641            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), Some(4)]).into_array(),
642            buffer![0u32, 2, 3].into_array(),
643            buffer![2u32, 1, 1].into_array(),
644            Validity::NonNullable,
645            &mut ctx,
646        )
647        .into_array();
648        // [[10], [20], [30]]
649        let if_false = ListViewArray::new(
650            buffer![10i32, 20, 30].into_array(),
651            buffer![0u32, 1, 2].into_array(),
652            buffer![1u32, 1, 1].into_array(),
653            Validity::NonNullable,
654            &mut ctx,
655        )
656        .into_array();
657        let mask = Mask::from_iter([true, false, true]);
658
659        let result = mask
660            .into_array()
661            .zip(if_true, if_false)?
662            .execute::<ArrayRef>(&mut SESSION.create_execution_ctx())?;
663        assert!(result.is::<ListView>());
664        assert_eq!(
665            result.dtype(),
666            &DType::List(
667                Arc::new(DType::Primitive(PType::I32, Nullability::Nullable)),
668                Nullability::NonNullable,
669            )
670        );
671
672        // [[1, null], [20], [4]]
673        let expected = ListViewArray::new(
674            PrimitiveArray::from_option_iter([Some(1i32), None, Some(20), Some(4)]).into_array(),
675            buffer![0u32, 2, 3].into_array(),
676            buffer![2u32, 1, 1].into_array(),
677            Validity::NonNullable,
678            &mut ctx,
679        )
680        .into_array();
681        assert_arrays_eq!(result, expected, &mut ctx);
682        Ok(())
683    }
684}