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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::sync::Arc;
use std::sync::LazyLock;

use rstest::rstest;
use vortex_array::ArrayRef;
use vortex_array::IntoArray;
use vortex_array::RecursiveCanonical;
use vortex_array::VortexSessionExecute;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::Dict;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::FixedSizeListArray;
use vortex_array::arrays::List;
use vortex_array::arrays::ListArray;
use vortex_array::arrays::ListViewArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::StructArray;
use vortex_array::arrays::list::ListArraySlotsExt;
use vortex_array::arrays::listview::ListViewArraySlotsExt;
use vortex_array::assert_arrays_eq;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::expr::BoundExpression;
use vortex_array::optimizer::ArrayOptimizer;
use vortex_array::scalar::Scalar;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::validity::Validity;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use vortex_error::vortex_err;
use vortex_expr::ArrayExprExt;
use vortex_expr::Expression;
use vortex_expr::Lambda;
use vortex_expr::checked_add;
use vortex_expr::col;
use vortex_expr::eq;
use vortex_expr::get_item;
use vortex_expr::is_not_null;
use vortex_expr::lit;
use vortex_expr::proto::ExprSerializeProtoExt;
use vortex_expr::root;
use vortex_expr::transform::replace;
use vortex_expr::var;
use vortex_session::VortexSession;

use super::ListTransform;
use super::ListTransformOptions;
use super::transform_list;
use crate::expr::list_contains;
use crate::expr::list_transform;

static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);

/// `[[1, 2], null (hiding [i32::MAX]), [3, null]]`
fn lists() -> VortexResult<ArrayRef> {
    list_of(
        PrimitiveArray::from_option_iter([Some(1_i32), Some(2), Some(i32::MAX), Some(3), None])
            .into_array(),
        &[0, 2, 3, 5],
        Validity::from_iter([true, false, true]),
    )
}

/// Rows `{l}`.
fn rows(l: ArrayRef) -> VortexResult<ArrayRef> {
    let len = l.len();
    Ok(
        StructArray::try_new(FieldNames::from(["l"]), vec![l], len, Validity::NonNullable)?
            .into_array(),
    )
}

fn list_of(values: ArrayRef, offsets: &[u32], validity: Validity) -> VortexResult<ArrayRef> {
    let mut ctx = SESSION.create_execution_ctx();
    Ok(ListArray::try_new(
        values,
        PrimitiveArray::from_iter(offsets.iter().copied()).into_array(),
        validity,
        &mut ctx,
    )?
    .into_array())
}

/// The lists of [`lists`] with new elements: the null list keeps no elements.
fn transformed(values: ArrayRef) -> VortexResult<ArrayRef> {
    list_of(
        values,
        &[0, 2, 2, 4],
        Validity::from_iter([true, false, true]),
    )
}

/// `x -> x + 1`, which fails on `i32::MAX`.
fn plus_one() -> VortexResult<Lambda> {
    Lambda::new(["x"], checked_add(var("x"), lit(1_i32)))
}

fn assert_applies(input: ArrayRef, expr: &Expression, expected: ArrayRef) -> VortexResult<()> {
    let actual = input.apply(expr)?;
    let mut ctx = SESSION.create_execution_ctx();
    assert_arrays_eq!(actual, expected, &mut ctx);
    Ok(())
}

#[test]
fn the_lambda_runs_on_every_element() -> VortexResult<()> {
    let expr = list_transform(col("l"), plus_one()?);
    assert_eq!(
        expr.to_string(),
        "vortex.list.transform($.l, (x) -> (@x + 1i32))"
    );
    // The null list's `i32::MAX` would overflow, so it must not reach the lambda.
    let expected = transformed(
        PrimitiveArray::from_option_iter([Some(2_i32), Some(3), Some(4), None]).into_array(),
    )?;
    assert_applies(rows(lists()?)?, &expr, expected)
}

