vortex-functions 0.94.0

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

use std::sync::LazyLock;

use rstest::rstest;
use vortex_array::ArrayRef;
use vortex_array::ExecutionCtx;
use vortex_array::IntoArray;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::Bool;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::Chunked;
use vortex_array::arrays::ChunkedArray;
use vortex_array::arrays::ConstantArray;
use vortex_array::arrays::DecimalArray;
use vortex_array::arrays::Dict;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::FilterArray;
use vortex_array::arrays::FixedSizeListArray;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::ScalarFn;
use vortex_array::arrays::ScalarFnArray;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::VarBinViewArray;
use vortex_array::arrays::chunked::ChunkedArrayExt;
use vortex_array::arrays::dict::DictArraySlotsExt;
use vortex_array::arrays::scalar_fn::ScalarFnArrayExt;
use vortex_array::assert_arrays_eq;
use vortex_array::builders::builder_with_capacity_in;
use vortex_array::dtype::DType;
use vortex_array::dtype::DecimalDType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::dtype::extension::ExtDType;
use vortex_array::dtype::extension::ExtId;
use vortex_array::dtype::extension::ExtVTable;
use vortex_array::dtype::i256;
use vortex_array::optimizer::ArrayOptimizer;
use vortex_array::scalar::Scalar;
use vortex_array::scalar::ScalarValue;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::scalar_fn::TypedScalarFnInstance;
use vortex_array::validity::Validity;
use vortex_buffer::BitBuffer;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_expr::ArrayExprExt;
use vortex_expr::lit;
use vortex_expr::root;
use vortex_mask::Mask;
use vortex_session::VortexSession;

use super::PreparedSet;
use crate::expr::list_contains;
use crate::list_contains::ListContains;
use crate::list_contains::ListContainsOptions;
use crate::list_contains::PreparedSetData;

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

    vortex_array::initialize(&session);

    crate::initialize(&session);

    session
});

/// Prepares the non-null list scalar `list`.
fn prepare(list: &Scalar) -> VortexResult<PreparedSetData> {
    PreparedSetData::try_new(list.clone())
}

/// Prepares the non-null list scalar `list` as a set repeated `len` times.
fn prepare_array(list: &Scalar, len: usize) -> VortexResult<ArrayRef> {
    PreparedSet::try_new_array(list.clone(), len)
}

