You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "pepijnve (via GitHub)" <gi...@apache.org> on 2025/11/19 15:12:48 UTC

[PR] Guarantees [datafusion]

pepijnve opened a new pull request, #18821:
URL: https://github.com/apache/datafusion/pull/18821

   ## Which issue does this PR close?
   
   - None, break out PR of changes done in #17813
   
   ## Rationale for this change
   
   In #17813 `GuaranteeRewriter` is used from the `datafusion_expr` crate. In order to enable this the type needed to be moved from `datafusion_optimizer` to `datafusion_expr`.
   
   Additionally, during the development of #17813 some latent bugs were discovered in `GuaranteeRewriter` that have been resolved.
   
   ## What changes are included in this PR?
   
   - Move `GuaranteeRewriter` to `datafusion_expr`
   - Fix two bugs where rewrites of 'between' expression would fail
   * when one of the bounds was untyped null
   * when the lower bound was greater than the upper bound
   
   ## Are these changes tested?
   
   - Existing tests updated
   - Tests added for bugfixes
   
   ## Are there any user-facing changes?
   
   No


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542497145


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(

Review Comment:
   It's not so much that I find it easier to work with, but that it provides more room to change things in the future without API breakage. The public struct commits to using a `TreeNodeRewriter` which wasn't actually necessary since there was no code in the `transform_down` path.
   
   It also required an owned HashMap which wasn't really necessary either; just convenient.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542952000


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))