#[test]
fn a_body_of_another_dtype() -> VortexResult<()> {
    let expr = list_transform(root(), Lambda::new(["x"], eq(var("x"), lit(3_i32)))?);
    let expected = transformed(
        BoolArray::from_iter([Some(false), Some(false), Some(true), None]).into_array(),
    )?;
    assert_applies(lists()?, &expr, expected)
}

#[test]
fn a_null_list_without_elements() -> VortexResult<()> {
    // `[[1, 2], null, [3]]` with nothing under the null list.
    let validity = || Validity::from_iter([true, false, true]);
    let lists = list_of(buffer![1_i32, 2, 3].into_array(), &[0, 2, 2, 3], validity())?;
    let expected = list_of(buffer![2_i32, 3, 4].into_array(), &[0, 2, 2, 3], validity())?;
    assert_applies(lists, &list_transform(root(), plus_one()?), expected)
}

#[test]
fn a_sliced_list_skips_a_null_lists_elements() -> VortexResult<()> {
    // `[[1, 2], null (hiding [i32::MAX]), [3], [4]]` sliced to `[null, [3], [4]]`, whose offsets
    // no longer start at 0.
    let lists = list_of(
        buffer![1_i32, 2, i32::MAX, 3, 4].into_array(),
        &[0, 2, 3, 4, 5],
        Validity::from_iter([true, false, true, true]),
    )?
    .slice(1..4)?;
    let expected = list_of(
        buffer![4_i32, 5].into_array(),
        &[0, 0, 1, 2],
        Validity::from_iter([false, true, true]),
    )?;
    assert_applies(lists, &list_transform(root(), plus_one()?), expected)
}

/// `[[1], [2]]` over `[MAX, 1, 2, MAX]`.
fn sliced_list_with_leftovers() -> VortexResult<ArrayRef> {
    list_of(
        buffer![i32::MAX, 1_i32, 2, i32::MAX].into_array(),
        &[1, 2, 3],
        Validity::NonNullable,
    )
}

/// `[[1], [2]]` over `[MAX, 1, 2]`: the lists are back to back, after a leftover.
fn list_view_with_a_leftover_in_front() -> VortexResult<ArrayRef> {
    let mut ctx = SESSION.create_execution_ctx();
    let view = ListViewArray::try_new(
        buffer![i32::MAX, 1_i32, 2].into_array(),
        buffer![1_u32, 2].into_array(),
        buffer![1_u32, 1].into_array(),
        Validity::NonNullable,
        &mut ctx,
    )?;
    // SAFETY: the lists are sorted, with nothing between them.
    Ok(unsafe { view.with_zero_copy_to_list(true) }.into_array())
}

/// `[[1], [2]]` over `[1, MAX, 2]`: the lists skip an element.
fn list_view_with_a_gap() -> VortexResult<ArrayRef> {
    let mut ctx = SESSION.create_execution_ctx();
    Ok(ListViewArray::try_new(
        buffer![1_i32, i32::MAX, 2].into_array(),
        buffer![0_u32, 2].into_array(),
        buffer![1_u32, 1].into_array(),
        Validity::NonNullable,
        &mut ctx,
    )?
    .into_array())
}

/// `x + 1` would overflow on `i32::MAX`, which no list shows.
#[rstest]
#[case::sliced_list(sliced_list_with_leftovers)]
#[case::list_view_with_a_leftover_in_front(list_view_with_a_leftover_in_front)]
#[case::list_view_with_a_gap(list_view_with_a_gap)]
fn a_lambda_that_can_fail_sees_only_the_lists_elements(
    #[case] input: fn() -> VortexResult<ArrayRef>,
) -> VortexResult<()> {
    let expected = list_of(
        buffer![2_i32, 3].into_array(),
        &[0, 1, 2],
        Validity::NonNullable,
    )?;
    assert_applies(input()?, &list_transform(root(), plus_one()?), expected)
}