/// A non-null list scalar of the rows of `elements`.
fn list_scalar(elements: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Scalar> {
    let values = (0..elements.len())
        .map(|idx| elements.execute_scalar(idx, ctx))
        .collect::<VortexResult<Vec<_>>>()?;
    Ok(Scalar::list(
        elements.dtype().clone(),
        values,
        Nullability::NonNullable,
    ))
}

fn nested_needles() -> ArrayRef {
    let mut ctx = SESSION.create_execution_ctx();
    ListArray::try_new(
        PrimitiveArray::from_option_iter([Some(1i32), None, Some(2), None, Some(9)]).into_array(),
        buffer![0u32, 2, 2, 4, 5].into_array(),
        Validity::from(BitBuffer::from_iter([true, false, true, true])),
        &mut ctx,
    )
    .unwrap()
    .into_array()
}

fn map_needles() -> ArrayRef {
    let ctx = SESSION.create_execution_ctx();
    let dtype = DType::map(
        DType::Primitive(PType::I32, Nullability::NonNullable),
        DType::Utf8(Nullability::Nullable),
        false,
        Nullability::Nullable,
    )
    .unwrap();
    let mut builder = builder_with_capacity_in(&dtype, 4, ctx.allocator());
    for key in [Some(1i32), None, Some(2), Some(9)] {
        let scalar = match key {
            Some(key) => Scalar::map(
                dtype.clone(),
                [(key.into(), Scalar::null(DType::Utf8(Nullability::Nullable)))],
            ),
            None => Scalar::null(dtype.clone()),
        };
        builder.append_scalar(&scalar).unwrap();
    }
    builder.finish()
}

fn struct_needles() -> ArrayRef {
    StructArray::from_fields(&[("list", nested_needles())])
        .unwrap()
        .into_array()
}

#[rstest]
#[case::list(nested_needles())]
#[case::map(map_needles())]
#[case::struct_of_lists(struct_needles())]
#[case::fixed_size_list(FixedSizeListArray::new(
    PrimitiveArray::from_option_iter([
        Some(1i32), None, Some(2), None, Some(9), None, Some(8), None,
    ]).into_array(),
    2, Validity::NonNullable, 4,
).into_array())]
fn test_row_set_returns_membership_bits(
    #[case] needles: ArrayRef,
    #[values(false, true)] sql_null_semantics: bool,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let dtype = needles.dtype().as_nullable();
    // Unsorted, repeated members and a top-level null exercise normalization and SQL's
    // unknown non-match independently of any nulls nested inside the members.
    let members = [2, 0, 2]
        .map(|idx| needles.execute_scalar(idx, &mut ctx)?.cast(&dtype))
        .into_iter()
        .collect::<VortexResult<Vec<_>>>()?;
    let mut elements = members.clone();
    elements.push(Scalar::null(dtype.clone()));
    let list = Scalar::list(dtype, elements, Nullability::NonNullable);
    let options = ListContainsOptions { sql_null_semantics };
    let set = prepare(&list)?;
    let result = set.contains(&needles, &options, &mut ctx)?;
    // The old fallback returned a lazy OR tree here.
    assert!(result.is::<Bool>());
    let expected = (0..needles.len())
        .map(|idx| {
            let value = needles.execute_scalar(idx, &mut ctx)?;
            Ok(if value.is_null() {
                None
            } else if members.contains(&value) {
                Some(true)
            } else if sql_null_semantics {
                None
            } else {
                Some(false)
            })
        })
        .collect::<VortexResult<Vec<_>>>()?;

    // The list is not null, so only a null needle can make the result null. Under SQL null
    // semantics the null element also can, by leaving a non-match unknown.
    let nullability = needles.dtype().nullability() | Nullability::from(sql_null_semantics);
    assert_eq!(result.dtype(), &DType::Bool(nullability));

    let validity = match nullability {
        Nullability::NonNullable => Validity::NonNullable,
        Nullability::Nullable => Validity::from_iter(expected.iter().map(Option::is_some)),
    };
    let expected = BoolArray::new(
        BitBuffer::from_iter(expected.into_iter().map(Option::unwrap_or_default)),
        validity,
    );
    assert_arrays_eq!(result, expected, &mut ctx);
    Ok(())
}

#[rstest]
fn test_decimal_bitmap_across_storage_widths(
    #[values(2, 4, 9, 18, 38, 76)] precision: u8,
    #[values(false, true)] sql_null_semantics: bool,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let decimal = DecimalDType::new(precision, 1);
    let dtype = DType::Decimal(decimal, Nullability::Nullable);
    let mut elements: Vec<_> = [1i8, -2, 1]
        .map(|value| Scalar::decimal(value.into(), decimal, Nullability::Nullable))
        .into();
    elements.push(Scalar::null(dtype.clone()));
    let list = Scalar::list(dtype, elements, Nullability::NonNullable);
    let needles =
        DecimalArray::from_option_iter([Some(-2i8), Some(0), Some(1), None], decimal).into_array();
    let options = ListContainsOptions { sql_null_semantics };
    let set = prepare(&list)?;
    let non_match = (!sql_null_semantics).then_some(false);
    assert_arrays_eq!(
        set.contains(&needles, &options, &mut ctx)?,
        BoolArray::from_iter([Some(true), non_match, Some(true), None]),
        &mut ctx
    );
    Ok(())
}

