vortex-scan 0.94.0

Scanning operations for Vortex
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Plans reads from structs stored as separate children.
//!
//! A [`Pack`] assembles the field children and, for a nullable struct, a validity child. An
//! expression that uses part of the struct can read the relevant children directly.

pub(crate) mod execute;

use std::borrow::Cow;
use std::iter;
use std::ops::Range;

use vortex_array::EmptyMetadata;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldName;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::StructFields;
use vortex_array::expr::BoundExpression;
use vortex_array::scalar_fn::builtin::get_item::GetItem;
use vortex_array::scalar_fn::builtin::is_not_null::IsNotNull;
use vortex_array::scalar_fn::builtin::mask::Mask as MaskFn;
use vortex_array::scalar_fn::builtin::pack::Pack as PackFn;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_err;
use vortex_expr as unbound;
use vortex_expr::Expression;
use vortex_expr::bound;
use vortex_expr::traversal::NodeExt;
use vortex_expr::traversal::NodeRewriter;
use vortex_expr::traversal::Transformed;
use vortex_functions::is_null::IsNull;
use vortex_functions::select::FieldSelection;
use vortex_functions::select::Select;
use vortex_mask::Mask;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;

use crate::execution::operators::OnceSource;
use crate::execution::operators::PackSource;
use crate::execution::operators::WrapStage;
use crate::execution::operators::empty_struct;
use crate::execution::pipeline::Chain;
use crate::execution::pipeline::Compiler;
use crate::plan::Eval;
use crate::plan::EvalPlan;
use crate::plan::Plan;
use crate::plan::PlanId;
use crate::plan::PlanParts;
use crate::plan::PlanRef;
use crate::plan::PlanSlots;
use crate::plan::PlanVTable;
use crate::plan::optimizer::PlanParentReduceRule;
use crate::plan::partition::PartitionRule;
use crate::plan::partition::PartitionSession;
use crate::plan::partition::PartitionedExpression;
use crate::plan::partition::PartitionedPlan;
use crate::plan::partition::Partitions;
use crate::plan::partition::PlanSlot;
use crate::plan::partition::Slots;
use crate::plan::partition::positional_name;

/// Assembles a struct from a validity slot followed by one slot per field.
///
/// The slots match those of a struct array and a struct layout: slot
/// [`VALIDITY_SLOT`](Self::VALIDITY_SLOT) holds the validity, present exactly when the struct is
/// nullable, and field `i` is in slot `FIELDS_OFFSET + i`.
#[derive(Clone, Debug)]
pub struct Pack;

impl Pack {
    /// The slot holding struct validity, absent when the struct is non-nullable.
    pub const VALIDITY_SLOT: usize = 0;
    /// The slot of field zero; field `i` is in slot `FIELDS_OFFSET + i`.
    pub const FIELDS_OFFSET: usize = 1;
}

/// Operator-specific struct assembly data.
#[derive(Clone, Debug)]
pub struct PackData;

/// A plan that assembles a struct from its children.
pub type PackPlan = Plan<Pack>;

impl PackPlan {
    /// Creates a struct assembly from potentially unbuilt slots without validation.
    ///
    /// # Safety
    ///
    /// `slots` must hold a validity slot followed by one slot per field. The validity slot must
    /// be present exactly when `nullability` is nullable and produce non-nullable booleans. Every
    /// field slot must be present with its field dtype, and every child must have `row_count`
    /// rows.
    pub unsafe fn from_slots_unchecked(
        fields: StructFields,
        nullability: Nullability,
        row_count: u64,
        slots: PlanSlots,
    ) -> Self {
        PlanParts {
            vtable: Pack,
            dtype: DType::Struct(fields, nullability),
            row_count,
            slots,
            data: PackData,
        }
        .into_typed()
    }