Review Comment:
   I've added the skip you suggested



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2543169865


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   Changes merged in



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#issuecomment-3554589454

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                                 guarantees                             main
   -----                                                 ----------                             ----
   logical_aggregate_with_join                           1.00    622.5±4.41µs        ? ?/sec    1.00    621.7±3.60µs        ? ?/sec
   logical_select_all_from_1000                          1.00     11.0±0.04ms        ? ?/sec    1.02     11.2±0.08ms        ? ?/sec
   logical_select_one_from_700                           1.00    408.3±1.71µs        ? ?/sec    1.00    408.7±2.22µs        ? ?/sec
   logical_trivial_join_high_numbered_columns            1.00    367.3±1.86µs        ? ?/sec    1.01    370.8±2.24µs        ? ?/sec
   logical_trivial_join_low_numbered_columns             1.00    353.8±6.28µs        ? ?/sec    1.01    356.6±2.58µs        ? ?/sec
   physical_intersection                                 1.00    819.1±8.81µs        ? ?/sec    1.01    826.9±5.02µs        ? ?/sec
   physical_join_consider_sort                           1.00   1364.7±6.96µs        ? ?/sec    1.00   1366.1±8.30µs        ? ?/sec
   physical_join_distinct                                1.00    344.7±1.23µs        ? ?/sec    1.01    346.9±2.72µs        ? ?/sec
   physical_many_self_joins                              1.00      9.3±0.04ms        ? ?/sec    1.00      9.3±0.03ms        ? ?/sec
   physical_plan_clickbench_all                          1.00    178.4±1.23ms        ? ?/sec    1.01    180.4±1.42ms        ? ?/sec
   physical_plan_clickbench_q1                           1.00      2.4±0.02ms        ? ?/sec    1.00      2.4±0.02ms        ? ?/sec
   physical_plan_clickbench_q10                          1.02      3.3±0.04ms        ? ?/sec    1.00      3.2±0.03ms        ? ?/sec
   physical_plan_clickbench_q11                          1.03      3.5±0.05ms        ? ?/sec    1.00      3.4±0.03ms        ? ?/sec
   physical_plan_clickbench_q12                          1.02      3.6±0.04ms        ? ?/sec    1.00      3.5±0.03ms        ? ?/sec
   physical_plan_clickbench_q13                          1.02      3.2±0.03ms        ? ?/sec    1.00      3.2±0.03ms        ? ?/sec
   physical_plan_clickbench_q14                          1.01      3.4±0.05ms        ? ?/sec    1.00      3.4±0.04ms        ? ?/sec
   physical_plan_clickbench_q15                          1.01      3.3±0.05ms        ? ?/sec    1.00      3.3±0.03ms        ? ?/sec
   physical_plan_clickbench_q16                          1.00      3.1±0.02ms        ? ?/sec    1.00      3.1±0.03ms        ? ?/sec
   physical_plan_clickbench_q17                          1.00      3.2±0.02ms        ? ?/sec    1.00      3.2±0.02ms        ? ?/sec
   physical_plan_clickbench_q18                          1.00      2.7±0.03ms        ? ?/sec    1.01      2.7±0.03ms        ? ?/sec
   physical_plan_clickbench_q19                          1.00      3.6±0.03ms        ? ?/sec    1.00      3.6±0.04ms        ? ?/sec
   physical_plan_clickbench_q2                           1.00      2.7±0.02ms        ? ?/sec    1.00      2.8±0.02ms        ? ?/sec
   physical_plan_clickbench_q20                          1.00      2.5±0.02ms        ? ?/sec    1.01      2.5±0.01ms        ? ?/sec
   physical_plan_clickbench_q21                          1.00      2.8±0.03ms        ? ?/sec    1.01      2.8±0.02ms        ? ?/sec
   physical_plan_clickbench_q22                          1.00      3.4±0.03ms        ? ?/sec    1.00      3.4±0.03ms        ? ?/sec
   physical_plan_clickbench_q23                          1.00      3.7±0.05ms        ? ?/sec    1.00      3.7±0.03ms        ? ?/sec
   physical_plan_clickbench_q24                          1.00      4.1±0.03ms        ? ?/sec    1.01      4.1±0.04ms        ? ?/sec
   physical_plan_clickbench_q25                          1.00      2.9±0.02ms        ? ?/sec    1.01      3.0±0.02ms        ? ?/sec
   physical_plan_clickbench_q26                          1.00      2.7±0.02ms        ? ?/sec    1.00      2.7±0.02ms        ? ?/sec
   physical_plan_clickbench_q27                          1.00      3.0±0.02ms        ? ?/sec    1.00      3.0±0.02ms        ? ?/sec
   physical_plan_clickbench_q28                          1.00      3.7±0.03ms        ? ?/sec    1.01      3.7±0.04ms        ? ?/sec
   physical_plan_clickbench_q29                          1.00      4.0±0.03ms        ? ?/sec    1.02      4.1±0.11ms        ? ?/sec
   physical_plan_clickbench_q3                           1.00      2.7±0.02ms        ? ?/sec    1.01      2.7±0.02ms        ? ?/sec
   physical_plan_clickbench_q30                          1.00     12.5±0.13ms        ? ?/sec    1.01     12.6±0.18ms        ? ?/sec
   physical_plan_clickbench_q31                          1.00      3.7±0.02ms        ? ?/sec    1.00      3.7±0.04ms        ? ?/sec
   physical_plan_clickbench_q32                          1.00      3.7±0.03ms        ? ?/sec    1.00      3.7±0.03ms        ? ?/sec
   physical_plan_clickbench_q33                          1.00      3.2±0.03ms        ? ?/sec    1.01      3.2±0.05ms        ? ?/sec
   physical_plan_clickbench_q34                          1.00      2.9±0.03ms        ? ?/sec    1.00      2.9±0.03ms        ? ?/sec
   physical_plan_clickbench_q35                          1.00      3.0±0.02ms        ? ?/sec    1.01      3.0±0.02ms        ? ?/sec
   physical_plan_clickbench_q36                          1.01      3.7±0.04ms        ? ?/sec    1.00      3.7±0.03ms        ? ?/sec
   physical_plan_clickbench_q37                          1.00      3.8±0.04ms        ? ?/sec    1.00      3.8±0.03ms        ? ?/sec
   physical_plan_clickbench_q38                          1.00      3.8±0.04ms        ? ?/sec    1.00      3.8±0.03ms        ? ?/sec
   physical_plan_clickbench_q39                          1.00      3.7±0.05ms        ? ?/sec    1.00      3.7±0.03ms        ? ?/sec
   physical_plan_clickbench_q4                           1.00      2.4±0.02ms        ? ?/sec    1.00      2.4±0.02ms        ? ?/sec
   physical_plan_clickbench_q40                          1.00      4.5±0.04ms        ? ?/sec    1.00      4.5±0.04ms        ? ?/sec
   physical_plan_clickbench_q41                          1.00      3.9±0.04ms        ? ?/sec    1.01      3.9±0.03ms        ? ?/sec
   physical_plan_clickbench_q42                          1.01      3.8±0.03ms        ? ?/sec    1.00      3.8±0.03ms        ? ?/sec
   physical_plan_clickbench_q43                          1.00      4.2±0.04ms        ? ?/sec    1.01      4.2±0.05ms        ? ?/sec
   physical_plan_clickbench_q44                          1.05      2.7±0.08ms        ? ?/sec    1.00      2.6±0.02ms        ? ?/sec
   physical_plan_clickbench_q45                          1.01      2.6±0.03ms        ? ?/sec    1.00      2.6±0.02ms        ? ?/sec
   physical_plan_clickbench_q46                          1.00      3.0±0.02ms        ? ?/sec    1.00      3.0±0.03ms        ? ?/sec
   physical_plan_clickbench_q47                          1.00      3.5±0.03ms        ? ?/sec    1.01      3.6±0.03ms        ? ?/sec
   physical_plan_clickbench_q48                          1.00      4.3±0.04ms        ? ?/sec    1.00      4.3±0.05ms        ? ?/sec
   physical_plan_clickbench_q49                          1.01      4.6±0.04ms        ? ?/sec    1.00      4.5±0.03ms        ? ?/sec
   physical_plan_clickbench_q5                           1.01      2.7±0.02ms        ? ?/sec    1.00      2.7±0.02ms        ? ?/sec
   physical_plan_clickbench_q50                          1.00      4.1±0.05ms        ? ?/sec    1.02      4.2±0.04ms        ? ?/sec
   physical_plan_clickbench_q51                          1.00      3.1±0.03ms        ? ?/sec    1.01      3.2±0.03ms        ? ?/sec
   physical_plan_clickbench_q6                           1.00      2.7±0.02ms        ? ?/sec    1.00      2.7±0.02ms        ? ?/sec
   physical_plan_clickbench_q7                           1.01      2.4±0.02ms        ? ?/sec    1.00      2.4±0.02ms        ? ?/sec
   physical_plan_clickbench_q8                           1.02      3.3±0.06ms        ? ?/sec    1.00      3.2±0.02ms        ? ?/sec
   physical_plan_clickbench_q9                           1.01      3.1±0.04ms        ? ?/sec    1.00      3.1±0.02ms        ? ?/sec
   physical_plan_tpcds_all                               1.00   1021.4±2.97ms        ? ?/sec    1.00   1023.2±3.70ms        ? ?/sec
   physical_plan_tpch_all                                1.00     63.5±0.36ms        ? ?/sec    1.00     63.6±0.32ms        ? ?/sec
   physical_plan_tpch_q1                                 1.00  1983.4±11.25µs        ? ?/sec    1.01      2.0±0.01ms        ? ?/sec
   physical_plan_tpch_q10                                1.00      3.9±0.01ms        ? ?/sec    1.00      3.9±0.02ms        ? ?/sec
   physical_plan_tpch_q11                                1.00      3.5±0.02ms        ? ?/sec    1.00      3.5±0.02ms        ? ?/sec
   physical_plan_tpch_q12                                1.00  1787.7±11.35µs        ? ?/sec    1.00  1793.0±12.71µs        ? ?/sec
   physical_plan_tpch_q13                                1.00   1434.3±6.68µs        ? ?/sec    1.00   1436.6±6.07µs        ? ?/sec
   physical_plan_tpch_q14                                1.00  1943.9±10.44µs        ? ?/sec    1.01   1958.8±9.69µs        ? ?/sec
   physical_plan_tpch_q16                                1.00      2.4±0.01ms        ? ?/sec    1.00      2.4±0.01ms        ? ?/sec
   physical_plan_tpch_q17                                1.00      2.6±0.01ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
   physical_plan_tpch_q18                                1.00      2.6±0.02ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
   physical_plan_tpch_q19                                1.00      3.1±0.01ms        ? ?/sec    1.01      3.2±0.02ms        ? ?/sec
   physical_plan_tpch_q2                                 1.00      5.8±0.03ms        ? ?/sec    1.01      5.9±0.04ms        ? ?/sec
   physical_plan_tpch_q20                                1.00      3.1±0.01ms        ? ?/sec    1.00      3.1±0.02ms        ? ?/sec
   physical_plan_tpch_q21                                1.00      4.2±0.02ms        ? ?/sec    1.00      4.2±0.02ms        ? ?/sec
   physical_plan_tpch_q22                                1.00      2.8±0.02ms        ? ?/sec    1.01      2.8±0.05ms        ? ?/sec
   physical_plan_tpch_q3                                 1.00      2.6±0.01ms        ? ?/sec    1.00      2.6±0.01ms        ? ?/sec
   physical_plan_tpch_q4                                 1.00   1472.6±8.69µs        ? ?/sec    1.01  1484.6±12.50µs        ? ?/sec
   physical_plan_tpch_q5                                 1.00      3.2±0.02ms        ? ?/sec    1.01      3.2±0.02ms        ? ?/sec
   physical_plan_tpch_q6                                 1.00    838.8±6.84µs        ? ?/sec    1.01    846.8±8.23µs        ? ?/sec
   physical_plan_tpch_q7                                 1.00      4.2±0.08ms        ? ?/sec    1.00      4.2±0.03ms        ? ?/sec
   physical_plan_tpch_q8                                 1.00      5.4±0.04ms        ? ?/sec    1.00      5.4±0.03ms        ? ?/sec
   physical_plan_tpch_q9                                 1.00      4.0±0.01ms        ? ?/sec    1.00      4.0±0.02ms        ? ?/sec
   physical_select_aggregates_from_200                   1.00     17.0±0.30ms        ? ?/sec    1.00     17.0±0.08ms        ? ?/sec
   physical_select_all_from_1000                         1.00     23.9±0.07ms        ? ?/sec    1.01     24.0±0.08ms        ? ?/sec
   physical_select_one_from_700                          1.00   1044.9±4.42µs        ? ?/sec    1.00   1043.3±4.96µs        ? ?/sec
   physical_sorted_union_order_by_10_int64               1.00      6.0±0.02ms        ? ?/sec    1.00      5.9±0.02ms        ? ?/sec
   physical_sorted_union_order_by_10_uint64              1.00     12.9±0.06ms        ? ?/sec    1.00     12.8±0.07ms        ? ?/sec
   physical_sorted_union_order_by_50_int64               1.00    162.5±0.99ms        ? ?/sec    1.00    162.3±0.94ms        ? ?/sec
   physical_sorted_union_order_by_50_uint64              1.00    375.3±2.02ms        ? ?/sec    1.01    379.0±3.30ms        ? ?/sec
   physical_theta_join_consider_sort                     1.00  1739.3±20.57µs        ? ?/sec    1.00  1740.2±16.52µs        ? ?/sec
   physical_unnest_to_join                               1.00  1826.2±17.88µs        ? ?/sec    1.00   1831.8±8.35µs        ? ?/sec
   physical_window_function_partition_by_12_on_values    1.00   1086.8±7.36µs        ? ?/sec    1.00   1089.5±9.95µs        ? ?/sec
   physical_window_function_partition_by_30_on_values    1.00      2.2±0.01ms        ? ?/sec    1.00      2.2±0.01ms        ? ?/sec
   physical_window_function_partition_by_4_on_values     1.00    657.2±4.82µs        ? ?/sec    1.00    655.7±5.15µs        ? ?/sec
   physical_window_function_partition_by_7_on_values     1.00    807.4±4.23µs        ? ?/sec    1.00    805.6±4.28µs        ? ?/sec
   physical_window_function_partition_by_8_on_values     1.00    868.4±4.37µs        ? ?/sec    1.00    868.2±7.81µs        ? ?/sec
   with_param_values_many_columns                        1.00    660.5±3.53µs        ? ?/sec    1.00    662.4±9.48µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542702978


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   If you like you can target #18823 to this one and we can tackle them both in one go.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542710913


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -458,7 +527,9 @@ mod tests {
                     .collect(),
                 *negated,
             );
