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