#[rstest]
#[case::cannot_fail(eq(var("x"), lit(3_i32)))]
#[case::can_fail(checked_add(var("x"), lit(1_i32)))]
fn the_lambda_runs_on_a_slice_without_its_leftovers(#[case] body: Expression) -> VortexResult<()> {
    // Canonicalizing the result drops the leftovers too, so look at the transformed list itself.
    let mut ctx = SESSION.create_execution_ctx();
    let lambda = Lambda::new(["x"], body)?
        .bind(&[DType::Primitive(PType::I32, Nullability::NonNullable)])?;
    let list = sliced_list_with_leftovers()?
        .try_downcast::<List>()
        .map_err(|_| vortex_err!("not a list"))?;
    let result = transform_list(list, &lambda, &mut ctx)?
        .try_downcast::<List>()
        .map_err(|_| vortex_err!("not a list"))?;
    assert_eq!(result.elements().len(), 2);
    Ok(())
}

#[test]
fn a_lambda_that_cannot_fail_runs_on_the_elements_in_place() -> VortexResult<()> {
    // `x = 3` cannot fail, so it runs over the whole elements buffer, the null list's `i32::MAX`
    // included, and nothing is copied.
    let mut ctx = SESSION.create_execution_ctx();
    let result = lists()?
        .apply(&list_transform(
            root(),
            Lambda::new(["x"], eq(var("x"), lit(3_i32)))?,
        ))?
        .execute::<ListViewArray>(&mut ctx)?;
    assert_eq!(result.elements().len(), 5);
    Ok(())
}

#[test]
fn every_list_null() -> VortexResult<()> {
    // `[null (hiding [i32::MAX]), null (hiding [i32::MAX])]`
    let lists = list_of(
        buffer![i32::MAX, i32::MAX].into_array(),
        &[0, 1, 2],
        Validity::from_iter([false, false]),
    )?;
    let expected = list_of(
        PrimitiveArray::from_iter::<[i32; 0]>([]).into_array(),
        &[0, 0, 0],
        Validity::from_iter([false, false]),
    )?;
    assert_applies(lists, &list_transform(root(), plus_one()?), expected)
}

#[test]
fn a_failure_in_a_valid_list_is_an_error() -> VortexResult<()> {
    let lists = list_of(
        buffer![1_i32, i32::MAX].into_array(),
        &[0, 1, 2],
        Validity::from_iter([false, true]),
    )?;
    let mut ctx = SESSION.create_execution_ctx();
    let error = lists
        .apply(&list_transform(root(), plus_one()?))?
        .execute::<RecursiveCanonical>(&mut ctx)
        .map(drop)
        .expect_err("i32::MAX + 1 overflows in a valid list");
    assert!(error.to_string().contains("overflow"), "{error}");
    Ok(())
}

#[test]
fn a_lambda_takes_one_parameter() -> VortexResult<()> {
    let expr = list_transform(root(), Lambda::new(["x", "i"], var("x"))?);
    let error = expr.bind(lists()?.dtype()).expect_err("two parameters");
    assert!(
        error
            .to_string()
            .contains("takes a lambda of one parameter"),
        "{error}"
    );
    Ok(())
}

#[test]
fn struct_elements_read_their_fields() -> VortexResult<()> {
    // `[[{x: 1}, {x: 2}], [{x: 3}]]` under `p -> p.x + 1`
    let points = StructArray::try_new(
        FieldNames::from(["x"]),
        vec![buffer![1_i32, 2, 3].into_array()],
        3,
        Validity::NonNullable,
    )?
    .into_array();
    let expr = list_transform(
        root(),
        Lambda::new(["p"], checked_add(get_item("x", var("p")), lit(1_i32)))?,
    );
    let expected = list_of(
        buffer![2_i32, 3, 4].into_array(),
        &[0, 2, 3],
        Validity::NonNullable,
    )?;
    assert_applies(
        list_of(points, &[0, 2, 3], Validity::NonNullable)?,
        &expr,
        expected,
    )
}