    /// Creates a struct assembly from `fields` and one child per field.
    ///
    /// Each field child must have the corresponding field dtype and `row_count` rows. `validity`
    /// is required exactly when `nullability` is [`Nullability::Nullable`] and must produce
    /// non-nullable booleans with `row_count` rows.
    pub fn try_new(
        fields: StructFields,
        nullability: Nullability,
        row_count: u64,
        field_plans: Vec<PlanRef>,
        validity: Option<PlanRef>,
    ) -> VortexResult<Self> {
        if field_plans.len() != fields.nfields() {
            vortex_bail!(
                "Pack expects {} field children but got {}",
                fields.nfields(),
                field_plans.len()
            );
        }
        if validity.is_some() != (nullability == Nullability::Nullable) {
            vortex_bail!("Pack validity child must be present exactly when the struct is nullable");
        }

        for (index, (field_dtype, field_plan)) in
            fields.fields().zip(field_plans.iter()).enumerate()
        {
            validate_field_child(index, &field_dtype, row_count, field_plan)?;
        }
        if let Some(validity) = validity.as_ref() {
            validate_validity_child(row_count, validity)?;
        }

        // SAFETY: The child count, presence, dtypes, and row counts were validated above.
        Ok(unsafe { Self::new_unchecked(fields, nullability, row_count, field_plans, validity) })
    }

    /// Creates a struct assembly without validating its children.
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    ///
    /// - `field_plans` contains exactly one child per field, in field order;
    /// - every field child has the corresponding field dtype and `row_count` rows; and
    /// - `validity` is present exactly when the struct is nullable and, when present, produces
    ///   non-nullable booleans with `row_count` rows.
    pub unsafe fn new_unchecked(
        fields: StructFields,
        nullability: Nullability,
        row_count: u64,
        field_plans: Vec<PlanRef>,
        validity: Option<PlanRef>,
    ) -> Self {
        let slots = iter::once(validity)
            .chain(field_plans.into_iter().map(Some))
            .collect();
        // SAFETY: The caller guarantees the same slot invariants required by this constructor.
        unsafe { Self::from_slots_unchecked(fields, nullability, row_count, slots) }
    }

    /// Returns the struct fields assembled by this plan.
    pub fn fields(&self) -> &StructFields {
        self.dtype()
            .as_struct_fields_opt()
            .vortex_expect("Pack dtype must be a struct")
    }

    /// Returns the number of struct fields, excluding any validity child.
    pub fn nfields(&self) -> usize {
        self.fields().nfields()
    }

    /// Returns the plan producing struct validity, if the struct is nullable.
    pub fn validity(&self) -> VortexResult<Option<PlanRef>> {
        self.slot(Pack::VALIDITY_SLOT)
    }

    /// Returns the plan producing field `index`.
    pub fn field(&self, index: usize) -> VortexResult<PlanRef> {
        self.slot_required(Pack::FIELDS_OFFSET + index)
    }
}

impl PlanVTable for Pack {
    type PlanData = PackData;
    type Metadata = EmptyMetadata;

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

    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
        // The struct fields are recoverable from the plan dtype.
        Some(EmptyMetadata)
    }

    fn with_slots(
        plan: &Plan<Self>,
        slots: &PlanSlots,
        _data: &mut Self::PlanData,
    ) -> VortexResult<()> {
        slots.check_len("Pack", Pack::FIELDS_OFFSET + plan.nfields())?;
        match (plan.dtype().is_nullable(), slots.get(Pack::VALIDITY_SLOT)?) {
            (true, Some(validity)) => validate_validity_child(plan.row_count(), validity)?,
            (false, None) => {}
            (true, None) => vortex_bail!("Nullable Pack has no validity child"),
            (false, Some(_)) => vortex_bail!("Non-nullable Pack has a validity child"),
        }
        for (index, field_dtype) in plan.fields().fields().enumerate() {
            let child = slots.required(Pack::FIELDS_OFFSET + index)?;
            validate_field_child(index, &field_dtype, plan.row_count(), child)?;
        }
        Ok(())
    }

    fn slot_name(plan: &Plan<Self>, slot: usize) -> Cow<'_, str> {
        if slot == Pack::VALIDITY_SLOT {
            return Cow::Borrowed("validity");
        }
        let name = plan
            .fields()
            .field_name(slot - Pack::FIELDS_OFFSET)
            .vortex_expect("Pack slot index out of bounds");
        Cow::Borrowed(name.as_ref())
    }

    fn compile(
        plan: &Plan<Self>,
        rows: Range<u64>,
        mask: &Mask,
        compiler: &mut Compiler<'_>,
    ) -> VortexResult<Option<Chain>> {
        // Inlet `i` reads the `i`-th present slot: validity first when nullable, then the fields.
        let count = plan.slots().present().count();
        if count == 0 {
            // A struct with no fields still has rows, so no child can carry them.
            let array = empty_struct(
                plan.fields().clone(),
                plan.dtype().nullability(),
                mask.true_count(),
            )?;
            return Ok(Some(Chain::new(OnceSource::new(array))));
        }
        if mask.all_false() {
            return Ok(None);
        }
        let mut chains = Vec::with_capacity(count);
        for child in plan.children() {
            chains.push(
                compiler
                    .compile(child?, rows.clone(), mask)?
                    .ok_or_else(|| vortex_err!("A Pack child produced no rows"))?,
            );
        }
        let nullable = plan.dtype().is_nullable();
        if count == 1 && !nullable {
            // One field needs no zip: each of its batches is wrapped as it passes.
            let chain = chains.remove(0);
            return Ok(Some(chain.with(WrapStage::new(plan.fields().clone()))));
        }
        let source = PackSource::new(plan.fields().clone(), nullable, count);
        Ok(Some(compiler.join(chains, source)))
    }
}

