vortex-functions 0.95.0

Vortex scalar functions beyond those the core array crate relies on
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

mod bool;
mod chunked;
mod decimal;
mod extension;
mod fixed_size_list;
mod fixed_width;
mod kernel;
mod listview;
mod map;
mod null;
mod paired_chunks;
mod primitive;
mod struct_;
mod varbinview;
mod widen;

use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;

pub use kernel::*;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::arrays::Bool;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::Chunked;
use vortex_array::arrays::Decimal;
use vortex_array::arrays::Extension;
use vortex_array::arrays::FixedSizeList;
use vortex_array::arrays::ListView;
use vortex_array::arrays::Map;
use vortex_array::arrays::Null;
use vortex_array::arrays::Primitive;
use vortex_array::arrays::ScalarFnArray;
use vortex_array::arrays::Struct;
use vortex_array::arrays::VarBinView;
use vortex_array::arrays::Widen;
use vortex_array::arrays::bool::BoolArrayExt;
use vortex_array::builders::ArrayBuilder;
use vortex_array::builders::builder_with_capacity_in;
use vortex_array::builtins::ArrayBuiltins;
use vortex_array::dtype::DType;
use vortex_array::dtype::StructFields;
use vortex_array::optimizer::ArrayOptimizer;
use vortex_array::optimizer::kernels::ArrayKernelsExt;
use vortex_array::scalar_fn::Arity;
use vortex_array::scalar_fn::ChildName;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::ExecutionArgs;
use vortex_array::scalar_fn::ReduceNode;
use vortex_array::scalar_fn::ScalarFnId;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::scalar_fn::ScalarFnVTableExt;
use vortex_array::scalar_fn::builtin::cast::Cast;
use vortex_array::scalar_fn::display::ExprDisplay;
use vortex_array::scalar_fn::session::ScalarFnSessionExt;
use vortex_array::validity::Validity;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_err;
use vortex_mask::Mask;
use vortex_mask::MaskValues;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;

use crate::builtins::ArrayFunctions;

/// Registers [`Zip`] and its kernels for vortex-array's canonical encodings.
pub(crate) fn initialize(session: &VortexSession) {
    session.scalar_fns().register(Zip);
    let kernels = session.kernels();
    kernels.register_execute_parent_kernel(Zip.id(), Bool, ZipExecuteAdaptor(Bool));
    kernels.register_execute_parent_kernel(Zip.id(), Chunked, ZipExecuteAdaptor(Chunked));
    kernels.register_execute_parent_kernel(Zip.id(), Decimal, ZipExecuteAdaptor(Decimal));
    kernels.register_execute_parent_kernel(
        Zip.id(),
        FixedSizeList,
        ZipExecuteAdaptor(FixedSizeList),
    );
    kernels.register_execute_parent_kernel(Zip.id(), ListView, ZipExecuteAdaptor(ListView));
    kernels.register_execute_parent_kernel(Zip.id(), Map, ZipExecuteAdaptor(Map));
    kernels.register_execute_parent_kernel(Zip.id(), Primitive, ZipExecuteAdaptor(Primitive));
    kernels.register_execute_parent_kernel(Zip.id(), Struct, ZipExecuteAdaptor(Struct));
    kernels.register_execute_parent_kernel(Zip.id(), VarBinView, ZipExecuteAdaptor(VarBinView));
    kernels.register_execute_parent_kernel(Zip.id(), Widen, ZipExecuteAdaptor(Widen));
    kernels.register_reduce_parent_rule(Zip, Extension, const { &ZipReduceAdaptor(Extension) });
    kernels.register_reduce_parent_rule(Zip, Null, const { &ZipReduceAdaptor(Null) });
}

/// An expression that conditionally selects between two arrays based on a boolean mask.
///
/// For each position `i`, `result[i] = if mask[i] then if_true[i] else if_false[i]`.
///
/// Null values in the mask are treated as false (selecting `if_false`). This follows
/// SQL semantics (DuckDB, Trino) where a null condition falls through to the ELSE branch,
/// rather than Arrow's `if_else` which propagates null conditions to the output.
#[derive(Clone)]
pub struct Zip;