#[test]
fn a_body_can_test_membership_in_a_literal_set() -> VortexResult<()> {
    // `[[1, 2], [3]]` under `x -> list_contains([2, 3], x)`
    let set = Scalar::list(
        Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
        vec![2_i32.into(), 3_i32.into()],
        Nullability::NonNullable,
    );
    let expr = list_transform(
        root(),
        Lambda::new(["x"], list_contains(lit(set), var("x")))?,
    );
    let lists = list_of(
        buffer![1_i32, 2, 3].into_array(),
        &[0, 2, 3],
        Validity::NonNullable,
    )?;
    let expected = list_of(
        BoolArray::from_iter([false, true, true]).into_array(),
        &[0, 2, 3],
        Validity::NonNullable,
    )?;
    assert_applies(lists, &expr, expected)
}

#[test]
fn a_nested_list_result_over_null_lists() -> VortexResult<()> {
    // `[[[1], [2]], null, [[3]]]` under `xs -> list_transform(xs, y -> y + 1)`: the body returns
    // a list, and a null list must not reach the inner body.
    let inner = list_of(
        buffer![1_i32, 2, i32::MAX, 3].into_array(),
        &[0, 1, 2, 3, 4],
        Validity::NonNullable,
    )?;
    let outer = list_of(
        inner,
        &[0, 2, 3, 4],
        Validity::from_iter([true, false, true]),
    )?;
    let expr = list_transform(
        root(),
        Lambda::new(["xs"], list_transform(var("xs"), plus_one()?))?,
    );
    assert_eq!(
        expr.to_string(),
        "vortex.list.transform($, (xs) -> vortex.list.transform(@xs, (x) -> (@x + 1i32)))"
    );
    let inner_expected = list_of(
        buffer![2_i32, 3, 4].into_array(),
        &[0, 1, 2, 3],
        Validity::NonNullable,
    )?;
    let expected = list_of(
        inner_expected,
        &[0, 2, 2, 3],
        Validity::from_iter([true, false, true]),
    )?;
    assert_applies(outer, &expr, expected)
}

#[test]
fn three_nested_lambdas() -> VortexResult<()> {
    // `[[[[1, 2], [3]]], [[[4]]]]` under
    // `x -> list_transform(x, y -> list_transform(y, z -> z + 1))`
    let l = list_of(
        list_of(
            list_of(
                buffer![1_i32, 2, 3, 4].into_array(),
                &[0, 2, 3, 4],
                Validity::NonNullable,
            )?,
            &[0, 2, 3],
            Validity::NonNullable,
        )?,
        &[0, 1, 2],
        Validity::NonNullable,
    )?;
    let innermost = Lambda::new(["z"], checked_add(var("z"), lit(1_i32)))?;
    let middle = Lambda::new(["y"], list_transform(var("y"), innermost))?;
    let expr = list_transform(
        root(),
        Lambda::new(["x"], list_transform(var("x"), middle))?,
    );
    let expected = list_of(
        list_of(
            list_of(
                buffer![2_i32, 3, 4, 5].into_array(),
                &[0, 2, 3, 4],
                Validity::NonNullable,
            )?,
            &[0, 2, 3],
            Validity::NonNullable,
        )?,
        &[0, 1, 2],
        Validity::NonNullable,
    )?;
    assert_applies(l, &expr, expected)
}

#[test]
fn sliced_list_views() -> VortexResult<()> {
    // `[[1, 2], [3], [4, 5]]` as a list view, sliced to `[[3], [4, 5]]`, which leaves unused
    // elements.
    let mut ctx = SESSION.create_execution_ctx();
    let view = list_of(
        buffer![1_i32, 2, 3, 4, 5].into_array(),
        &[0, 2, 3, 5],
        Validity::NonNullable,
    )?
    .execute::<ListViewArray>(&mut ctx)?
    .into_array()
    .slice(1..3)?;
    let expected = list_of(
        buffer![4_i32, 5, 6].into_array(),
        &[0, 1, 3],
        Validity::NonNullable,
    )?;
    assert_applies(view, &list_transform(root(), plus_one()?), expected)
}