#[rstest]
#[case::dense_i128(38, i256::from_i128(1i128 << 100), true)]
#[case::sparse_i128(38, i256::from_i128(1i128 << 100), false)]
#[case::dense_i256(76, i256::from_parts(0, 1i128 << 72), true)]
#[case::sparse_i256(76, i256::from_parts(0, 1i128 << 72), false)]
fn test_decimal_wide_values(
    #[case] precision: u8,
    #[case] base: i256,
    #[case] dense: bool,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let decimal = DecimalDType::new(precision, 2);
    let second = if dense { base + i256::ONE } else { -base };
    let list = Scalar::list(
        DType::Decimal(decimal, Nullability::NonNullable),
        [second, base, second]
            .map(|v| Scalar::decimal(v.into(), decimal, Nullability::NonNullable))
            .into(),
        Nullability::NonNullable,
    );
    // The last non-null value shares the low 64 bits of a member but must not match it.
    let needles = DecimalArray::from_option_iter::<i256, _>(
        [
            Some(base),
            Some(second),
            Some(base - i256::ONE),
            Some(i256::ZERO),
            Some(base + i256::from_i128(1i128 << 64)),
            None,
        ],
        decimal,
    )
    .into_array();
    let set = prepare(&list)?;
    assert_arrays_eq!(
        set.contains(&needles, &ListContainsOptions::default(), &mut ctx)?,
        BoolArray::from_iter([
            Some(true),
            Some(true),
            Some(false),
            Some(false),
            Some(false),
            None,
        ]),
        &mut ctx
    );
    Ok(())
}

#[rstest]
#[case::bitmap(
    PrimitiveArray::from_option_iter([Some(5i64), Some(-3), Some(5)]).into_array(),
    PrimitiveArray::from_option_iter([Some(-3i64), Some(4), Some(i64::MIN), None]).into_array(),
    [Some(true), Some(false), Some(false), None],
)]
#[case::unsigned_in_signed_order(
    PrimitiveArray::from_option_iter([Some(u64::MAX), Some(0), Some(1 << 40)]).into_array(),
    PrimitiveArray::from_option_iter([Some(1u64 << 40), Some(1), Some(u64::MAX), Some(0)])
        .into_array(),
    [Some(true), Some(false), Some(true), Some(true)],
)]
#[case::float_bits(
    PrimitiveArray::from_option_iter([Some(0.0f64), Some(f64::NAN)]).into_array(),
    PrimitiveArray::from_option_iter([Some(-0.0f64), Some(0.0), Some(f64::NAN), Some(1.5)])
        .into_array(),
    [Some(false), Some(true), Some(true), Some(false)],
)]
fn test_primitive_integers(
    #[case] elements: ArrayRef,
    #[case] needles: ArrayRef,
    #[case] expected: [Option<bool>; 4],
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let set = PreparedSetData::try_new(list_scalar(&elements, &mut ctx)?)?;
    assert_arrays_eq!(
        set.contains(&needles, &ListContainsOptions::default(), &mut ctx)?,
        BoolArray::from_iter(expected),
        &mut ctx
    );
    Ok(())
}

/// Needles longer than one lookup batch, in an encoding other than primitive, are looked up a
/// batch at a time.
#[test]
fn test_compressed_needles_in_batches() -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let set = PreparedSetData::try_new(list_scalar(
        &buffer![3i64, 9000, 20_001].into_array(),
        &mut ctx,
    )?)?;
    let values = |range: std::ops::Range<i64>| {
        PrimitiveArray::from_option_iter(range.map(|v| (v % 7 != 0).then_some(v))).into_array()
    };
    let needles = ChunkedArray::try_new(
        vec![values(0..12_000), values(12_000..25_000)],
        DType::Primitive(PType::I64, Nullability::Nullable),
    )?
    .into_array();
    let expected = BoolArray::from_iter(
        (0..25_000i64).map(|v| (v % 7 != 0).then_some(matches!(v, 3 | 9000 | 20_001))),
    );
    assert_arrays_eq!(
        set.contains(&needles, &ListContainsOptions::default(), &mut ctx)?,
        expected,
        &mut ctx
    );
    Ok(())
}

/// The set `{2, null}` of nullable `i32`.
fn set_with_null() -> Scalar {
    let element = DType::Primitive(PType::I32, Nullability::Nullable);
    Scalar::list(
        element.clone(),
        vec![
            Scalar::primitive(2i32, Nullability::Nullable),
            Scalar::null(element),
        ],
        Nullability::NonNullable,
    )
}