impl Zip {
    /// Creates a lazy conditional selection between `if_true` and `if_false`.
    ///
    /// # Errors
    ///
    /// Returns an error if the children have different lengths, the values have incompatible
    /// dtypes, or `mask` is not boolean data.
    pub fn try_new(
        if_true: ArrayRef,
        if_false: ArrayRef,
        mask: ArrayRef,
    ) -> VortexResult<ScalarFnArray> {
        ScalarFnArray::try_new(Zip.bind(EmptyOptions), [if_true, if_false, mask])
    }
}

impl ScalarFnVTable for Zip {
    type Options = EmptyOptions;

    fn id(&self) -> ScalarFnId {
        static ID: CachedId = CachedId::new("vortex.zip");
        *ID
    }

    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
        Ok(Some(vec![]))
    }

    fn deserialize(
        &self,
        _metadata: &[u8],
        _session: &VortexSession,
    ) -> VortexResult<Self::Options> {
        Ok(EmptyOptions)
    }

    fn arity(&self, _options: &Self::Options) -> Arity {
        Arity::Exact(3)
    }

    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
        match child_idx {
            0 => ChildName::from("if_true"),
            1 => ChildName::from("if_false"),
            2 => ChildName::from("mask"),
            _ => unreachable!("Invalid child index {} for Zip expression", child_idx),
        }
    }

    fn fmt_sql(
        &self,
        _options: &Self::Options,
        expr: &dyn ExprDisplay,
        f: &mut Formatter<'_>,
    ) -> std::fmt::Result {
        write!(f, "zip(")?;
        Display::fmt(expr.display_child(0), f)?;
        write!(f, ", ")?;
        Display::fmt(expr.display_child(1), f)?;
        write!(f, ", ")?;
        Display::fmt(expr.display_child(2), f)?;
        write!(f, ")")
    }

    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
        vortex_ensure!(
            matches!(arg_dtypes[2], DType::Bool(_)),
            "zip requires mask to be a boolean type, got {}",
            arg_dtypes[2]
        );
        zip_return_dtype(&arg_dtypes[0], &arg_dtypes[1])
    }

    fn execute(
        &self,
        _options: &Self::Options,
        args: &dyn ExecutionArgs,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrayRef> {
        let if_true = args.get(0)?;
        let if_false = args.get(1)?;
        let mask_array = args.get(2)?;

        let mask = mask_array
            .execute::<BoolArray>(ctx)?
            .to_mask_fill_null_false(ctx);

        let return_dtype = zip_return_dtype(if_true.dtype(), if_false.dtype())?;

        if mask.all_true() {
            return if_true.cast(return_dtype);
        }

        if mask.all_false() {
            return if_false.cast(return_dtype);
        }

        if !if_true.is_canonical() || !if_false.is_canonical() {
            let if_true = if_true.execute::<ArrayRef>(ctx)?;
            let if_false = if_false.execute::<ArrayRef>(ctx)?;
            return mask.into_array().zip(if_true, if_false);
        }

        let Mask::Values(mask) = mask else {
            unreachable!("trivial masks returned above");
        };
        zip_impl(&if_true, &if_false, &mask, ctx)
    }

    fn simplify<T: ReduceNode>(
        &self,
        _options: &Self::Options,
        node: &T,
    ) -> VortexResult<Option<T>> {
        let mask = node.child(2);
        let Some(mask_constant) = mask.as_constant() else {
            return Ok(None);
        };

        if let Some(mask_value) = mask_constant.as_bool().value() {
            let selected = if mask_value {
                node.child(0)
            } else {
                node.child(1)
            };
            // The selected branch can be less nullable than the zip result, which unions
            // both branches' nullability, so keep the dtype that binding inferred.
            let dtype = node.node_dtype()?;
            return Ok(Some(if selected.node_dtype()? == dtype {
                selected
            } else {
                selected.new_node(Cast.bind(dtype), std::slice::from_ref(&selected))?
            }));
        }

        Ok(None)
    }

    fn is_strict(&self, _options: &Self::Options) -> bool {
        // A null in an unselected branch does not force a null output.
        false
    }

    fn is_infallible(&self, _options: &Self::Options) -> bool {
        true
    }
}