-            let output = expr.clone().rewrite(&mut rewriter).data().unwrap();
+            let output = rewrite_with_guarantees(expr.clone(), guarantees.iter())
+                .data()
+                .unwrap();
             let expected_list = expected_list
                 .iter()
                 .map(|v| lit(ScalarValue::Int32(Some(*v))))

Review Comment:
   The fixes were related to 'between'. Covered by additional cases at https://github.com/apache/datafusion/pull/18821/files/0a7962eca41e1b126ecb1c810b54559962bae2aa#diff-e8ddf36e2e98953432564dbb9c4247fa4f9baeff629e4ba779357db99a6aa95cR285
   
   I'll add a couple more for the null handling



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542532665


##########
datafusion/optimizer/src/simplify_expressions/mod.rs:
##########
@@ -35,4 +34,4 @@ pub use simplify_exprs::*;
 pub use simplify_predicates::simplify_predicates;
 
 // Export for test in datafusion/core/tests/optimizer_integration.rs
-pub use guarantees::GuaranteeRewriter;
+pub use datafusion_expr::expr_rewriter::GuaranteeRewriter;

Review Comment:
   I think we should be conservative (keep it) unless there is a good reason not to
   
   My rationale is that it is really annoying as a downstream user if I have to change my code and get nothing from needing to do so (other than the upstream crate maintainers now feel their code is cleaner) 🤷  -- not a hard and fast rule, but one I think has served us well



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542503366