#[test]
fn test_prepared_set_rows_are_the_constant_list() -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let set = prepare_array(&set_with_null(), 4)?;

    assert_arrays_eq!(set, ConstantArray::new(set_with_null(), 4), &mut ctx);

    // A slice and a filter keep the haystack instead of building it again.
    let prepared = PreparedSet::set_of(&set).expect("prepared set");
    let sliced = set.slice(1..3)?.optimize_ctx(&SESSION)?;
    assert_eq!(sliced.len(), 2);
    assert!(PreparedSet::set_of(&sliced).is_some_and(|sliced| sliced.shares_set_with(prepared)));
    let filtered = set
        .filter(Mask::from_iter([true, false, true, true]))?
        .optimize_ctx(&SESSION)?;
    assert_eq!(filtered.len(), 3);
    assert!(
        PreparedSet::set_of(&filtered).is_some_and(|filtered| filtered.shares_set_with(prepared))
    );
    Ok(())
}

#[rstest]
#[case::default(ListContainsOptions::default(), [Some(false), Some(true), None, Some(false)])]
#[case::sql(
    ListContainsOptions { sql_null_semantics: true },
    [None, Some(true), None, None]
)]
fn test_list_contains_looks_up_in_a_prepared_set_list(
    #[case] options: ListContainsOptions,
    #[case] expected: [Option<bool>; 4],
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let set = prepare_array(&set_with_null(), 4)?;
    let needles =
        PrimitiveArray::from_option_iter([Some(1i32), Some(2), None, Some(3)]).into_array();

    let result = ListContains::try_new_opts(set, needles, options)?.into_array();
    assert_arrays_eq!(result, BoolArray::from_iter(expected), &mut ctx);
    Ok(())
}

#[rstest]
#[case::default(ListContainsOptions::default(), Some(false))]
#[case::sql(ListContainsOptions { sql_null_semantics: true }, None)]
fn test_constant_needle_gives_a_constant(
    #[case] options: ListContainsOptions,
    #[case] expected: Option<bool>,
) -> VortexResult<()> {
    // `3 IN (2, NULL)` against the prepared set is looked up once, and gives a constant.
    let mut ctx = SESSION.create_execution_ctx();
    let set = prepare_array(&set_with_null(), 4)?;
    let needle = ConstantArray::new(Scalar::primitive(3i32, Nullability::Nullable), 4).into_array();

    let result = ListContains::try_new_opts(set, needle, options)?
        .into_array()
        .execute::<ArrayRef>(&mut ctx)?;
    let expected = match expected {
        Some(value) => Scalar::bool(value, Nullability::Nullable),
        None => Scalar::null(DType::Bool(Nullability::Nullable)),
    };
    assert_eq!(result.as_constant(), Some(&expected));
    Ok(())
}

#[test]
fn test_constant_row_needle_looks_up_one_row() -> VortexResult<()> {
    // A row haystack cannot look a scalar needle up, so execution looks up one row.
    let mut ctx = SESSION.create_execution_ctx();
    let needles = nested_needles();
    let dtype = needles.dtype().as_nullable();
    let member = needles.execute_scalar(2, &mut ctx)?.cast(&dtype)?;
    let list = Scalar::list(dtype, vec![member.clone()], Nullability::NonNullable);

    let set = prepare_array(&list, 4)?;
    let needle = ConstantArray::new(member, 4).into_array();
    let result = ListContains::try_new_opts(set, needle, ListContainsOptions::default())?
        .into_array()
        .execute::<ArrayRef>(&mut ctx)?;
    assert_eq!(
        result.as_constant(),
        Some(&Scalar::bool(true, Nullability::Nullable))
    );
    Ok(())
}