fn zip_impl(
    if_true: &ArrayRef,
    if_false: &ArrayRef,
    mask: &MaskValues,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
    assert_eq!(
        if_true.len(),
        if_false.len(),
        "zip requires arrays to have the same size"
    );

    let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
    if !has_builder(&return_type) {
        vortex_bail!(
            "zip of {return_type} arrays with a mixed mask is not supported: the dtype has no \
             zip kernel and no array builder"
        );
    }

    // `append_to_builder` requires exact dtype equality, so normalize branch
    // nullability to the output dtype before appending slices into the builder.
    let if_true = if_true.cast(return_type.clone())?.optimize_ctx(ctx)?;
    let if_false = if_false.cast(return_type.clone())?.optimize_ctx(ctx)?;

    zip_impl_with_builder(
        &if_true,
        &if_false,
        mask,
        builder_with_capacity_in(&return_type, if_true.len(), ctx.allocator()),
        ctx,
    )
}

/// Returns whether [`builder_with_capacity_in`] supports `dtype`, which has no builder when it is
/// or contains a union.
fn has_builder(dtype: &DType) -> bool {
    match dtype {
        DType::Union(..) => false,
        DType::List(element, _) | DType::FixedSizeList(element, ..) => has_builder(element),
        DType::Map(map, _) => has_builder(&map.key_dtype()) && has_builder(&map.value_dtype()),
        DType::Struct(fields, _) => fields.fields().all(|field| has_builder(&field)),
        DType::Extension(ext) => has_builder(ext.storage_dtype()),
        DType::Null
        | DType::Bool(_)
        | DType::Primitive(..)
        | DType::Decimal(..)
        | DType::Utf8(_)
        | DType::Binary(_)
        | DType::Variant(_) => true,
    }
}

fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
    zip_nullability_union(if_true, if_false).ok_or_else(|| {
        vortex_err!(
            "zip requires if_true and if_false to have the same base type, got {} and {}",
            if_true,
            if_false
        )
    })
}

/// Unions the nullability of two dtypes at every nesting level.
///
/// Returns `None` when the dtypes differ in more than nullability.
pub fn zip_nullability_union(lhs: &DType, rhs: &DType) -> Option<DType> {
    let nullability = lhs.nullability() | rhs.nullability();

    match (lhs, rhs) {
        (DType::List(lhs_element, _), DType::List(rhs_element, _)) => Some(DType::List(
            Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
            nullability,
        )),
        (
            DType::FixedSizeList(lhs_element, lhs_size, _),
            DType::FixedSizeList(rhs_element, rhs_size, _),
        ) if lhs_size == rhs_size => Some(DType::FixedSizeList(
            Arc::new(zip_nullability_union(lhs_element, rhs_element)?),
            *lhs_size,
            nullability,
        )),
        (DType::Map(lhs_map, _), DType::Map(rhs_map, _))
            if lhs_map.keys_sorted() == rhs_map.keys_sorted() =>
        {
            DType::map(
                zip_nullability_union(&lhs_map.key_dtype(), &rhs_map.key_dtype())?,
                zip_nullability_union(&lhs_map.value_dtype(), &rhs_map.value_dtype())?,
                lhs_map.keys_sorted(),
                nullability,
            )
            .ok()
        }
        (DType::Struct(lhs_fields, _), DType::Struct(rhs_fields, _))
            if lhs_fields.names() == rhs_fields.names() =>
        {
            let fields = lhs_fields
                .fields()
                .zip(rhs_fields.fields())
                .map(|(lhs, rhs)| zip_nullability_union(&lhs, &rhs))
                .collect::<Option<Vec<_>>>()?;
            Some(DType::Struct(
                StructFields::new(lhs_fields.names().clone(), fields),
                nullability,
            ))
        }
        (DType::Union(lhs_variants, _), DType::Union(rhs_variants, _))
            if lhs_variants == rhs_variants =>
        {
            Some(DType::Union(lhs_variants.clone(), nullability))
        }
        _ if lhs.eq_ignore_nullability(rhs) => Some(lhs.with_nullability(nullability)),
        _ => None,
    }
}