fn validate_field_child(
    index: usize,
    expected_dtype: &DType,
    expected_row_count: u64,
    child: &PlanRef,
) -> VortexResult<()> {
    if child.dtype() != expected_dtype {
        vortex_bail!(
            "Pack field child {index} has dtype {} but the field has dtype {expected_dtype}",
            child.dtype()
        );
    }
    if child.row_count() != expected_row_count {
        vortex_bail!(
            "Pack field child {index} has {} rows but the plan has {expected_row_count}",
            child.row_count()
        );
    }
    Ok(())
}

fn validate_validity_child(expected_row_count: u64, child: &PlanRef) -> VortexResult<()> {
    let expected_dtype = DType::Bool(Nullability::NonNullable);
    if child.dtype() != &expected_dtype {
        vortex_bail!(
            "Pack validity child has dtype {} but must have dtype {expected_dtype}",
            child.dtype()
        );
    }
    if child.row_count() != expected_row_count {
        vortex_bail!(
            "Pack validity child has {} rows but the plan has {expected_row_count}",
            child.row_count()
        );
    }
    Ok(())
}

impl PackPlan {
    /// Builds the temporary struct that `$` refers to in the combiner.
    ///
    /// Each field holds one partition result and keeps its dtype. The combiner's input struct
    /// must be present on every row so it can read an original validity bit as `false` on a row
    /// where the original struct is null.
    fn with_partition_fields(&self, fields: Vec<(FieldName, PlanRef)>) -> VortexResult<Self> {
        let struct_fields = StructFields::from_iter(
            fields
                .iter()
                .map(|(name, plan)| (name.clone(), plan.dtype().clone())),
        );
        let field_plans = fields.into_iter().map(|(_, plan)| plan).collect::<Vec<_>>();
        PackPlan::try_new(
            struct_fields,
            Nullability::NonNullable,
            self.row_count(),
            field_plans,
            None,
        )
    }
}

/// Rewrites an evaluation to read only the children it needs from a [`Pack`].
///
/// For `$.address.zip` on a nullable struct, the first split puts the `address` child and
/// the original struct's validity in fields `0` and `1` of the combiner's input.
///
/// ```text
/// $.address.zip          // Original projection.
/// mask($.0, $.1).zip     // Partitioning still feeds the whole address into the mask.
/// mask($.0.zip, $.1)     // The rewriter moves the lookup onto the address child.
/// ```
///
/// The next pass pushes the lookup into the `address` child as `$.zip`. The scan can
/// skip `city` and read just `zip` and the validity of each nullable ancestor.
#[derive(Debug)]
pub(crate) struct ExpressionPackRule;

impl PlanParentReduceRule<Pack> for ExpressionPackRule {
    type Parent = Eval;