#[test]
fn overlapping_list_views() -> VortexResult<()> {
    // `[[3, 4], [1], [2, 3]]`, sharing element 3.
    let mut ctx = SESSION.create_execution_ctx();
    let view = ListViewArray::try_new(
        buffer![1_i32, 2, 3, 4].into_array(),
        buffer![2_u32, 0, 1].into_array(),
        buffer![2_u32, 1, 2].into_array(),
        Validity::NonNullable,
        &mut ctx,
    )?
    .into_array();
    let expr = list_transform(root(), Lambda::new(["x"], eq(var("x"), lit(3_i32)))?);
    let expected = list_of(
        BoolArray::from_iter([true, false, false, false, true]).into_array(),
        &[0, 2, 3, 5],
        Validity::NonNullable,
    )?;
    assert_applies(view, &expr, expected)
}

#[test]
fn fixed_size_lists_are_not_supported_yet() -> VortexResult<()> {
    let fsl = FixedSizeListArray::try_new(
        buffer![1_i32, 2, 3, 4].into_array(),
        2,
        Validity::NonNullable,
        2,
    )?;
    let error = list_transform(root(), plus_one()?)
        .bind(fsl.dtype())
        .expect_err("a fixed-size list is not a list");
    assert!(
        error.to_string().contains("list_transform() takes a List"),
        "{error}"
    );
    Ok(())
}

#[test]
fn a_constant_body() -> VortexResult<()> {
    let expr = list_transform(root(), Lambda::new(["x"], lit(7_i32))?);
    assert_applies(
        lists()?,
        &expr,
        transformed(buffer![7_i32, 7, 7, 7].into_array())?,
    )
}

#[test]
fn no_lists() -> VortexResult<()> {
    let empty = list_of(
        PrimitiveArray::from_iter::<[i32; 0]>([]).into_array(),
        &[0],
        Validity::NonNullable,
    )?;
    let expected = list_of(
        PrimitiveArray::from_iter::<[i32; 0]>([]).into_array(),
        &[0],
        Validity::NonNullable,
    )?;
    assert_applies(empty, &list_transform(root(), plus_one()?), expected)
}

#[test]
fn the_bound_node_is_an_ordinary_call() -> VortexResult<()> {
    let dtype = rows(lists()?)?.dtype().clone();
    let expr = list_transform(col("l"), plus_one()?);
    let bound = expr.bind(&dtype)?;
    // The bound lambda reads the struct of its inputs: `@x` became `$.x`.
    assert_eq!(
        bound.to_string(),
        "vortex.list.transform($.l, (x) -> ($.x + 1i32))"
    );
    assert_eq!(bound.children(), [col("l").bind(&dtype)?]);
    let nullable_i32 = DType::Primitive(PType::I32, Nullability::Nullable);
    assert_eq!(
        bound.dtype(),
        &DType::List(Arc::new(nullable_i32.clone()), Nullability::Nullable)
    );
    assert_eq!(&expr.return_dtype(&dtype)?, bound.dtype());
    assert_eq!(bound.validity()?, is_not_null(col("l")).bind(&dtype)?);
    // Binding the node bound its lambda to the element's dtype.
    assert!(matches!(
        bound.as_::<ListTransform>(),
        ListTransformOptions::Bound(lambda) if lambda.is_bound_to(&[nullable_i32])
    ));
    Ok(())
}

#[test]
fn applying_the_bound_node() -> VortexResult<()> {
    // A scan binds the expression once and applies the bound form to every batch.
    let input = rows(lists()?)?;
    let bound = list_transform(col("l"), plus_one()?).bind(input.dtype())?;
    let expected = transformed(
        PrimitiveArray::from_option_iter([Some(2_i32), Some(3), Some(4), None]).into_array(),
    )?;
    let mut ctx = SESSION.create_execution_ctx();
    assert_arrays_eq!(input.apply_bound(&bound)?, expected, &mut ctx);
    Ok(())
}