fn zip_impl_with_builder(
    if_true: &ArrayRef,
    if_false: &ArrayRef,
    mask: &MaskValues,
    mut builder: Box<dyn ArrayBuilder>,
    ctx: &mut ExecutionCtx,
) -> VortexResult<ArrayRef> {
    for (start, end) in mask.slices() {
        if builder.len() < *start {
            if_false
                .slice(builder.len()..*start)?
                .append_to_builder(builder.as_mut(), ctx)?;
        }
        if_true
            .slice(*start..*end)?
            .append_to_builder(builder.as_mut(), ctx)?;
    }
    if builder.len() < if_false.len() {
        if_false
            .slice(builder.len()..if_false.len())?
            .append_to_builder(builder.as_mut(), ctx)?;
    }
    Ok(builder.finish())
}

/// Combine two validities for a row-wise zip: take `if_true`'s validity where `mask` is set and
/// `if_false`'s where it is not.
///
/// That selection is itself a zip over the two boolean validity bitmaps, so it is built as a (lazy)
/// zip array — reusing the zip machinery rather than re-deriving the mask algebra. Trivial cases
/// where both sides' validity already agrees skip the zip. `mask` must already be null-filled so the
/// selection matches the accompanying value selection. Shared by the per-encoding zip kernels (e.g.
/// `Bool`, `Primitive`) that build their result directly.
pub(crate) fn zip_validity(
    if_true: Validity,
    if_false: Validity,
    mask: &Mask,
) -> VortexResult<Validity> {
    match (&if_true, &if_false) {
        (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
        (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
        (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
        _ => {}
    }

    let len = mask.len();
    let validity = mask
        .clone()
        .into_array()
        .zip(if_true.to_array(len), if_false.to_array(len))?;
    Ok(Validity::Array(validity))
}

#[cfg(test)]
mod tests {
    use std::sync::LazyLock;

    use rstest::rstest;
    use vortex_array::ArrayRef;
    use vortex_array::Canonical;
    use vortex_array::Columnar;
    use vortex_array::IntoArray;
    use vortex_array::VortexSessionExecute;
    use vortex_array::arrays::Constant;
    use vortex_array::arrays::ConstantArray;
    use vortex_array::arrays::PrimitiveArray;
    use vortex_array::arrays::Struct;
    use vortex_array::arrays::StructArray;
    use vortex_array::arrays::UnionArray;
    use vortex_array::arrays::VarBinView;
    use vortex_array::arrays::VarBinViewArray;
    use vortex_array::arrays::VariantArray;
    use vortex_array::assert_arrays_eq;
    use vortex_array::builders::ArrayBuilder;
    use vortex_array::builders::BufferGrowthStrategy;
    use vortex_array::builders::VarBinViewBuilder;
    use vortex_array::dtype::DType;
    use vortex_array::dtype::Nullability;
    use vortex_array::dtype::PType;
    use vortex_array::dtype::UnionVariants;
    use vortex_array::scalar::Scalar;
    use vortex_buffer::buffer;
    use vortex_error::VortexResult;
    use vortex_expr::Expression;
    use vortex_expr::lit;
    use vortex_expr::root;
    use vortex_mask::Mask;
    use vortex_session::VortexSession;

    use crate::builtins::ArrayFunctions;
    use crate::expr::zip_expr;

    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
        let session = VortexSession::empty();

        vortex_array::initialize(&session);

        crate::initialize(&session);

        session
    });

    #[test]
    fn dtype() {
        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
        let expr = zip_expr(lit(true), root(), lit(0i32));
        let result_dtype = expr.return_dtype(&dtype).unwrap();
        assert_eq!(
            result_dtype,
            DType::Primitive(PType::I32, Nullability::NonNullable)
        );
    }

    #[test]
    fn test_display() {
        let expr = zip_expr(lit(true), root(), lit(0i32));
        assert_eq!(expr.to_string(), "zip($, 0i32, true)");
    }

    #[test]
    fn test_zip_basic() {
        let mut ctx = SESSION.create_execution_ctx();
        let mask = Mask::from_iter([true, false, false, true, false]);
        let if_true = buffer![10, 20, 30, 40, 50].into_array();
        let if_false = buffer![1, 2, 3, 4, 5].into_array();

        let result = mask.into_array().zip(if_true, if_false).unwrap();
        let expected = buffer![10, 2, 3, 40, 5].into_array();

        assert_arrays_eq!(result, expected, &mut ctx);
    }

    #[test]
    fn test_zip_all_true() {
        let mut ctx = SESSION.create_execution_ctx();
        let mask = Mask::new_true(4);
        let if_true = buffer![10, 20, 30, 40].into_array();
        let if_false =
            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();

        let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
        let expected =
            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();

        assert_arrays_eq!(result, expected, &mut ctx);
        assert_eq!(result.dtype(), if_false.dtype())
    }

    #[test]
    fn test_zip_all_false_widens_nullability() {
        let mut ctx = SESSION.create_execution_ctx();
        let mask = Mask::new_false(4);
        let if_true =
            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
        let if_false = buffer![1i32, 2, 3, 4].into_array();

        let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
        let expected =
            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();

        assert_arrays_eq!(result, expected, &mut ctx);
        assert_eq!(result.dtype(), if_true.dtype());
    }

    #[rstest]
    #[case::all_true(Some(true), 10)]
    #[case::all_false(Some(false), 20)]
    #[case::null_mask(None, 20)]
    fn test_zip_constant_mask_preserves_constant(
        #[case] mask: Option<bool>,
        #[case] expected: i32,
        #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability,
    ) -> VortexResult<()> {
        let mut ctx = SESSION.create_execution_ctx();
        let if_true = ConstantArray::new(10i32, 4).into_array();
        let if_false = ConstantArray::new(Scalar::primitive(20i32, nullability), 4).into_array();
        let result = ConstantArray::new(mask, 4)
            .into_array()
            .zip(if_true, if_false)?
            .execute::<Columnar>(&mut ctx)?
            .into_array();

        assert!(result.is::<Constant>());
        let expected = ConstantArray::new(Scalar::primitive(expected, nullability), 4);
        assert_arrays_eq!(result, expected, &mut ctx);
        Ok(())
    }

    #[test]
    fn test_invalid_lengths() {
        let mask = Mask::new_false(4);
        let if_true = buffer![10, 20, 30].into_array();
        let if_false = buffer![1, 2, 3, 4].into_array();

        let error = mask.into_array().zip(if_true, if_false).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("children equal to the array length")
        );
    }

    #[test]
    fn test_fragmentation() -> VortexResult<()> {
        let len = 100;

        let const1 = ConstantArray::new(
            Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
            len,
        )
        .into_array();

        let const2 = ConstantArray::new(
            Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
            len,
        )
        .into_array();

        let indices: Vec<usize> = (0..len).step_by(2).collect();
        let mask = Mask::from_indices(len, indices);
        let mask_array = mask.into_array();

        let mut ctx = SESSION.create_execution_ctx();
        let result = mask_array
            .zip(const1.clone(), const2.clone())?
            .execute::<Columnar>(&mut ctx)?
            .into_array();

        insta::assert_snapshot!(result.display_tree(), @r"
        root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
          metadata: 
          buffer: buffer_0 host 29 B (align=1) (1.75%)
          buffer: buffer_1 host 28 B (align=1) (1.69%)
          buffer: views host 1.60 kB (align=16) (96.56%)
        ");

        let expected = VarBinViewArray::from_iter_nullable_str((0..len).map(|index| {
            Some(if index % 2 == 0 {
                "hello_this_is_a_longer_string"
            } else {
                "world_this_is_another_string"
            })
        }));
        assert_arrays_eq!(result, expected, &mut ctx);

        let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
        let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();

        let wrapped_result = mask_array
            .zip(wrapped1, wrapped2)?
            .execute::<ArrayRef>(&mut ctx)?;
        assert!(wrapped_result.is::<Struct>());
        assert_arrays_eq!(
            wrapped_result,
            StructArray::try_from_iter([("nested", expected.into_array())])?,
            &mut ctx
        );

        Ok(())
    }

    #[test]
    fn test_varbinview_zip() {
        let if_true = {
            let mut builder = VarBinViewBuilder::new_in(
                DType::Utf8(Nullability::NonNullable),
                10,
                Default::default(),
                BufferGrowthStrategy::fixed(64 * 1024),
                0.0,
                vortex_buffer::BufferAllocatorRef::statically_allocated(),
            );
            for _ in 0..100 {
                builder.append_value("Hello");
                builder.append_value("Hello this is a long string that won't be inlined.");
            }
            builder.finish()
        };

        let if_false = {
            let mut builder = VarBinViewBuilder::new_in(
                DType::Utf8(Nullability::NonNullable),
                10,
                Default::default(),
                BufferGrowthStrategy::fixed(64 * 1024),
                0.0,
                vortex_buffer::BufferAllocatorRef::statically_allocated(),
            );
            for _ in 0..100 {
                builder.append_value("Hello2");
                builder.append_value("Hello2 this is a long string that won't be inlined.");
            }
            builder.finish()
        };

        let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
        let mask_array = mask.clone().into_array();

        let mut ctx = SESSION.create_execution_ctx();
        let zipped = mask_array
            .zip(if_true, if_false)
            .unwrap()
            .execute::<ArrayRef>(&mut ctx)
            .unwrap();
        let zipped = zipped.as_opt::<VarBinView>().unwrap();
        assert_eq!(zipped.data_buffers().len(), 2);

        let true_value = |i: usize| {
            if i.is_multiple_of(2) {
                "Hello"
            } else {
                "Hello this is a long string that won't be inlined."
            }
        };
        let false_value = |i: usize| {
            if i.is_multiple_of(2) {
                "Hello2"
            } else {
                "Hello2 this is a long string that won't be inlined."
            }
        };
        let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
            if mask.value(i) {
                true_value(i)
            } else {
                false_value(i)
            }
        }));
        assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
    }
    #[rstest::rstest]
    #[case::zip_true(
        zip_expr(lit(true), lit(1i32), root()),
        DType::Primitive(PType::I32, Nullability::Nullable)
    )]
    #[case::zip_false(
        zip_expr(lit(false), root(), lit(1i32)),
        DType::Primitive(PType::I32, Nullability::Nullable)
    )]
    fn literal_simplification_preserves_result_dtype(
        #[case] expr: Expression,
        #[case] scope: DType,
    ) -> VortexResult<()> {
        let original = expr.bind(&scope)?;
        let optimized = expr.bind(&scope)?.optimize_recursive()?;
        assert_eq!(optimized.dtype(), original.dtype());
        Ok(())
    }

    /// Unshredded Variant arrays have a builder, so a mixed mask zips them through the fallback.
    #[test]
    fn test_zip_variant_mixed_mask() -> VortexResult<()> {
        let variants = |value: i32| -> VortexResult<ArrayRef> {
            let scalar = Scalar::variant(Scalar::primitive(value, Nullability::NonNullable));
            let core_storage = ConstantArray::new(scalar, 4).into_array();
            Ok(VariantArray::try_new(core_storage, None)?.into_array())
        };

        let mut ctx = SESSION.create_execution_ctx();
        let zipped = Mask::from_iter([true, false, true, false])
            .into_array()
            .zip(variants(1)?, variants(2)?)?
            .execute::<Canonical>(&mut ctx)?
            .into_array();

        for (i, expected) in [1i32, 2, 1, 2].into_iter().enumerate() {
            assert_eq!(
                zipped.execute_scalar(i, &mut ctx)?,
                Scalar::variant(Scalar::primitive(expected, Nullability::NonNullable)),
            );
        }
        Ok(())
    }

    /// Union arrays have no zip kernel and no builder, so a mixed mask fails with an error
    /// instead of a panic.
    #[test]
    fn test_zip_union_mixed_mask_errors() -> VortexResult<()> {
        let variants = UnionVariants::try_new(
            ["num"].into(),
            vec![DType::Primitive(PType::I32, Nullability::NonNullable)],
            vec![0],
        )?;
        let union_of = |value: i32| -> VortexResult<ArrayRef> {
            Ok(UnionArray::try_new(
                PrimitiveArray::from_iter([0u8, 0]).into_array(),
                variants.clone(),
                vec![PrimitiveArray::from_iter([value, value]).into_array()],
            )?
            .into_array())
        };

        let mut ctx = SESSION.create_execution_ctx();
        let error = Mask::from_iter([true, false])
            .into_array()
            .zip(union_of(1)?, union_of(2)?)?
            .execute::<Canonical>(&mut ctx)
            .unwrap_err();
        assert!(error.to_string().contains("is not supported"), "{error}");
        Ok(())
    }
}