Skip to main content

vortex_array/expr/
optimize.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5
6use crate::expr::BoundExpression;
7use crate::scalar_fn::ExpressionReduceNode;
8
9impl BoundExpression {
10    /// Optimize the root expression node only, iterating to convergence.
11    ///
12    /// This applies optimization rules repeatedly until no more changes occur:
13    /// 1. `simplify` - scalar-function simplifications over the node
14    /// 2. `reduce` - abstract reduction rules via `ReduceNode`
15    pub fn optimize(&self) -> VortexResult<BoundExpression> {
16        Ok(self.try_optimize()?.unwrap_or_else(|| self.clone()))
17    }
18
19    /// Apply this node's own simplification rule, if it has one.
20    ///
21    /// Non-scalar nodes carry no rules, so they never simplify.
22    fn simplify_node(&self) -> VortexResult<Option<BoundExpression>> {
23        match self {
24            BoundExpression::Scalar { scalar_fn, .. } => Ok(scalar_fn
25                .simplify_expression(&ExpressionReduceNode::new(self))?
26                .map(ExpressionReduceNode::into_expression)),
27            BoundExpression::Root { .. } => Ok(None),
28        }
29    }
30
31    /// Apply this node's own abstract reduction rule, if it has one.
32    fn reduce_node(&self) -> VortexResult<Option<BoundExpression>> {
33        match self {
34            BoundExpression::Scalar { scalar_fn, .. } => Ok(scalar_fn
35                .reduce_expression(&ExpressionReduceNode::new(self))?
36                .map(ExpressionReduceNode::into_expression)),
37            BoundExpression::Root { .. } => Ok(None),
38        }
39    }
40
41    /// Try to optimize the root expression node only, returning None if no optimizations applied.
42    fn try_optimize(&self) -> VortexResult<Option<BoundExpression>> {
43        // Copy-on-write: `current` stays None until a rule fires, so unchanged nodes (the common
44        // case) are never cloned.
45        let mut current: Option<BoundExpression> = None;
46        let mut loop_counter = 0;
47
48        loop {
49            if loop_counter > 100 {
50                vortex_error::vortex_bail!(
51                    "Exceeded maximum optimization iterations (possible infinite loop)"
52                );
53            }
54            loop_counter += 1;
55
56            let expr = current.as_ref().unwrap_or(self);
57            let mut changed = false;
58
59            if let Some(simplified) = expr.simplify_node()? {
60                current = Some(simplified);
61                changed = true;
62            }
63
64            let expr = current.as_ref().unwrap_or(self);
65            if let Some(reduced) = expr.reduce_node()? {
66                current = Some(reduced);
67                changed = true;
68            }
69
70            if !changed {
71                break;
72            }
73        }
74
75        Ok(current)
76    }
77    /// Optimize the entire expression tree recursively.
78    ///
79    /// Optimizes children first (bottom-up), then optimizes the root.
80    pub fn optimize_recursive(&self) -> VortexResult<BoundExpression> {
81        Ok(self
82            .try_optimize_recursive()?
83            .unwrap_or_else(|| self.clone()))
84    }
85
86    /// Try to optimize the entire expression tree recursively.
87    pub fn try_optimize_recursive(&self) -> VortexResult<Option<BoundExpression>> {
88        // First optimize the root
89        let mut current = self.try_optimize()?;
90
91        // Then recursively optimize children. The new children vector is only allocated once a
92        // child actually changes, so fully-optimized subtrees cost no allocations.
93        let expr = current.as_ref().unwrap_or(self);
94        let children = expr.children();
95        let mut new_children: Option<Vec<BoundExpression>> = None;
96        for (idx, child) in children.iter().enumerate() {
97            if let Some(optimized) = child.try_optimize_recursive()? {
98                new_children
99                    .get_or_insert_with(|| children[..idx].to_vec())
100                    .push(optimized);
101            } else if let Some(new_children) = new_children.as_mut() {
102                new_children.push(child.clone());
103            }
104        }
105
106        if let Some(new_children) = new_children {
107            let updated = expr.clone().with_children(new_children)?;
108
109            // After updating children, try to optimize root again
110            current = Some(updated.try_optimize()?.unwrap_or(updated));
111        }
112
113        Ok(current)
114    }
115}