alamb commented on code in PR #19722: URL: https://github.com/apache/datafusion/pull/19722#discussion_r2702378875
########## datafusion/optimizer/src/simplify_expressions/udf_preimage.rs: ########## @@ -0,0 +1,114 @@ +// 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::{ + BinaryExpr, Expr, Operator, and, 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 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( Review Comment: I think we should add unit tests for this function as part of the initial PR. In order to do so, I recommend creating: 1. A test scalarfunction (not date_part, but something defined in this module) that always returns a specified pre-image 2. Unit tests that then exercise this rewrite Unit tests would look something like define a preimage function `preimag_func` and then verify rewrites * input = `preimage_func(x) = 500` --> `x <= 100 && x >= 200` I am thinking once you have the rewrite well tested with unit tests, then hooking up date_part will be straightforward, and we just need to write a few .slt tests to validate everything is hooked up correctly ########## datafusion/optimizer/src/simplify_expressions/udf_preimage.rs: ########## @@ -0,0 +1,114 @@ +// 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::{ + BinaryExpr, Expr, Operator, and, 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 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 => Expr::BinaryExpr(BinaryExpr { Review Comment: FWIW you can potentially use `binary_expr` to make this code more concise: https://docs.rs/datafusion/latest/datafusion/logical_expr/fn.binary_expr.html ########## datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs: ########## @@ -1952,12 +1955,98 @@ impl TreeNodeRewriter for Simplifier<'_> { })) } + // ======================================= + // preimage_in_comparison + // ======================================= + // + // For case: + // date_part(expr as 'YEAR') op literal + // + // Background: + // Datasources such as Parquet can prune partitions using simple predicates, + // but they cannot do so for complex expressions. + // For a complex predicate like `date_part('YEAR', c1) < 2000`, pruning is not possible. + // After rewriting it to `c1 < 2000-01-01`, pruning becomes feasible. + // NOTE: we only consider immutable UDFs with literal RHS values + Expr::BinaryExpr(BinaryExpr { left, op, right }) => { + use datafusion_expr::Operator::*; + let is_preimage_op = matches!( Review Comment: it might be nice (as a follow on PR) to mention this list in the docs for preimage -- e.g. that it only applies to predicates `=, !=, ...` ########## datafusion/optimizer/src/simplify_expressions/udf_preimage.rs: ########## @@ -0,0 +1,114 @@ +// 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::{ + BinaryExpr, Expr, Operator, and, 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 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 => Expr::BinaryExpr(BinaryExpr { + left: expr, + op, + right: Box::new(lower), + }), + // <expr> > x ==> <expr> >= upper + Operator::Gt => Expr::BinaryExpr(BinaryExpr { + left: expr, + op: Operator::GtEq, + right: Box::new(upper), + }), + // <expr> <= x ==> <expr> < upper + Operator::LtEq => Expr::BinaryExpr(BinaryExpr { + left: expr, + op: Operator::Lt, + right: Box::new(upper), + }), + // <expr> = x ==> (<expr> >= lower) and (<expr> < upper) Review Comment: Why isn't this `expr <= upper`? For the example of `date_part(x, 'year')=2024` the preimage would be (`2024-01-01`, `2024-01-31`) in which case the correct rewrite would be `2024-01-01` <= x <= `2024-01-31`). I think this code would return `2024-01-01` <= x < `2024-01-31` which would incorrectly exclude `2024-01-31` Maybe I am missing something (or the semantics of preimage are not entirely clear) ########## datafusion/expr/src/udf.rs: ########## @@ -696,6 +715,36 @@ pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + Sync { Ok(ExprSimplifyResult::Original(args)) } + /// Returns the [preimage] for this function and the specified scalar value, if any. + /// + /// A preimage is a single contiguous [`Interval`] of values where the function + /// will always return `lit_value` + /// + /// This rewrite is described in the [ClickHouse Paper] and is particularly Review Comment: Can you please also document the precise semantics required for the preimage rewrite to maintain correctness -- specifically something like "For correctness, the function must return the exact same value for **all** arguments within the range (lower, upper) inclusive" I am pretty sure the bounds must be inclusive for the primage -- 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]