#[test]
fn a_lambda_bound_to_another_element_dtype_is_an_error() -> VortexResult<()> {
    let list = |elements| {
        DType::List(
            Arc::new(DType::Primitive(PType::I32, elements)),
            Nullability::NonNullable,
        )
    };
    let bound = list_transform(root(), plus_one()?).bind(&list(Nullability::NonNullable))?;
    let error = bound
        .clone()
        .with_children([BoundExpression::new_root(list(Nullability::Nullable))])
        .expect_err("bound to i32, rebuilt over i32?");
    let options = bound.as_::<ListTransform>();
    let return_dtype_error = ListTransform
        .return_dtype(options, &[list(Nullability::Nullable)])
        .expect_err("bound to i32, given i32?");
    for error in [error, return_dtype_error] {
        assert!(
            error
                .to_string()
                .contains("is bound to element dtype i32, not i32?"),
            "{error}"
        );
    }
    Ok(())
}

#[test]
fn a_list_in_a_nested_field() -> VortexResult<()> {
    // Rows `{s: {l}}`.
    let input = StructArray::try_new(
        FieldNames::from(["s"]),
        vec![rows(lists()?)?],
        3,
        Validity::NonNullable,
    )?
    .into_array();
    let expr = list_transform(get_item("l", col("s")), plus_one()?);
    assert_eq!(
        expr.to_string(),
        "vortex.list.transform($.s.l, (x) -> (@x + 1i32))"
    );
    let expected = transformed(
        PrimitiveArray::from_option_iter([Some(2_i32), Some(3), Some(4), None]).into_array(),
    )?;
    assert_applies(input, &expr, expected)
}

#[test]
fn an_infallible_transform_pushes_into_dictionary_values() -> VortexResult<()> {
    let values = list_of(
        buffer![1_i32, 2, 3].into_array(),
        &[0, 2, 3],
        Validity::NonNullable,
    )?;
    let dict = DictArray::try_new(buffer![0_u8, 1, 0, 1].into_array(), values)?.into_array();
    let expr = list_transform(root(), Lambda::new(["x"], eq(var("x"), lit(1_i32)))?);

    let actual = dict.apply(&expr)?.optimize_ctx(&SESSION)?;
    assert!(actual.is::<Dict>(), "{actual}");
    let expected = list_of(
        BoolArray::from_iter([true, false, false, true, false, false]).into_array(),
        &[0, 2, 3, 5, 6],
        Validity::NonNullable,
    )?;
    let mut ctx = SESSION.create_execution_ctx();
    assert_arrays_eq!(actual, expected, &mut ctx);
    Ok(())
}

#[test]
fn a_fallible_transform_skips_unused_dictionary_values() -> VortexResult<()> {
    // Dictionary values `[[1], [i32::MAX]]`, of which the codes use only the first.
    let values = list_of(
        buffer![1_i32, i32::MAX].into_array(),
        &[0, 1, 2],
        Validity::NonNullable,
    )?;
    let dict = DictArray::try_new(buffer![0_u8, 0].into_array(), values)?.into_array();
    let expected = list_of(
        buffer![2_i32, 2].into_array(),
        &[0, 1, 2],
        Validity::NonNullable,
    )?;
    assert_applies(dict, &list_transform(root(), plus_one()?), expected)
}

#[test]
fn lambdas_are_not_serializable_yet() -> VortexResult<()> {
    let expr = list_transform(col("l"), Lambda::new(["x"], var("x"))?);
    let error = expr
        .serialize_proto()
        .expect_err("lambdas are not serializable");
    assert!(error.to_string().contains("is not serializable"), "{error}");
    Ok(())
}

#[test]
fn replace_leaves_a_lambda_alone() -> VortexResult<()> {
    // The lambda is in `list_transform`'s options, not among its children.
    let expr = list_transform(col("l"), Lambda::new(["x"], checked_add(var("x"), lit(1)))?);
    assert_eq!(replace(expr.clone(), &var("x"), lit(0)), expr);
    assert_eq!(
        replace(expr, &root(), col("s")).to_string(),
        "vortex.list.transform($.s.l, (x) -> (@x + 1i32))"
    );
    Ok(())
}