##########
datafusion/expr/src/expr_rewriter/mod.rs:
##########
@@ -31,7 +31,12 @@ use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
 use datafusion_common::TableReference;
 use datafusion_common::{Column, DFSchema, Result};
 
+mod guarantees;
+pub use guarantees::rewrite_with_guarantees;
+pub use guarantees::rewrite_with_guarantees_map;
+pub use guarantees::GuaranteeRewriter;

Review Comment:
   Only being made public to be able to keep the reexport from `datafusion_optimizer`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542761393


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   - https://github.com/pepijnve/datafusion/pull/1



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542645965


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   this PR doesn't introduce it, but I noticed that the way this code is structured it deep clones the expr in many cases (on rewrite)
   
   I don't think it is a huge deal, but I was able to remove many of the clones (I pushed the changes up to #18823)
   
   This is the commit in particular if you are interested: https://github.com/apache/datafusion/pull/18823/commits/b53d2cfca9f9136da70a39f1896f4885253dbd92



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#issuecomment-3554771456

   Thank you @pepijnve 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542482873


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(

Review Comment:
   Copy/paste of comment by @alamb at https://github.com/apache/datafusion/pull/17813#discussion_r2542032635 here.
   
   > Unless there is a good reason, I think we should avoid removing this API as it will cause unecessary churn on downstream crates
   > 
   > If you find rewrite_with_guarantees easier to work with, maybe you leave GuaranteeRewriter and but implement rewrite_with_guarantees in terms of that



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#issuecomment-3554368293

   🤖 `./gh_compare_branch_bench.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking/blob/main/gh_compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing guarantees (8340cc36236824a4d4c43c7b8d4c064ae4a1a7ac) to 794660482bb21a9f974c6345d4b9a631009a316b [diff](https://github.com/apache/datafusion/compare/794660482bb21a9f974c6345d4b9a631009a316b..8340cc36236824a4d4c43c7b8d4c064ae4a1a7ac)
   BENCH_NAME=sql_planner
   BENCH_COMMAND=cargo bench --bench sql_planner
   BENCH_FILTER=
   BENCH_BRANCH_NAME=guarantees
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542953009


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   I'll process this asap



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#issuecomment-3553281992

   I've retained the public visibility of GuaranteeRewriter for now, but I wonder if this is actually necessary. Per the code comments it was only exported for tests in `datafusion/core/tests/optimizer_integration.rs`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542626934


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -458,7 +527,9 @@ mod tests {
                     .collect(),
                 *negated,
             );
-            let output = expr.clone().rewrite(&mut rewriter).data().unwrap();
+            let output = rewrite_with_guarantees(expr.clone(), guarantees.iter())
+                .data()
+                .unwrap();
             let expected_list = expected_list
                 .iter()
                 .map(|v| lit(ScalarValue::Int32(Some(*v))))

Review Comment:
   Did you want to add a test for the newly fixed case too? 
   
   As in I don't see any tests for the bug fixes



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #18821:
URL: https://github.com/apache/datafusion/pull/18821


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542501127


##########
datafusion/optimizer/src/simplify_expressions/mod.rs:
##########
@@ -35,4 +34,4 @@ pub use simplify_exprs::*;
 pub use simplify_predicates::simplify_predicates;
 
 // Export for test in datafusion/core/tests/optimizer_integration.rs
-pub use guarantees::GuaranteeRewriter;
+pub use datafusion_expr::expr_rewriter::GuaranteeRewriter;

Review Comment:
   If this was only exported for testing purposes, is it really necessary to keep it? Once it's out there, there's no taking back of course, so perhaps best to be conservative?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542539166


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -15,30 +15,16 @@
 // specific language governing permissions and limitations
 // under the License.
 
-//! Simplifier implementation for [`ExprSimplifier::with_guarantees()`]
-//!
-//! [`ExprSimplifier::with_guarantees()`]: crate::simplify_expressions::expr_simplifier::ExprSimplifier::with_guarantees
+//! Rewrite expressions based on external expression value range guarantees.
 
-use std::{borrow::Cow, collections::HashMap};
+use std::borrow::Cow;
 
-use datafusion_common::tree_node::{Transformed, TreeNodeRewriter};
-use datafusion_common::{DataFusionError, Result};
-use datafusion_expr::interval_arithmetic::{Interval, NullableInterval};
-use datafusion_expr::{expr::InList, lit, Between, BinaryExpr, Expr};
+use crate::{expr::InList, lit, Between, BinaryExpr, Expr};
+use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRewriter};
+use datafusion_common::{DataFusionError, HashMap, Result, ScalarValue};
+use datafusion_expr_common::interval_arithmetic::{Interval, NullableInterval};
 
 /// Rewrite expressions to incorporate guarantees.

Review Comment:
   Can we please add a doc link to point people at `rewrite_with_guarantees`?
   
   Something like
   
   ```suggestion
   /// Rewrite expressions to incorporate guarantees.
   ///
   /// See [`rewrite_with_guarantees`] for more information
   ```



##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {
+        Expr::IsNull(inner) => match guarantees.get(inner.as_ref()) {

Review Comment:
   this looks really nice now



##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))

Review Comment:
   We could probably make this more efficient by skipping the entire recursion / tree walk in `rewrite_with_guarantees_map`  -- rewriting the entire tree tree is not free, even if no changes are made
   
   The same check is in `rewrite_expr` but that is called on each node in the tree always even if there are no guarantees
   
   ```suggestion
       if guarantees.is_empty() {
         return Ok(Transformed::no(expr));
       }
       expr.transform_up(|e| rewrite_expr(e, guarantees))
   ```
   
   It does look like the rewrite code is called for all plans (and the guarantees will be empty for almost all of them), so it might save non trivial time



##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -458,7 +527,9 @@ mod tests {
                     .collect(),
                 *negated,
             );
-            let output = expr.clone().rewrite(&mut rewriter).data().unwrap();
+            let output = rewrite_with_guarantees(expr.clone(), guarantees.iter())
+                .data()
+                .unwrap();
             let expected_list = expected_list
                 .iter()
                 .map(|v| lit(ScalarValue::Int32(Some(*v))))

Review Comment:
   Did you want to add a test for the newly fixed case too? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "pepijnve (via GitHub)" <gi...@apache.org>.
pepijnve commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542950506


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -458,7 +527,9 @@ mod tests {
                     .collect(),
                 *negated,
             );
-            let output = expr.clone().rewrite(&mut rewriter).data().unwrap();
+            let output = rewrite_with_guarantees(expr.clone(), guarantees.iter())
+                .data()
+                .unwrap();
             let expected_list = expected_list
                 .iter()
                 .map(|v| lit(ScalarValue::Int32(Some(*v))))

Review Comment:
   I've added test cases that (I think) cover every possible permutation of between and null boundaries



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Move `GuaranteeRewriter` to datafusion_expr [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18821:
URL: https://github.com/apache/datafusion/pull/18821#discussion_r2542751330


##########
datafusion/expr/src/expr_rewriter/guarantees.rs:
##########
@@ -48,199 +34,282 @@ impl<'a> GuaranteeRewriter<'a> {
         guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
     ) -> Self {
         Self {
-            // TODO: Clippy wants the "map" call removed, but doing so generates
-            //       a compilation error. Remove the clippy directive once this
-            //       issue is fixed.
-            #[allow(clippy::map_identity)]
             guarantees: guarantees.into_iter().map(|(k, v)| (k, v)).collect(),
         }
     }
 }
 
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval] that represents the known possible
+/// values of the expression.
+///
+/// Rewriting expressions using this type of guarantee can make the work of other expression
+/// simplifications, like const evaluation, easier.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+///
+/// If the set of guarantees will be used to rewrite more than one expression, consider using
+/// [rewrite_with_guarantees_map] instead.
+///
+/// A full example of using this rewrite rule can be found in
+/// [`ExprSimplifier::with_guarantees()`](https://docs.rs/datafusion/latest/datafusion/optimizer/simplify_expressions/struct.ExprSimplifier.html#method.with_guarantees).
+pub fn rewrite_with_guarantees<'a>(
+    expr: Expr,
+    guarantees: impl IntoIterator<Item = &'a (Expr, NullableInterval)>,
+) -> Result<Transformed<Expr>> {
+    let guarantees_map: HashMap<&Expr, &NullableInterval> =
+        guarantees.into_iter().map(|(k, v)| (k, v)).collect();
+    rewrite_with_guarantees_map(expr, &guarantees_map)
+}
+
+/// Rewrite expressions to incorporate guarantees.
+///
+/// Guarantees are a mapping from an expression (which currently is always a
+/// column reference) to a [NullableInterval]. The interval represents the known
+/// possible values of the column.
+///
+/// For example, if we know that a column is not null and has values in the
+/// range [1, 10), we can rewrite `x IS NULL` to `false` or `x < 10` to `true`.
+pub fn rewrite_with_guarantees_map<'a>(
+    expr: Expr,
+    guarantees: &'a HashMap<&'a Expr, &'a NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    expr.transform_up(|e| rewrite_expr(e, guarantees))
+}
+
 impl TreeNodeRewriter for GuaranteeRewriter<'_> {
     type Node = Expr;
 
     fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
-        if self.guarantees.is_empty() {
-            return Ok(Transformed::no(expr));
-        }
+        rewrite_expr(expr, &self.guarantees)
+    }
+}
 
-        match &expr {
-            Expr::IsNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(true))),
-                Some(NullableInterval::NotNull { .. }) => {
-                    Ok(Transformed::yes(lit(false)))
-                }
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::IsNotNull(inner) => match self.guarantees.get(inner.as_ref()) {
-                Some(NullableInterval::Null { .. }) => Ok(Transformed::yes(lit(false))),
-                Some(NullableInterval::NotNull { .. }) => Ok(Transformed::yes(lit(true))),
-                _ => Ok(Transformed::no(expr)),
-            },
-            Expr::Between(Between {
-                expr: inner,
-                negated,
-                low,
-                high,
-            }) => {
-                if let (Some(interval), Expr::Literal(low, _), Expr::Literal(high, _)) = (
-                    self.guarantees.get(inner.as_ref()),
-                    low.as_ref(),
-                    high.as_ref(),
-                ) {
-                    let expr_interval = NullableInterval::NotNull {
-                        values: Interval::try_new(low.clone(), high.clone())?,
-                    };
-
-                    let contains = expr_interval.contains(*interval)?;
-
-                    if contains.is_certainly_true() {
-                        Ok(Transformed::yes(lit(!negated)))
-                    } else if contains.is_certainly_false() {
-                        Ok(Transformed::yes(lit(*negated)))
-                    } else {
-                        Ok(Transformed::no(expr))
-                    }
-                } else {
-                    Ok(Transformed::no(expr))
-                }
-            }
+fn rewrite_expr(
+    expr: Expr,
+    guarantees: &HashMap<&Expr, &NullableInterval>,
+) -> Result<Transformed<Expr>> {
+    if guarantees.is_empty() {
+        return Ok(Transformed::no(expr));
+    }
 
-            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
-                // The left or right side of expression might either have a guarantee
-                // or be a literal. Either way, we can resolve them to a NullableInterval.
-                let left_interval = self
-                    .guarantees
-                    .get(left.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = left.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-                let right_interval = self
-                    .guarantees
-                    .get(right.as_ref())
-                    .map(|interval| Cow::Borrowed(*interval))
-                    .or_else(|| {
-                        if let Expr::Literal(value, _) = right.as_ref() {
-                            Some(Cow::Owned(value.clone().into()))
-                        } else {
-                            None
-                        }
-                    });
-
-                match (left_interval, right_interval) {
-                    (Some(left_interval), Some(right_interval)) => {
-                        let result =
-                            left_interval.apply_operator(op, right_interval.as_ref())?;
-                        if result.is_certainly_true() {
-                            Ok(Transformed::yes(lit(true)))
-                        } else if result.is_certainly_false() {
-                            Ok(Transformed::yes(lit(false)))
-                        } else {
-                            Ok(Transformed::no(expr))
-                        }
-                    }
-                    _ => Ok(Transformed::no(expr)),
-                }
+    let new_expr = match &expr {

Review Comment:
   will do



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org