Skip to main content

vortex_expr/stats/
rewrite.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Session-registered rewrite rules for aggregate-backed stats expressions.
5
6use std::fmt::Debug;
7use std::sync::Arc;
8
9use vortex_array::dtype::DType;
10use vortex_array::scalar_fn::ScalarFnId;
11use vortex_array::scalar_fn::builtin::boolean::Boolean;
12use vortex_array::scalar_fn::builtin::operators::BooleanOperator;
13use vortex_error::VortexResult;
14use vortex_error::vortex_ensure;
15use vortex_session::VortexSession;
16use vortex_utils::iter::ReduceBalancedIterExt;
17
18use crate::BoundExpression;
19use crate::ScalarFnExprExt;
20use crate::stats::session::StatsSessionExt;
21
22mod builtins;
23#[cfg(test)]
24mod fn_tests;
25pub mod helpers;
26
27pub(crate) use builtins::register_builtins;
28
29/// Shared reference to a stats rewrite rule.
30pub type StatsRewriteRuleRef = Arc<dyn StatsRewriteRule>;
31
32/// A plugin-provided rule for predicates whose root scalar function matches this rule.
33///
34/// Rules do not produce expressions equivalent to `expr`. They produce optional sufficient
35/// conditions over stats for the current scope:
36///
37/// - a falsifier evaluating to `true` proves that `expr` is false for every row in the scope;
38/// - a satisfier evaluating to `true` proves that `expr` is true for every row in the scope.
39///
40/// Returning `None` means this rule cannot prove anything for the expression. A returned proof
41/// expression that evaluates to `false` or `null` is also inconclusive.
42///
43/// Multiple rules may be registered for the same scalar function. Their proofs are combined with
44/// `OR`, so every proof returned by an individual rule must be sound on its own.
45///
46/// `expr` is the full predicate expression whose root scalar function id is
47/// [`Self::scalar_fn_id`].
48pub trait StatsRewriteRule: Debug + Send + Sync + 'static {
49    /// Returns the scalar function id handled by this rule.
50    fn scalar_fn_id(&self) -> ScalarFnId;
51
52    /// Returns a stats-backed proof that `expr` is false for the current scope.
53    ///
54    /// If the returned expression evaluates to `true` against the scope's stats, then `expr` is
55    /// guaranteed to be false for every row in that scope. A returned proof expression that
56    /// evaluates to `false` or `null` is inconclusive.
57    ///
58    /// Returns `Ok(None)` when this rule cannot construct a sound falsity proof for `expr`.
59    fn falsify(
60        &self,
61        expr: &BoundExpression,
62        session: &VortexSession,
63    ) -> VortexResult<Option<BoundExpression>> {
64        _ = expr;
65        _ = session;
66        Ok(None)
67    }
68
69    /// Returns a stats-backed proof that `expr` is true for the current scope.
70    ///
71    /// If the returned expression evaluates to `true` against the scope's stats, then `expr` is
72    /// guaranteed to be true for every row in that scope. A returned proof expression that
73    /// evaluates to `false` or `null` is inconclusive.
74    ///
75    /// This is not the complement of [`Self::falsify`]; both methods are one-way proofs and may be
76    /// implemented independently.
77    ///
78    /// Returns `Ok(None)` when this rule cannot construct a sound truth proof for `expr`.
79    fn satisfy(
80        &self,
81        expr: &BoundExpression,
82        session: &VortexSession,
83    ) -> VortexResult<Option<BoundExpression>> {
84        _ = expr;
85        _ = session;
86        Ok(None)
87    }
88}
89
90fn ensure_predicate(expr: &BoundExpression) -> VortexResult<()> {
91    let dtype = expr.dtype();
92    vortex_ensure!(
93        matches!(dtype, DType::Bool(_)),
94        "Stats rewrites require a boolean predicate, got {dtype}",
95    );
96    Ok(())
97}
98
99/// Rewrite `expr` into a stats-backed falsifier.
100pub fn falsify(
101    expr: &BoundExpression,
102    session: &VortexSession,
103) -> VortexResult<Option<BoundExpression>> {
104    ensure_predicate(expr)?;
105    rewrite(expr, session, StatsRewriteRule::falsify)
106}
107
108/// Rewrite `expr` into a stats-backed satisfier.
109pub fn satisfy(
110    expr: &BoundExpression,
111    session: &VortexSession,
112) -> VortexResult<Option<BoundExpression>> {
113    ensure_predicate(expr)?;
114    rewrite(expr, session, StatsRewriteRule::satisfy)
115}
116
117/// Statistics-based pruning methods on [`BoundExpression`] predicates.
118pub trait BoundExpressionPruneExt {
119    /// Return an expression that proves this predicate is definitely false from statistics.
120    fn falsify(&self, session: &VortexSession) -> VortexResult<Option<BoundExpression>>;
121
122    /// Return an expression that proves this predicate is definitely true from statistics.
123    fn satisfy(&self, session: &VortexSession) -> VortexResult<Option<BoundExpression>>;
124}
125
126impl BoundExpressionPruneExt for BoundExpression {
127    fn falsify(&self, session: &VortexSession) -> VortexResult<Option<BoundExpression>> {
128        falsify(self, session)
129    }
130
131    fn satisfy(&self, session: &VortexSession) -> VortexResult<Option<BoundExpression>> {
132        satisfy(self, session)
133    }
134}
135
136fn rewrite(
137    expr: &BoundExpression,
138    session: &VortexSession,
139    apply: fn(
140        &dyn StatsRewriteRule,
141        &BoundExpression,
142        &VortexSession,
143    ) -> VortexResult<Option<BoundExpression>>,
144) -> VortexResult<Option<BoundExpression>> {
145    // The scope alone proves nothing about the rows it contains.
146    let Some(scalar_fn) = expr.as_scalar() else {
147        return Ok(None);
148    };
149    let rules = session.stats().rewrite_rules_for(scalar_fn.id());
150    let Some(rules) = rules else {
151        return Ok(None);
152    };
153
154    let mut rewrites = Vec::new();
155    for rule in rules.iter() {
156        if let Some(rewrite) = apply(rule.as_ref(), expr, session)? {
157            rewrites.push(rewrite);
158        }
159    }
160
161    rewrites
162        .into_iter()
163        .try_reduce_balanced(|lhs, rhs| Boolean.try_new_bound_expr(BooleanOperator::Or, [lhs, rhs]))
164}
165
166#[cfg(test)]
167mod tests {
168    use std::sync::LazyLock;
169
170    use vortex_array::dtype::DType;
171    use vortex_array::dtype::Nullability;
172    use vortex_array::dtype::PType;
173    use vortex_array::scalar_fn::ScalarFnId;
174    use vortex_array::scalar_fn::ScalarFnVTable;
175    use vortex_array::scalar_fn::builtin::not::Not;
176    use vortex_error::VortexResult;
177    use vortex_session::VortexSession;
178
179    use super::StatsRewriteRule;
180    use crate::BoundExpression;
181    use crate::lit;
182    use crate::not;
183    use crate::or;
184    use crate::stats::rewrite::BoundExpressionPruneExt;
185    use crate::stats::session::StatsSessionExt;
186
187    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
188
189    #[derive(Debug)]
190    struct StaticNotRule {
191        falsifier: Option<BoundExpression>,
192        satisfier: Option<BoundExpression>,
193    }
194
195    impl StatsRewriteRule for StaticNotRule {
196        fn scalar_fn_id(&self) -> ScalarFnId {
197            Not.id()
198        }
199
200        fn falsify(
201            &self,
202            _expr: &BoundExpression,
203            _session: &VortexSession,
204        ) -> VortexResult<Option<BoundExpression>> {
205            Ok(self.falsifier.clone())
206        }
207
208        fn satisfy(
209            &self,
210            _expr: &BoundExpression,
211            _session: &VortexSession,
212        ) -> VortexResult<Option<BoundExpression>> {
213            Ok(self.satisfier.clone())
214        }
215    }
216
217    #[test]
218    fn combines_multiple_falsifiers_with_or() -> VortexResult<()> {
219        let session = VortexSession::empty();
220        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
221        session.stats().register_rewrite(StaticNotRule {
222            falsifier: Some(lit(false).bind(&dtype)?),
223            satisfier: None,
224        });
225        session.stats().register_rewrite(StaticNotRule {
226            falsifier: Some(lit(true).bind(&dtype)?),
227            satisfier: None,
228        });
229
230        assert_eq!(
231            not(lit(true)).bind(&dtype)?.falsify(&session)?,
232            Some(or(lit(false), lit(true)).bind(&dtype)?)
233        );
234        Ok(())
235    }
236
237    #[test]
238    fn combines_multiple_satisfiers_with_or() -> VortexResult<()> {
239        let session = VortexSession::empty();
240        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
241        session.stats().register_rewrite(StaticNotRule {
242            falsifier: None,
243            satisfier: Some(lit(false).bind(&dtype)?),
244        });
245        session.stats().register_rewrite(StaticNotRule {
246            falsifier: None,
247            satisfier: Some(lit(true).bind(&dtype)?),
248        });
249
250        assert_eq!(
251            not(lit(true)).bind(&dtype)?.satisfy(&session)?,
252            Some(or(lit(false), lit(true)).bind(&dtype)?)
253        );
254        Ok(())
255    }
256
257    #[test]
258    fn unregistered_expression_has_no_rewrite() -> VortexResult<()> {
259        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
260
261        let expr = not(lit(true)).bind(&dtype)?;
262        assert_eq!(expr.falsify(&SESSION)?, None);
263        assert_eq!(expr.satisfy(&SESSION)?, None);
264        Ok(())
265    }
266
267    #[test]
268    fn non_predicate_expression_errors() -> VortexResult<()> {
269        let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
270
271        let expr = lit(7).bind(&dtype)?;
272        assert!(expr.falsify(&SESSION).is_err());
273        assert!(expr.satisfy(&SESSION).is_err());
274        Ok(())
275    }
276}