Skip to main content

vortex_functions/list_contains/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod chunked;
5mod dict;
6mod haystack;
7mod kernel;
8mod prepared;
9mod runend;
10
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::hash::Hash;
14use std::iter;
15use std::ops::BitOr;
16
17pub use kernel::*;
18use num_traits::Zero;
19pub use prepared::PreparedSet;
20pub use prepared::PreparedSetData;
21use prost::Message;
22use vortex_array::ArrayRef;
23use vortex_array::Columnar;
24use vortex_array::ExecutionCtx;
25use vortex_array::IntoArray;
26use vortex_array::arrays::BoolArray;
27use vortex_array::arrays::Chunked;
28use vortex_array::arrays::Constant;
29use vortex_array::arrays::ConstantArray;
30use vortex_array::arrays::Dict;
31use vortex_array::arrays::ListViewArray;
32use vortex_array::arrays::PrimitiveArray;
33use vortex_array::arrays::RunEnd;
34use vortex_array::arrays::ScalarFnArray;
35use vortex_array::arrays::bool::BoolArrayExt;
36use vortex_array::arrays::listview::ListViewArraySlotsExt;
37use vortex_array::arrays::primitive::PrimitiveArrayExt;
38use vortex_array::builtins::ArrayBuiltins;
39use vortex_array::dtype::DType;
40use vortex_array::dtype::IntegerPType;
41use vortex_array::dtype::Nullability;
42use vortex_array::match_each_integer_ptype;
43use vortex_array::match_each_unsigned_integer_ptype;
44use vortex_array::optimizer::kernels::ArrayKernelsExt;
45use vortex_array::proto::expr as pb;
46use vortex_array::scalar::Scalar;
47use vortex_array::scalar_fn::Arity;
48use vortex_array::scalar_fn::ChildName;
49use vortex_array::scalar_fn::ExecutionArgs;
50use vortex_array::scalar_fn::ReduceNode;
51use vortex_array::scalar_fn::ReduceNodeValidity;
52use vortex_array::scalar_fn::ScalarFnId;
53use vortex_array::scalar_fn::ScalarFnVTable;
54use vortex_array::scalar_fn::ScalarFnVTableExt;
55use vortex_array::scalar_fn::builtin::compare::Compare;
56use vortex_array::scalar_fn::builtin::literal::Literal;
57use vortex_array::scalar_fn::builtin::operators::CompareOperator;
58use vortex_array::scalar_fn::is_not_null_node;
59use vortex_array::scalar_fn::session::ScalarFnSessionExt;
60use vortex_array::validity::Validity;
61use vortex_buffer::BitBuffer;
62use vortex_buffer::Buffer;
63use vortex_buffer::BufferMut;
64use vortex_error::VortexResult;
65use vortex_error::vortex_bail;
66use vortex_error::vortex_err;
67use vortex_mask::Mask;
68use vortex_session::VortexSession;
69use vortex_session::registry::CachedId;
70
71/// Registers [`ListContains`], [`PreparedSet`] and the element rules of [`ListContains`] for
72/// chunked, dictionary and run-end needles.
73pub(crate) fn initialize(session: &VortexSession) {
74    let scalar_fns = session.scalar_fns();
75    scalar_fns.register(ListContains);
76    scalar_fns.register(PreparedSet);
77
78    let kernels = session.kernels();
79    kernels.register_reduce_parent_rule(
80        ListContains,
81        Chunked,
82        const { &ListContainsElementReduceAdaptor(Chunked) },
83    );
84    kernels.register_reduce_parent_rule(
85        ListContains,
86        Dict,
87        const { &ListContainsElementReduceAdaptor(Dict) },
88    );
89    kernels.register_reduce_parent_rule(
90        ListContains,
91        RunEnd,
92        const { &ListContainsElementReduceAdaptor(RunEnd) },
93    );
94}
95
96#[derive(Clone)]
97pub struct ListContains;
98
99/// Options for [`ListContains`].
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
101pub struct ListContainsOptions {
102    /// Whether a null list element is SQL's unknown value.
103    ///
104    /// Off, the default, a null element is never equal to anything: a needle that matches no
105    /// element yields `false`, and a needle that matches some element yields `true`. On, the
106    /// comparison against a null element is unknown, so a needle that matches no element yields
107    /// `null` when the list holds a null — the three-valued semantics of SQL `IN`, under which
108    /// `x NOT IN (1, NULL)` is never true.
109    ///
110    /// A null needle yields `null` against a list with elements either way. Against an empty list
111    /// there is nothing to compare it to: off, that is `false`; on, a null needle is `null` against
112    /// any list, which makes [`ListContains`] strict.
113    pub sql_null_semantics: bool,
114}
115
116impl Display for ListContainsOptions {
117    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
118        if self.sql_null_semantics {
119            write!(f, "sql_null_semantics")?;
120        }
121        Ok(())
122    }
123}
124
125impl ListContainsOptions {
126    /// The declared nullability of a `list_contains` result: a null list or needle can yield
127    /// null, and under [`sql_null_semantics`](Self::sql_null_semantics) so can a null element.
128    pub fn result_nullability(&self, list_dtype: &DType, needle_dtype: &DType) -> Nullability {
129        let mut nullability = list_dtype.nullability().bitor(needle_dtype.nullability());
130        if self.sql_null_semantics
131            && let Some(element_dtype) = list_dtype.as_any_size_list_element_opt()
132        {
133            nullability |= element_dtype.nullability();
134        }
135        nullability
136    }
137
138    /// Builds a `list_contains` result from precomputed membership `bits` and needle validity,
139    /// applying the null semantics of a constant list with `is_empty` and `has_null_element`.
140    pub fn result_from_bits(
141        &self,
142        bits: BitBuffer,
143        needle_validity: Validity,
144        list_dtype: &DType,
145        needle_dtype: &DType,
146        is_empty: bool,
147        has_null_element: bool,
148    ) -> VortexResult<ArrayRef> {
149        let nullability = self.result_nullability(list_dtype, needle_dtype);
150        let validity = if is_empty && !self.sql_null_semantics {
151            Validity::NonNullable
152        } else if self.sql_null_semantics && has_null_element {
153            // Only a match is known. A comparison with the null element makes a non-match unknown.
154            needle_validity.and(Validity::from(bits.clone()))?
155        } else {
156            needle_validity
157        };
158
159        Ok(BoolArray::new(bits, validity.union_nullability(nullability)).into_array())
160    }
161
162    /// Builds a `list_contains` result when no valid needle row can match any list element.
163    pub fn all_false_result(
164        &self,
165        len: usize,
166        needle_validity: Validity,
167        list_dtype: &DType,
168        needle_dtype: &DType,
169        is_empty: bool,
170        has_null_element: bool,
171    ) -> VortexResult<ArrayRef> {
172        let nullability = self.result_nullability(list_dtype, needle_dtype);
173        if self.sql_null_semantics && has_null_element {
174            return Ok(
175                ConstantArray::new(Scalar::null(DType::Bool(nullability)), len).into_array(),
176            );
177        }
178        if is_empty && !self.sql_null_semantics {
179            return Ok(ConstantArray::new(Scalar::bool(false, nullability), len).into_array());
180        }
181
182        match needle_validity.union_nullability(nullability) {
183            Validity::NonNullable | Validity::AllValid => {
184                Ok(ConstantArray::new(Scalar::bool(false, nullability), len).into_array())
185            }
186            Validity::AllInvalid => {
187                Ok(ConstantArray::new(Scalar::null(DType::Bool(nullability)), len).into_array())
188            }
189            Validity::Array(validity) => ConstantArray::new(Scalar::bool(false, nullability), len)
190                .into_array()
191                .mask(validity),
192        }
193    }
194}
195
196impl ListContains {
197    /// Creates a lazy list membership check for `needle` in `list`, with a null element that
198    /// never matches.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error if the children have different lengths, `list` is not a list array,
203    /// or its element dtype differs from the needle's dtype ignoring nullability.
204    pub fn try_new(list: ArrayRef, needle: ArrayRef) -> VortexResult<ScalarFnArray> {
205        Self::try_new_opts(list, needle, ListContainsOptions::default())
206    }
207
208    /// Creates a lazy list membership check for `needle` in `list` with explicit
209    /// [`ListContainsOptions`].
210    ///
211    /// # Errors
212    ///
213    /// Returns an error if the children have different lengths, `list` is not a list array,
214    /// or its element dtype differs from the needle's dtype ignoring nullability.
215    pub fn try_new_opts(
216        list: ArrayRef,
217        needle: ArrayRef,
218        options: ListContainsOptions,
219    ) -> VortexResult<ScalarFnArray> {
220        ScalarFnArray::try_new(ListContains.bind(options), [list, needle])
221    }
222}
223
224impl ScalarFnVTable for ListContains {
225    type Options = ListContainsOptions;
226
227    fn id(&self) -> ScalarFnId {
228        static ID: CachedId = CachedId::new("vortex.list.contains");
229        *ID
230    }
231
232    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
233        // The default encodes to no bytes, which is also what every file written before the
234        // option existed carries.
235        Ok(Some(
236            pb::ListContainsOpts {
237                sql_null_semantics: instance.sql_null_semantics,
238            }
239            .encode_to_vec(),
240        ))
241    }
242
243    fn deserialize(
244        &self,
245        metadata: &[u8],
246        _session: &VortexSession,
247    ) -> VortexResult<Self::Options> {
248        let opts = pb::ListContainsOpts::decode(metadata)?;
249        Ok(ListContainsOptions {
250            sql_null_semantics: opts.sql_null_semantics,
251        })
252    }
253
254    fn arity(&self, _options: &Self::Options) -> Arity {
255        Arity::Exact(2)
256    }
257
258    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
259        match child_idx {
260            0 => ChildName::from("list"),
261            1 => ChildName::from("needle"),
262            _ => unreachable!(
263                "Invalid child index {} for ListContains expression",
264                child_idx
265            ),
266        }
267    }
268    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
269        let list_dtype = &arg_dtypes[0];
270        let needle_dtype = &arg_dtypes[1];
271
272        let DType::List(element_dtype, _) = list_dtype else {
273            vortex_bail!(
274                "First argument to ListContains must be a List, got {:?}",
275                list_dtype
276            );
277        };
278        if !element_dtype.eq_ignore_nullability(needle_dtype) {
279            vortex_bail!(
280                "Element type {} of list does not match search value {}",
281                element_dtype,
282                needle_dtype,
283            );
284        }
285
286        Ok(DType::Bool(
287            options.result_nullability(list_dtype, needle_dtype),
288        ))
289    }
290
291    fn execute(
292        &self,
293        options: &Self::Options,
294        args: &dyn ExecutionArgs,
295        ctx: &mut ExecutionCtx,
296    ) -> VortexResult<ArrayRef> {
297        let list_array = args.get(0)?;
298        let value_array = args.get(1)?;
299
300        // Borrow the list: a constant list scalar owns every element, so cloning it is not free.
301        if let Some(value_scalar) = value_array.as_constant()
302            && let Some(list) = constant_list(&list_array)
303        {
304            let result = compute_contains_scalar(list, value_scalar, options)?;
305            return Ok(ConstantArray::new(result, args.row_count()).into_array());
306        }
307
308        compute_list_contains(&list_array, &value_array, options, ctx)
309    }
310
311    /// A constant list and a constant needle fold to their constant answer, in expression and
312    /// array trees alike. Otherwise a constant list becomes a [`PreparedSet`], so that every
313    /// batch, and every part of the needle that the set is pushed into, looks up its needles in
314    /// one shared set rather than preparing the list again.
315    fn reduce<T: ReduceNode>(&self, options: &Self::Options, node: &T) -> VortexResult<Option<T>> {
316        let list = node.child(0);
317        let needle = node.child(1);
318
319        if let Some(needle) = needle.as_constant()
320            && let Some(list) = constant_list_node(&list)
321        {
322            let result = compute_contains_scalar(list, needle, options)?;
323            return Ok(Some(node.new_constant(result)));
324        }
325
326        let Some(set) = prepare_constant_list(&list, &needle)? else {
327            return Ok(None);
328        };
329
330        let set = node.new_node(PreparedSet.bind(set), &[])?;
331        Ok(Some(
332            node.new_node(ListContains.bind(*options), &[set, needle])?,
333        ))
334    }
335
336    /// The validity of `needle IN list` for a literal list, decided without a lookup.
337    ///
338    /// Off SQL null semantics only a null needle gives null, unless the list is empty, which
339    /// answers `false` for every needle. Under them a null element can give null too, by leaving
340    /// a non-match unknown, so only a list without one is decided from the needle alone. A null
341    /// list gives null for every needle.
342    ///
343    /// Without this the validity of a node over a constant list would execute the node, which
344    /// prepares the list as a set only to read the validity off the result.
345    fn validity<T: ReduceNode>(
346        &self,
347        options: &Self::Options,
348        node: &T,
349    ) -> VortexResult<ReduceNodeValidity<T>> {
350        let list = node.child(0);
351        let Some(list) = constant_list_node(&list) else {
352            return Ok(ReduceNodeValidity::Irreducible);
353        };
354        if !matches!(list.dtype(), DType::List(..)) {
355            return Ok(ReduceNodeValidity::Irreducible);
356        }
357        let Some(elements) = list.as_list().element_values() else {
358            return Ok(ReduceNodeValidity::Reduced(node.new_constant(false.into())));
359        };
360
361        if options.sql_null_semantics && elements.iter().any(Option::is_none) {
362            return Ok(ReduceNodeValidity::Irreducible);
363        }
364        if elements.is_empty() && !options.sql_null_semantics {
365            return Ok(ReduceNodeValidity::Reduced(node.new_constant(true.into())));
366        }
367        Ok(ReduceNodeValidity::Reduced(is_not_null_node(
368            &node.child(1),
369        )?))
370    }
371
372    // Off SQL null semantics an empty list answers `false` even for a null needle; on them a null
373    // needle is null against any list, as a null list always is.
374    fn is_strict(&self, options: &Self::Options) -> bool {
375        options.sql_null_semantics
376    }
377
378    fn is_infallible(&self, _options: &Self::Options) -> bool {
379        true
380    }
381}
382
383fn compute_contains_scalar(
384    list: &Scalar,
385    needle: &Scalar,
386    options: &ListContainsOptions,
387) -> VortexResult<Scalar> {
388    if !matches!(list.dtype(), DType::List(..)) {
389        vortex_bail!(
390            "First argument to ListContains must be a List, got {}",
391            list.dtype()
392        );
393    }
394    let nullability = options.result_nullability(list.dtype(), needle.dtype());
395
396    if list.is_null() {
397        return Ok(Scalar::null(DType::Bool(nullability)));
398    }
399
400    let list_scalar = list.as_list();
401    let elements = list_scalar
402        .elements()
403        .ok_or_else(|| vortex_err!("Expected non-null list"))?;
404
405    if needle.is_null() {
406        return Ok(if elements.is_empty() && !options.sql_null_semantics {
407            Scalar::bool(false, nullability)
408        } else {
409            Scalar::null(DType::Bool(nullability))
410        });
411    }
412
413    let contains = elements.iter().any(|elem| elem == needle);
414    if !contains && options.sql_null_semantics && elements.iter().any(Scalar::is_null) {
415        return Ok(Scalar::null(DType::Bool(nullability)));
416    }
417    Ok(Scalar::bool(contains, nullability))
418}
419
420fn compute_list_contains(
421    array: &ArrayRef,
422    value: &ArrayRef,
423    options: &ListContainsOptions,
424    ctx: &mut ExecutionCtx,
425) -> VortexResult<ArrayRef> {
426    let DType::List(elem_dtype, _) = array.dtype() else {
427        vortex_bail!("Array must be of List type");
428    };
429    if !elem_dtype.as_ref().eq_ignore_nullability(value.dtype()) {
430        vortex_bail!(
431            "Element type {} of list does not match search value {}",
432            elem_dtype,
433            value.dtype(),
434        );
435    }
436
437    let nullability = options.result_nullability(array.dtype(), value.dtype());
438    if array.is_empty() {
439        return Ok(BoolArray::new(BitBuffer::empty(), nullability.into()).into_array());
440    }
441
442    // A null needle is null against every list only when the function is strict: otherwise an
443    // empty list still answers `false`, which the paths below work out per list.
444    if array.all_invalid(ctx)? || (options.sql_null_semantics && value.all_invalid(ctx)?) {
445        return Ok(ConstantArray::new(
446            Scalar::null(DType::Bool(Nullability::Nullable)),
447            array.len(),
448        )
449        .into_array());
450    }
451
452    // The reduce step has already replaced a constant list with a prepared set.
453    if let Some(set) = PreparedSet::set_of(array) {
454        return set.contains(value, options, ctx);
455    }
456
457    if let Some(value_scalar) = value.as_constant() {
458        return list_contains_scalar(array, value_scalar, nullability, options, ctx);
459    }
460    lists_contain_needles(array, value, nullability, options, ctx)
461}
462
463/// The list that every row of `array` holds: a constant, or a set prepared from one.
464fn constant_list(array: &ArrayRef) -> Option<&Scalar> {
465    if let Some(constant) = array.as_opt::<Constant>() {
466        return Some(constant.data().scalar());
467    }
468    PreparedSet::set_of(array).map(PreparedSetData::list)
469}
470
471/// The set of `list` when it is a non-null constant list, a literal in an expression tree or a
472/// constant array in an array tree, whose elements have the dtype of `needle`.
473///
474/// A null list has no set, and a needle of another dtype is an error for execution to report.
475fn prepare_constant_list<T: ReduceNode>(
476    list: &T,
477    needle: &T,
478) -> VortexResult<Option<PreparedSetData>> {
479    let DType::List(element_dtype, _) = list.node_dtype()? else {
480        return Ok(None);
481    };
482    if !element_dtype.eq_ignore_nullability(&needle.node_dtype()?) {
483        return Ok(None);
484    }
485
486    // A literal shares its list with the set, so the list is not cloned. Any other scalar
487    // function, a prepared set included, is not a constant list.
488    if let Some(scalar_fn) = list.scalar_fn() {
489        return match scalar_fn.as_opt::<Literal>() {
490            Some(literal) if !literal.is_null() => {
491                PreparedSetData::try_from_literal(scalar_fn.clone()).map(Some)
492            }
493            _ => Ok(None),
494        };
495    }
496
497    match list.as_constant() {
498        Some(list) if !list.is_null() => PreparedSetData::try_new(list.clone()).map(Some),
499        _ => Ok(None),
500    }
501}
502
503/// The list a reduce node holds when it is a constant or a prepared set, in an expression or an
504/// array tree.
505fn constant_list_node<T: ReduceNode>(node: &T) -> Option<&Scalar> {
506    if let Some(list) = node.as_constant() {
507        return Some(list);
508    }
509    node.scalar_fn()?
510        .as_opt::<PreparedSet>()
511        .map(|set| set.list())
512}
513
514/// Returns a [`BoolArray`] where each bit represents if a list contains the scalar.
515///
516/// This is the canonical implementation, over an executed [`ListViewArray`].
517fn list_contains_scalar(
518    array: &ArrayRef,
519    value: &Scalar,
520    nullability: Nullability,
521    options: &ListContainsOptions,
522    ctx: &mut ExecutionCtx,
523) -> VortexResult<ArrayRef> {
524    // If the list array is constant, we perform a single comparison.
525    if array.len() > 1 && array.is::<Constant>() {
526        let contains = list_contains_scalar(&array.slice(0..1)?, value, nullability, options, ctx)?;
527        return Ok(ConstantArray::new(contains.execute_scalar(0, ctx)?, array.len()).into_array());
528    }
529
530    let list_array = array.clone().execute::<ListViewArray>(ctx)?;
531
532    if value.is_null() {
533        return null_needle_in_lists(&list_array, nullability, ctx);
534    }
535
536    let elems = list_array.elements();
537    if elems.is_empty() {
538        // Must return false when a list is empty (but valid), or null when the list itself is null.
539        return list_false_or_null(&list_array, nullability, ctx);
540    }
541
542    let rhs = ConstantArray::new(value.clone(), elems.len());
543    let matching_elements =
544        Compare::try_new(elems.clone(), rhs.into_array(), CompareOperator::Eq)?.into_array();
545
546    let mut matches = match matching_elements.execute::<Columnar>(ctx)? {
547        Columnar::Constant(constant) => {
548            return match constant.scalar().as_bool().value() {
549                // The needle is not null, so every comparison is null only if every element is.
550                None if options.sql_null_semantics => {
551                    null_needle_in_lists(&list_array, nullability, ctx)
552                }
553                // No element matches: false, unless the list itself is null.
554                None | Some(false) => list_false_or_null(&list_array, nullability, ctx),
555                // Every element matches: true, unless the list itself is empty or null.
556                Some(true) => list_is_not_empty(&list_array, nullability, ctx),
557            };
558        }
559        Columnar::Canonical(canonical) => canonical.into_bool(),
560    };
561    let valid = matches.validity()?.execute_mask(matches.len(), ctx)?;
562
563    // Under SQL null semantics a list holding a null element answers `null` for a needle that
564    // matches none of its other elements. The needle is non-null here, so a null comparison is a
565    // null element; fold "any match" and "any null" per list and keep only the decided rows.
566    if options.sql_null_semantics && !valid.all_true() {
567        let valid = valid.to_bit_buffer();
568        let any_true = fold_lists(
569            BoolArray::new(&matches.to_bit_buffer() & &valid, Validity::NonNullable),
570            &list_array,
571            ctx,
572        )?;
573        let any_null = fold_lists(
574            BoolArray::new(!valid, Validity::NonNullable),
575            &list_array,
576            ctx,
577        )?;
578        let decided = &any_true | &!any_null;
579        let validity = list_array
580            .validity()?
581            .and(Validity::from(decided))?
582            .union_nullability(nullability);
583        return Ok(BoolArray::new(any_true, validity).into_array());
584    }
585
586    // Null comparisons carry unspecified value bits, which must not contribute a match.
587    if !valid.all_true() {
588        matches = BoolArray::new(
589            &matches.to_bit_buffer() & &valid.to_bit_buffer(),
590            Validity::NonNullable,
591        );
592    }
593
594    let list_matches = fold_lists(matches, &list_array, ctx)?;
595
596    Ok(BoolArray::new(
597        list_matches,
598        list_array.validity()?.union_nullability(nullability),
599    )
600    .into_array())
601}
602
603/// Neither side is constant: row `i` asks whether list `i` holds needle `i`.
604///
605/// Each list's elements are gathered next to one copy of its row's needle, so a single equality
606/// answers every comparison, and a fold over each list's contiguous range answers each row.
607fn lists_contain_needles(
608    array: &ArrayRef,
609    values: &ArrayRef,
610    nullability: Nullability,
611    options: &ListContainsOptions,
612    ctx: &mut ExecutionCtx,
613) -> VortexResult<ArrayRef> {
614    let list_array = array.clone().execute::<ListViewArray>(ctx)?;
615    let len = list_array.len();
616    let list_valid = list_array.validity()?.execute_mask(len, ctx)?;
617
618    let offsets = list_array
619        .offsets()
620        .clone()
621        .execute::<PrimitiveArray>(ctx)?;
622    let offsets = offsets.reinterpret_cast(offsets.ptype().to_unsigned());
623    let sizes = list_array.sizes().clone().execute::<PrimitiveArray>(ctx)?;
624    let sizes = sizes.reinterpret_cast(sizes.ptype().to_unsigned());
625    let gathered = match_each_unsigned_integer_ptype!(offsets.ptype(), |O| {
626        match_each_unsigned_integer_ptype!(sizes.ptype(), |S| {
627            GatheredLists::new(
628                offsets.as_slice::<O>(),
629                sizes.as_slice::<S>(),
630                &list_valid,
631                ctx,
632            )
633        })
634    });
635
636    let elements = list_array
637        .elements()
638        .take(PrimitiveArray::new(gathered.element_idx, Validity::NonNullable).into_array())?;
639    let needles =
640        values.take(PrimitiveArray::new(gathered.row_idx, Validity::NonNullable).into_array())?;
641    // A valid list with elements gathered at least one comparison. A null list gathered none,
642    // and its row is null whatever its bit here.
643    let non_empty =
644        BitBuffer::collect_bool_in(len, |row| gathered.lens[row] != 0, ctx.allocator().clone());
645
646    // `any_null` is only read under SQL null semantics.
647    let comparisons = Compare::try_new(elements, needles, CompareOperator::Eq)?.into_array();
648    let (any_true, any_null) = match comparisons.execute::<Columnar>(ctx)? {
649        // One answer for every comparison decides each row from whether it compared anything.
650        Columnar::Constant(constant) => match constant.scalar().as_bool().value() {
651            Some(true) => (non_empty.clone(), Mask::new_false(len)),
652            Some(false) => (BitBuffer::new_unset(len), Mask::new_false(len)),
653            None => (BitBuffer::new_unset(len), Mask::from(non_empty.clone())),
654        },
655        Columnar::Canonical(canonical) => {
656            let matches = canonical.into_bool();
657            let compared = matches.validity()?.execute_mask(matches.len(), ctx)?;
658            let starts = PrimitiveArray::new(gathered.starts, Validity::NonNullable);
659            let lens = PrimitiveArray::new(gathered.lens, Validity::NonNullable);
660
661            let matched = Mask::from(matches.to_bit_buffer()) & &compared;
662            let any_true = process_matches::<u64, u64>(
663                BoolArray::new(matched.into_bit_buffer(), Validity::NonNullable),
664                len,
665                starts.clone(),
666                lens.clone(),
667                ctx,
668            );
669
670            let any_null = if options.sql_null_semantics && !compared.all_true() {
671                Mask::from(process_matches::<u64, u64>(
672                    BoolArray::new((!&compared).into_bit_buffer(), Validity::NonNullable),
673                    len,
674                    starts,
675                    lens,
676                    ctx,
677                ))
678            } else {
679                Mask::new_false(len)
680            };
681            (any_true, any_null)
682        }
683    };
684
685    // A null needle is null against a list with elements, but an empty list holds nothing to
686    // compare it to unless the function is strict.
687    let needle_valid = values.validity()?.execute_mask(len, ctx)?;
688    let decided = if options.sql_null_semantics {
689        // A comparison with a null element leaves a non-match unknown.
690        needle_valid & &(Mask::from(any_true.clone()) | &!any_null)
691    } else {
692        &needle_valid | &!Mask::from(non_empty)
693    };
694
695    // A non-nullable result has non-null lists and needles, and no null element that could leave
696    // a row undecided.
697    let validity = match nullability {
698        Nullability::NonNullable => Validity::NonNullable,
699        Nullability::Nullable => list_array
700            .validity()?
701            .and(Validity::from_mask(decided, Nullability::Nullable))?,
702    };
703    Ok(BoolArray::new(any_true, validity).into_array())
704}
705
706/// The elements of every valid list laid out contiguously, each next to the row it belongs to.
707struct GatheredLists {
708    /// The position of each gathered element in the list view's elements.
709    element_idx: Buffer<u64>,
710    /// The row, and so the needle, each gathered element is compared to.
711    row_idx: Buffer<u64>,
712    /// Where each row's run of gathered elements starts.
713    starts: Buffer<u64>,
714    /// How long each row's run is: the list's size, or zero for a null list.
715    lens: Buffer<u64>,
716}
717
718impl GatheredLists {
719    fn new<O: IntegerPType, S: IntegerPType>(
720        offsets: &[O],
721        sizes: &[S],
722        list_valid: &Mask,
723        ctx: &mut ExecutionCtx,
724    ) -> Self {
725        let rows = sizes.len();
726        let total: usize = (0..rows)
727            .filter(|&row| list_valid.value(row))
728            .map(|row| sizes[row].as_())
729            .sum();
730        let allocator = ctx.allocator();
731        let mut element_idx = BufferMut::<u64>::with_capacity_in(total, allocator.clone());
732        let mut row_idx = BufferMut::<u64>::with_capacity_in(total, allocator.clone());
733        let mut starts = BufferMut::<u64>::with_capacity_in(rows, allocator.clone());
734        let mut lens = BufferMut::<u64>::with_capacity_in(rows, allocator.clone());
735
736        for row in 0..rows {
737            starts.push(element_idx.len() as u64);
738            // A null list's offset and size need not point at anything.
739            if !list_valid.value(row) {
740                lens.push(0);
741                continue;
742            }
743            let offset: usize = offsets[row].as_();
744            let size: usize = sizes[row].as_();
745            element_idx.extend((offset..offset + size).map(|idx| idx as u64));
746            row_idx.extend(iter::repeat_n(row as u64, size));
747            lens.push(size as u64);
748        }
749
750        Self {
751            element_idx: element_idx.freeze(),
752            row_idx: row_idx.freeze(),
753            starts: starts.freeze(),
754            lens: lens.freeze(),
755        }
756    }
757}
758
759/// For each list, whether any set bit of `matches` falls in the list's element range.
760fn fold_lists(
761    matches: BoolArray,
762    list_array: &ListViewArray,
763    ctx: &mut ExecutionCtx,
764) -> VortexResult<BitBuffer> {
765    // Get the offsets and sizes as primitive arrays. They are non-negative, so reinterpret to
766    // unsigned and dispatch over the 4 unsigned widths each (4x4 instead of 8x8).
767    let offsets = list_array
768        .offsets()
769        .clone()
770        .execute::<PrimitiveArray>(ctx)?;
771    let offsets = offsets.reinterpret_cast(offsets.ptype().to_unsigned());
772    let sizes = list_array.sizes().clone().execute::<PrimitiveArray>(ctx)?;
773    let sizes = sizes.reinterpret_cast(sizes.ptype().to_unsigned());
774
775    Ok(match_each_unsigned_integer_ptype!(offsets.ptype(), |O| {
776        match_each_unsigned_integer_ptype!(sizes.ptype(), |S| {
777            process_matches::<O, S>(matches, list_array.len(), offsets, sizes, ctx)
778        })
779    }))
780}
781
782/// Returns a [`BitBuffer`] where each bit represents if a list contains the scalar, derived from a
783/// [`BoolArray`] of matches on the child elements array.
784fn process_matches<O, S>(
785    matches: BoolArray,
786    list_array_len: usize,
787    offsets: PrimitiveArray,
788    sizes: PrimitiveArray,
789    ctx: &mut ExecutionCtx,
790) -> BitBuffer
791where
792    O: IntegerPType,
793    S: IntegerPType,
794{
795    let offsets_slice = offsets.as_slice::<O>();
796    let sizes_slice = sizes.as_slice::<S>();
797    let bits = matches.bit_buffer_view();
798
799    BitBuffer::collect_bool_in(
800        list_array_len,
801        |i| {
802            let offset = offsets_slice[i].as_();
803            let size = sizes_slice[i].as_();
804
805            // A set bit means at least one element in this list's range matches.
806            bits.slice(offset..offset + size)
807                .set_indices()
808                .next()
809                .is_some()
810        },
811        ctx.allocator().clone(),
812    )
813}
814
815/// Returns a `Bool` array with `false` for lists that are valid,
816/// or `NULL` if the list itself is null.
817fn list_false_or_null(
818    list_array: &ListViewArray,
819    nullability: Nullability,
820    ctx: &mut ExecutionCtx,
821) -> VortexResult<ArrayRef> {
822    match list_array.validity()? {
823        Validity::NonNullable => {
824            // All false.
825            Ok(ConstantArray::new(Scalar::bool(false, nullability), list_array.len()).into_array())
826        }
827        Validity::AllValid => {
828            // All false, but nullable.
829            Ok(
830                ConstantArray::new(Scalar::bool(false, Nullability::Nullable), list_array.len())
831                    .into_array(),
832            )
833        }
834        Validity::AllInvalid => {
835            // All nulls, must be nullable result.
836            Ok(ConstantArray::new(
837                Scalar::null(DType::Bool(Nullability::Nullable)),
838                list_array.len(),
839            )
840            .into_array())
841        }
842        Validity::Array(validity_array) => {
843            // Create a new bool array with false, and the provided nulls
844            let buffer = BitBuffer::new_unset_in(list_array.len(), ctx.allocator().clone());
845            Ok(BoolArray::new(buffer, Validity::Array(validity_array)).into_array())
846        }
847    }
848}
849
850/// `false` for an empty list, which holds nothing to compare against, and `null` for any other list.
851///
852/// This is a null needle off SQL null semantics, or under them a needle against lists that hold
853/// only nulls.
854fn null_needle_in_lists(
855    list_array: &ListViewArray,
856    nullability: Nullability,
857    ctx: &mut ExecutionCtx,
858) -> VortexResult<ArrayRef> {
859    let empty = !&non_empty_lists(list_array, ctx)?;
860    let validity = list_array
861        .validity()?
862        .and(Validity::from(empty))?
863        .union_nullability(nullability);
864    Ok(BoolArray::new(
865        BitBuffer::new_unset_in(list_array.len(), ctx.allocator().clone()),
866        validity,
867    )
868    .into_array())
869}
870
871/// One bit per list, set when the list holds at least one element.
872fn non_empty_lists(list_array: &ListViewArray, ctx: &mut ExecutionCtx) -> VortexResult<BitBuffer> {
873    let sizes = list_array.sizes().clone().execute::<PrimitiveArray>(ctx)?;
874    Ok(match_each_integer_ptype!(sizes.ptype(), |S| {
875        let sizes = sizes.as_slice::<S>();
876        BitBuffer::collect_bool_in(
877            sizes.len(),
878            |idx| sizes[idx] != S::zero(),
879            ctx.allocator().clone(),
880        )
881    }))
882}
883
884/// Returns a `Bool` array with `true` for lists which are NOT empty, or `false` if they are empty,
885/// or `NULL` if the list itself is null.
886fn list_is_not_empty(
887    list_array: &ListViewArray,
888    nullability: Nullability,
889    ctx: &mut ExecutionCtx,
890) -> VortexResult<ArrayRef> {
891    // Short-circuit for all invalid.
892    if list_array.validity()?.definitely_all_null() {
893        return Ok(ConstantArray::new(
894            Scalar::null(DType::Bool(Nullability::Nullable)),
895            list_array.len(),
896        )
897        .into_array());
898    }
899
900    // Copy over the validity mask from the input.
901    Ok(BoolArray::new(
902        non_empty_lists(list_array, ctx)?,
903        list_array.validity()?.union_nullability(nullability),
904    )
905    .into_array())
906}
907
908#[cfg(test)]
909mod tests {
910    use std::sync::Arc;
911    use std::sync::LazyLock;
912
913    use itertools::Itertools;
914    use num_traits::PrimInt;
915    use rstest::rstest;
916    use vortex_array::ArrayRef;
917    use vortex_array::IntoArray;
918    use vortex_array::VortexSessionExecute;
919    use vortex_array::arrays::BoolArray;
920    use vortex_array::arrays::ChunkedArray;
921    use vortex_array::arrays::ConstantArray;
922    use vortex_array::arrays::DictArray;
923    use vortex_array::arrays::ListArray;
924    use vortex_array::arrays::ListViewArray;
925    use vortex_array::arrays::PrimitiveArray;
926    use vortex_array::arrays::VarBinArray;
927    use vortex_array::arrays::VarBinViewArray;
928    use vortex_array::assert_arrays_eq;
929    use vortex_array::dtype::DType;
930    use vortex_array::dtype::NativePType;
931    use vortex_array::dtype::Nullability;
932    use vortex_array::dtype::PType;
933    use vortex_array::dtype::PType::I32;
934    use vortex_array::dtype::StructFields;
935    use vortex_array::optimizer::ArrayOptimizer;
936    use vortex_array::scalar::PValue;
937    use vortex_array::scalar::Scalar;
938    use vortex_array::scalar_fn::builtin::literal::Literal;
939    use vortex_array::validity::Validity;
940    use vortex_buffer::BitBuffer;
941    use vortex_buffer::Buffer;
942    use vortex_buffer::buffer;
943    use vortex_error::VortexExpect;
944    use vortex_error::VortexResult;
945    use vortex_expr::ArrayExprExt;
946    use vortex_expr::Expression;
947    use vortex_expr::bound;
948    use vortex_expr::col;
949    use vortex_expr::get_item;
950    use vortex_expr::lit;
951    use vortex_expr::root;
952    use vortex_session::VortexSession;
953
954    use super::process_matches;
955    use crate::expr::in_list;
956    use crate::expr::list_contains;
957    use crate::expr::list_contains_opts;
958    use crate::list_contains::ListContains;
959    use crate::list_contains::ListContainsOptions;
960    use crate::list_contains::PreparedSet;
961    use crate::list_contains::PreparedSetData;
962
963    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
964        let session = VortexSession::empty();
965
966        vortex_array::initialize(&session);
967
968        crate::initialize(&session);
969
970        session
971    });
972
973    fn test_array() -> ArrayRef {
974        let mut ctx = SESSION.create_execution_ctx();
975        ListArray::try_new(
976            PrimitiveArray::from_iter(vec![1, 1, 2, 2, 2, 2, 2, 3, 3, 3]).into_array(),
977            PrimitiveArray::from_iter(vec![0, 5, 10]).into_array(),
978            Validity::AllValid,
979            &mut ctx,
980        )
981        .unwrap()
982        .into_array()
983    }
984
985    #[test]
986    pub fn test_one() {
987        let arr = test_array();
988
989        let expr = list_contains(root(), lit(1));
990        let item = arr.apply(&expr).unwrap();
991
992        assert_eq!(
993            item.execute_scalar(0, &mut SESSION.create_execution_ctx())
994                .unwrap(),
995            Scalar::bool(true, Nullability::Nullable)
996        );
997        assert_eq!(
998            item.execute_scalar(1, &mut SESSION.create_execution_ctx())
999                .unwrap(),
1000            Scalar::bool(false, Nullability::Nullable)
1001        );
1002    }
1003
1004    #[test]
1005    pub fn test_all() {
1006        let arr = test_array();
1007
1008        let expr = list_contains(root(), lit(2));
1009        let item = arr.apply(&expr).unwrap();
1010
1011        assert_eq!(
1012            item.execute_scalar(0, &mut SESSION.create_execution_ctx())
1013                .unwrap(),
1014            Scalar::bool(true, Nullability::Nullable)
1015        );
1016        assert_eq!(
1017            item.execute_scalar(1, &mut SESSION.create_execution_ctx())
1018                .unwrap(),
1019            Scalar::bool(true, Nullability::Nullable)
1020        );
1021    }
1022
1023    #[test]
1024    pub fn test_none() {
1025        let arr = test_array();
1026
1027        let expr = list_contains(root(), lit(4));
1028        let item = arr.apply(&expr).unwrap();
1029
1030        assert_eq!(
1031            item.execute_scalar(0, &mut SESSION.create_execution_ctx())
1032                .unwrap(),
1033            Scalar::bool(false, Nullability::Nullable)
1034        );
1035        assert_eq!(
1036            item.execute_scalar(1, &mut SESSION.create_execution_ctx())
1037                .unwrap(),
1038            Scalar::bool(false, Nullability::Nullable)
1039        );
1040    }
1041
1042    #[test]
1043    pub fn test_empty() {
1044        let mut ctx = SESSION.create_execution_ctx();
1045        let arr = ListArray::try_new(
1046            PrimitiveArray::from_iter(vec![1, 1, 2, 2, 2]).into_array(),
1047            PrimitiveArray::from_iter(vec![0, 5, 5]).into_array(),
1048            Validity::AllValid,
1049            &mut ctx,
1050        )
1051        .unwrap()
1052        .into_array();
1053
1054        let expr = list_contains(root(), lit(2));
1055        let item = arr.apply(&expr).unwrap();
1056
1057        assert_eq!(
1058            item.execute_scalar(0, &mut SESSION.create_execution_ctx())
1059                .unwrap(),
1060            Scalar::bool(true, Nullability::Nullable)
1061        );
1062        assert_eq!(
1063            item.execute_scalar(1, &mut SESSION.create_execution_ctx())
1064                .unwrap(),
1065            Scalar::bool(false, Nullability::Nullable)
1066        );
1067    }
1068
1069    #[test]
1070    pub fn test_nullable() {
1071        let mut ctx = SESSION.create_execution_ctx();
1072        let arr = ListArray::try_new(
1073            PrimitiveArray::from_iter(vec![1, 1, 2, 2, 2]).into_array(),
1074            PrimitiveArray::from_iter(vec![0, 5, 5]).into_array(),
1075            Validity::Array(BoolArray::from(BitBuffer::from(vec![true, false])).into_array()),
1076            &mut ctx,
1077        )
1078        .unwrap()
1079        .into_array();
1080
1081        let expr = list_contains(root(), lit(2));
1082        let item = arr.apply(&expr).unwrap();
1083
1084        assert_eq!(
1085            item.execute_scalar(0, &mut SESSION.create_execution_ctx())
1086                .unwrap(),
1087            Scalar::bool(true, Nullability::Nullable)
1088        );
1089        assert!(
1090            !item
1091                .is_valid(1, &mut SESSION.create_execution_ctx())
1092                .unwrap()
1093        );
1094    }
1095
1096    #[test]
1097    pub fn test_return_type() {
1098        let scope = DType::Struct(
1099            StructFields::new(
1100                ["array"].into(),
1101                vec![DType::List(
1102                    Arc::new(DType::Primitive(I32, Nullability::NonNullable)),
1103                    Nullability::Nullable,
1104                )],
1105            ),
1106            Nullability::NonNullable,
1107        );
1108
1109        let expr = list_contains(get_item("array", root()), lit(2));
1110
1111        // Expect nullable, although scope is non-nullable
1112        assert_eq!(
1113            expr.return_dtype(&scope).unwrap(),
1114            DType::Bool(Nullability::Nullable)
1115        );
1116    }
1117
1118    #[test]
1119    pub fn test_display() {
1120        let expr = list_contains(get_item("tags", root()), lit("urgent"));
1121        assert_eq!(expr.to_string(), "vortex.list.contains($.tags, \"urgent\")");
1122
1123        let expr2 = list_contains(root(), lit(42));
1124        assert_eq!(expr2.to_string(), "vortex.list.contains($, 42i32)");
1125    }
1126
1127    #[test]
1128    pub fn test_constant_scalars() {
1129        let arr = test_array();
1130
1131        // Both list and needle are constants - should use scalar optimization
1132        let list_scalar = Scalar::list(
1133            Arc::new(DType::Primitive(I32, Nullability::NonNullable)),
1134            vec![1.into(), 2.into(), 3.into()],
1135            Nullability::NonNullable,
1136        );
1137
1138        // Test contains true
1139        let expr = list_contains(lit(list_scalar.clone()), lit(2i32));
1140        let result = arr.clone().apply(&expr).unwrap();
1141        assert_eq!(
1142            result
1143                .execute_scalar(0, &mut SESSION.create_execution_ctx())
1144                .unwrap(),
1145            Scalar::bool(true, Nullability::NonNullable)
1146        );
1147
1148        // Test contains false
1149        let expr = list_contains(lit(list_scalar), lit(42i32));
1150        let result = arr.apply(&expr).unwrap();
1151        assert_eq!(
1152            result
1153                .execute_scalar(0, &mut SESSION.create_execution_ctx())
1154                .unwrap(),
1155            Scalar::bool(false, Nullability::NonNullable)
1156        );
1157    }
1158
1159    #[test]
1160    fn test_null_in_empty_list() -> VortexResult<()> {
1161        let mut ctx = SESSION.create_execution_ctx();
1162        let array = test_array();
1163        let dtype = Arc::new(DType::Primitive(I32, Nullability::NonNullable));
1164
1165        let list = Scalar::list(Arc::clone(&dtype), vec![], Nullability::NonNullable);
1166        let needle = Scalar::null(DType::Primitive(I32, Nullability::Nullable));
1167
1168        let expr = list_contains(lit(list.clone()), lit(needle.clone()));
1169        let result = array.clone().apply(&expr)?;
1170        assert_eq!(
1171            result.execute_scalar(0, &mut ctx)?,
1172            Scalar::bool(false, Nullability::Nullable)
1173        );
1174
1175        let expr = list_contains(lit(list), lit(2i32));
1176        let result = array.clone().apply(&expr)?;
1177        assert_eq!(
1178            result.execute_scalar(0, &mut ctx)?,
1179            Scalar::bool(false, Nullability::NonNullable)
1180        );
1181
1182        let list = Scalar::null(DType::List(dtype, Nullability::Nullable));
1183        let expr = list_contains(lit(list), lit(needle));
1184        let result = array.apply(&expr)?;
1185        assert!(result.execute_scalar(0, &mut ctx)?.is_null());
1186        Ok(())
1187    }
1188
1189    fn nonnull_strings(values: Vec<Vec<&str>>) -> ArrayRef {
1190        let mut ctx = SESSION.create_execution_ctx();
1191
1192        ListArray::from_iter_slow::<u64, _>(values, Arc::new(DType::Utf8(Nullability::NonNullable)))
1193            .unwrap()
1194            .into_array()
1195            .execute::<ListViewArray>(&mut ctx)
1196            .vortex_expect("failed to convert to listview")
1197            .into_array()
1198    }
1199
1200    fn null_strings(values: Vec<Vec<Option<&str>>>) -> ArrayRef {
1201        let elements = values.iter().flatten().cloned().collect_vec();
1202
1203        let mut offsets = values
1204            .iter()
1205            .scan(0u64, |st, v| {
1206                *st += v.len() as u64;
1207                Some(*st)
1208            })
1209            .collect_vec();
1210        offsets.insert(0, 0u64);
1211        let offsets = Buffer::from_iter(offsets).into_array();
1212
1213        let elements =
1214            VarBinArray::from_iter(elements, DType::Utf8(Nullability::Nullable)).into_array();
1215
1216        let mut ctx = SESSION.create_execution_ctx();
1217
1218        ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)
1219            .unwrap()
1220            .as_array()
1221            .clone()
1222            .execute::<ListViewArray>(&mut ctx)
1223            .vortex_expect("failed to convert to listview")
1224            .into_array()
1225    }
1226
1227    fn bool_array(values: Vec<bool>, validity: Validity) -> BoolArray {
1228        BoolArray::new(values.into_iter().collect(), validity)
1229    }
1230
1231    #[rstest]
1232    #[case(
1233        nonnull_strings(vec![vec![], vec!["a"], vec!["a", "b"]]),
1234        Some("a"),
1235        bool_array(vec![false, true, true], Validity::NonNullable)
1236    )]
1237    #[case(
1238        null_strings(vec![vec![], vec![Some("a"), None], vec![Some("a"), None, Some("b")]]),
1239        Some("a"),
1240        bool_array(vec![false, true, true], Validity::AllValid)
1241    )]
1242    #[case(
1243        null_strings(vec![vec![], vec![Some("a"), None], vec![Some("b"), None, None]]),
1244        Some("a"),
1245        bool_array(vec![false, true, false], Validity::AllValid)
1246    )]
1247    #[case(
1248        nonnull_strings(vec![vec![], vec!["a"], vec!["a"]]),
1249        Some("a"),
1250        bool_array(vec![false, true, true], Validity::NonNullable)
1251    )]
1252    #[case(
1253        nonnull_strings(vec![vec![], vec![], vec![]]),
1254        Some("a"),
1255        bool_array(vec![false, false, false], Validity::NonNullable)
1256    )]
1257    #[case(
1258        nonnull_strings(vec![vec!["b"], vec![], vec!["b"]]),
1259        Some("a"),
1260        bool_array(vec![false, false, false], Validity::NonNullable)
1261    )]
1262    // A null needle is null against a list with elements, but an empty list holds nothing to
1263    // compare it to.
1264    #[case(
1265        null_strings(vec![vec![], vec![None, None], vec![None, None, None]]),
1266        None,
1267        bool_array(vec![false, false, false], Validity::from_iter([true, false, false]))
1268    )]
1269    #[case(
1270        null_strings(vec![vec![], vec![None, None], vec![None, None, None]]),
1271        Some("a"),
1272        bool_array(vec![false, false, false], Validity::AllValid)
1273    )]
1274    fn test_contains_nullable(
1275        #[case] list_array: ArrayRef,
1276        #[case] value: Option<&str>,
1277        #[case] expected: BoolArray,
1278    ) {
1279        let mut ctx = SESSION.create_execution_ctx();
1280        let element_nullability = list_array
1281            .dtype()
1282            .as_list_element_opt()
1283            .unwrap()
1284            .nullability();
1285        let scalar = match value {
1286            None => Scalar::null(DType::Utf8(Nullability::Nullable)),
1287            Some(v) => Scalar::utf8(v, element_nullability),
1288        };
1289        let elem = ConstantArray::new(scalar, list_array.len());
1290        let expr = list_contains(root(), lit(elem.scalar().clone()));
1291        let result = list_array.apply(&expr).unwrap();
1292        assert_arrays_eq!(result, expected, &mut ctx);
1293    }
1294
1295    #[test]
1296    fn test_constant_list() {
1297        let mut ctx = SESSION.create_execution_ctx();
1298        let list_array = ConstantArray::new(
1299            Scalar::list(
1300                Arc::new(DType::Primitive(I32, Nullability::NonNullable)),
1301                vec![1i32.into(), 2i32.into(), 3i32.into()],
1302                Nullability::NonNullable,
1303            ),
1304            2,
1305        )
1306        .into_array();
1307
1308        let expr = list_contains(root(), lit(2i32));
1309        let contains = list_array.apply(&expr).unwrap();
1310        let expected = BoolArray::from_iter([true, true]);
1311        assert_arrays_eq!(contains, expected, &mut ctx);
1312    }
1313
1314    #[test]
1315    fn test_all_nulls() {
1316        let mut ctx = SESSION.create_execution_ctx();
1317        let list_array = ConstantArray::new(
1318            Scalar::null(DType::List(
1319                Arc::new(DType::Primitive(I32, Nullability::NonNullable)),
1320                Nullability::Nullable,
1321            )),
1322            5,
1323        )
1324        .into_array();
1325
1326        let expr = list_contains(root(), lit(2i32));
1327        let contains = list_array.apply(&expr).unwrap();
1328
1329        let expected = BoolArray::new(
1330            [false, false, false, false, false].into_iter().collect(),
1331            Validity::AllInvalid,
1332        );
1333        assert_arrays_eq!(contains, expected, &mut ctx);
1334    }
1335
1336    #[test]
1337    fn test_list_array_element() {
1338        let mut ctx = SESSION.create_execution_ctx();
1339        let list_scalar = Scalar::list(
1340            Arc::new(DType::Primitive(I32, Nullability::NonNullable)),
1341            vec![1.into(), 3.into(), 6.into()],
1342            Nullability::NonNullable,
1343        );
1344
1345        let arr = (0..7).collect::<PrimitiveArray>().into_array();
1346        let expr = list_contains(lit(list_scalar), root());
1347        let contains = arr.apply(&expr).unwrap();
1348
1349        let expected = BoolArray::from_iter([false, true, false, true, false, false, true]);
1350        assert_arrays_eq!(contains, expected, &mut ctx);
1351    }
1352
1353    #[test]
1354    fn test_list_contains_empty_listview() {
1355        let mut ctx = SESSION.create_execution_ctx();
1356        let empty_elements = PrimitiveArray::empty::<i32>(Nullability::NonNullable);
1357        let offsets = Buffer::from_iter([0u32, 0, 0, 0]).into_array();
1358        let sizes = Buffer::from_iter([0u32, 0, 0, 0]).into_array();
1359
1360        let list_array = unsafe {
1361            ListViewArray::new_unchecked(
1362                empty_elements.into_array(),
1363                offsets,
1364                sizes,
1365                Validity::NonNullable,
1366            )
1367            .with_zero_copy_to_list(true)
1368        };
1369
1370        let expr = list_contains(root(), lit(42i32));
1371        let result = list_array.into_array().apply(&expr).unwrap();
1372
1373        let expected = BoolArray::from_iter([false, false, false, false]);
1374        assert_arrays_eq!(result, expected, &mut ctx);
1375    }
1376
1377    #[test]
1378    fn test_list_contains_all_null_elements() {
1379        let mut ctx = SESSION.create_execution_ctx();
1380        let elements = PrimitiveArray::from_option_iter::<i32, _>([None, None, None, None, None]);
1381        let offsets = Buffer::from_iter([0u32, 2, 4]).into_array();
1382        let sizes = Buffer::from_iter([2u32, 2, 1]).into_array();
1383
1384        let list_array = unsafe {
1385            ListViewArray::new_unchecked(
1386                elements.into_array(),
1387                offsets,
1388                sizes,
1389                Validity::NonNullable,
1390            )
1391            .with_zero_copy_to_list(true)
1392        };
1393
1394        // Searching for null
1395        let null_scalar = Scalar::null(DType::Primitive(I32, Nullability::Nullable));
1396        let expr = list_contains(root(), lit(null_scalar));
1397        let result = list_array.clone().into_array().apply(&expr).unwrap();
1398
1399        let expected = BoolArray::new(
1400            [false, false, false].into_iter().collect(),
1401            Validity::AllInvalid,
1402        );
1403        assert_arrays_eq!(result, expected, &mut ctx);
1404
1405        // Searching for non-null
1406        let expr2 = list_contains(root(), lit(42i32));
1407        let result2 = list_array.into_array().apply(&expr2).unwrap();
1408
1409        let expected2 = BoolArray::from_iter([false, false, false]);
1410        assert_arrays_eq!(result2, expected2, &mut ctx);
1411    }
1412
1413    #[test]
1414    fn test_list_contains_large_offsets() {
1415        let mut ctx = SESSION.create_execution_ctx();
1416        let elements = Buffer::from_iter([1i32, 2, 3, 4, 5]).into_array();
1417
1418        let offsets = Buffer::from_iter([0u32, 1, 4, 0]).into_array();
1419        let sizes = Buffer::from_iter([1u32, 2, 1, 0]).into_array();
1420
1421        let list_array = ListViewArray::new(
1422            elements.into_array(),
1423            offsets,
1424            sizes,
1425            Validity::NonNullable,
1426            &mut ctx,
1427        );
1428
1429        let expr = list_contains(root(), lit(2i32));
1430        let result = list_array.clone().into_array().apply(&expr).unwrap();
1431
1432        let expected = BoolArray::from_iter([false, true, false, false]);
1433        assert_arrays_eq!(result, expected, &mut ctx);
1434
1435        let expr5 = list_contains(root(), lit(5i32));
1436        let result5 = list_array.into_array().apply(&expr5).unwrap();
1437
1438        let expected5 = BoolArray::from_iter([false, false, true, false]);
1439        assert_arrays_eq!(result5, expected5, &mut ctx);
1440    }
1441
1442    #[test]
1443    fn test_list_contains_offset_size_boundary() {
1444        let mut ctx = SESSION.create_execution_ctx();
1445        let elements = Buffer::from_iter(0..256).into_array();
1446        let offsets = Buffer::from_iter([0u8, 100, 200, 254]).into_array();
1447        let sizes = Buffer::from_iter([50u8, 50, 54, 2]).into_array();
1448
1449        let list_array = ListViewArray::new(
1450            elements.into_array(),
1451            offsets,
1452            sizes,
1453            Validity::NonNullable,
1454            &mut ctx,
1455        );
1456
1457        let expr = list_contains(root(), lit(255i32));
1458        let result = list_array.clone().into_array().apply(&expr).unwrap();
1459
1460        let expected = BoolArray::from_iter([false, false, false, true]);
1461        assert_arrays_eq!(result, expected, &mut ctx);
1462
1463        let expr_zero = list_contains(root(), lit(0i32));
1464        let result_zero = list_array.into_array().apply(&expr_zero).unwrap();
1465
1466        let expected_zero = BoolArray::from_iter([true, false, false, false]);
1467        assert_arrays_eq!(result_zero, expected_zero, &mut ctx);
1468    }
1469
1470    const SQL: ListContainsOptions = ListContainsOptions {
1471        sql_null_semantics: true,
1472    };
1473
1474    #[rstest]
1475    #[case::default(ListContainsOptions::default(), Some(false))]
1476    #[case::sql(SQL, None)]
1477    fn test_constant_needle_ignores_null_value_bits(
1478        #[case] options: ListContainsOptions,
1479        #[case] null_element_result: Option<bool>,
1480    ) -> VortexResult<()> {
1481        // Both the null element and the valid match have the same physical value.
1482        let elements = PrimitiveArray::new(
1483            buffer![7i32, 7, 8],
1484            Validity::from(BitBuffer::from_iter([false, true, true])),
1485        );
1486        let lists = ListArray::try_new(
1487            elements.into_array(),
1488            buffer![0u32, 1, 2, 3, 3].into_array(),
1489            Validity::AllValid,
1490            &mut SESSION.create_execution_ctx(),
1491        )?
1492        .into_array();
1493        assert_result(
1494            lists.apply(&list_contains_opts(root(), lit(7i32), options)),
1495            [null_element_result, Some(true), Some(false), Some(false)],
1496        )
1497    }
1498
1499    #[rstest]
1500    #[case::default(ListContainsOptions::default())]
1501    #[case::sql(SQL)]
1502    fn test_no_matches_preserves_null_lists(
1503        #[case] options: ListContainsOptions,
1504    ) -> VortexResult<()> {
1505        let lists = ListArray::try_new(
1506            buffer![1i32, 2].into_array(),
1507            buffer![0u32, 1, 2].into_array(),
1508            Validity::from(BitBuffer::from_iter([true, false])),
1509            &mut SESSION.create_execution_ctx(),
1510        )?
1511        .into_array();
1512        assert_result(
1513            lists.apply(&list_contains_opts(root(), lit(9i32), options)),
1514            [Some(false), None],
1515        )
1516    }
1517
1518    #[test]
1519    fn test_fold_sliced_match_bitmap() {
1520        let mut ctx = SESSION.create_execution_ctx();
1521        let bits = BitBuffer::from_iter([true, false, true, false]).slice(1..);
1522        let result = process_matches::<u32, u32>(
1523            BoolArray::new(bits, Validity::NonNullable),
1524            3,
1525            PrimitiveArray::from_iter([0u32, 1, 2]),
1526            PrimitiveArray::from_iter([1u32, 1, 1]),
1527            &mut ctx,
1528        );
1529        assert_eq!(result, BitBuffer::from_iter([false, true, false]));
1530    }
1531
1532    #[rstest]
1533    #[case::default(ListContainsOptions::default())]
1534    #[case::sql(SQL)]
1535    fn test_reject_mismatched_needle_type(#[case] options: ListContainsOptions) {
1536        let list = lit(i32_set(vec![Some(1)]));
1537        let dtype = DType::Utf8(Nullability::NonNullable);
1538        assert!(
1539            list_contains_opts(list.clone(), root(), options)
1540                .bind(&dtype)
1541                .is_err()
1542        );
1543        assert!(
1544            list_contains_opts(list, lit("1"), options)
1545                .bind(&dtype)
1546                .is_err()
1547        );
1548    }
1549
1550    /// A constant `List<i32?>` set, so that it can hold a null element.
1551    fn i32_set(values: Vec<Option<i32>>) -> Scalar {
1552        let element = DType::Primitive(I32, Nullability::Nullable);
1553        Scalar::list(
1554            Arc::new(element.clone()),
1555            values
1556                .into_iter()
1557                .map(|v| match v {
1558                    Some(v) => Scalar::primitive(v, Nullability::Nullable),
1559                    None => Scalar::null(element.clone()),
1560                })
1561                .collect(),
1562            Nullability::NonNullable,
1563        )
1564    }
1565
1566    fn f64_set(values: Vec<f64>) -> Scalar {
1567        Scalar::list(
1568            Arc::new(DType::Primitive(PType::F64, Nullability::NonNullable)),
1569            values.into_iter().map(Scalar::from).collect(),
1570            Nullability::NonNullable,
1571        )
1572    }
1573
1574    fn utf8_set(values: Vec<Option<&str>>) -> Scalar {
1575        let element = DType::Utf8(Nullability::Nullable);
1576        Scalar::list(
1577            Arc::new(element.clone()),
1578            values
1579                .into_iter()
1580                .map(|v| match v {
1581                    Some(v) => Scalar::utf8(v, Nullability::Nullable),
1582                    None => Scalar::null(element.clone()),
1583                })
1584                .collect(),
1585            Nullability::NonNullable,
1586        )
1587    }
1588
1589    fn assert_result(
1590        result: VortexResult<ArrayRef>,
1591        expected: impl IntoIterator<Item = Option<bool>>,
1592    ) -> VortexResult<()> {
1593        let mut ctx = SESSION.create_execution_ctx();
1594        assert_arrays_eq!(result?, BoolArray::from_iter(expected), &mut ctx);
1595        Ok(())
1596    }
1597
1598    #[test]
1599    fn constant_set_of_floats_is_bitwise() -> VortexResult<()> {
1600        // Membership has to agree with the compare kernel: `-0.0` and `0.0` are different
1601        // members, and NaN is a member of a set that holds NaN.
1602        let needles = PrimitiveArray::from_option_iter([
1603            Some(1.0f64),
1604            Some(f64::NAN),
1605            Some(0.0),
1606            Some(-0.0),
1607            Some(2.0),
1608            None,
1609        ])
1610        .into_array();
1611        let set = f64_set(vec![1.0, f64::NAN, -0.0]);
1612        assert_result(
1613            needles.apply(&list_contains(lit(set), root())),
1614            [
1615                Some(true),
1616                Some(true),
1617                Some(false),
1618                Some(true),
1619                Some(false),
1620                None,
1621            ],
1622        )
1623    }
1624
1625    #[test]
1626    fn constant_set_null_element_never_matches_by_default() -> VortexResult<()> {
1627        let needles =
1628            PrimitiveArray::from_option_iter([Some(1), Some(2), None, Some(4)]).into_array();
1629        let set = i32_set(vec![Some(2), None, Some(4)]);
1630        assert_result(
1631            needles.apply(&list_contains(lit(set), root())),
1632            [Some(false), Some(true), None, Some(true)],
1633        )
1634    }
1635
1636    #[test]
1637    fn constant_set_null_element_is_unknown_under_sql_semantics() -> VortexResult<()> {
1638        // `x IN (2, NULL, 4)`: a match is still true, but a non-match is null, so `NOT IN` never
1639        // admits it. A null needle stays null either way.
1640        let needles =
1641            PrimitiveArray::from_option_iter([Some(1), Some(2), None, Some(4)]).into_array();
1642        let set = i32_set(vec![Some(2), None, Some(4)]);
1643        assert_result(
1644            needles.clone().apply(&in_list(root(), lit(set.clone()))),
1645            [None, Some(true), None, Some(true)],
1646        )?;
1647        assert_result(
1648            needles.apply(&vortex_expr::not(in_list(root(), lit(set)))),
1649            [None, Some(false), None, Some(false)],
1650        )
1651    }
1652
1653    #[test]
1654    fn sql_semantics_without_a_null_element_match_the_default() -> VortexResult<()> {
1655        let needles = PrimitiveArray::from_option_iter([Some(1), Some(2), None]).into_array();
1656        let set = i32_set(vec![Some(2)]);
1657        assert_result(
1658            needles.apply(&in_list(root(), lit(set))),
1659            [Some(false), Some(true), None],
1660        )
1661    }
1662
1663    fn empty_i32_list() -> Scalar {
1664        Scalar::list(
1665            Arc::new(DType::Primitive(I32, Nullability::Nullable)),
1666            vec![],
1667            Nullability::NonNullable,
1668        )
1669    }
1670
1671    #[rstest]
1672    #[case::default(ListContainsOptions::default(), Some(false))]
1673    #[case::sql(SQL, None)]
1674    fn null_needle_in_an_empty_list(
1675        #[case] options: ListContainsOptions,
1676        #[case] expected: Option<bool>,
1677    ) -> VortexResult<()> {
1678        // Off SQL null semantics an empty list holds nothing to compare a null needle to; on them
1679        // the function is strict. Every evaluation path has to agree, a single row included.
1680        let mut ctx = SESSION.create_execution_ctx();
1681        let null = Scalar::null(DType::Primitive(I32, Nullability::Nullable));
1682
1683        let scalar = ConstantArray::new(null, 2)
1684            .into_array()
1685            .apply(&list_contains_opts(lit(empty_i32_list()), root(), options))?;
1686        assert_eq!(
1687            scalar.execute_scalar(0, &mut ctx)?.as_bool().value(),
1688            expected
1689        );
1690
1691        let needles = PrimitiveArray::from_option_iter([Some(1), None]).into_array();
1692        let column = needles.apply(&list_contains_opts(lit(empty_i32_list()), root(), options))?;
1693        assert_eq!(
1694            column.execute_scalar(1, &mut ctx)?.as_bool().value(),
1695            expected
1696        );
1697        assert_arrays_eq!(
1698            column,
1699            BoolArray::from_iter([Some(false), expected]),
1700            &mut ctx
1701        );
1702        Ok(())
1703    }
1704
1705    #[rstest]
1706    #[case::default(ListContainsOptions::default(), [None, Some(false), None])]
1707    #[case::sql(SQL, [None, None, None])]
1708    fn null_needle_in_a_list_column(
1709        #[case] options: ListContainsOptions,
1710        #[case] expected: [Option<bool>; 3],
1711    ) -> VortexResult<()> {
1712        // Lists `[1]`, `[]` and a null list against a null needle.
1713        let lists = ListArray::try_new(
1714            PrimitiveArray::from_option_iter([Some(1i32)]).into_array(),
1715            PrimitiveArray::from_iter(vec![0, 1, 1, 1]).into_array(),
1716            Validity::from_iter([true, true, false]),
1717            &mut SESSION.create_execution_ctx(),
1718        )?
1719        .into_array();
1720        let null = Scalar::null(DType::Primitive(I32, Nullability::Nullable));
1721        assert_result(
1722            lists.apply(&list_contains_opts(root(), lit(null), options)),
1723            expected,
1724        )
1725    }
1726
1727    /// Every row of `result` agrees with that row evaluated on its own, then matches `expected`.
1728    fn assert_rows_agree(result: ArrayRef, expected: BoolArray) -> VortexResult<()> {
1729        let mut ctx = SESSION.create_execution_ctx();
1730        let whole = result.clone().execute::<BoolArray>(&mut ctx)?.into_array();
1731        for row in 0..result.len() {
1732            assert_eq!(
1733                result.execute_scalar(row, &mut ctx)?,
1734                whole.execute_scalar(row, &mut ctx)?,
1735                "row {row}"
1736            );
1737        }
1738        assert_arrays_eq!(whole, expected, &mut ctx);
1739        Ok(())
1740    }
1741
1742    #[rstest]
1743    #[case::default(
1744        ListContainsOptions::default(),
1745        [Some(true), Some(false), None, Some(false), None, Some(true)]
1746    )]
1747    #[case::sql(SQL, [Some(true), None, None, None, None, Some(true)])]
1748    fn list_column_against_needle_column(
1749        #[case] options: ListContainsOptions,
1750        #[case] expected: [Option<bool>; 6],
1751    ) -> VortexResult<()> {
1752        // Lists `[1, 2]`, `[]`, null, `[3, null]`, `[4]`, `[5]` against needles 2, null, 1, 7,
1753        // null, 5.
1754        let lists = ListArray::try_new(
1755            PrimitiveArray::from_option_iter([
1756                Some(1i32),
1757                Some(2),
1758                Some(3),
1759                None,
1760                Some(4),
1761                Some(5),
1762            ])
1763            .into_array(),
1764            PrimitiveArray::from_iter(vec![0, 2, 2, 2, 4, 5, 6]).into_array(),
1765            Validity::from_iter([true, true, false, true, true, true]),
1766            &mut SESSION.create_execution_ctx(),
1767        )?
1768        .into_array();
1769        let needles =
1770            PrimitiveArray::from_option_iter([Some(2i32), None, Some(1), Some(7), None, Some(5)])
1771                .into_array();
1772        let result = ListContains::try_new_opts(lists, needles, options)?.into_array();
1773        assert_rows_agree(result, BoolArray::from_iter(expected))
1774    }
1775
1776    #[test]
1777    fn list_view_column_with_overlapping_views() -> VortexResult<()> {
1778        let mut ctx = SESSION.create_execution_ctx();
1779        // Views out of order and overlapping in `[1, 2, 3, 4]`: `[3, 4]` then `[1, 2, 3]`.
1780        let lists = ListViewArray::try_new(
1781            buffer![1i32, 2, 3, 4].into_array(),
1782            buffer![2u32, 0].into_array(),
1783            buffer![2u32, 3].into_array(),
1784            Validity::NonNullable,
1785            &mut ctx,
1786        )?
1787        .into_array();
1788        let needles = buffer![4i32, 4].into_array();
1789        let result = ListContains::try_new(lists, needles)?.into_array();
1790        assert_rows_agree(result, BoolArray::from_iter([true, false]))
1791    }
1792
1793    /// Looks up each element of `set`, its neighbours and the type's extremes, against a naive
1794    /// oracle.
1795    fn assert_integer_membership<T>(set: Vec<T>) -> VortexResult<()>
1796    where
1797        T: NativePType + PrimInt + Into<PValue>,
1798    {
1799        let mut needles = vec![T::min_value(), T::max_value()];
1800        for &element in &set {
1801            needles.push(element);
1802            needles.extend(element.checked_sub(&T::one()));
1803            needles.extend(element.checked_add(&T::one()));
1804        }
1805        let expected = BoolArray::from_iter(needles.iter().map(|needle| set.contains(needle)));
1806        let list = Scalar::list(
1807            Arc::new(DType::Primitive(T::PTYPE, Nullability::NonNullable)),
1808            set.into_iter()
1809                .map(|v| Scalar::primitive(v, Nullability::NonNullable))
1810                .collect(),
1811            Nullability::NonNullable,
1812        );
1813        let mut ctx = SESSION.create_execution_ctx();
1814        let result = PrimitiveArray::from_iter(needles)
1815            .into_array()
1816            .apply(&list_contains(lit(list), root()))?;
1817        assert_arrays_eq!(result, expected, &mut ctx);
1818        Ok(())
1819    }
1820
1821    #[test]
1822    fn integer_sets_through_every_haystack() -> VortexResult<()> {
1823        // Dense spans look up in a bitmap, including spans straddling zero and whole types.
1824        assert_integer_membership(vec![-3i32, -1, 0, 2])?;
1825        assert_integer_membership(vec![i8::MIN, 0, i8::MAX])?;
1826        assert_integer_membership(vec![u64::MAX, u64::MAX - 2])?;
1827        assert_integer_membership(vec![i64::MIN, i64::MIN + 5])?;
1828        // A sparse set looks up through a binary search when small and a hash set when large.
1829        assert_integer_membership(vec![-(1i64 << 40), 1, 1 << 40])?;
1830        assert_integer_membership((0..100u64).map(|v| v << 30).collect())?;
1831        assert_integer_membership(vec![i64::MIN, i64::MAX])
1832    }
1833
1834    #[rstest]
1835    #[case::default(ListContainsOptions::default())]
1836    #[case::sql(SQL)]
1837    fn chunked_needles_agree_with_flat_needles(
1838        #[case] options: ListContainsOptions,
1839    ) -> VortexResult<()> {
1840        // Chunks in different encodings, one of them empty, against a set with a null element.
1841        let chunks = vec![
1842            PrimitiveArray::from_option_iter([Some(1i32), None, Some(4)]).into_array(),
1843            PrimitiveArray::from_option_iter::<i32, _>([]).into_array(),
1844            DictArray::try_new(
1845                PrimitiveArray::from_option_iter([Some(0u32), None, Some(1)]).into_array(),
1846                PrimitiveArray::from_option_iter([Some(2i32), Some(9)]).into_array(),
1847            )?
1848            .into_array(),
1849        ];
1850        let dtype = chunks[0].dtype().clone();
1851        let chunked = ChunkedArray::try_new(chunks, dtype)?.into_array();
1852        let expr = list_contains_opts(lit(i32_set(vec![Some(2), None, Some(4)])), root(), options);
1853
1854        let mut ctx = SESSION.create_execution_ctx();
1855        let flat =
1856            PrimitiveArray::from_option_iter([Some(1i32), None, Some(4), Some(2), None, Some(9)])
1857                .into_array()
1858                .apply(&expr)?
1859                .execute::<BoolArray>(&mut ctx)?;
1860        assert_rows_agree(chunked.apply(&expr)?, flat)
1861    }
1862
1863    #[test]
1864    fn chunked_string_needles() -> VortexResult<()> {
1865        let chunks = vec![
1866            VarBinViewArray::from_iter_nullable_str([Some("a"), None]).into_array(),
1867            VarBinViewArray::from_iter_nullable_str([
1868                Some("a value longer than twelve bytes"),
1869                Some("b"),
1870            ])
1871            .into_array(),
1872        ];
1873        let dtype = chunks[0].dtype().clone();
1874        let chunked = ChunkedArray::try_new(chunks, dtype)?.into_array();
1875        let set = utf8_set(vec![Some("a"), Some("a value longer than twelve bytes")]);
1876        assert_rows_agree(
1877            chunked.apply(&list_contains(lit(set), root()))?,
1878            BoolArray::from_iter([Some(true), None, Some(true), Some(false)]),
1879        )
1880    }
1881
1882    #[test]
1883    fn strict_only_under_sql_semantics() {
1884        let default = list_contains(lit(empty_i32_list()), root());
1885        let sql = in_list(root(), lit(empty_i32_list()));
1886        assert!(
1887            !default
1888                .as_scalar()
1889                .is_some_and(|f| f.signature().is_strict())
1890        );
1891        assert!(sql.as_scalar().is_some_and(|f| f.signature().is_strict()));
1892    }
1893
1894    #[test]
1895    fn constant_set_of_only_nulls() -> VortexResult<()> {
1896        // Every element is dropped from the set, so nothing matches; under SQL null semantics no
1897        // answer is known instead.
1898        let needles = PrimitiveArray::from_option_iter([Some(1), None]).into_array();
1899        let set = i32_set(vec![None, None]);
1900        assert_result(
1901            needles
1902                .clone()
1903                .apply(&list_contains(lit(set.clone()), root())),
1904            [Some(false), None],
1905        )?;
1906        assert_result(needles.apply(&in_list(root(), lit(set))), [None, None])
1907    }
1908
1909    #[test]
1910    fn constant_set_row_haystack_keeps_the_declared_nullability() -> VortexResult<()> {
1911        // A nullable element dtype decides nothing off SQL null semantics, so non-null needles give
1912        // a non-nullable result, though each comparison is against a nullable element.
1913        let needles = BoolArray::from_iter([true, false]).into_array();
1914        let element = DType::Bool(Nullability::Nullable);
1915        let set = Scalar::list(
1916            Arc::new(element.clone()),
1917            vec![
1918                Scalar::bool(true, Nullability::Nullable),
1919                Scalar::null(element),
1920            ],
1921            Nullability::NonNullable,
1922        );
1923        let result = needles.apply(&list_contains(lit(set), root()))?;
1924        assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable));
1925        assert_rows_agree(result, BoolArray::from_iter([true, false]))
1926    }
1927
1928    #[test]
1929    fn constant_set_row_haystack_of_only_nulls() -> VortexResult<()> {
1930        // The row haystack must also preserve the distinction between an empty set and null
1931        // elements.
1932        let needles = BoolArray::from_iter([Some(true), None]).into_array();
1933        let element = DType::Bool(Nullability::Nullable);
1934        let set = Scalar::list(
1935            Arc::new(element.clone()),
1936            vec![Scalar::null(element.clone()), Scalar::null(element)],
1937            Nullability::NonNullable,
1938        );
1939        assert_result(
1940            needles
1941                .clone()
1942                .apply(&list_contains(lit(set.clone()), root())),
1943            [Some(false), None],
1944        )?;
1945        assert_result(needles.apply(&in_list(root(), lit(set))), [None, None])
1946    }
1947
1948    #[test]
1949    fn constant_set_of_strings_reaches_out_of_line_values() -> VortexResult<()> {
1950        // Values longer than 12 bytes live outside the view; both kinds must be looked up.
1951        let long = "a value longer than twelve bytes";
1952        let needles = VarBinViewArray::from_iter_nullable_str([
1953            Some("a"),
1954            Some(long),
1955            Some("a value longer than twelve byteX"),
1956            Some("b"),
1957            None,
1958        ])
1959        .into_array();
1960        let set = utf8_set(vec![Some("a"), Some(long)]);
1961        assert_result(
1962            needles.clone().apply(&list_contains(lit(set), root())),
1963            [Some(true), Some(true), Some(false), Some(false), None],
1964        )?;
1965        let set_with_null = utf8_set(vec![Some("a"), None]);
1966        assert_result(
1967            needles.apply(&in_list(root(), lit(set_with_null))),
1968            [Some(true), None, None, None, None],
1969        )
1970    }
1971
1972    #[rstest]
1973    // Non-strict, so a null code keeps the dictionary rewrite from pushing the function into the
1974    // values: the needle is executed into its canonical encoding and looked up in the set.
1975    #[case::executed(ListContainsOptions::default(), [Some(false), Some(true), None, Some(true)])]
1976    // Strict, so the rewrite looks up the dictionary's two values instead of its four rows.
1977    #[case::pushed_into_values(SQL, [Some(false), Some(true), None, Some(true)])]
1978    fn constant_set_looks_up_a_dictionary_needle(
1979        #[case] options: ListContainsOptions,
1980        #[case] expected: [Option<bool>; 4],
1981    ) -> VortexResult<()> {
1982        let needles = DictArray::try_new(
1983            PrimitiveArray::from_option_iter([Some(0u32), Some(1), None, Some(1)]).into_array(),
1984            PrimitiveArray::from_iter([1i32, 2]).into_array(),
1985        )?
1986        .into_array();
1987        let set = i32_set(vec![Some(2), Some(4)]);
1988        assert_rows_agree(
1989            needles.apply(&list_contains_opts(lit(set), root(), options))?,
1990            BoolArray::from_iter(expected),
1991        )
1992    }
1993
1994    #[test]
1995    fn constant_set_of_strings_looks_up_an_encoded_needle() -> VortexResult<()> {
1996        let needles = VarBinArray::from_iter(
1997            [Some("a"), Some("b"), None],
1998            DType::Utf8(Nullability::Nullable),
1999        )
2000        .into_array();
2001        let set = utf8_set(vec![Some("a"), Some("c")]);
2002        assert_result(
2003            needles.apply(&list_contains(lit(set), root())),
2004            [Some(true), Some(false), None],
2005        )
2006    }
2007
2008    #[test]
2009    fn constant_set_row_haystack_honours_both_semantics() -> VortexResult<()> {
2010        // Boolean sets use the general sorted row haystack.
2011        let needles = BoolArray::from_iter([Some(true), Some(false), None]).into_array();
2012        let element = DType::Bool(Nullability::Nullable);
2013        let set = Scalar::list(
2014            Arc::new(element.clone()),
2015            vec![
2016                Scalar::bool(true, Nullability::Nullable),
2017                Scalar::null(element),
2018            ],
2019            Nullability::NonNullable,
2020        );
2021        assert_result(
2022            needles
2023                .clone()
2024                .apply(&list_contains(lit(set.clone()), root())),
2025            [Some(true), Some(false), None],
2026        )?;
2027        assert_result(
2028            needles.apply(&in_list(root(), lit(set))),
2029            [Some(true), None, None],
2030        )
2031    }
2032
2033    #[test]
2034    fn list_array_null_elements_under_sql_semantics() -> VortexResult<()> {
2035        let mut ctx = SESSION.create_execution_ctx();
2036        // Lists `[1, null]`, `[2]`, `[3]`, `[]` against a constant needle.
2037        let lists = ListArray::try_new(
2038            PrimitiveArray::from_option_iter([Some(1), None, Some(2), Some(3)]).into_array(),
2039            PrimitiveArray::from_iter(vec![0, 2, 3, 4, 4]).into_array(),
2040            Validity::AllValid,
2041            &mut ctx,
2042        )?
2043        .into_array();
2044        assert_result(
2045            lists.clone().apply(&list_contains(root(), lit(5))),
2046            [Some(false), Some(false), Some(false), Some(false)],
2047        )?;
2048        assert_result(
2049            lists
2050                .clone()
2051                .apply(&list_contains_opts(root(), lit(5), SQL)),
2052            [None, Some(false), Some(false), Some(false)],
2053        )?;
2054        assert_result(
2055            lists.apply(&list_contains_opts(root(), lit(1), SQL)),
2056            [Some(true), Some(false), Some(false), Some(false)],
2057        )
2058    }
2059
2060    #[test]
2061    fn scalar_needle_in_scalar_set_under_sql_semantics() -> VortexResult<()> {
2062        let set = i32_set(vec![Some(2), None]);
2063        let mut ctx = SESSION.create_execution_ctx();
2064        let hit = ConstantArray::new(Scalar::primitive(2i32, Nullability::Nullable), 1)
2065            .into_array()
2066            .apply(&in_list(root(), lit(set.clone())))?;
2067        assert_eq!(
2068            hit.execute_scalar(0, &mut ctx)?.as_bool().value(),
2069            Some(true)
2070        );
2071        let miss = ConstantArray::new(Scalar::primitive(3i32, Nullability::Nullable), 1)
2072            .into_array()
2073            .apply(&in_list(root(), lit(set)))?;
2074        assert!(miss.execute_scalar(0, &mut ctx)?.is_null());
2075        Ok(())
2076    }
2077
2078    #[test]
2079    fn sql_semantics_widen_the_return_dtype_to_the_element_nullability() -> VortexResult<()> {
2080        let dtype = DType::Struct(
2081            StructFields::new(
2082                ["a"].into(),
2083                vec![DType::Primitive(I32, Nullability::NonNullable)],
2084            ),
2085            Nullability::NonNullable,
2086        );
2087        let set = lit(i32_set(vec![Some(1)]));
2088        assert_eq!(
2089            list_contains(set.clone(), col("a")).return_dtype(&dtype)?,
2090            DType::Bool(Nullability::NonNullable)
2091        );
2092        assert_eq!(
2093            in_list(col("a"), set).return_dtype(&dtype)?,
2094            DType::Bool(Nullability::Nullable)
2095        );
2096        Ok(())
2097    }
2098
2099    #[test]
2100    fn options_round_trip_through_serde() -> VortexResult<()> {
2101        use vortex_array::scalar_fn::ScalarFnVTable;
2102        for options in [ListContainsOptions::default(), SQL] {
2103            let bytes = ListContains
2104                .serialize(&options)?
2105                .vortex_expect("serialized");
2106            assert_eq!(ListContains.deserialize(&bytes, &SESSION)?, options);
2107        }
2108        // Files written before the option existed carry no bytes at all.
2109        assert_eq!(
2110            ListContains.deserialize(&[], &SESSION)?,
2111            ListContainsOptions::default()
2112        );
2113        Ok(())
2114    }
2115
2116    #[rstest]
2117    #[case::default(ListContainsOptions::default(), Some(false))]
2118    #[case::sql(SQL, None)]
2119    fn constant_needle_in_constant_set_folds_to_a_constant(
2120        #[case] options: ListContainsOptions,
2121        #[case] expected: Option<bool>,
2122    ) -> VortexResult<()> {
2123        // `3 IN (2, NULL)` is decided at optimization, in an expression and in an array tree.
2124        let set = i32_set(vec![Some(2), None]);
2125        let needle = Scalar::primitive(3i32, Nullability::Nullable);
2126        let expected = match expected {
2127            Some(value) => Scalar::bool(value, Nullability::Nullable),
2128            None => Scalar::null(DType::Bool(Nullability::Nullable)),
2129        };
2130
2131        let expr = list_contains_opts(lit(set.clone()), lit(needle.clone()), options)
2132            .bind(&DType::Primitive(I32, Nullability::Nullable))?
2133            .optimize()?;
2134        assert_eq!(expr.as_opt::<Literal>(), Some(&expected));
2135
2136        let array = ListContains::try_new_opts(
2137            ConstantArray::new(set, 3).into_array(),
2138            ConstantArray::new(needle, 3).into_array(),
2139            options,
2140        )?
2141        .into_array()
2142        .optimize_ctx(&SESSION)?;
2143        assert_eq!(array.as_constant(), Some(&expected));
2144        Ok(())
2145    }
2146
2147    #[test]
2148    fn validity_of_a_constant_set_needs_no_lookup() -> VortexResult<()> {
2149        // Off SQL null semantics the needle alone decides validity. Under them a null element
2150        // makes validity depend on the lookup, which only the fallback computes.
2151        let dtype = DType::Primitive(I32, Nullability::Nullable);
2152        let bound = |expr: Expression| expr.bind(&dtype);
2153        let needle = bound(root())?;
2154        let with_null = lit(i32_set(vec![Some(2), None]));
2155        let without_null = lit(i32_set(vec![Some(2)]));
2156
2157        let expr = bound(list_contains(with_null.clone(), root()))?;
2158        assert_eq!(expr.validity()?, bound::is_not_null(needle.clone()));
2159        let expr = bound(in_list(root(), without_null))?;
2160        assert_eq!(expr.validity()?, bound::is_not_null(needle));
2161        let expr = bound(in_list(root(), with_null))?;
2162        assert_eq!(expr.validity()?, bound::is_not_null(expr));
2163
2164        let expr = bound(list_contains(lit(empty_i32_list()), root()))?;
2165        assert_eq!(expr.validity()?, bound::lit(true));
2166        let null_list = Scalar::null(DType::List(
2167            Arc::new(DType::Primitive(I32, Nullability::Nullable)),
2168            Nullability::Nullable,
2169        ));
2170        let expr = bound(list_contains(lit(null_list), root()))?;
2171        assert_eq!(expr.validity()?, bound::lit(false));
2172        Ok(())
2173    }
2174
2175    #[test]
2176    fn optimize_prepares_a_literal_list_once() -> VortexResult<()> {
2177        // The literal becomes a prepared set that every batch the expression is applied to
2178        // looks up in, and a prepared set is left alone, so optimization reaches a fixed point.
2179        let dtype = DType::Primitive(I32, Nullability::Nullable);
2180        let set = i32_set(vec![Some(2), None]);
2181        let expr = in_list(root(), lit(set.clone())).bind(&dtype)?.optimize()?;
2182        assert_eq!(
2183            expr.child(0)
2184                .as_opt::<PreparedSet>()
2185                .map(PreparedSetData::list),
2186            Some(&set)
2187        );
2188        assert_eq!(expr.optimize()?, expr);
2189
2190        let mut ctx = SESSION.create_execution_ctx();
2191        let first = PrimitiveArray::from_option_iter([Some(1i32), Some(2), None])
2192            .into_array()
2193            .apply_bound(&expr)?;
2194        assert_arrays_eq!(
2195            first,
2196            BoolArray::from_iter([None, Some(true), None]),
2197            &mut ctx
2198        );
2199        let second = PrimitiveArray::from_option_iter([Some(2i32), Some(3)])
2200            .into_array()
2201            .apply_bound(&expr)?;
2202        assert_arrays_eq!(second, BoolArray::from_iter([Some(true), None]), &mut ctx);
2203        Ok(())
2204    }
2205
2206    #[test]
2207    fn optimize_leaves_a_null_list_a_literal() -> VortexResult<()> {
2208        let dtype = DType::Primitive(I32, Nullability::Nullable);
2209        let null_list = Scalar::null(DType::List(Arc::new(dtype.clone()), Nullability::Nullable));
2210        let expr = list_contains(lit(null_list.clone()), root())
2211            .bind(&dtype)?
2212            .optimize()?;
2213        assert_eq!(expr.child(0).as_opt::<Literal>(), Some(&null_list));
2214        Ok(())
2215    }
2216
2217    #[rstest]
2218    #[case::non_nullable_non_sql(Nullability::NonNullable, false, Nullability::NonNullable)]
2219    #[case::non_nullable_sql(Nullability::NonNullable, true, Nullability::NonNullable)]
2220    #[case::nullable_non_sql(Nullability::Nullable, false, Nullability::Nullable)]
2221    #[case::nullable_sql(Nullability::Nullable, true, Nullability::Nullable)]
2222    fn empty_input_preserves_result_dtype(
2223        #[case] input_nullability: Nullability,
2224        #[case] sql_null_semantics: bool,
2225        #[case] expected_nullability: Nullability,
2226    ) -> VortexResult<()> {
2227        let mut ctx = SESSION.create_execution_ctx();
2228        let list_elem_dtype = DType::Primitive(I32, Nullability::NonNullable);
2229        let list_scalar = Scalar::list(
2230            Arc::new(list_elem_dtype),
2231            vec![Scalar::primitive(1i32, Nullability::NonNullable)],
2232            Nullability::NonNullable,
2233        );
2234        let list = ConstantArray::new(list_scalar, 0).into_array();
2235        let needle = PrimitiveArray::empty::<i32>(input_nullability).into_array();
2236        let options = ListContainsOptions { sql_null_semantics };
2237        let result = super::compute_list_contains(&list, &needle, &options, &mut ctx)?;
2238        assert_eq!(result.len(), 0);
2239        assert_eq!(result.dtype(), &DType::Bool(expected_nullability));
2240        Ok(())
2241    }
2242}