alamb commented on code in PR #19722:
URL: https://github.com/apache/datafusion/pull/19722#discussion_r2706394549


##########
datafusion/optimizer/src/simplify_expressions/udf_preimage.rs:
##########
@@ -0,0 +1,270 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use datafusion_common::{Result, internal_err, tree_node::Transformed};
+use datafusion_expr::{
+    Expr, Operator, and, binary_expr, lit, or, simplify::SimplifyContext,
+};
+use datafusion_expr_common::interval_arithmetic::Interval;
+
+/// Rewrites a binary expression using its "preimage"
+///
+/// Specifically it rewrites expressions of the form `<expr> OP x` (e.g. 
`<expr> =
+/// x`) where `<expr>` is known to have a pre-image (aka the entire single
+/// range for which it is valid)
+///
+/// This rewrite is described in the [ClickHouse Paper] and is particularly
+/// useful for simplifying expressions `date_part` or equivalent functions. The
+/// idea is that if you have an expression like `date_part(YEAR, k) = 2024` 
and you
+/// can find a [preimage] for `date_part(YEAR, k)`, which is the range of dates
+/// covering the entire year of 2024. Thus, you can rewrite the expression to
+/// `k >= '2024-01-01' AND k < '2025-01-01'`, which uses an inclusive lower 
bound
+/// and exclusive upper bound and is often more optimizable.
+///
+/// [ClickHouse Paper]:  https://www.vldb.org/pvldb/vol17/p3731-schulze.pdf
+/// [preimage]: https://en.wikipedia.org/wiki/Image_(mathematics)#Inverse_image
+///
+pub(super) fn rewrite_with_preimage(
+    _info: &SimplifyContext,
+    preimage_interval: Interval,
+    op: Operator,
+    expr: Box<Expr>,
+) -> Result<Transformed<Expr>> {
+    let (lower, upper) = preimage_interval.into_bounds();
+    let (lower, upper) = (lit(lower), lit(upper));
+
+    let rewritten_expr = match op {
+        // <expr> < x   ==>  <expr> < lower
+        // <expr> >= x  ==>  <expr> >= lower
+        Operator::Lt | Operator::GtEq => binary_expr(*expr, op, lower),
+        // <expr> > x ==> <expr> >= upper
+        Operator::Gt => binary_expr(*expr, Operator::GtEq, upper),
+        // <expr> <= x ==> <expr> < upper
+        Operator::LtEq => binary_expr(*expr, Operator::Lt, upper),
+        // <expr> = x ==> (<expr> >= lower) and (<expr> < upper)
+        //
+        // <expr> is not distinct from x ==> (<expr> is NULL and x is NULL) or 
((<expr> >= lower) and (<expr> < upper))
+        // but since x is always not NULL => (<expr> >= lower) and (<expr> < 
upper)
+        Operator::Eq | Operator::IsNotDistinctFrom => and(
+            binary_expr(*expr.clone(), Operator::GtEq, lower),
+            binary_expr(*expr, Operator::Lt, upper),
+        ),
+        // <expr> != x ==> (<expr> < lower) or (<expr> >= upper)
+        Operator::NotEq => or(
+            binary_expr(*expr.clone(), Operator::Lt, lower),
+            binary_expr(*expr, Operator::GtEq, upper),
+        ),
+        // <expr> is distinct from x ==> (<expr> < lower) or (<expr> >= upper) 
or (<expr> is NULL and x is not NULL) or (<expr> is not NULL and x is NULL)

Review Comment:
   I think we have to be careful about NULLs here -- specifically I think the 
preimage must be "null pure" -- aka if given a NULL input, it can't return an 
preimage interval, otherwise the results will be false. 
   
   I think we can resolve this by  either
   1. adding a comment to the pre_image method call that explains the need to 
be null pure.
   2. Don't call pre_image if the literal is NULL
   
   Here is an example (made by codex and I double checked carefully) where we 
could get wrong answers if a null literal is passed in and preimage returns a 
non null
   
   For example, given
   ```sql
     f(x) IS DISTINCT FROM NULL
   ```
   
     This is equivalent to `f(x) IS NOT NULL`, so:
   - For `x = NULL`, `f(x) = NULL` → predicate is false.
   
   Rewritten predicate (current logic in rewrite_with_preimage):
   
   ```sql
     x < 100 OR x >= 200 OR x IS NULL
   ```
     - For `x = NULL`, this is true because of `x IS NULL`.
   
   So the rewrite returns true while the original is false—a correctness bug.
   
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to