    fn reduce_parent(
        &self,
        child: &Plan<Pack>,
        parent: &Plan<Eval>,
        _child_idx: usize,
        session: &VortexSession,
    ) -> VortexResult<Option<PlanRef>> {
        let expression = parent.expression();
        let fields = child.fields();
        if fields.nfields() == 0 {
            return Ok(None);
        }

        let partitioned = match Pack.partition(child.dtype(), expression, session)? {
            PartitionedExpression::One(slot, expr) => {
                let field = child.slot_required(slot)?;
                return Ok(Some(EvalPlan::try_new(expr, field)?.into_plan()));
            }
            PartitionedExpression::Any(expr) => {
                let empty_scope = child.with_partition_fields(Vec::new())?.into_plan();
                return Ok(Some(EvalPlan::try_new(expr, empty_scope)?.into_plan()));
            }
            PartitionedExpression::Many(partitioned) => partitioned,
        };
        let Partitions {
            mut combiner,
            partitions,
        } = partitioned;

        let nullable = child.dtype().is_nullable();
        if nullable {
            combiner = combiner.rewrite(&mut ProjectMaskedFields)?.into_inner();
        }

        // The combiner's root is non-nullable even when it uses every original field.
        let mut pack_changed = nullable || partitions.len() != fields.nfields();
        let mut partition_fields = Vec::with_capacity(partitions.len());
        for (position, partition) in partitions.into_iter().enumerate() {
            let name = positional_name(position);
            pack_changed |= partition.slot != Pack::FIELDS_OFFSET + position
                || fields.field_name(position) != Some(&name);

            let field = child.slot_required(partition.slot)?;
            let field = if is_identity_expression(&partition.expr, field.dtype()) {
                field
            } else {
                pack_changed = true;
                EvalPlan::try_new(partition.expr, field)?.into_plan()
            };
            partition_fields.push((name, field));
        }

        if !pack_changed && combiner == *expression {
            return Ok(None);
        }

        let combiner_input = if pack_changed {
            child.with_partition_fields(partition_fields)?.into_plan()
        } else {
            child.to_plan()
        };

        Ok(Some(
            EvalPlan::try_new(combiner, combiner_input)?.into_plan(),
        ))
    }
}

/// Moves a field lookup inside the masks on its input struct.
///
/// A field of a null struct is null, so applying the same masks to just the field
/// preserves the result.
struct ProjectMaskedFields;

impl NodeRewriter for ProjectMaskedFields {
    type NodeTy = BoundExpression;

    fn visit_up(&mut self, node: BoundExpression) -> VortexResult<Transformed<BoundExpression>> {
        let Some(field) = node.as_opt::<GetItem>() else {
            return Ok(Transformed::no(node));
        };
        let input = node.child(0);
        if !input.is::<MaskFn>() {
            return Ok(Transformed::no(node));
        }

        Ok(Transformed::yes(project_field_through_masks(field, input)))
    }
}

fn project_field_through_masks(field: &FieldName, input: &BoundExpression) -> BoundExpression {
    if !input.is::<MaskFn>() {
        return bound::get_item(field.clone(), input.clone());
    }

    let projected = project_field_through_masks(field, input.child(0));
    bound::mask(projected, input.child(1).clone())
}

fn is_identity_expression(expression: &BoundExpression, input_dtype: &DType) -> bool {
    if expression.is_root() {
        return expression.dtype() == input_dtype;
    }
    if input_dtype.is_nullable() {
        return false;
    }
    let Some(fields) = input_dtype.as_struct_fields_opt() else {
        return false;
    };
    let Some(options) = expression.as_opt::<PackFn>() else {
        return false;
    };
    !options.nullability.is_nullable()
        && options.names == *fields.names()
        && expression
            .children()
            .iter()
            .zip(fields.names().iter())
            .all(|(child, name)| {
                child.as_opt::<GetItem>().is_some_and(|item| item == name)
                    && child.children()[0].is_root()
                    && child.children()[0].dtype() == input_dtype
            })
}

#[derive(Clone, Copy)]
/// A struct field or its validity within a pack plan.
pub enum PackSlot {
    /// A field identified by its plan slot.
    Field(PlanSlot),
    /// The struct's validity slot.
    Validity,
}
impl From<PackSlot> for PlanSlot {
    fn from(slot: PackSlot) -> Self {
        match slot {
            PackSlot::Validity => Pack::VALIDITY_SLOT,
            PackSlot::Field(index) => Pack::FIELDS_OFFSET + index,
        }
    }
}

