Skip to main content

vortex_expr/analysis/
labeling.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::expr::BoundExpression;
5use vortex_array::expr::ExactBoundExpr;
6use vortex_array::expr::traversal::NodeExt;
7use vortex_array::expr::traversal::NodeVisitor;
8use vortex_array::expr::traversal::TraversalOrder;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_utils::aliases::hash_map::HashMap;
12
13/// Labels keyed by bound-tree identity.
14pub type BoundLabels<L> = HashMap<ExactBoundExpr, L>;
15
16/// Label each node in a bound expression using identity-keyed lookups.
17///
18/// This avoids structurally hashing bound dtypes, which may deserialize a lazy schema.
19pub fn label_bound_tree<L: Clone>(
20    expr: &BoundExpression,
21    self_label: impl Fn(&BoundExpression) -> L,
22    mut merge_child: impl FnMut(L, &L) -> L,
23) -> BoundLabels<L> {
24    let mut visitor = BoundLabelingVisitor {
25        labels: Default::default(),
26        self_label,
27        merge_child: &mut merge_child,
28    };
29    expr.accept(&mut visitor)
30        .vortex_expect("BoundLabelingVisitor is infallible");
31    visitor.labels
32}
33
34struct BoundLabelingVisitor<'a, L, F, G>
35where
36    F: Fn(&BoundExpression) -> L,
37    G: FnMut(L, &L) -> L,
38{
39    labels: BoundLabels<L>,
40    self_label: F,
41    merge_child: &'a mut G,
42}
43
44impl<'node, 'visitor, L: Clone, F, G> NodeVisitor<'node> for BoundLabelingVisitor<'visitor, L, F, G>
45where
46    F: Fn(&BoundExpression) -> L,
47    G: FnMut(L, &L) -> L,
48{
49    type NodeTy = BoundExpression;
50
51    fn visit_down(&mut self, _node: &'node Self::NodeTy) -> VortexResult<TraversalOrder> {
52        Ok(TraversalOrder::Continue)
53    }
54
55    fn visit_up(&mut self, node: &'node Self::NodeTy) -> VortexResult<TraversalOrder> {
56        let self_label = (self.self_label)(node);
57        let final_label = node.children().iter().fold(self_label, |acc, child| {
58            let child_label = self
59                .labels
60                .get(&ExactBoundExpr(child.clone()))
61                .vortex_expect("child must have label");
62            (self.merge_child)(acc, child_label)
63        });
64        self.labels
65            .insert(ExactBoundExpr(node.clone()), final_label);
66        Ok(TraversalOrder::Continue)
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use vortex_array::expr::col;
73    use vortex_array::expr::eq;
74    use vortex_array::expr::lit;
75    use vortex_array::expr::test_harness::struct_dtype;
76
77    use super::*;
78
79    #[test]
80    fn test_tree_depth() -> VortexResult<()> {
81        // Expression: $.col1 = 5
82        // Tree: eq(get_item(root(), "col1"), lit(5))
83        // Depth: root = 1, get_item = 2, lit = 1, eq = 3
84        let expr = eq(col("col1"), lit(5u16)).bind(&struct_dtype())?;
85        let depths = label_bound_tree(
86            &expr,
87            |_node| 1, // Each node has depth 1 by itself
88            |self_depth, child_depth| self_depth.max(*child_depth + 1),
89        );
90
91        // The root (eq) should have depth 3
92        assert_eq!(depths.get(&ExactBoundExpr(expr)), Some(&3));
93        Ok(())
94    }
95
96    #[test]
97    fn test_node_count() -> VortexResult<()> {
98        // Count total nodes in subtree (including self)
99        // Tree: eq(get_item(root(), "col1"), lit(5))
100        // Nodes: eq, get_item, root, lit = 4
101        let expr = eq(col("col1"), lit(5u16)).bind(&struct_dtype())?;
102        let counts = label_bound_tree(
103            &expr,
104            |_node| 1, // Each node counts as 1
105            |self_count, child_count| self_count + *child_count,
106        );
107
108        // Root should have count of 4 (eq, get_item, root, lit)
109        assert_eq!(counts.get(&ExactBoundExpr(expr)), Some(&4));
110        Ok(())
111    }
112}