vortex_expr/stats/
rewrite.rs1use 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
29pub type StatsRewriteRuleRef = Arc<dyn StatsRewriteRule>;
31
32pub trait StatsRewriteRule: Debug + Send + Sync + 'static {
49 fn scalar_fn_id(&self) -> ScalarFnId;
51
52 fn falsify(
60 &self,
61 expr: &BoundExpression,
62 session: &VortexSession,
63 ) -> VortexResult<Option<BoundExpression>> {
64 _ = expr;
65 _ = session;
66 Ok(None)
67 }
68
69 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
99pub fn falsify(
101 expr: &BoundExpression,
102 session: &VortexSession,
103) -> VortexResult<Option<BoundExpression>> {
104 ensure_predicate(expr)?;
105 rewrite(expr, session, StatsRewriteRule::falsify)
106}
107
108pub fn satisfy(
110 expr: &BoundExpression,
111 session: &VortexSession,
112) -> VortexResult<Option<BoundExpression>> {
113 ensure_predicate(expr)?;
114 rewrite(expr, session, StatsRewriteRule::satisfy)
115}
116
117pub trait BoundExpressionPruneExt {
119 fn falsify(&self, session: &VortexSession) -> VortexResult<Option<BoundExpression>>;
121
122 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 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}