impl PartitionedPlan for Pack {
    type Slot = PackSlot;
    fn slot_dtype(scope: &DType, slot: PackSlot) -> VortexResult<DType> {
        match slot {
            PackSlot::Validity => Ok(validity_dtype()),
            PackSlot::Field(index) => field_dtype(struct_fields(scope)?, index),
        }
    }
}

/// Registers expression partitioning rules for pack plans.
pub fn register_pack_partition_rules(session: &PartitionSession) {
    session.register_root_rule(Pack, &RootRule);
    session.register_rule(Pack, GetItem, &GetItemRule);
    session.register_rule(Pack, Select, &SelectRule);
    session.register_rule(Pack, IsNotNull, &IsNotNullRule);
    session.register_rule(Pack, IsNull, &IsNullRule);
}

fn struct_fields(scope: &DType) -> VortexResult<&StructFields> {
    scope
        .as_struct_fields_opt()
        .ok_or_else(|| vortex_err!("Not a struct scope"))
}

fn field_dtype(fields: &StructFields, index: PlanSlot) -> VortexResult<DType> {
    fields
        .field_by_index(index)
        .ok_or_else(|| vortex_err!("No field {index} in struct scope"))
}

fn validity_dtype() -> DType {
    DType::Bool(Nullability::NonNullable)
}

fn select_fields(
    slots: &Slots<'_, Pack>,
    fields: &StructFields,
    names: FieldNames,
    indices: Vec<PlanSlot>,
) -> VortexResult<Expression> {
    vortex_ensure!(fields.nfields() > 0);
    let elements = names
        .iter()
        .cloned()
        .zip(indices)
        .map(|(name, index)| (name, slots.read(PackSlot::Field(index))));
    let packed = unbound::pack(elements, Nullability::NonNullable);
    if !slots.scope().is_nullable() {
        return Ok(packed);
    }
    Ok(unbound::mask(packed, slots.read(PackSlot::Validity)))
}

/// $ -> pack(...) (non-nullable) or mask(pack(...), validity)
struct RootRule;
impl PartitionRule for RootRule {
    type Plan = Pack;
    fn apply(
        &self,
        slots: &Slots<'_, Pack>,
        _node: &BoundExpression,
    ) -> VortexResult<Option<Expression>> {
        let fields = struct_fields(slots.scope())?;
        let indices = (0..fields.nfields()).collect();
        select_fields(slots, fields, fields.names().clone(), indices).map(Some)
    }
}

/// select(..., $) -> pack(... + optional validity)
struct SelectRule;
impl PartitionRule for SelectRule {
    type Plan = Pack;
    fn apply(
        &self,
        slots: &Slots<'_, Pack>,
        node: &BoundExpression,
    ) -> VortexResult<Option<Expression>> {
        let selection = node.as_::<Select>();
        let fields = struct_fields(slots.scope())?;
        let names = match selection {
            FieldSelection::Include(names) => names.clone(),
            FieldSelection::Exclude(_) => selection.normalize_to_included_fields(fields.names())?,
        };
        let indices = names
            .iter()
            .map(|name| {
                fields
                    .find(name)
                    .ok_or_else(|| vortex_err!("field {name} not found"))
            })
            .collect::<VortexResult<Vec<_>>>()?;
        select_fields(slots, fields, names, indices).map(Some)
    }
}

/// $.x -> $.x (non-nullable) or mask($.x, $.validity)
struct GetItemRule;
impl PartitionRule for GetItemRule {
    type Plan = Pack;
    fn apply(
        &self,
        slots: &Slots<'_, Pack>,
        node: &BoundExpression,
    ) -> VortexResult<Option<Expression>> {
        let field_name = node.as_::<GetItem>();
        let index = struct_fields(slots.scope())?
            .find(field_name)
            .ok_or_else(|| vortex_err!("Field {field_name} not found"))?;
        let read = slots.read(PackSlot::Field(index));
        if !slots.scope().is_nullable() {
            return Ok(Some(read));
        }
        Ok(Some(unbound::mask(read, slots.read(PackSlot::Validity))))
    }
}