#[rstest]
#[case::default(ListContainsOptions::default(), [Some(true), Some(false), None])]
#[case::sql(ListContainsOptions { sql_null_semantics: true }, [Some(true), None, None])]
fn test_result_from_bits_applies_null_semantics(
    #[case] options: ListContainsOptions,
    #[case] expected: [Option<bool>; 3],
) -> VortexResult<()> {
    // Against `{2, null}`: a match, a non-match, and a null needle whose bit has no effect.
    let mut ctx = SESSION.create_execution_ctx();
    let set = prepare(&set_with_null())?;
    let needle_dtype = DType::Primitive(PType::I32, Nullability::Nullable);
    let bits = BitBuffer::from_iter([true, false, true]);
    let validity = Validity::from_iter([true, true, false]);

    let result = set.result_from_bits(bits, validity, &needle_dtype, &options)?;
    assert_arrays_eq!(result, BoolArray::from_iter(expected), &mut ctx);
    Ok(())
}

#[test]
fn test_result_from_bits_rejects_mismatched_needles() -> VortexResult<()> {
    let set = prepare(&set_with_null())?;
    let options = ListContainsOptions::default();
    let bits = BitBuffer::from_iter([true, false]);

    // A validity with a null keeps its row count; an all-valid one folds to `AllValid`, which
    // has none to check.
    let long_validity = Validity::from_iter([true, false, true]);
    let needle_dtype = DType::Primitive(PType::I32, Nullability::Nullable);
    assert!(
        set.result_from_bits(bits.clone(), long_validity, &needle_dtype, &options)
            .is_err()
    );

    let wrong_dtype = DType::Primitive(PType::I64, Nullability::Nullable);
    assert!(
        set.result_from_bits(bits, Validity::AllValid, &wrong_dtype, &options)
            .is_err()
    );
    Ok(())
}

#[test]
fn test_bytes_set_short_and_long_views() -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let elements = VarBinViewArray::from_iter_nullable_str([
        Some("ab"),
        Some(""),
        Some("a long string with suffix A"),
        Some("another long string"),
        None,
        Some("ab"),
    ])
    .into_array();
    let set = PreparedSetData::try_new(list_scalar(&elements, &mut ctx)?)?;

    // "abc" shares the prefix of a short element, and "... suffix B" shares the head of a long
    // one: length and first 4 bytes. Neither is an element.
    let needles = VarBinViewArray::from_iter_nullable_str([
        Some("ab"),
        Some("abc"),
        Some(""),
        Some("a long string with suffix B"),
        Some("another long string"),
        Some("a string never in the set"),
        None,
    ])
    .into_array();

    assert_arrays_eq!(
        set.contains(&needles, &ListContainsOptions::default(), &mut ctx)?,
        BoolArray::from_iter([
            Some(true),
            Some(false),
            Some(true),
            Some(false),
            Some(true),
            Some(false),
            None,
        ]),
        &mut ctx
    );
    Ok(())
}

fn chunked_needles() -> VortexResult<ArrayRef> {
    Ok(ChunkedArray::try_new(
        vec![
            PrimitiveArray::from_option_iter([Some(1i32), Some(2)]).into_array(),
            PrimitiveArray::from_option_iter::<i32, _>([]).into_array(),
            PrimitiveArray::from_option_iter([None, Some(3), Some(2)]).into_array(),
        ],
        DType::Primitive(PType::I32, Nullability::Nullable),
    )?
    .into_array())
}

/// The set that the list of a `list_contains` node holds.
fn list_set(node: &ArrayRef) -> PreparedSetData {
    PreparedSet::set_of(node.as_::<ScalarFn>().get_child(0))
        .expect("the list of the node is a prepared set")
        .clone()
}

/// Asserts that `array` was pushed into its chunks, and that every non-empty chunk looks up in
/// one set.
fn assert_chunks_share_one_set(array: &ArrayRef) {
    let chunked = array.as_::<Chunked>();
    let sets: Vec<_> = chunked
        .iter_chunks()
        .filter(|chunk| !chunk.is_empty())
        .map(list_set)
        .collect();
    assert!(sets.len() > 1);
    assert!(sets.iter().all(|set| set.shares_set_with(&sets[0])));
}

