Skip to main content

vortex_scan/plan/builtins/pack/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Plans reads from structs stored as separate children.
5//!
6//! A [`Pack`] assembles the field children and, for a nullable struct, a validity child. An
7//! expression that uses part of the struct can read the relevant children directly.
8
9pub(crate) mod execute;
10
11use std::borrow::Cow;
12use std::iter;
13use std::ops::Range;
14
15use vortex_array::EmptyMetadata;
16use vortex_array::dtype::DType;
17use vortex_array::dtype::FieldName;
18use vortex_array::dtype::FieldNames;
19use vortex_array::dtype::Nullability;
20use vortex_array::dtype::StructFields;
21use vortex_array::expr::BoundExpression;
22use vortex_array::scalar_fn::builtin::get_item::GetItem;
23use vortex_array::scalar_fn::builtin::is_not_null::IsNotNull;
24use vortex_array::scalar_fn::builtin::mask::Mask as MaskFn;
25use vortex_array::scalar_fn::builtin::pack::Pack as PackFn;
26use vortex_error::VortexExpect;
27use vortex_error::VortexResult;
28use vortex_error::vortex_bail;
29use vortex_error::vortex_ensure;
30use vortex_error::vortex_err;
31use vortex_expr as unbound;
32use vortex_expr::Expression;
33use vortex_expr::bound;
34use vortex_expr::traversal::NodeExt;
35use vortex_expr::traversal::NodeRewriter;
36use vortex_expr::traversal::Transformed;
37use vortex_functions::is_null::IsNull;
38use vortex_functions::select::FieldSelection;
39use vortex_functions::select::Select;
40use vortex_mask::Mask;
41use vortex_session::VortexSession;
42use vortex_session::registry::CachedId;
43
44use crate::execution::operators::OnceSource;
45use crate::execution::operators::PackSource;
46use crate::execution::operators::WrapStage;
47use crate::execution::operators::empty_struct;
48use crate::execution::pipeline::Chain;
49use crate::execution::pipeline::Compiler;
50use crate::plan::Eval;
51use crate::plan::EvalPlan;
52use crate::plan::Plan;
53use crate::plan::PlanId;
54use crate::plan::PlanParts;
55use crate::plan::PlanRef;
56use crate::plan::PlanSlots;
57use crate::plan::PlanVTable;
58use crate::plan::optimizer::PlanParentReduceRule;
59use crate::plan::partition::PartitionRule;
60use crate::plan::partition::PartitionSession;
61use crate::plan::partition::PartitionedExpression;
62use crate::plan::partition::PartitionedPlan;
63use crate::plan::partition::Partitions;
64use crate::plan::partition::PlanSlot;
65use crate::plan::partition::Slots;
66use crate::plan::partition::positional_name;
67
68/// Assembles a struct from a validity slot followed by one slot per field.
69///
70/// The slots match those of a struct array and a struct layout: slot
71/// [`VALIDITY_SLOT`](Self::VALIDITY_SLOT) holds the validity, present exactly when the struct is
72/// nullable, and field `i` is in slot `FIELDS_OFFSET + i`.
73#[derive(Clone, Debug)]
74pub struct Pack;
75
76impl Pack {
77    /// The slot holding struct validity, absent when the struct is non-nullable.
78    pub const VALIDITY_SLOT: usize = 0;
79    /// The slot of field zero; field `i` is in slot `FIELDS_OFFSET + i`.
80    pub const FIELDS_OFFSET: usize = 1;
81}
82
83/// Operator-specific struct assembly data.
84#[derive(Clone, Debug)]
85pub struct PackData;
86
87/// A plan that assembles a struct from its children.
88pub type PackPlan = Plan<Pack>;
89
90impl PackPlan {
91    /// Creates a struct assembly from potentially unbuilt slots without validation.
92    ///
93    /// # Safety
94    ///
95    /// `slots` must hold a validity slot followed by one slot per field. The validity slot must
96    /// be present exactly when `nullability` is nullable and produce non-nullable booleans. Every
97    /// field slot must be present with its field dtype, and every child must have `row_count`
98    /// rows.
99    pub unsafe fn from_slots_unchecked(
100        fields: StructFields,
101        nullability: Nullability,
102        row_count: u64,
103        slots: PlanSlots,
104    ) -> Self {
105        PlanParts {
106            vtable: Pack,
107            dtype: DType::Struct(fields, nullability),
108            row_count,
109            slots,
110            data: PackData,
111        }
112        .into_typed()
113    }
114
115    /// Creates a struct assembly from `fields` and one child per field.
116    ///
117    /// Each field child must have the corresponding field dtype and `row_count` rows. `validity`
118    /// is required exactly when `nullability` is [`Nullability::Nullable`] and must produce
119    /// non-nullable booleans with `row_count` rows.
120    pub fn try_new(
121        fields: StructFields,
122        nullability: Nullability,
123        row_count: u64,
124        field_plans: Vec<PlanRef>,
125        validity: Option<PlanRef>,
126    ) -> VortexResult<Self> {
127        if field_plans.len() != fields.nfields() {
128            vortex_bail!(
129                "Pack expects {} field children but got {}",
130                fields.nfields(),
131                field_plans.len()
132            );
133        }
134        if validity.is_some() != (nullability == Nullability::Nullable) {
135            vortex_bail!("Pack validity child must be present exactly when the struct is nullable");
136        }
137
138        for (index, (field_dtype, field_plan)) in
139            fields.fields().zip(field_plans.iter()).enumerate()
140        {
141            validate_field_child(index, &field_dtype, row_count, field_plan)?;
142        }
143        if let Some(validity) = validity.as_ref() {
144            validate_validity_child(row_count, validity)?;
145        }
146
147        // SAFETY: The child count, presence, dtypes, and row counts were validated above.
148        Ok(unsafe { Self::new_unchecked(fields, nullability, row_count, field_plans, validity) })
149    }
150
151    /// Creates a struct assembly without validating its children.
152    ///
153    /// # Safety
154    ///
155    /// The caller must ensure that:
156    ///
157    /// - `field_plans` contains exactly one child per field, in field order;
158    /// - every field child has the corresponding field dtype and `row_count` rows; and
159    /// - `validity` is present exactly when the struct is nullable and, when present, produces
160    ///   non-nullable booleans with `row_count` rows.
161    pub unsafe fn new_unchecked(
162        fields: StructFields,
163        nullability: Nullability,
164        row_count: u64,
165        field_plans: Vec<PlanRef>,
166        validity: Option<PlanRef>,
167    ) -> Self {
168        let slots = iter::once(validity)
169            .chain(field_plans.into_iter().map(Some))
170            .collect();
171        // SAFETY: The caller guarantees the same slot invariants required by this constructor.
172        unsafe { Self::from_slots_unchecked(fields, nullability, row_count, slots) }
173    }
174
175    /// Returns the struct fields assembled by this plan.
176    pub fn fields(&self) -> &StructFields {
177        self.dtype()
178            .as_struct_fields_opt()
179            .vortex_expect("Pack dtype must be a struct")
180    }
181
182    /// Returns the number of struct fields, excluding any validity child.
183    pub fn nfields(&self) -> usize {
184        self.fields().nfields()
185    }
186
187    /// Returns the plan producing struct validity, if the struct is nullable.
188    pub fn validity(&self) -> VortexResult<Option<PlanRef>> {
189        self.slot(Pack::VALIDITY_SLOT)
190    }
191
192    /// Returns the plan producing field `index`.
193    pub fn field(&self, index: usize) -> VortexResult<PlanRef> {
194        self.slot_required(Pack::FIELDS_OFFSET + index)
195    }
196}
197
198impl PlanVTable for Pack {
199    type PlanData = PackData;
200    type Metadata = EmptyMetadata;
201
202    fn id(&self) -> PlanId {
203        static ID: CachedId = CachedId::new("vortex.plan.pack");
204        *ID
205    }
206
207    fn metadata(_plan: &Plan<Self>) -> Option<Self::Metadata> {
208        // The struct fields are recoverable from the plan dtype.
209        Some(EmptyMetadata)
210    }
211
212    fn with_slots(
213        plan: &Plan<Self>,
214        slots: &PlanSlots,
215        _data: &mut Self::PlanData,
216    ) -> VortexResult<()> {
217        slots.check_len("Pack", Pack::FIELDS_OFFSET + plan.nfields())?;
218        match (plan.dtype().is_nullable(), slots.get(Pack::VALIDITY_SLOT)?) {
219            (true, Some(validity)) => validate_validity_child(plan.row_count(), validity)?,
220            (false, None) => {}
221            (true, None) => vortex_bail!("Nullable Pack has no validity child"),
222            (false, Some(_)) => vortex_bail!("Non-nullable Pack has a validity child"),
223        }
224        for (index, field_dtype) in plan.fields().fields().enumerate() {
225            let child = slots.required(Pack::FIELDS_OFFSET + index)?;
226            validate_field_child(index, &field_dtype, plan.row_count(), child)?;
227        }
228        Ok(())
229    }
230
231    fn slot_name(plan: &Plan<Self>, slot: usize) -> Cow<'_, str> {
232        if slot == Pack::VALIDITY_SLOT {
233            return Cow::Borrowed("validity");
234        }
235        let name = plan
236            .fields()
237            .field_name(slot - Pack::FIELDS_OFFSET)
238            .vortex_expect("Pack slot index out of bounds");
239        Cow::Borrowed(name.as_ref())
240    }
241
242    fn compile(
243        plan: &Plan<Self>,
244        rows: Range<u64>,
245        mask: &Mask,
246        compiler: &mut Compiler<'_>,
247    ) -> VortexResult<Option<Chain>> {
248        // Inlet `i` reads the `i`-th present slot: validity first when nullable, then the fields.
249        let count = plan.slots().present().count();
250        if count == 0 {
251            // A struct with no fields still has rows, so no child can carry them.
252            let array = empty_struct(
253                plan.fields().clone(),
254                plan.dtype().nullability(),
255                mask.true_count(),
256            )?;
257            return Ok(Some(Chain::new(OnceSource::new(array))));
258        }
259        if mask.all_false() {
260            return Ok(None);
261        }
262        let mut chains = Vec::with_capacity(count);
263        for child in plan.children() {
264            chains.push(
265                compiler
266                    .compile(child?, rows.clone(), mask)?
267                    .ok_or_else(|| vortex_err!("A Pack child produced no rows"))?,
268            );
269        }
270        let nullable = plan.dtype().is_nullable();
271        if count == 1 && !nullable {
272            // One field needs no zip: each of its batches is wrapped as it passes.
273            let chain = chains.remove(0);
274            return Ok(Some(chain.with(WrapStage::new(plan.fields().clone()))));
275        }
276        let source = PackSource::new(plan.fields().clone(), nullable, count);
277        Ok(Some(compiler.join(chains, source)))
278    }
279}
280
281fn validate_field_child(
282    index: usize,
283    expected_dtype: &DType,
284    expected_row_count: u64,
285    child: &PlanRef,
286) -> VortexResult<()> {
287    if child.dtype() != expected_dtype {
288        vortex_bail!(
289            "Pack field child {index} has dtype {} but the field has dtype {expected_dtype}",
290            child.dtype()
291        );
292    }
293    if child.row_count() != expected_row_count {
294        vortex_bail!(
295            "Pack field child {index} has {} rows but the plan has {expected_row_count}",
296            child.row_count()
297        );
298    }
299    Ok(())
300}
301
302fn validate_validity_child(expected_row_count: u64, child: &PlanRef) -> VortexResult<()> {
303    let expected_dtype = DType::Bool(Nullability::NonNullable);
304    if child.dtype() != &expected_dtype {
305        vortex_bail!(
306            "Pack validity child has dtype {} but must have dtype {expected_dtype}",
307            child.dtype()
308        );
309    }
310    if child.row_count() != expected_row_count {
311        vortex_bail!(
312            "Pack validity child has {} rows but the plan has {expected_row_count}",
313            child.row_count()
314        );
315    }
316    Ok(())
317}
318
319impl PackPlan {
320    /// Builds the temporary struct that `$` refers to in the combiner.
321    ///
322    /// Each field holds one partition result and keeps its dtype. The combiner's input struct
323    /// must be present on every row so it can read an original validity bit as `false` on a row
324    /// where the original struct is null.
325    fn with_partition_fields(&self, fields: Vec<(FieldName, PlanRef)>) -> VortexResult<Self> {
326        let struct_fields = StructFields::from_iter(
327            fields
328                .iter()
329                .map(|(name, plan)| (name.clone(), plan.dtype().clone())),
330        );
331        let field_plans = fields.into_iter().map(|(_, plan)| plan).collect::<Vec<_>>();
332        PackPlan::try_new(
333            struct_fields,
334            Nullability::NonNullable,
335            self.row_count(),
336            field_plans,
337            None,
338        )
339    }
340}
341
342/// Rewrites an evaluation to read only the children it needs from a [`Pack`].
343///
344/// For `$.address.zip` on a nullable struct, the first split puts the `address` child and
345/// the original struct's validity in fields `0` and `1` of the combiner's input.
346///
347/// ```text
348/// $.address.zip          // Original projection.
349/// mask($.0, $.1).zip     // Partitioning still feeds the whole address into the mask.
350/// mask($.0.zip, $.1)     // The rewriter moves the lookup onto the address child.
351/// ```
352///
353/// The next pass pushes the lookup into the `address` child as `$.zip`. The scan can
354/// skip `city` and read just `zip` and the validity of each nullable ancestor.
355#[derive(Debug)]
356pub(crate) struct ExpressionPackRule;
357
358impl PlanParentReduceRule<Pack> for ExpressionPackRule {
359    type Parent = Eval;
360
361    fn reduce_parent(
362        &self,
363        child: &Plan<Pack>,
364        parent: &Plan<Eval>,
365        _child_idx: usize,
366        session: &VortexSession,
367    ) -> VortexResult<Option<PlanRef>> {
368        let expression = parent.expression();
369        let fields = child.fields();
370        if fields.nfields() == 0 {
371            return Ok(None);
372        }
373
374        let partitioned = match Pack.partition(child.dtype(), expression, session)? {
375            PartitionedExpression::One(slot, expr) => {
376                let field = child.slot_required(slot)?;
377                return Ok(Some(EvalPlan::try_new(expr, field)?.into_plan()));
378            }
379            PartitionedExpression::Any(expr) => {
380                let empty_scope = child.with_partition_fields(Vec::new())?.into_plan();
381                return Ok(Some(EvalPlan::try_new(expr, empty_scope)?.into_plan()));
382            }
383            PartitionedExpression::Many(partitioned) => partitioned,
384        };
385        let Partitions {
386            mut combiner,
387            partitions,
388        } = partitioned;
389
390        let nullable = child.dtype().is_nullable();
391        if nullable {
392            combiner = combiner.rewrite(&mut ProjectMaskedFields)?.into_inner();
393        }
394
395        // The combiner's root is non-nullable even when it uses every original field.
396        let mut pack_changed = nullable || partitions.len() != fields.nfields();
397        let mut partition_fields = Vec::with_capacity(partitions.len());
398        for (position, partition) in partitions.into_iter().enumerate() {
399            let name = positional_name(position);
400            pack_changed |= partition.slot != Pack::FIELDS_OFFSET + position
401                || fields.field_name(position) != Some(&name);
402
403            let field = child.slot_required(partition.slot)?;
404            let field = if is_identity_expression(&partition.expr, field.dtype()) {
405                field
406            } else {
407                pack_changed = true;
408                EvalPlan::try_new(partition.expr, field)?.into_plan()
409            };
410            partition_fields.push((name, field));
411        }
412
413        if !pack_changed && combiner == *expression {
414            return Ok(None);
415        }
416
417        let combiner_input = if pack_changed {
418            child.with_partition_fields(partition_fields)?.into_plan()
419        } else {
420            child.to_plan()
421        };
422
423        Ok(Some(
424            EvalPlan::try_new(combiner, combiner_input)?.into_plan(),
425        ))
426    }
427}
428
429/// Moves a field lookup inside the masks on its input struct.
430///
431/// A field of a null struct is null, so applying the same masks to just the field
432/// preserves the result.
433struct ProjectMaskedFields;
434
435impl NodeRewriter for ProjectMaskedFields {
436    type NodeTy = BoundExpression;
437
438    fn visit_up(&mut self, node: BoundExpression) -> VortexResult<Transformed<BoundExpression>> {
439        let Some(field) = node.as_opt::<GetItem>() else {
440            return Ok(Transformed::no(node));
441        };
442        let input = node.child(0);
443        if !input.is::<MaskFn>() {
444            return Ok(Transformed::no(node));
445        }
446
447        Ok(Transformed::yes(project_field_through_masks(field, input)))
448    }
449}
450
451fn project_field_through_masks(field: &FieldName, input: &BoundExpression) -> BoundExpression {
452    if !input.is::<MaskFn>() {
453        return bound::get_item(field.clone(), input.clone());
454    }
455
456    let projected = project_field_through_masks(field, input.child(0));
457    bound::mask(projected, input.child(1).clone())
458}
459
460fn is_identity_expression(expression: &BoundExpression, input_dtype: &DType) -> bool {
461    if expression.is_root() {
462        return expression.dtype() == input_dtype;
463    }
464    if input_dtype.is_nullable() {
465        return false;
466    }
467    let Some(fields) = input_dtype.as_struct_fields_opt() else {
468        return false;
469    };
470    let Some(options) = expression.as_opt::<PackFn>() else {
471        return false;
472    };
473    !options.nullability.is_nullable()
474        && options.names == *fields.names()
475        && expression
476            .children()
477            .iter()
478            .zip(fields.names().iter())
479            .all(|(child, name)| {
480                child.as_opt::<GetItem>().is_some_and(|item| item == name)
481                    && child.children()[0].is_root()
482                    && child.children()[0].dtype() == input_dtype
483            })
484}
485
486#[derive(Clone, Copy)]
487/// A struct field or its validity within a pack plan.
488pub enum PackSlot {
489    /// A field identified by its plan slot.
490    Field(PlanSlot),
491    /// The struct's validity slot.
492    Validity,
493}
494impl From<PackSlot> for PlanSlot {
495    fn from(slot: PackSlot) -> Self {
496        match slot {
497            PackSlot::Validity => Pack::VALIDITY_SLOT,
498            PackSlot::Field(index) => Pack::FIELDS_OFFSET + index,
499        }
500    }
501}
502
503impl PartitionedPlan for Pack {
504    type Slot = PackSlot;
505    fn slot_dtype(scope: &DType, slot: PackSlot) -> VortexResult<DType> {
506        match slot {
507            PackSlot::Validity => Ok(validity_dtype()),
508            PackSlot::Field(index) => field_dtype(struct_fields(scope)?, index),
509        }
510    }
511}
512
513/// Registers expression partitioning rules for pack plans.
514pub fn register_pack_partition_rules(session: &PartitionSession) {
515    session.register_root_rule(Pack, &RootRule);
516    session.register_rule(Pack, GetItem, &GetItemRule);
517    session.register_rule(Pack, Select, &SelectRule);
518    session.register_rule(Pack, IsNotNull, &IsNotNullRule);
519    session.register_rule(Pack, IsNull, &IsNullRule);
520}
521
522fn struct_fields(scope: &DType) -> VortexResult<&StructFields> {
523    scope
524        .as_struct_fields_opt()
525        .ok_or_else(|| vortex_err!("Not a struct scope"))
526}
527
528fn field_dtype(fields: &StructFields, index: PlanSlot) -> VortexResult<DType> {
529    fields
530        .field_by_index(index)
531        .ok_or_else(|| vortex_err!("No field {index} in struct scope"))
532}
533
534fn validity_dtype() -> DType {
535    DType::Bool(Nullability::NonNullable)
536}
537
538fn select_fields(
539    slots: &Slots<'_, Pack>,
540    fields: &StructFields,
541    names: FieldNames,
542    indices: Vec<PlanSlot>,
543) -> VortexResult<Expression> {
544    vortex_ensure!(fields.nfields() > 0);
545    let elements = names
546        .iter()
547        .cloned()
548        .zip(indices)
549        .map(|(name, index)| (name, slots.read(PackSlot::Field(index))));
550    let packed = unbound::pack(elements, Nullability::NonNullable);
551    if !slots.scope().is_nullable() {
552        return Ok(packed);
553    }
554    Ok(unbound::mask(packed, slots.read(PackSlot::Validity)))
555}
556
557/// $ -> pack(...) (non-nullable) or mask(pack(...), validity)
558struct RootRule;
559impl PartitionRule for RootRule {
560    type Plan = Pack;
561    fn apply(
562        &self,
563        slots: &Slots<'_, Pack>,
564        _node: &BoundExpression,
565    ) -> VortexResult<Option<Expression>> {
566        let fields = struct_fields(slots.scope())?;
567        let indices = (0..fields.nfields()).collect();
568        select_fields(slots, fields, fields.names().clone(), indices).map(Some)
569    }
570}
571
572/// select(..., $) -> pack(... + optional validity)
573struct SelectRule;
574impl PartitionRule for SelectRule {
575    type Plan = Pack;
576    fn apply(
577        &self,
578        slots: &Slots<'_, Pack>,
579        node: &BoundExpression,
580    ) -> VortexResult<Option<Expression>> {
581        let selection = node.as_::<Select>();
582        let fields = struct_fields(slots.scope())?;
583        let names = match selection {
584            FieldSelection::Include(names) => names.clone(),
585            FieldSelection::Exclude(_) => selection.normalize_to_included_fields(fields.names())?,
586        };
587        let indices = names
588            .iter()
589            .map(|name| {
590                fields
591                    .find(name)
592                    .ok_or_else(|| vortex_err!("field {name} not found"))
593            })
594            .collect::<VortexResult<Vec<_>>>()?;
595        select_fields(slots, fields, names, indices).map(Some)
596    }
597}
598
599/// $.x -> $.x (non-nullable) or mask($.x, $.validity)
600struct GetItemRule;
601impl PartitionRule for GetItemRule {
602    type Plan = Pack;
603    fn apply(
604        &self,
605        slots: &Slots<'_, Pack>,
606        node: &BoundExpression,
607    ) -> VortexResult<Option<Expression>> {
608        let field_name = node.as_::<GetItem>();
609        let index = struct_fields(slots.scope())?
610            .find(field_name)
611            .ok_or_else(|| vortex_err!("Field {field_name} not found"))?;
612        let read = slots.read(PackSlot::Field(index));
613        if !slots.scope().is_nullable() {
614            return Ok(Some(read));
615        }
616        Ok(Some(unbound::mask(read, slots.read(PackSlot::Validity))))
617    }
618}
619
620/// is_not_null -> lit(true) (non-nullable) or $.validity
621struct IsNotNullRule;
622impl PartitionRule for IsNotNullRule {
623    type Plan = Pack;
624    fn apply(
625        &self,
626        slots: &Slots<'_, Pack>,
627        _node: &BoundExpression,
628    ) -> VortexResult<Option<Expression>> {
629        let expr = if slots.scope().is_nullable() {
630            slots.read(PackSlot::Validity)
631        } else {
632            unbound::lit(true)
633        };
634        Ok(Some(expr))
635    }
636}
637
638/// is_null-> lit(false) (non-nullable) or !$.validity
639struct IsNullRule;
640impl PartitionRule for IsNullRule {
641    type Plan = Pack;
642    fn apply(
643        &self,
644        slots: &Slots<'_, Pack>,
645        _node: &BoundExpression,
646    ) -> VortexResult<Option<Expression>> {
647        let expr = if slots.scope().is_nullable() {
648            unbound::not(slots.read(PackSlot::Validity))
649        } else {
650            unbound::lit(false)
651        };
652        Ok(Some(expr))
653    }
654}
655
656#[cfg(test)]
657mod partition_tests {
658    use insta::assert_snapshot;
659    use vortex_array::dtype::PType;
660    use vortex_expr as unbound;
661    use vortex_expr::bound::get_item;
662    use vortex_expr::bound::is_not_null;
663    use vortex_expr::bound::pack;
664
665    use super::*;
666    use crate::plan::partition::PartitionedExpression;
667    use crate::plan::partition::Partitions;
668    use crate::test::SESSION;
669
670    fn scope_of(expr: &BoundExpression) -> Option<&DType> {
671        if expr.is_root() {
672            return Some(expr.dtype());
673        }
674        expr.children().iter().find_map(scope_of)
675    }
676
677    fn i32() -> DType {
678        DType::Primitive(PType::I32, Nullability::NonNullable)
679    }
680
681    fn struct_of(fields: &[(&str, DType)], nullability: Nullability) -> DType {
682        DType::Struct(
683            StructFields::from_iter(fields.iter().map(|(name, dtype)| (*name, dtype.clone()))),
684            nullability,
685        )
686    }
687
688    fn two_field_struct() -> DType {
689        struct_of(&[("a", i32()), ("b", i32())], Nullability::NonNullable)
690    }
691
692    fn fmt_slot(slot: PlanSlot) -> String {
693        match slot {
694            Pack::VALIDITY_SLOT => "validity".to_string(),
695            slot => (slot - Pack::FIELDS_OFFSET).to_string(),
696        }
697    }
698
699    fn line(label: &str, expr: &BoundExpression) -> String {
700        let scope = scope_of(expr)
701            .map(|dtype| dtype.to_string())
702            .unwrap_or_else(|| "-".to_string());
703        format!("{label} scope={scope}: {expr}\n")
704    }
705
706    fn snap(partitioning: PartitionedExpression) -> String {
707        match partitioning {
708            PartitionedExpression::Any(expr) => line("mono none", &expr),
709            PartitionedExpression::One(slot, expr) => {
710                line(&format!("mono {}", fmt_slot(slot)), &expr)
711            }
712            PartitionedExpression::Many(Partitions {
713                combiner: root,
714                partitions,
715            }) => {
716                let mut out = String::new();
717                for partition in &partitions {
718                    out.push_str(&line(
719                        &format!("partition {}", fmt_slot(partition.slot)),
720                        &partition.expr,
721                    ));
722                }
723                out.push_str(&line("root", &root));
724                out
725            }
726        }
727    }
728
729    fn partition(expr: Expression, scope: &DType) -> VortexResult<String> {
730        Ok(snap(Pack.partition(scope, &expr.bind(scope)?, &SESSION)?))
731    }
732
733    #[test]
734    fn is_not_null_of_non_nullable() -> VortexResult<()> {
735        let root = BoundExpression::new_root(two_field_struct());
736        let expr = pack(
737            [
738                ("v", is_not_null(root.clone())),
739                ("a", get_item("a", root.clone())),
740                ("b", get_item("b", root)),
741            ],
742            Nullability::NonNullable,
743        );
744        assert_snapshot!(snap(Pack.partition(&two_field_struct(), &expr, &SESSION)?), @"
745        partition 0 scope=i32: $
746        partition 1 scope=i32: $
747        root scope={0=i32, 1=i32}: pack(v: true, a: $.0, b: $.1)
748        ");
749        Ok(())
750    }
751
752    #[test]
753    fn validity_select_and_root() -> VortexResult<()> {
754        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
755        let expr = vortex_functions::expr::select(["a"], unbound::root());
756        assert_snapshot!(partition(expr, &scope)?, @"
757        partition 0 scope=i32: $
758        partition validity scope=bool: $
759        root scope={0=i32, 1=bool}: vortex.mask(pack(a: $.0), $.1)
760        ");
761        assert_snapshot!(partition(unbound::root(), &scope)?, @"
762        partition 0 scope=i32: $
763        partition 1 scope=i32: $
764        partition validity scope=bool: $
765        root scope={0=i32, 1=i32, 2=bool}: vortex.mask(pack(a: $.0, b: $.1), $.2)
766        ");
767        Ok(())
768    }
769
770    #[test]
771    fn validity_and_field() -> VortexResult<()> {
772        let inner = struct_of(&[("c", i32()), ("d", i32())], Nullability::NonNullable);
773        let scope = struct_of(&[("a", i32()), ("s", inner)], Nullability::Nullable);
774        let expr = unbound::and(
775            vortex_functions::expr::is_null(unbound::root()),
776            unbound::gt(
777                unbound::get_item("d", unbound::get_item("s", unbound::root())),
778                unbound::lit(0i32),
779            ),
780        );
781        assert_snapshot!(partition(expr, &scope)?, @"
782        partition 1 scope={c=i32, d=i32}: $
783        partition validity scope=bool: pack(0: $, 1: vortex.not($))
784        root scope={0={c=i32, d=i32}, 1={0=bool, 1=bool}}: ($.1.1 and (vortex.mask($.0, $.1.0).d > 0i32))
785        ");
786        Ok(())
787    }
788
789    #[test]
790    fn validity_only() -> VortexResult<()> {
791        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
792        let expr = unbound::is_not_null(unbound::root());
793        assert_snapshot!(partition(expr, &scope)?, @"mono validity scope=bool: $");
794        let expr = vortex_functions::expr::is_null(unbound::root());
795        assert_snapshot!(partition(expr, &scope)?, @"mono validity scope=bool: vortex.not($)");
796
797        let a = struct_of(&[("x", i32())], Nullability::Nullable);
798        let b = struct_of(&[("y", i32())], Nullability::Nullable);
799        let scope = struct_of(&[("a", a), ("b", b)], Nullability::NonNullable);
800        let expr = unbound::and(
801            unbound::is_not_null(unbound::get_item("a", unbound::root())),
802            unbound::is_not_null(unbound::get_item("b", unbound::root())),
803        );
804        assert_snapshot!(partition(expr, &scope)?, @"
805        partition 0 scope={x=i32}?: is_not_null($)
806        partition 1 scope={y=i32}?: is_not_null($)
807        root scope={0=bool, 1=bool}: ($.0 and $.1)
808        ");
809        Ok(())
810    }
811
812    #[test]
813    fn equal_cuts() -> VortexResult<()> {
814        let root = BoundExpression::new_root(two_field_struct());
815        let a = get_item("a", root.clone());
816        let b = get_item("b", root);
817        let expr = pack(
818            [("x", a.clone()), ("y", b), ("z", a)],
819            Nullability::NonNullable,
820        );
821        assert_snapshot!(snap(Pack.partition(&two_field_struct(), &expr, &SESSION)?), @"
822        partition 0 scope=i32: $
823        partition 1 scope=i32: $
824        root scope={0=i32, 1=i32}: pack(x: $.0, y: $.1, z: $.0)
825        ");
826        Ok(())
827    }
828
829    #[test]
830    fn is_not_null_one_partition() -> VortexResult<()> {
831        let expr = unbound::is_not_null(unbound::get_item("a", unbound::root()));
832        assert_snapshot!(partition(expr, &two_field_struct())?, @"mono 0 scope=i32: is_not_null($)");
833        Ok(())
834    }
835
836    #[test]
837    fn is_not_null_two_fields() -> VortexResult<()> {
838        let scope = struct_of(&[("a", i32()), ("b", i32())], Nullability::Nullable);
839        let expr = unbound::is_not_null(unbound::get_item("a", unbound::root()));
840        assert_snapshot!(partition(expr, &scope)?, @"
841        partition 0 scope=i32: $
842        partition validity scope=bool: $
843        root scope={0=i32, 1=bool}: $.1
844        ");
845        Ok(())
846    }
847
848    #[test]
849    fn test_pack() -> VortexResult<()> {
850        let expr = unbound::get_item(
851            "a",
852            unbound::get_item(
853                "a",
854                unbound::pack([("a", unbound::root())], Nullability::NonNullable),
855            ),
856        );
857        assert_snapshot!(partition(expr, &two_field_struct())?, @"
858        partition 0 scope=i32: $
859        partition 1 scope=i32: $
860        root scope={0=i32, 1=i32}: $.0
861        ");
862        Ok(())
863    }
864
865    #[test]
866    fn test_ab_greater_c() -> VortexResult<()> {
867        let inner = struct_of(&[("b", i32())], Nullability::NonNullable);
868        let scope = struct_of(&[("a", inner), ("c", i32())], Nullability::NonNullable);
869        let expr = unbound::gt(
870            unbound::get_item("b", unbound::get_item("a", unbound::root())),
871            unbound::get_item("c", unbound::root()),
872        );
873        assert_snapshot!(partition(expr, &scope)?, @"
874        partition 0 scope={b=i32}: $.b
875        partition 1 scope=i32: $
876        root scope={0=i32, 1=i32}: ($.0 > $.1)
877        ");
878        Ok(())
879    }
880
881    #[test]
882    fn test_x_plus_1() -> VortexResult<()> {
883        let scope = struct_of(&[("x", i32()), ("y", i32())], Nullability::NonNullable);
884        let expr = unbound::gt(
885            unbound::checked_add(unbound::get_item("x", unbound::root()), unbound::lit(1i32)),
886            unbound::get_item("y", unbound::root()),
887        );
888        assert_snapshot!(partition(expr, &scope)?, @"
889        partition 0 scope=i32: ($ + 1i32)
890        partition 1 scope=i32: $
891        root scope={0=i32, 1=i32}: ($.0 > $.1)
892        ");
893        Ok(())
894    }
895
896    #[test]
897    fn test_nested_comparison() -> VortexResult<()> {
898        let inner = struct_of(&[("a", i32())], Nullability::NonNullable);
899        let scope = struct_of(
900            &[("a", inner.clone()), ("b", inner)],
901            Nullability::NonNullable,
902        );
903        let expr = unbound::gt(
904            unbound::get_item("a", unbound::get_item("a", unbound::root())),
905            unbound::get_item("a", unbound::get_item("b", unbound::root())),
906        );
907        assert_snapshot!(partition(expr, &scope)?, @"
908        partition 0 scope={a=i32}: $.a
909        partition 1 scope={a=i32}: $.a
910        root scope={0=i32, 1=i32}: ($.0 > $.1)
911        ");
912        Ok(())
913    }
914
915    #[test]
916    fn test_nested_and() -> VortexResult<()> {
917        let a = unbound::get_item("a", unbound::root());
918        let b = unbound::get_item("b", unbound::root());
919        let expr = unbound::and(
920            unbound::and(
921                unbound::gt(a.clone(), unbound::lit(5i32)),
922                unbound::gt(b, unbound::lit(5i32)),
923            ),
924            unbound::lt(a, unbound::lit(1i32)),
925        );
926        assert_snapshot!(partition(expr, &two_field_struct())?, @"
927        partition 0 scope=i32: pack(0: ($ > 5i32), 1: ($ < 1i32))
928        partition 1 scope=i32: ($ > 5i32)
929        root scope={0={0=bool, 1=bool}, 1=bool}: (($.0.0 and $.1) and $.0.1)
930        ");
931        Ok(())
932    }
933
934    #[test]
935    fn test_duplicate_predicate() -> VortexResult<()> {
936        let a = unbound::get_item("a", unbound::root());
937        let b = unbound::get_item("b", unbound::root());
938        let gt5_a = unbound::gt(a, unbound::lit(5i32));
939        let expr = unbound::and(
940            unbound::and(gt5_a.clone(), unbound::gt(b, unbound::lit(5i32))),
941            gt5_a,
942        );
943        assert_snapshot!(partition(expr, &two_field_struct())?, @"
944        partition 0 scope=i32: ($ > 5i32)
945        partition 1 scope=i32: ($ > 5i32)
946        root scope={0=bool, 1=bool}: (($.0 and $.1) and $.0)
947        ");
948        Ok(())
949    }
950
951    #[test]
952    fn test_deeply_nested_comparison() -> VortexResult<()> {
953        let leaf = struct_of(&[("c", i32()), ("d", i32())], Nullability::NonNullable);
954        let middle = struct_of(&[("b", leaf)], Nullability::NonNullable);
955        let scope = struct_of(&[("a", middle)], Nullability::NonNullable);
956        let expr = unbound::gt(
957            unbound::get_item(
958                "c",
959                unbound::get_item("b", unbound::get_item("a", unbound::root())),
960            ),
961            unbound::get_item(
962                "d",
963                unbound::get_item("b", unbound::get_item("a", unbound::root())),
964            ),
965        );
966        assert_snapshot!(partition(expr, &scope)?, @"mono 0 scope={b={c=i32, d=i32}}: ($.b.c > $.b.d)");
967        Ok(())
968    }
969}
970
971#[cfg(test)]
972mod tests;