Skip to main content

vortex_array/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_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure_eq;
12use vortex_utils::aliases::hash_map::HashMap;
13
14use crate::dtype::DType;
15use crate::dtype::FieldName;
16use crate::dtype::FieldNames;
17use crate::dtype::Nullability;
18use crate::dtype::StructFields;
19use crate::expr::BoundExpression;
20use crate::expr::ExactBoundExpr;
21use crate::expr::analysis::Annotation;
22use crate::expr::analysis::AnnotationFn;
23use crate::expr::analysis::BoundAnnotations;
24use crate::expr::analysis::descendent_bound_annotations;
25use crate::expr::bound::get_item;
26use crate::expr::bound::pack;
27use crate::expr::traversal::NodeExt;
28use crate::expr::traversal::NodeRewriter;
29use crate::expr::traversal::Transformed;
30use crate::expr::traversal::TraversalOrder;
31
32/// Partition an expression into sub-expressions that are uniquely associated with an annotation.
33/// A root expression is also returned that can be used to recombine the results of the partitions
34/// into the result of the original expression.
35///
36/// ## Note
37///
38/// This function currently respects the validity of each field in the scope, but the not validity
39/// of the scope itself. The fix would be for the returned `BoundPartitionedExpr` to include a
40/// partition expression for computing the validity, or to include that expression as part of the
41/// root.
42///
43/// See <https://github.com/vortex-data/vortex/issues/1907>.
44pub fn partition_bound<A: AnnotationFn<BoundExpression>>(
45    expr: BoundExpression,
46    annotate_fn: A,
47) -> VortexResult<BoundPartitionedExpr<A::Annotation>>
48where
49    A::Annotation: Display,
50    FieldName: From<A::Annotation>,
51{
52    // Annotate each expression with the annotations that any of its descendent expressions have.
53    let annotations = descendent_bound_annotations(&expr, annotate_fn);
54    partition_bound_annotations(expr, annotations)
55}
56
57/// Partition an already-annotated bound expression tree.
58///
59/// Prefer [`partition_bound`] when annotations can be derived by an [`AnnotationFn`].
60pub fn partition_bound_annotations<A>(
61    expr: BoundExpression,
62    annotations: BoundAnnotations<A>,
63) -> VortexResult<BoundPartitionedExpr<A>>
64where
65    A: Display + Clone + Eq + Hash,
66    FieldName: From<A>,
67{
68    let mut collector = PartitionCollector::<A>::new(&annotations);
69    expr.clone().rewrite(&mut collector)?;
70
71    let mut partitions = Vec::with_capacity(collector.sub_expressions.len());
72    let mut partition_annotations = Vec::with_capacity(collector.sub_expressions.len());
73
74    for (annotation, exprs) in collector.sub_expressions {
75        // We pack all sub-expressions for the same annotation into a single expression.
76        let names: FieldNames = exprs
77            .iter()
78            .enumerate()
79            .map(|(idx, _)| PartitionCollector::field_name(&annotation, idx))
80            .collect();
81        let expr = pack(names.into_iter().zip(exprs), Nullability::NonNullable);
82
83        partitions.push(expr);
84        partition_annotations.push(annotation);
85    }
86
87    let partition_names = partition_annotations
88        .iter()
89        .map(|id| FieldName::from(id.clone()))
90        .collect::<FieldNames>();
91    let root_scope = partition_root_dtype(&partition_names, &partitions);
92    let mut rewriter = PartitionRootRewriter::new(&annotations, root_scope);
93    let root = expr.rewrite(&mut rewriter)?.value;
94
95    Ok(BoundPartitionedExpr {
96        root,
97        partitions: partitions.into_boxed_slice(),
98        partition_names,
99        partition_annotations: partition_annotations.into_boxed_slice(),
100    })
101}
102
103/// The result of partitioning a bound expression.
104///
105/// The root and partitions remain bound so callers can cache and reuse their shared tree identity
106/// without an unbind/rebind round trip.
107#[derive(Debug)]
108pub struct BoundPartitionedExpr<A> {
109    /// The root expression used to re-assemble the results.
110    pub root: BoundExpression,
111    /// The partition expressions themselves.
112    pub partitions: Box<[BoundExpression]>,
113    /// The field name of each partition as referenced in the root expression.
114    pub partition_names: FieldNames,
115    /// The annotation associated with each partition.
116    pub partition_annotations: Box<[A]>,
117}
118
119impl<A: Display> Display for BoundPartitionedExpr<A> {
120    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
121        write!(
122            f,
123            "root: {} {{{}}}",
124            self.root,
125            self.partition_names
126                .iter()
127                .zip(self.partitions.iter())
128                .map(|(name, partition)| format!("{name}: {partition}"))
129                .join(", ")
130        )
131    }
132}
133
134impl<A: Annotation> BoundPartitionedExpr<A>
135where
136    FieldName: From<A>,
137{
138    /// Return the partition for a given field, if it exists.
139    // FIXME(ngates): this should return an iterator since an annotation may have multiple partitions.
140    pub fn find_partition(&self, id: &A) -> Option<&BoundExpression> {
141        let id = FieldName::from(id.clone());
142        self.partition_names
143            .iter()
144            .position(|field| field == id)
145            .map(|idx| &self.partitions[idx])
146    }
147
148    /// Replace the partition expressions and update every root dtype in the recombination tree.
149    pub fn replace_partitions(&mut self, partitions: Box<[BoundExpression]>) -> VortexResult<()> {
150        vortex_ensure_eq!(partitions.len(), self.partition_names.len());
151
152        let root_dtype = partition_root_dtype(&self.partition_names, &partitions);
153        let root = replace_root_dtype(self.root.clone(), root_dtype)?;
154        self.partitions = partitions;
155        self.root = root;
156        Ok(())
157    }
158}
159
160#[derive(Debug)]
161struct PartitionCollector<'a, A: Annotation> {
162    annotations: &'a BoundAnnotations<A>,
163    sub_expressions: HashMap<A, Vec<BoundExpression>>,
164}
165
166impl<'a, A: Annotation + Display> PartitionCollector<'a, A> {
167    fn new(annotations: &'a BoundAnnotations<A>) -> Self {
168        Self {
169            sub_expressions: HashMap::new(),
170            annotations,
171        }
172    }
173
174    /// Each annotation may be associated with multiple sub-expressions, so we need to
175    /// a unique name for each sub-expression.
176    fn field_name(annotation: &A, idx: usize) -> FieldName {
177        format!("{annotation}_{idx}").into()
178    }
179}
180
181impl<A: Annotation + Display> NodeRewriter for PartitionCollector<'_, A>
182where
183    FieldName: From<A>,
184{
185    type NodeTy = BoundExpression;
186
187    fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
188        match self.annotations.get(&ExactBoundExpr(node.clone())) {
189            // If this expression only accesses a single field, then we can skip the children
190            Some(annotations) if annotations.len() == 1 => {
191                let annotation = annotations
192                    .iter()
193                    .next()
194                    .vortex_expect("expected one field");
195                let sub_exprs = self.sub_expressions.entry(annotation.clone()).or_default();
196                sub_exprs.push(node.clone());
197                Ok(Transformed {
198                    value: node,
199                    changed: false,
200                    order: TraversalOrder::Skip,
201                })
202            }
203
204            // Otherwise, continue traversing.
205            _ => Ok(Transformed::no(node)),
206        }
207    }
208
209    fn visit_up(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
210        Ok(Transformed::no(node))
211    }
212}
213
214struct PartitionRootRewriter<'a, A: Annotation> {
215    annotations: &'a BoundAnnotations<A>,
216    partition_offsets: HashMap<A, usize>,
217    root_dtype: DType,
218}
219
220impl<'a, A: Annotation> PartitionRootRewriter<'a, A> {
221    fn new(annotations: &'a BoundAnnotations<A>, root_dtype: DType) -> Self {
222        Self {
223            annotations,
224            partition_offsets: HashMap::new(),
225            root_dtype,
226        }
227    }
228}
229
230impl<A: Annotation + Display> NodeRewriter for PartitionRootRewriter<'_, A>
231where
232    FieldName: From<A>,
233{
234    type NodeTy = BoundExpression;
235
236    fn visit_down(&mut self, node: Self::NodeTy) -> VortexResult<Transformed<Self::NodeTy>> {
237        let Some(annotations) = self.annotations.get(&ExactBoundExpr(node.clone())) else {
238            return Ok(Transformed::no(node));
239        };
240        if annotations.len() != 1 {
241            return Ok(Transformed::no(node));
242        }
243
244        let annotation = annotations
245            .iter()
246            .next()
247            .vortex_expect("expected one annotation");
248        let offset = self
249            .partition_offsets
250            .entry(annotation.clone())
251            .or_default();
252        let field_name = PartitionCollector::field_name(annotation, *offset);
253        *offset += 1;
254
255        let partition = get_item(
256            FieldName::from(annotation.clone()),
257            BoundExpression::new_root(self.root_dtype.clone()),
258        );
259        let value = get_item(field_name, partition);
260
261        Ok(Transformed {
262            value,
263            changed: true,
264            order: TraversalOrder::Skip,
265        })
266    }
267}
268
269fn partition_root_dtype(names: &FieldNames, partitions: &[BoundExpression]) -> DType {
270    DType::Struct(
271        StructFields::new(
272            names.clone(),
273            partitions
274                .iter()
275                .map(|partition| partition.dtype().clone())
276                .collect(),
277        ),
278        Nullability::NonNullable,
279    )
280}
281
282fn replace_root_dtype(expr: BoundExpression, root_dtype: DType) -> VortexResult<BoundExpression> {
283    Ok(expr
284        .transform_down(|node| {
285            if node.is_root() {
286                Ok(Transformed {
287                    value: BoundExpression::new_root(root_dtype.clone()),
288                    changed: true,
289                    order: TraversalOrder::Skip,
290                })
291            } else {
292                Ok(Transformed::no(node))
293            }
294        })?
295        .into_inner())
296}
297
298#[cfg(test)]
299mod tests {
300    use rstest::fixture;
301    use rstest::rstest;
302
303    use super::*;
304    use crate::dtype::DType;
305    use crate::dtype::Nullability::NonNullable;
306    use crate::dtype::Nullability::Nullable;
307    use crate::dtype::PType::I32;
308    use crate::dtype::StructFields;
309    use crate::expr::analysis::make_bound_free_field_annotator;
310    use crate::expr::checked_add;
311    use crate::expr::col;
312    use crate::expr::get_item;
313    use crate::expr::lit;
314    use crate::expr::merge;
315    use crate::expr::pack;
316    use crate::expr::root;
317
318    #[fixture]
319    fn dtype() -> DType {
320        DType::Struct(
321            StructFields::from_iter([
322                (
323                    "a",
324                    DType::Struct(
325                        StructFields::from_iter([("x", I32.into()), ("y", DType::from(I32))]),
326                        NonNullable,
327                    ),
328                ),
329                ("b", I32.into()),
330                ("c", I32.into()),
331            ]),
332            NonNullable,
333        )
334    }
335
336    fn partition_by_field(
337        expr: BoundExpression,
338        dtype: &DType,
339    ) -> VortexResult<BoundPartitionedExpr<FieldName>> {
340        let fields = dtype.as_struct_fields_opt().unwrap();
341        partition_bound(expr, make_bound_free_field_annotator(fields))
342    }
343
344    #[rstest]
345    fn test_expr_top_level_ref(dtype: DType) {
346        let fields = dtype.as_struct_fields_opt().unwrap();
347
348        let expr = root();
349        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
350
351        // An un-expanded root expression is annotated by all fields, but since it is a single node
352        assert_eq!(partitioned.partitions.len(), 0);
353        assert_eq!(partitioned.root, root().bind(&dtype).unwrap());
354
355        // Instead, callers must expand the root expression themselves.
356        let expr = pack(
357            fields
358                .names()
359                .iter()
360                .map(|name| (name.clone(), col(name.clone()))),
361            NonNullable,
362        );
363        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
364
365        assert_eq!(partitioned.partitions.len(), fields.names().len());
366    }
367
368    #[rstest]
369    fn test_expr_top_level_ref_get_item_and_split(dtype: DType) {
370        let expr = get_item("y", get_item("a", root()));
371
372        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
373        let root_dtype =
374            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
375        assert_eq!(
376            partitioned.root,
377            get_item("a_0", get_item("a", root()))
378                .bind(&root_dtype)
379                .unwrap()
380        );
381    }
382
383    #[rstest]
384    fn test_expr_top_level_ref_get_item_and_split_pack(dtype: DType) {
385        let expr = pack(
386            [
387                ("x", get_item("x", get_item("a", root()))),
388                ("y", get_item("y", get_item("a", root()))),
389                ("c", get_item("c", root())),
390            ],
391            NonNullable,
392        );
393        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
394
395        let split_a = partitioned.find_partition(&"a".into()).unwrap();
396        assert_eq!(
397            split_a,
398            &pack(
399                [
400                    ("a_0", get_item("x", get_item("a", root()))),
401                    ("a_1", get_item("y", get_item("a", root())))
402                ],
403                NonNullable
404            )
405            .bind(&dtype)
406            .unwrap()
407        );
408    }
409
410    #[rstest]
411    fn test_expr_top_level_ref_get_item_add(dtype: DType) {
412        let expr = checked_add(get_item("y", get_item("a", root())), lit(1));
413        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
414
415        // Whole expr is a single split
416        assert_eq!(partitioned.partitions.len(), 1);
417    }
418
419    #[rstest]
420    fn test_expr_top_level_ref_get_item_add_cannot_split(dtype: DType) {
421        let expr = checked_add(get_item("y", get_item("a", root())), get_item("b", root()));
422        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
423
424        // One for id.a and id.b
425        assert_eq!(partitioned.partitions.len(), 2);
426    }
427
428    #[rstest]
429    fn test_expr_merge(dtype: DType) {
430        let expr = merge([col("a"), pack([("b", col("b"))], NonNullable)]);
431
432        let partitioned = partition_by_field(expr.bind(&dtype).unwrap(), &dtype).unwrap();
433        let expected = merge([get_item("a_0", col("a")), get_item("b_0", col("b"))]);
434        let root_dtype =
435            partition_root_dtype(&partitioned.partition_names, &partitioned.partitions);
436        assert_eq!(
437            partitioned.root,
438            expected.bind(&root_dtype).unwrap(),
439            "{} {}",
440            partitioned.root,
441            expected
442        );
443
444        assert_eq!(partitioned.partitions.len(), 2);
445
446        let part_a = partitioned.find_partition(&"a".into()).unwrap();
447        let expected_a = pack([("a_0", col("a"))], NonNullable);
448        assert_eq!(
449            part_a,
450            &expected_a.bind(&dtype).unwrap(),
451            "{part_a} {expected_a}"
452        );
453
454        let part_b = partitioned.find_partition(&"b".into()).unwrap();
455        let expected_b = pack([("b_0", pack([("b", col("b"))], NonNullable))], NonNullable);
456        assert_eq!(
457            part_b,
458            &expected_b.bind(&dtype).unwrap(),
459            "{part_b} {expected_b}"
460        );
461    }
462
463    #[rstest]
464    fn replacing_partitions_refreshes_root_dtype(dtype: DType) -> VortexResult<()> {
465        let mut partitioned = partition_by_field(col("b").bind(&dtype)?, &dtype)?;
466        let field_dtype = DType::Primitive(I32, Nullable);
467        let replacement = pack([("b_0", root())], NonNullable).bind(&field_dtype)?;
468
469        partitioned.replace_partitions(vec![replacement].into_boxed_slice())?;
470
471        assert_eq!(partitioned.root.dtype(), &field_dtype);
472        Ok(())
473    }
474}