/// is_not_null -> lit(true) (non-nullable) or $.validity
struct IsNotNullRule;
impl PartitionRule for IsNotNullRule {
    type Plan = Pack;
    fn apply(
        &self,
        slots: &Slots<'_, Pack>,
        _node: &BoundExpression,
    ) -> VortexResult<Option<Expression>> {
        let expr = if slots.scope().is_nullable() {
            slots.read(PackSlot::Validity)
        } else {
            unbound::lit(true)
        };
        Ok(Some(expr))
    }
}

/// is_null-> lit(false) (non-nullable) or !$.validity
struct IsNullRule;
impl PartitionRule for IsNullRule {
    type Plan = Pack;
    fn apply(
        &self,
        slots: &Slots<'_, Pack>,
        _node: &BoundExpression,
    ) -> VortexResult<Option<Expression>> {
        let expr = if slots.scope().is_nullable() {
            unbound::not(slots.read(PackSlot::Validity))
        } else {
            unbound::lit(false)
        };
        Ok(Some(expr))
    }
}

#[cfg(test)]
mod partition_tests {
    use insta::assert_snapshot;
    use vortex_array::dtype::PType;
    use vortex_expr as unbound;
    use vortex_expr::bound::get_item;
    use vortex_expr::bound::is_not_null;
    use vortex_expr::bound::pack;

    use super::*;
    use crate::plan::partition::PartitionedExpression;
    use crate::plan::partition::Partitions;
    use crate::test::SESSION;

    fn scope_of(expr: &BoundExpression) -> Option<&DType> {
        if expr.is_root() {
            return Some(expr.dtype());
        }
        expr.children().iter().find_map(scope_of)
    }

    fn i32() -> DType {
        DType::Primitive(PType::I32, Nullability::NonNullable)
    }

    fn struct_of(fields: &[(&str, DType)], nullability: Nullability) -> DType {
        DType::Struct(
            StructFields::from_iter(fields.iter().map(|(name, dtype)| (*name, dtype.clone()))),
            nullability,
        )
    }

    fn two_field_struct() -> DType {
        struct_of(&[("a", i32()), ("b", i32())], Nullability::NonNullable)
    }

    fn fmt_slot(slot: PlanSlot) -> String {
        match slot {
            Pack::VALIDITY_SLOT => "validity".to_string(),
            slot => (slot - Pack::FIELDS_OFFSET).to_string(),
        }
    }

    fn line(label: &str, expr: &BoundExpression) -> String {
        let scope = scope_of(expr)
            .map(|dtype| dtype.to_string())
            .unwrap_or_else(|| "-".to_string());
        format!("{label} scope={scope}: {expr}\n")
    }

    fn snap(partitioning: PartitionedExpression) -> String {
        match partitioning {
            PartitionedExpression::Any(expr) => line("mono none", &expr),
            PartitionedExpression::One(slot, expr) => {
                line(&format!("mono {}", fmt_slot(slot)), &expr)
            }
            PartitionedExpression::Many(Partitions {
                combiner: root,
                partitions,
            }) => {
                let mut out = String::new();
                for partition in &partitions {
                    out.push_str(&line(
                        &format!("partition {}", fmt_slot(partition.slot)),
                        &partition.expr,
                    ));
                }
                out.push_str(&line("root", &root));
                out
            }
        }
    }

    fn partition(expr: Expression, scope: &DType) -> VortexResult<String> {
        Ok(snap(Pack.partition(scope, &expr.bind(scope)?, &SESSION)?))
    }

