Skip to main content

vortex_array/scalar_fn/fns/zip/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6use std::fmt::Formatter;
7
8pub use kernel::*;
9use vortex_error::VortexExpect as _;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure;
12use vortex_mask::Mask;
13use vortex_mask::MaskValues;
14use vortex_session::VortexSession;
15use vortex_session::registry::CachedId;
16
17use crate::ArrayRef;
18use crate::ExecutionCtx;
19use crate::IntoArray;
20use crate::arrays::BoolArray;
21use crate::arrays::bool::BoolArrayExt;
22use crate::builders::ArrayBuilder;
23use crate::builders::builder_with_capacity;
24use crate::builtins::ArrayBuiltins;
25use crate::dtype::DType;
26use crate::expr::Expression;
27use crate::scalar_fn::Arity;
28use crate::scalar_fn::ChildName;
29use crate::scalar_fn::EmptyOptions;
30use crate::scalar_fn::ExecutionArgs;
31use crate::scalar_fn::ScalarFnId;
32use crate::scalar_fn::ScalarFnVTable;
33use crate::scalar_fn::SimplifyCtx;
34use crate::scalar_fn::fns::literal::Literal;
35use crate::validity::Validity;
36
37/// An expression that conditionally selects between two arrays based on a boolean mask.
38///
39/// For each position `i`, `result[i] = if mask[i] then if_true[i] else if_false[i]`.
40///
41/// Null values in the mask are treated as false (selecting `if_false`). This follows
42/// SQL semantics (DuckDB, Trino) where a null condition falls through to the ELSE branch,
43/// rather than Arrow's `if_else` which propagates null conditions to the output.
44#[derive(Clone)]
45pub struct Zip;
46
47impl ScalarFnVTable for Zip {
48    type Options = EmptyOptions;
49
50    fn id(&self) -> ScalarFnId {
51        static ID: CachedId = CachedId::new("vortex.zip");
52        *ID
53    }
54
55    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
56        Ok(Some(vec![]))
57    }
58
59    fn deserialize(
60        &self,
61        _metadata: &[u8],
62        _session: &VortexSession,
63    ) -> VortexResult<Self::Options> {
64        Ok(EmptyOptions)
65    }
66
67    fn arity(&self, _options: &Self::Options) -> Arity {
68        Arity::Exact(3)
69    }
70
71    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
72        match child_idx {
73            0 => ChildName::from("if_true"),
74            1 => ChildName::from("if_false"),
75            2 => ChildName::from("mask"),
76            _ => unreachable!("Invalid child index {} for Zip expression", child_idx),
77        }
78    }
79
80    fn fmt_sql(
81        &self,
82        _options: &Self::Options,
83        expr: &Expression,
84        f: &mut Formatter<'_>,
85    ) -> std::fmt::Result {
86        write!(f, "zip(")?;
87        expr.child(0).fmt_sql(f)?;
88        write!(f, ", ")?;
89        expr.child(1).fmt_sql(f)?;
90        write!(f, ", ")?;
91        expr.child(2).fmt_sql(f)?;
92        write!(f, ")")
93    }
94
95    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
96        vortex_ensure!(
97            matches!(arg_dtypes[2], DType::Bool(_)),
98            "zip requires mask to be a boolean type, got {}",
99            arg_dtypes[2]
100        );
101        zip_return_dtype(&arg_dtypes[0], &arg_dtypes[1])
102    }
103
104    fn execute(
105        &self,
106        _options: &Self::Options,
107        args: &dyn ExecutionArgs,
108        ctx: &mut ExecutionCtx,
109    ) -> VortexResult<ArrayRef> {
110        let if_true = args.get(0)?;
111        let if_false = args.get(1)?;
112        let mask_array = args.get(2)?;
113
114        let mask = mask_array
115            .execute::<BoolArray>(ctx)?
116            .to_mask_fill_null_false(ctx);
117
118        let return_dtype = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
119
120        if mask.all_true() {
121            return if_true.cast(return_dtype)?.execute(ctx);
122        }
123
124        if mask.all_false() {
125            return if_false.cast(return_dtype)?.execute(ctx);
126        }
127
128        if !if_true.is_canonical() || !if_false.is_canonical() {
129            let if_true = if_true.execute::<ArrayRef>(ctx)?;
130            let if_false = if_false.execute::<ArrayRef>(ctx)?;
131            return mask.into_array().zip(if_true, if_false);
132        }
133
134        zip_impl(&if_true, &if_false, &mask, ctx)
135    }
136
137    fn simplify(
138        &self,
139        _options: &Self::Options,
140        expr: &Expression,
141        _ctx: &dyn SimplifyCtx,
142    ) -> VortexResult<Option<Expression>> {
143        let Some(mask_lit) = expr.child(2).as_opt::<Literal>() else {
144            return Ok(None);
145        };
146
147        if let Some(mask_val) = mask_lit.as_bool().value() {
148            if mask_val {
149                return Ok(Some(expr.child(0).clone()));
150            } else {
151                return Ok(Some(expr.child(1).clone()));
152            }
153        }
154
155        Ok(None)
156    }
157
158    fn is_null_sensitive(&self, _options: &Self::Options) -> bool {
159        true
160    }
161
162    fn is_fallible(&self, _options: &Self::Options) -> bool {
163        false
164    }
165}
166
167pub(crate) fn zip_impl(
168    if_true: &ArrayRef,
169    if_false: &ArrayRef,
170    mask: &Mask,
171    ctx: &mut ExecutionCtx,
172) -> VortexResult<ArrayRef> {
173    assert_eq!(
174        if_true.len(),
175        if_false.len(),
176        "zip requires arrays to have the same size"
177    );
178
179    let return_type = zip_return_dtype(if_true.dtype(), if_false.dtype())?;
180
181    if mask.all_true() {
182        return if_true.cast(return_type);
183    }
184    if mask.all_false() {
185        return if_false.cast(return_type);
186    }
187
188    // `append_to_builder` requires exact dtype equality, so normalize branch
189    // nullability to the output dtype before appending slices into the builder.
190    let if_true = if_true.cast(return_type.clone())?;
191    let if_false = if_false.cast(return_type.clone())?;
192
193    zip_impl_with_builder(
194        &if_true,
195        &if_false,
196        mask.values()
197            .vortex_expect("zip_impl_with_builder: mask is not all-true or all-false"),
198        builder_with_capacity(&return_type, if_true.len()),
199        ctx,
200    )
201}
202
203fn zip_return_dtype(if_true: &DType, if_false: &DType) -> VortexResult<DType> {
204    vortex_ensure!(
205        if_true.eq_ignore_nullability(if_false),
206        "zip requires if_true and if_false to have the same base type, got {} and {}",
207        if_true,
208        if_false
209    );
210    Ok(if_true
211        .least_supertype(if_false)
212        .vortex_expect("zip inputs with the same base type must have a common dtype"))
213}
214
215fn zip_impl_with_builder(
216    if_true: &ArrayRef,
217    if_false: &ArrayRef,
218    mask: &MaskValues,
219    mut builder: Box<dyn ArrayBuilder>,
220    ctx: &mut ExecutionCtx,
221) -> VortexResult<ArrayRef> {
222    for (start, end) in mask.slices() {
223        if builder.len() < *start {
224            if_false
225                .slice(builder.len()..*start)?
226                .append_to_builder(builder.as_mut(), ctx)?;
227        }
228        if_true
229            .slice(*start..*end)?
230            .append_to_builder(builder.as_mut(), ctx)?;
231    }
232    if builder.len() < if_false.len() {
233        if_false
234            .slice(builder.len()..if_false.len())?
235            .append_to_builder(builder.as_mut(), ctx)?;
236    }
237    Ok(builder.finish())
238}
239
240/// Combine two validities for a row-wise zip: take `if_true`'s validity where `mask` is set and
241/// `if_false`'s where it is not.
242///
243/// That selection is itself a zip over the two boolean validity bitmaps, so it is built as a (lazy)
244/// zip array — reusing the zip machinery rather than re-deriving the mask algebra. Trivial cases
245/// where both sides' validity already agrees skip the zip. `mask` must already be null-filled so the
246/// selection matches the accompanying value selection. Shared by the per-encoding zip kernels (e.g.
247/// `Bool`, `Primitive`) that build their result directly.
248pub(crate) fn zip_validity(
249    if_true: Validity,
250    if_false: Validity,
251    mask: &Mask,
252) -> VortexResult<Validity> {
253    match (&if_true, &if_false) {
254        (Validity::NonNullable, Validity::NonNullable) => return Ok(Validity::NonNullable),
255        (Validity::AllValid, Validity::AllValid) => return Ok(Validity::AllValid),
256        (Validity::AllInvalid, Validity::AllInvalid) => return Ok(Validity::AllInvalid),
257        _ => {}
258    }
259
260    let len = mask.len();
261    let validity = mask
262        .clone()
263        .into_array()
264        .zip(if_true.to_array(len), if_false.to_array(len))?;
265    Ok(Validity::Array(validity))
266}
267
268#[cfg(test)]
269mod tests {
270    use vortex_buffer::buffer;
271    use vortex_error::VortexResult;
272    use vortex_mask::Mask;
273
274    use super::zip_impl;
275    use crate::ArrayRef;
276    use crate::IntoArray;
277    use crate::VortexSessionExecute;
278    use crate::array_session;
279    use crate::arrays::ConstantArray;
280    use crate::arrays::PrimitiveArray;
281    use crate::arrays::Struct;
282    use crate::arrays::StructArray;
283    use crate::arrays::VarBinView;
284    use crate::arrays::VarBinViewArray;
285    use crate::assert_arrays_eq;
286    use crate::builders::ArrayBuilder;
287    use crate::builders::BufferGrowthStrategy;
288    use crate::builders::VarBinViewBuilder;
289    use crate::builtins::ArrayBuiltins;
290    use crate::columnar::Columnar;
291    use crate::dtype::DType;
292    use crate::dtype::Nullability;
293    use crate::dtype::PType;
294    use crate::expr::lit;
295    use crate::expr::root;
296    use crate::expr::zip_expr;
297    use crate::scalar::Scalar;
298
299    #[test]
300    fn dtype() {
301        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
302        let expr = zip_expr(lit(true), root(), lit(0i32));
303        let result_dtype = expr.return_dtype(&dtype).unwrap();
304        assert_eq!(
305            result_dtype,
306            DType::Primitive(PType::I32, Nullability::NonNullable)
307        );
308    }
309
310    #[test]
311    fn test_display() {
312        let expr = zip_expr(lit(true), root(), lit(0i32));
313        assert_eq!(expr.to_string(), "zip($, 0i32, true)");
314    }
315
316    #[test]
317    fn test_zip_basic() {
318        let mut ctx = array_session().create_execution_ctx();
319        let mask = Mask::from_iter([true, false, false, true, false]);
320        let if_true = buffer![10, 20, 30, 40, 50].into_array();
321        let if_false = buffer![1, 2, 3, 4, 5].into_array();
322
323        let result = mask.into_array().zip(if_true, if_false).unwrap();
324        let expected = buffer![10, 2, 3, 40, 5].into_array();
325
326        assert_arrays_eq!(result, expected, &mut ctx);
327    }
328
329    #[test]
330    fn test_zip_all_true() {
331        let mut ctx = array_session().create_execution_ctx();
332        let mask = Mask::new_true(4);
333        let if_true = buffer![10, 20, 30, 40].into_array();
334        let if_false =
335            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
336
337        let result = mask.into_array().zip(if_true, if_false.clone()).unwrap();
338        let expected =
339            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), Some(40)]).into_array();
340
341        assert_arrays_eq!(result, expected, &mut ctx);
342        assert_eq!(result.dtype(), if_false.dtype())
343    }
344
345    #[test]
346    fn test_zip_all_false_widens_nullability() {
347        let mut ctx = array_session().create_execution_ctx();
348        let mask = Mask::new_false(4);
349        let if_true =
350            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
351        let if_false = buffer![1i32, 2, 3, 4].into_array();
352
353        let result = mask.into_array().zip(if_true.clone(), if_false).unwrap();
354        let expected =
355            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), Some(4)]).into_array();
356
357        assert_arrays_eq!(result, expected, &mut ctx);
358        assert_eq!(result.dtype(), if_true.dtype());
359    }
360
361    #[test]
362    fn test_zip_impl_all_true_widens_nullability() -> VortexResult<()> {
363        let mask = Mask::new_true(4);
364        let if_true = buffer![10i32, 20, 30, 40].into_array();
365        let if_false =
366            PrimitiveArray::from_option_iter([Some(1), Some(2), Some(3), None]).into_array();
367
368        let mut ctx = array_session().create_execution_ctx();
369        let result = zip_impl(&if_true, &if_false, &mask, &mut ctx)?;
370        assert_arrays_eq!(
371            result,
372            PrimitiveArray::from_option_iter([Some(10i32), Some(20), Some(30), Some(40)])
373                .into_array(),
374            &mut ctx
375        );
376        assert_eq!(result.dtype(), if_false.dtype());
377        Ok(())
378    }
379
380    #[test]
381    fn test_zip_impl_all_false_widens_nullability() -> VortexResult<()> {
382        let mask = Mask::new_false(4);
383        let if_true =
384            PrimitiveArray::from_option_iter([Some(10), Some(20), Some(30), None]).into_array();
385        let if_false = buffer![1i32, 2, 3, 4].into_array();
386
387        let mut ctx = array_session().create_execution_ctx();
388        let result = zip_impl(&if_true, &if_false, &mask, &mut ctx)?;
389        assert_arrays_eq!(
390            result,
391            PrimitiveArray::from_option_iter([Some(1i32), Some(2), Some(3), Some(4)]).into_array(),
392            &mut ctx
393        );
394        assert_eq!(result.dtype(), if_true.dtype());
395        Ok(())
396    }
397
398    #[test]
399    #[should_panic]
400    fn test_invalid_lengths() {
401        let mask = Mask::new_false(4);
402        let if_true = buffer![10, 20, 30].into_array();
403        let if_false = buffer![1, 2, 3, 4].into_array();
404
405        let _result = mask.into_array().zip(if_true, if_false).unwrap();
406    }
407
408    #[test]
409    fn test_fragmentation() -> VortexResult<()> {
410        let len = 100;
411
412        let const1 = ConstantArray::new(
413            Scalar::utf8("hello_this_is_a_longer_string", Nullability::Nullable),
414            len,
415        )
416        .into_array();
417
418        let const2 = ConstantArray::new(
419            Scalar::utf8("world_this_is_another_string", Nullability::Nullable),
420            len,
421        )
422        .into_array();
423
424        let indices: Vec<usize> = (0..len).step_by(2).collect();
425        let mask = Mask::from_indices(len, indices);
426        let mask_array = mask.into_array();
427
428        let mut ctx = array_session().create_execution_ctx();
429        let result = mask_array
430            .zip(const1.clone(), const2.clone())?
431            .execute::<Columnar>(&mut ctx)?
432            .into_array();
433
434        insta::assert_snapshot!(result.display_tree(), @r"
435        root: vortex.varbinview(utf8?, len=100) nbytes=1.66 kB (100.00%) [all_valid]
436          metadata: 
437          buffer: buffer_0 host 29 B (align=1) (1.75%)
438          buffer: buffer_1 host 28 B (align=1) (1.69%)
439          buffer: views host 1.60 kB (align=16) (96.56%)
440        ");
441
442        let wrapped1 = StructArray::try_from_iter([("nested", const1)])?.into_array();
443        let wrapped2 = StructArray::try_from_iter([("nested", const2)])?.into_array();
444
445        let wrapped_result = mask_array
446            .zip(wrapped1, wrapped2)?
447            .execute::<ArrayRef>(&mut ctx)?;
448        assert!(wrapped_result.is::<Struct>());
449
450        Ok(())
451    }
452
453    #[test]
454    fn test_varbinview_zip() {
455        let if_true = {
456            let mut builder = VarBinViewBuilder::new(
457                DType::Utf8(Nullability::NonNullable),
458                10,
459                Default::default(),
460                BufferGrowthStrategy::fixed(64 * 1024),
461                0.0,
462            );
463            for _ in 0..100 {
464                builder.append_value("Hello");
465                builder.append_value("Hello this is a long string that won't be inlined.");
466            }
467            builder.finish()
468        };
469
470        let if_false = {
471            let mut builder = VarBinViewBuilder::new(
472                DType::Utf8(Nullability::NonNullable),
473                10,
474                Default::default(),
475                BufferGrowthStrategy::fixed(64 * 1024),
476                0.0,
477            );
478            for _ in 0..100 {
479                builder.append_value("Hello2");
480                builder.append_value("Hello2 this is a long string that won't be inlined.");
481            }
482            builder.finish()
483        };
484
485        let mask = Mask::from_indices(200, (0..100).filter(|i| i % 3 != 0));
486        let mask_array = mask.clone().into_array();
487
488        let mut ctx = array_session().create_execution_ctx();
489        let zipped = mask_array
490            .zip(if_true, if_false)
491            .unwrap()
492            .execute::<ArrayRef>(&mut ctx)
493            .unwrap();
494        let zipped = zipped.as_opt::<VarBinView>().unwrap();
495        assert_eq!(zipped.data_buffers().len(), 2);
496
497        let true_value = |i: usize| {
498            if i.is_multiple_of(2) {
499                "Hello"
500            } else {
501                "Hello this is a long string that won't be inlined."
502            }
503        };
504        let false_value = |i: usize| {
505            if i.is_multiple_of(2) {
506                "Hello2"
507            } else {
508                "Hello2 this is a long string that won't be inlined."
509            }
510        };
511        let expected = VarBinViewArray::from_iter_str((0..200).map(|i| {
512            if mask.value(i) {
513                true_value(i)
514            } else {
515                false_value(i)
516            }
517        }));
518        assert_arrays_eq!(zipped.array().clone(), expected, &mut ctx);
519    }
520}