Skip to main content

vortex_expr/transform/
bound_partition.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::hash::Hash;
7
8use itertools::Itertools;
9use vortex_array::dtype::DType;
10use vortex_array::dtype::FieldName;
11use vortex_array::dtype::FieldNames;
12use vortex_array::dtype::Nullability;
13use vortex_array::dtype::StructFields;
14use vortex_array::expr::BoundExpression;
15use vortex_array::expr::ExactBoundExpr;
16use vortex_array::scalar_fn::builtin::get_item::GetItem;
17use vortex_array::scalar_fn::builtin::pack::Pack;
18use vortex_error::VortexExpect;
19use vortex_error::VortexResult;
20use vortex_error::vortex_ensure_eq;
21use vortex_utils::aliases::hash_map::HashMap;
22
23use crate::analysis::Annotation;
24use crate::analysis::AnnotationFn;
25use crate::analysis::BoundAnnotations;
26use crate::analysis::descendent_bound_annotations;
27use crate::bound::get_item;
28use crate::bound::pack;
29use crate::traversal::NodeExt;
30use crate::traversal::NodeRewriter;
31use crate::traversal::Transformed;
32use crate::traversal::TraversalOrder;
33
34/// Partition an expression into sub-expressions that are uniquely associated with an annotation.
35/// A root expression is also returned that can be used to recombine the results of the partitions
36/// into the result of the original expression.
37pub fn partition_bound<A: AnnotationFn<BoundExpression>>(
38    expr: BoundExpression,
39    annotate_fn: A,
40) -> VortexResult<BoundPartitionedExpr<A::Annotation>>
41where
42    A::Annotation: Display,
43    FieldName: From<A::Annotation>,
44{
45    // Annotate each expression with the annotations that any of its descendent expressions have.
46    let annotations = descendent_bound_annotations(&expr, annotate_fn);
47    partition_bound_annotations(expr, annotations)
48}
49
50/// Partition an already-annotated bound expression tree.
51///
52/// Prefer [`partition_bound`] when annotations can be derived by an [`AnnotationFn`].
53pub fn partition_bound_annotations<A>(
54    expr: BoundExpression,
55    annotations: BoundAnnotations<A>,
56) -> VortexResult<BoundPartitionedExpr<A>>
57where
58    A: Display + Clone + Eq + Hash,
59    FieldName: From<A>,
60{
61    let mut collector = PartitionCollector::<A>::new(&annotations);
62    expr.clone().rewrite(&mut collector)?;
63
64    let mut partitions = Vec::with_capacity(collector.sub_expressions.len());
65    let mut partition_annotations = Vec::with_capacity(collector.sub_expressions.len());
66
67    for (annotation, exprs) in collector.sub_expressions {
68        // We pack all sub-expressions for the same annotation into a single expression.
69        let names: FieldNames = exprs
70            .iter()
71            .enumerate()
72            .map(|(idx, _)| PartitionCollector::field_name(&annotation, idx))
73            .collect();
74        let expr = pack(names.into_iter().zip(exprs), Nullability::NonNullable);
75
76        partitions.push(expr);
77        partition_annotations.push(annotation);
78    }
79
80    let partition_names = partition_annotations
81        .iter()
82        .map(|id| FieldName::from(id.clone()))
83        .collect::<FieldNames>();
84    let root_scope = partition_root_dtype(&partition_names, &partitions);
85    let mut rewriter = PartitionRootRewriter::new(&annotations, root_scope);
86    let root = expr.rewrite(&mut rewriter)?.value;
87
88    Ok(BoundPartitionedExpr {
89        root,
90        partitions: partitions.into_boxed_slice(),
91        partition_names,
92        partition_annotations: partition_annotations.into_boxed_slice(),
93    })
94}
95
96/// The result of partitioning a bound expression.
97///
98/// The root and partitions remain bound so callers can cache and reuse their shared tree identity
99/// without an unbind/rebind round trip.
100#[derive(Debug)]
101pub struct BoundPartitionedExpr<A> {
102    /// The root expression used to re-assemble the results.
103    pub root: BoundExpression,
104    /// The partition expressions themselves.
105    pub partitions: Box<[BoundExpression]>,
106    /// The field name of each partition as referenced in the root expression.
107    pub partition_names: FieldNames,
108    /// The annotation associated with each partition.
109    pub partition_annotations: Box<[A]>,
110}
111
112impl<A: Display> Display for BoundPartitionedExpr<A> {
113    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
114        write!(
115            f,
116            "root: {} {{{}}}",
117            self.root,
118            self.partition_names
119                .iter()
120                .zip(self.partitions.iter())
121                .map(|(name, partition)| format!("{name}: {partition}"))
122                .join(", ")
123        )
124    }
125}
126
127impl<A: Annotation> BoundPartitionedExpr<A>
128where
129    FieldName: From<A>,
130{
131    /// Return the partition for a given field, if it exists.
132    // FIXME(ngates): this should return an iterator since an annotation may have multiple partitions.
133    pub fn find_partition(&self, id: &A) -> Option<&BoundExpression> {
134        let id = FieldName::from(id.clone());
135        self.partition_names
136            .iter()
137            .position(|field| field == id)
138            .map(|idx| &self.partitions[idx])
139    }
140
141    /// Replace the partition expressions and update every root dtype in the recombination tree.
142    pub fn replace_partitions(&mut self, partitions: Box<[BoundExpression]>) -> VortexResult<()> {
143        vortex_ensure_eq!(partitions.len(), self.partition_names.len());
144
145        let root_dtype = partition_root_dtype(&self.partition_names, &partitions);
146        let root = replace_root_dtype(self.root.clone(), root_dtype)?;
147        self.partitions = partitions;
148        self.root = root;
149        Ok(())
150    }
151
152    /// Unwrap every partition that holds a single sub-expression.
153    ///
154    /// Such a partition is `pack(<name>_0: expr)`; it becomes `expr`, and the root's
155    /// `$.<name>.<name>_0` accesses become `$.<name>`. Callers then evaluate `expr` directly
156    /// instead of wrapping each result in a one-field struct, and a pass-through projection's root
157    /// reduces to a pack of the partitions themselves.
158    ///
159    /// Call this at most once: a second call would unwrap a single-field `pack` written in the
160    /// original expression.
161    pub fn collapse_single_partitions(&mut self) -> VortexResult<()> {
162        let mut collapsed = HashMap::new();
163        let partitions = self
164            .partitions
165            .iter()
166            .zip_eq(self.partition_names.iter())
167            .map(|(partition, partition_name)| {
168                if let Some(pack) = partition.as_opt::<Pack>()
169                    && let [value] = partition.children()
170                {
171                    let value_name = pack.names.get(0).vortex_expect("pack has one field");
172                    collapsed.insert(partition_name.clone(), value_name.clone());
173                    value.clone()
174                } else {
175                    partition.clone()
176                }
177            })
178            .collect::<Box<[_]>>();
179        if collapsed.is_empty() {
180            return Ok(());
181        }
182
183        let root_dtype = partition_root_dtype(&self.partition_names, &partitions);
184        let root = self
185            .root
186            .clone()
187            .transform_down(|node| {
188                if let Some(value_name) = node.as_opt::<GetItem>()
189                    && let partition_access = &node.children()[0]
190                    && let Some(partition_name) = partition_access.as_opt::<GetItem>()
191                    && partition_access.children()[0].is_root()
192                    && collapsed.get(partition_name) == Some(value_name)
193                {
194                    return Ok(Transformed {
195                        value: get_item(
196                            partition_name.clone(),
197                            BoundExpression::new_root(root_dtype.clone()),
198                        ),
199                        changed: true,
200                        order: TraversalOrder::Skip,
201                    });
202                }
203                if node.is_root() {
204                    return Ok(Transformed {
205                        value: BoundExpression::new_root(root_dtype.clone()),
206                        changed: true,
207                        order: TraversalOrder::Skip,
208                    });
209                }
210                Ok(Transformed::no(node))
211            })?
212            .into_inner();
213
214        self.partitions = partitions;
215        self.root = root;
216        Ok(())
217    }
218}
219
220#[derive(Debug)]
221struct PartitionCollector<'a, A: Annotation> {
222    annotations: &'a BoundAnnotations<A>,
223    /// Sub-expressions per annotation, in the order each annotation is first visited, so that
224    /// partitions follow the order of the expression rather than hash order.
225    sub_expressions: Vec<(A, Vec<BoundExpression>)>,
226    /// Index into `sub_expressions` for each annotation.
227    positions: HashMap<A, usize>,
228}
229
230impl<'a, A: Annotation + Display> PartitionCollector<'a, A> {
231    fn new(annotations: &'a BoundAnnotations<A>) -> Self {
232        Self {
233            sub_expressions: Vec::new(),
234            positions: HashMap::new(),
235            annotations,
236        }
237    }
238
239    /// Each annotation may be associated with multiple sub-expressions, so we need to
240    /// a unique name for each sub-expression.
241    fn field_name(annotation: &A, idx: usize) -> FieldName {
242        format!("{annotation}_{idx}").into()
243    }
244}
245
246impl<A: Annotation + Display> NodeRewriter for PartitionCollector<'_, A>
247where
248    FieldName: From<A>,
249{
250    type NodeTy = BoundExpression;
251
252    fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
253        match self.annotations.get(&ExactBoundExpr(node.clone())) {
254            // If this expression only accesses a single field, then we can skip the children
255            Some(annotations) if annotations.len() == 1 => {
256                let annotation = annotations
257                    .iter()
258                    .next()
259                    .vortex_expect("expected one field");
260                let position = *self.positions.entry(annotation.clone()).or_insert_with(|| {
261                    self.sub_expressions.push((annotation.clone(), Vec::new()));
262                    self.sub_expressions.len() - 1
263                });
264                self.sub_expressions[position].1.push(node.clone());
265                Ok(Transformed {
266                    value: node,
267                    changed: false,
268                    order: TraversalOrder::Skip,
269                })
270            }
271
272            // Otherwise, continue traversing.
273            _ => Ok(Transformed::no(node)),
274        }
275    }
276
277    fn visit_up(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
278        Ok(Transformed::no(node))
279    }
280}
281
282struct PartitionRootRewriter<'a, A: Annotation> {
283    annotations: &'a BoundAnnotations<A>,
284    partition_offsets: HashMap<A, usize>,
285    root_dtype: DType,
286}
287
288impl<'a, A: Annotation> PartitionRootRewriter<'a, A> {
289    fn new(annotations: &'a BoundAnnotations<A>, root_dtype: DType) -> Self {
290        Self {
291            annotations,
292            partition_offsets: HashMap::new(),
293            root_dtype,
294        }
295    }
296}
297
298impl<A: Annotation + Display> NodeRewriter for PartitionRootRewriter<'_, A>
299where
300    FieldName: From<A>,
301{
302    type NodeTy = BoundExpression;
303
304    fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
305        let Some(annotations) = self.annotations.get(&ExactBoundExpr(node.clone())) else {
306            return Ok(Transformed::no(node));
307        };
308        if annotations.len() != 1 {
309            return Ok(Transformed::no(node));
310        }
311
312        let annotation = annotations
313            .iter()
314            .next()
315            .vortex_expect("expected one annotation");
316        let offset = self
317            .partition_offsets
318            .entry(annotation.clone())
319            .or_default();
320        let field_name = PartitionCollector::field_name(annotation, *offset);
321        *offset += 1;
322
323        let partition = get_item(
324            FieldName::from(annotation.clone()),
325            BoundExpression::new_root(self.root_dtype.clone()),
326        );
327        let value = get_item(field_name, partition);
328
329        Ok(Transformed {
330            value,
331            changed: true,
332            order: TraversalOrder::Skip,
333        })
334    }
335}
336
337fn partition_root_dtype(names: &FieldNames, partitions: &[BoundExpression]) -> DType {
338    DType::Struct(
339        StructFields::new(
340            names.clone(),
341            partitions
342                .iter()
343                .map(|partition| partition.dtype().clone())
344                .collect(),
345        ),
346        Nullability::NonNullable,
347    )
348}
349
350fn replace_root_dtype(expr: BoundExpression, root_dtype: DType) -> VortexResult<BoundExpression> {
351    Ok(expr
352        .transform_down(|node| {
353            if node.is_root() {
354                Ok(Transformed {
355                    value: BoundExpression::new_root(root_dtype.clone()),
356                    changed: true,
357                    order: TraversalOrder::Skip,
358                })
359            } else {
360                Ok(Transformed::no(node))
361            }
362        })?
363        .into_inner())
364}
365
366#[cfg(test)]
367mod tests {
368    use rstest::fixture;
369    use rstest::rstest;
370    use vortex_array::dtype::DType;
371    use vortex_array::dtype::FieldName;
372    use vortex_array::dtype::Nullability::NonNullable;
373    use vortex_array::dtype::Nullability::Nullable;
374    use vortex_array::dtype::PType::I32;
375    use vortex_array::dtype::StructFields;
376    use vortex_array::scalar_fn::builtin::get_item::GetItem;
377
378    use super::*;
379    use crate::analysis::AnnotationFn;
380    use crate::checked_add;
381    use crate::col;
382    use crate::get_item;
383    use crate::lit;
384    use crate::pack;
385    use crate::root;
386
387    /// Annotates each top-level field read from the root scope, the way the scan's field-access
388    /// analysis does for expressions without a `select`.
389    fn free_field_annotator(
390        scope: &StructFields,
391    ) -> impl AnnotationFn<BoundExpression, Annotation = FieldName> {
392        move |expr: &BoundExpression| {
393            let Some(scalar_fn) = expr.as_scalar() else {
394                return scope.names().iter().cloned().collect();
395            };
396            match scalar_fn.as_opt::<GetItem>() {
397                Some(field_name) if expr.children()[0].is_root() => vec![field_name.clone()],
398                _ => vec![],
399            }
400        }
401    }
402
403    #[fixture]
404    fn dtype() -> DType {
405        DType::Struct(
406            StructFields::from_iter([
407                (
408                    "a",
409                    DType::Struct(
410                        StructFields::from_iter([("x", I32.into()), ("y", DType::from(I32))]),
411                        NonNullable,
412                    ),
413                ),
414                ("b", I32.into()),
415                ("c", I32.into()),
416            ]),
417            NonNullable,
418        )
419    }
420
421    fn partition_by_field(
422        expr: BoundExpression,
423        dtype: &DType,
424    ) -> VortexResult<BoundPartitionedExpr<FieldName>> {
425        let fields = dtype.as_struct_fields_opt().unwrap();
426        partition_bound(expr, free_field_annotator(fields))
427    }
428
429    #[rstest]
430    fn test_expr_top_level_ref(dtype: DType) {
431        let fields = dtype.as_struct_fields_opt().unwrap();
432
433        let expr = root();
434        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
435
436        // An un-expanded root expression is annotated by all fields, but since it is a single node
437        assert_eq!(partitioned.partitions.len(), 0);
438        assert_eq!(partitioned.root, root().bind(&dtype).unwrap());
439
440        // Instead, callers must expand the root expression themselves.
441        let expr = pack(
442            fields
443                .names()
444                .iter()
445                .map(|name| (name.clone(), col(name.clone()))),
446            NonNullable,
447        );
448        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
449
450        assert_eq!(partitioned.partitions.len(), fields.names().len());
451        for name in fields.names().iter() {
452            let expected = pack([(format!("{name}_0"), col(name.clone()))], NonNullable)
453                .bind(&dtype)
454                .unwrap();
455            assert_eq!(partitioned.find_partition(name), Some(&expected));
456        }
457    }
458
459    #[rstest]
460    fn test_collapse_single_partitions(dtype: DType) -> VortexResult<()> {
461        let expr = pack(
462            [
463                ("x", get_item("c", root())),
464                ("y", get_item("x", get_item("a", root()))),
465                ("z", get_item("y", get_item("a", root()))),
466            ],
467            NonNullable,
468        );
469        let mut partitioned = partition_by_field(expr.bind(&dtype)?, &dtype)?;
470        // Partitions follow the order in which the expression references them.
471        assert_eq!(
472            partitioned.partition_names,
473            FieldNames::from_iter(["c", "a"].map(FieldName::from))
474        );
475
476        partitioned.collapse_single_partitions()?;
477
478        assert_eq!(
479            partitioned.partitions[0],
480            get_item("c", root()).bind(&dtype)?
481        );
482        assert_eq!(
483            partitioned.partitions[1],
484            pack(
485                [
486                    ("a_0", get_item("x", get_item("a", root()))),
487                    ("a_1", get_item("y", get_item("a", root()))),
488                ],
489                NonNullable
490            )
491            .bind(&dtype)?
492        );
493        let root_dtype =
494            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
495        assert_eq!(
496            partitioned.root,
497            pack(
498                [
499                    ("x", get_item("c", root())),
500                    ("y", get_item("a_0", get_item("a", root()))),
501                    ("z", get_item("a_1", get_item("a", root()))),
502                ],
503                NonNullable
504            )
505            .bind(&root_dtype)?
506        );
507        Ok(())
508    }
509
510    #[rstest]
511    fn test_expr_top_level_ref_get_item_and_split(dtype: DType) {
512        let expr = get_item("y", get_item("a", root()));
513
514        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
515        let root_dtype =
516            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
517        assert_eq!(
518            partitioned.root,
519            get_item("a_0", get_item("a", root()))
520                .bind(&root_dtype)
521                .unwrap()
522        );
523    }
524
525    #[rstest]
526    fn test_expr_top_level_ref_get_item_and_split_pack(dtype: DType) {
527        let expr = pack(
528            [
529                ("x", get_item("x", get_item("a", root()))),
530                ("y", get_item("y", get_item("a", root()))),
531                ("c", get_item("c", root())),
532            ],
533            NonNullable,
534        );
535        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
536
537        let split_a = partitioned.find_partition(&"a".into()).unwrap();
538        assert_eq!(
539            split_a,
540            &pack(
541                [
542                    ("a_0", get_item("x", get_item("a", root()))),
543                    ("a_1", get_item("y", get_item("a", root())))
544                ],
545                NonNullable
546            )
547            .bind(&dtype)
548            .unwrap()
549        );
550    }
551
552    #[rstest]
553    fn test_expr_top_level_ref_get_item_add(dtype: DType) {
554        let expr = checked_add(get_item("y", get_item("a", root())), lit(1));
555        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
556
557        // Whole expr is a single split
558        assert_eq!(partitioned.partitions.len(), 1);
559        let expected = pack([("a_0", expr)], NonNullable).bind(&dtype).unwrap();
560        assert_eq!(partitioned.find_partition(&"a".into()), Some(&expected));
561        let root_dtype =
562            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
563        assert_eq!(
564            partitioned.root,
565            get_item("a_0", col("a")).bind(&root_dtype).unwrap()
566        );
567    }
568
569    #[rstest]
570    fn test_expr_top_level_ref_get_item_add_cannot_split(dtype: DType) {
571        let expr = checked_add(get_item("y", get_item("a", root())), get_item("b", root()));
572        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
573
574        // One for id.a and id.b
575        assert_eq!(partitioned.partitions.len(), 2);
576        let expected_a = pack([("a_0", get_item("y", col("a")))], NonNullable)
577            .bind(&dtype)
578            .unwrap();
579        let expected_b = pack([("b_0", col("b"))], NonNullable).bind(&dtype).unwrap();
580        assert_eq!(partitioned.find_partition(&"a".into()), Some(&expected_a));
581        assert_eq!(partitioned.find_partition(&"b".into()), Some(&expected_b));
582        let root_dtype =
583            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
584        let expected_root = checked_add(get_item("a_0", col("a")), get_item("b_0", col("b")))
585            .bind(&root_dtype)
586            .unwrap();
587        assert_eq!(partitioned.root, expected_root);
588    }
589
590    #[rstest]
591    fn replacing_partitions_refreshes_root_dtype(dtype: DType) -> VortexResult<()> {
592        let mut partitioned = partition_by_field(col("b").bind(&dtype)?, &dtype)?;
593        let field_dtype = DType::Primitive(I32, Nullable);
594        let replacement = pack([("b_0", root())], NonNullable).bind(&field_dtype)?;
595
596        partitioned.replace_partitions(vec![replacement].into_boxed_slice())?;
597
598        assert_eq!(partitioned.root.dtype(), &field_dtype);
599        Ok(())
600    }
601}