    #[test]
    fn is_not_null_of_non_nullable() -> VortexResult<()> {
        let root = BoundExpression::new_root(two_field_struct());
        let expr = pack(
            [
                ("v", is_not_null(root.clone())),
                ("a", get_item("a", root.clone())),
                ("b", get_item("b", root)),
            ],
            Nullability::NonNullable,
        );
        assert_snapshot!(snap(Pack.partition(&two_field_struct(), &expr, &SESSION)?), @"
        partition 0 scope=i32: $
        partition 1 scope=i32: $
        root scope={0=i32, 1=i32}: pack(v: true, a: $.0, b: $.1)
        ");
        Ok(())
    }

    #[test]
    fn validity_select_and_root() -> VortexResult<()> {
        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
        let expr = vortex_functions::expr::select(["a"], unbound::root());
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope=i32: $
        partition validity scope=bool: $
        root scope={0=i32, 1=bool}: vortex.mask(pack(a: $.0), $.1)
        ");
        assert_snapshot!(partition(unbound::root(), &scope)?, @"
        partition 0 scope=i32: $
        partition 1 scope=i32: $
        partition validity scope=bool: $
        root scope={0=i32, 1=i32, 2=bool}: vortex.mask(pack(a: $.0, b: $.1), $.2)
        ");
        Ok(())
    }

    #[test]
    fn validity_and_field() -> VortexResult<()> {
        let inner = struct_of(&[("c", i32()), ("d", i32())], Nullability::NonNullable);
        let scope = struct_of(&[("a", i32()), ("s", inner)], Nullability::Nullable);
        let expr = unbound::and(
            vortex_functions::expr::is_null(unbound::root()),
            unbound::gt(
                unbound::get_item("d", unbound::get_item("s", unbound::root())),
                unbound::lit(0i32),
            ),
        );
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 1 scope={c=i32, d=i32}: $
        partition validity scope=bool: pack(0: $, 1: vortex.not($))
        root scope={0={c=i32, d=i32}, 1={0=bool, 1=bool}}: ($.1.1 and (vortex.mask($.0, $.1.0).d > 0i32))
        ");
        Ok(())
    }

    #[test]
    fn validity_only() -> VortexResult<()> {
        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
        let expr = unbound::is_not_null(unbound::root());
        assert_snapshot!(partition(expr, &scope)?, @"mono validity scope=bool: $");
        let expr = vortex_functions::expr::is_null(unbound::root());
        assert_snapshot!(partition(expr, &scope)?, @"mono validity scope=bool: vortex.not($)");

        let a = struct_of(&[("x", i32())], Nullability::Nullable);
        let b = struct_of(&[("y", i32())], Nullability::Nullable);
        let scope = struct_of(&[("a", a), ("b", b)], Nullability::NonNullable);
        let expr = unbound::and(
            unbound::is_not_null(unbound::get_item("a", unbound::root())),
            unbound::is_not_null(unbound::get_item("b", unbound::root())),
        );
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope={x=i32}?: is_not_null($)
        partition 1 scope={y=i32}?: is_not_null($)
        root scope={0=bool, 1=bool}: ($.0 and $.1)
        ");
        Ok(())
    }

    #[test]
    fn equal_cuts() -> VortexResult<()> {
        let root = BoundExpression::new_root(two_field_struct());
        let a = get_item("a", root.clone());
        let b = get_item("b", root);
        let expr = pack(
            [("x", a.clone()), ("y", b), ("z", a)],
            Nullability::NonNullable,
        );
        assert_snapshot!(snap(Pack.partition(&two_field_struct(), &expr, &SESSION)?), @"
        partition 0 scope=i32: $
        partition 1 scope=i32: $
        root scope={0=i32, 1=i32}: pack(x: $.0, y: $.1, z: $.0)
        ");
        Ok(())
    }

    #[test]
    fn is_not_null_one_partition() -> VortexResult<()> {
        let expr = unbound::is_not_null(unbound::get_item("a", unbound::root()));
        assert_snapshot!(partition(expr, &two_field_struct())?, @"mono 0 scope=i32: is_not_null($)");
        Ok(())
    }

    #[test]
    fn is_not_null_two_fields() -> VortexResult<()> {
        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
        let expr = unbound::is_not_null(unbound::get_item("a", unbound::root()));
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope=i32: $
        partition validity scope=bool: $
        root scope={0=i32, 1=bool}: $.1
        ");
        Ok(())
    }

    #[test]
    fn test_pack() -> VortexResult<()> {
        let expr = unbound::get_item(
            "a",
            unbound::get_item(
                "a",
                unbound::pack([("a", unbound::root())], Nullability::NonNullable),
            ),
        );
        assert_snapshot!(partition(expr, &two_field_struct())?, @"
        partition 0 scope=i32: $
        partition 1 scope=i32: $
        root scope={0=i32, 1=i32}: $.0
        ");
        Ok(())
    }

    #[test]
    fn test_ab_greater_c() -> VortexResult<()> {
        let inner = struct_of(&[("b", i32())], Nullability::NonNullable);
        let scope = struct_of(&[("a", inner), ("c", i32())], Nullability::NonNullable);
        let expr = unbound::gt(
            unbound::get_item("b", unbound::get_item("a", unbound::root())),
            unbound::get_item("c", unbound::root()),
        );
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope={b=i32}: $.b
        partition 1 scope=i32: $
        root scope={0=i32, 1=i32}: ($.0 > $.1)
        ");
        Ok(())
    }

    #[test]
    fn test_x_plus_1() -> VortexResult<()> {
        let scope = struct_of(&[("x", i32()), ("y", i32())], Nullability::NonNullable);
        let expr = unbound::gt(
            unbound::checked_add(unbound::get_item("x", unbound::root()), unbound::lit(1i32)),
            unbound::get_item("y", unbound::root()),
        );
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope=i32: ($ + 1i32)
        partition 1 scope=i32: $
        root scope={0=i32, 1=i32}: ($.0 > $.1)
        ");
        Ok(())
    }

    #[test]
    fn test_nested_comparison() -> VortexResult<()> {
        let inner = struct_of(&[("a", i32())], Nullability::NonNullable);
        let scope = struct_of(
            &[("a", inner.clone()), ("b", inner)],
            Nullability::NonNullable,
        );
        let expr = unbound::gt(
            unbound::get_item("a", unbound::get_item("a", unbound::root())),
            unbound::get_item("a", unbound::get_item("b", unbound::root())),
        );
        assert_snapshot!(partition(expr, &scope)?, @"
        partition 0 scope={a=i32}: $.a
        partition 1 scope={a=i32}: $.a
        root scope={0=i32, 1=i32}: ($.0 > $.1)
        ");
        Ok(())
    }

    #[test]
    fn test_nested_and() -> VortexResult<()> {
        let a = unbound::get_item("a", unbound::root());
        let b = unbound::get_item("b", unbound::root());
        let expr = unbound::and(
            unbound::and(
                unbound::gt(a.clone(), unbound::lit(5i32)),
                unbound::gt(b, unbound::lit(5i32)),
            ),
            unbound::lt(a, unbound::lit(1i32)),
        );
        assert_snapshot!(partition(expr, &two_field_struct())?, @"
        partition 0 scope=i32: pack(0: ($ > 5i32), 1: ($ < 1i32))
        partition 1 scope=i32: ($ > 5i32)
        root scope={0={0=bool, 1=bool}, 1=bool}: (($.0.0 and $.1) and $.0.1)
        ");
        Ok(())
    }

    #[test]
    fn test_duplicate_predicate() -> VortexResult<()> {
        let a = unbound::get_item("a", unbound::root());
        let b = unbound::get_item("b", unbound::root());
        let gt5_a = unbound::gt(a, unbound::lit(5i32));
        let expr = unbound::and(
            unbound::and(gt5_a.clone(), unbound::gt(b, unbound::lit(5i32))),
            gt5_a,
        );
        assert_snapshot!(partition(expr, &two_field_struct())?, @"
        partition 0 scope=i32: ($ > 5i32)
        partition 1 scope=i32: ($ > 5i32)
        root scope={0=bool, 1=bool}: (($.0 and $.1) and $.0)
        ");
        Ok(())
    }

    #[test]
    fn test_deeply_nested_comparison() -> VortexResult<()> {
        let leaf = struct_of(&[("c", i32()), ("d", i32())], Nullability::NonNullable);
        let middle = struct_of(&[("b", leaf)], Nullability::NonNullable);
        let scope = struct_of(&[("a", middle)], Nullability::NonNullable);
        let expr = unbound::gt(
            unbound::get_item(
                "c",
                unbound::get_item("b", unbound::get_item("a", unbound::root())),
            ),
            unbound::get_item(
                "d",
                unbound::get_item("b", unbound::get_item("a", unbound::root())),
            ),
        );
        assert_snapshot!(partition(expr, &scope)?, @"mono 0 scope={b={c=i32, d=i32}}: ($.b.c > $.b.d)");
        Ok(())
    }
}

#[cfg(test)]
mod tests;