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