#[rstest]
#[case::default(
    ListContainsOptions::default(),
    [Some(false), Some(true), None, Some(false), Some(true)],
)]
#[case::sql(
    ListContainsOptions { sql_null_semantics: true },
    [None, Some(true), None, None, Some(true)],
)]
fn test_constant_list_over_chunked_needles(
    #[case] options: ListContainsOptions,
    #[case] expected: [Option<bool>; 5],
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let needles = chunked_needles()?;
    let list = ConstantArray::new(set_with_null(), needles.len()).into_array();

    // The list is prepared before the push-down, so every chunk gets a slice of the one set.
    let array = ListContains::try_new_opts(list, needles, options)?
        .into_array()
        .optimize_ctx(&SESSION)?;
    assert_chunks_share_one_set(&array);

    assert_arrays_eq!(array, BoolArray::from_iter(expected), &mut ctx);
    Ok(())
}

#[test]
fn test_optimized_expression_over_chunked_needles() -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let needles = chunked_needles()?;
    let expr = list_contains(lit(set_with_null()), root())
        .bind(needles.dtype())?
        .optimize()?;

    let array = needles.apply_bound(&expr)?.optimize_ctx(&SESSION)?;
    assert_chunks_share_one_set(&array);

    assert_arrays_eq!(
        array,
        BoolArray::from_iter([Some(false), Some(true), None, Some(false), Some(true)]),
        &mut ctx
    );
    Ok(())
}

/// A prepared set has no children, so its `ScalarFnArray` takes an explicit length.
#[test]
fn test_scalar_fn_without_children_requires_explicit_len() -> VortexResult<()> {
    let list = Scalar::list(
        DType::Primitive(PType::I32, Nullability::NonNullable),
        vec![Scalar::from(1i32)],
        Nullability::NonNullable,
    );
    let scalar_fn =
        TypedScalarFnInstance::new(PreparedSet, PreparedSetData::try_new(list.clone())?).erased();

    let Err(err) = ScalarFnArray::try_new(scalar_fn.clone(), vec![]) else {
        panic!("ScalarFnArray::try_new should reject zero children");
    };
    assert!(
        err.to_string()
            .contains("ScalarFnArray length cannot be inferred without children")
    );

    let scalar_fn_array = ScalarFnArray::try_new_with_len(scalar_fn, vec![], 3)?;
    assert_eq!(scalar_fn_array.len(), 3);
    assert_eq!(scalar_fn_array.child_count(), 0);
    assert_arrays_eq!(
        scalar_fn_array,
        ConstantArray::new(list, 3),
        &mut SESSION.create_execution_ctx()
    );
    Ok(())
}

/// Filtering a prepared set, which has no children, keeps a prepared set of the filtered length.
#[test]
fn test_filter_pushdown_without_children() -> VortexResult<()> {
    let list = Scalar::list(
        DType::Primitive(PType::I32, Nullability::NonNullable),
        vec![Scalar::from(7i32)],
        Nullability::NonNullable,
    );
    let array = PreparedSet::try_new_array(list.clone(), 3)?;
    let result = FilterArray::try_new(array, Mask::from_iter([true, false, true]))?
        .into_array()
        .optimize_ctx(&SESSION)?;

    assert_eq!(result.as_::<ScalarFn>().nchildren(), 0);
    assert_eq!(result.len(), 2);
    assert_arrays_eq!(
        result,
        ConstantArray::new(list, 2),
        &mut SESSION.create_execution_ctx()
    );
    Ok(())
}

/// An extension type whose metadata serializer always fails, standing in for a plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
struct FailingMetadata;

impl ExtVTable for FailingMetadata {
    type Metadata = usize;
    type StoredMetadata = Self::Metadata;
    type NativeValue<'a> = &'a str;

    #[expect(clippy::disallowed_methods, reason = "test-only id")]
    fn id(&self) -> ExtId {
        ExtId::new("test.failing_metadata")
    }

    fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
        vortex_bail!("metadata serializer failed")
    }

    fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult<Self::StoredMetadata> {
        Ok(0)
    }

    fn metadata_from_storage(
        &self,
        stored_metadata: Self::StoredMetadata,
        _storage_dtype: &DType,
    ) -> VortexResult<Self::Metadata> {
        Ok(stored_metadata)
    }

    fn storage_dtype(_metadata: &Self::Metadata) -> DType {
        DType::Primitive(PType::I32, Nullability::NonNullable)
    }

    fn unpack_native<'a>(
        _ext_dtype: &'a ExtDType<Self>,
        _storage_value: &'a ScalarValue,
    ) -> VortexResult<Self::NativeValue<'a>> {
        Ok("")
    }
}

#[test]
fn serialize_propagates_extension_metadata_error() -> VortexResult<()> {
    let scalar =
        Scalar::extension::<FailingMetadata>(0, Scalar::primitive(1i32, Nullability::NonNullable));
    let list = Scalar::list(
        scalar.dtype().clone(),
        vec![scalar],
        Nullability::NonNullable,
    );
    let set = PreparedSetData::try_new(list)?;
    let err = PreparedSet
        .serialize(&set)
        .expect_err("serializing an extension whose metadata serializer fails must fail");
    assert!(
        err.to_string().contains("metadata serializer failed"),
        "{err}"
    );
    Ok(())
}

/// Dictionary needles with a null code or a null value, against a set that is empty or not.
#[rstest]
#[case::default(null_code_needles(), ListContainsOptions::default(), set_with_null(), vec![Some(true), Some(false), None, Some(true)])]
#[case::sql(null_code_needles(), ListContainsOptions { sql_null_semantics: true }, set_with_null(), vec![Some(true), None, None, Some(true)])]
// Off SQL null semantics an empty list answers `false` even for the null code.
#[case::empty(null_code_needles(), ListContainsOptions::default(), empty_i32_set(), vec![Some(false); 4])]
#[case::empty_sql(null_code_needles(), ListContainsOptions { sql_null_semantics: true }, empty_i32_set(), vec![Some(false), Some(false), None, Some(false)])]
#[case::null_value(null_value_needles(), ListContainsOptions::default(), set_with_null(), vec![Some(true), Some(false), Some(true), None, Some(false)])]
fn test_dictionary_needles(
    #[case] needles: VortexResult<ArrayRef>,
    #[case] options: ListContainsOptions,
    #[case] set: Scalar,
    #[case] expected: Vec<Option<bool>>,
) -> VortexResult<()> {
    let mut ctx = SESSION.create_execution_ctx();
    let needles = needles?;
    let list = ConstantArray::new(set, needles.len()).into_array();

    let array = ListContains::try_new_opts(list, needles, options)?
        .into_array()
        .optimize_ctx(&SESSION)?;

    // The rule took the node: it is a dictionary of answers, or a constant for the empty list.
    assert!(!array.is::<ScalarFn>());

    // The prepared list still lets the function into the values of the dictionary.
    if let Some(dict) = array.as_opt::<Dict>() {
        let values = dict.values().clone();
        assert!(PreparedSet::set_of(values.as_::<ScalarFn>().get_child(0)).is_some());
    }

    assert_arrays_eq!(array, BoolArray::from_iter(expected), &mut ctx);
    Ok(())
}

/// Dictionary needles of `i32` with a null code.
fn null_code_needles() -> VortexResult<ArrayRef> {
    Ok(DictArray::try_new(
        PrimitiveArray::from_option_iter([Some(0u8), Some(1), None, Some(0)]).into_array(),
        buffer![2i32, 3].into_array(),
    )?
    .into_array())
}

/// Dictionary needles of `i32` with a null value.
fn null_value_needles() -> VortexResult<ArrayRef> {
    Ok(DictArray::try_new(
        buffer![0u8, 1, 0, 2, 1].into_array(),
        PrimitiveArray::from_option_iter([Some(2i32), Some(3), None]).into_array(),
    )?
    .into_array())
}

/// The empty set of nullable `i32`.
fn empty_i32_set() -> Scalar {
    Scalar::list(
        DType::Primitive(PType::I32, Nullability::Nullable),
        vec![],
        Nullability::NonNullable,
    )
}