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

[PR] decomposed date_trunc optimization into expr simplifier [datafusion]

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

   This decomposes a custom optimizer rule into the datafusion expression simplifier (work-in-progress).
   
   ## Which issue does this PR close?
   Closes #18319.
   
   ## Rationale for this change
   To transform binary expressions that compare `date_trunc` with a constant value into a form that can be better utilized (improved performance).
   
   For Bauplan, we can see the following (approximate average over a handful of runs):
   
   Q1:
   ```sql
   SELECT PULocationID, trip_miles, tips
     FROM taxi_fhvhv
    WHERE date_trunc('month', pickup_datetime) <= '2025-01-08'::DATE
   ```
   
   Q2:
   ```sql
   SELECT PULocationID, trip_miles, tips
     FROM taxi_fhvhv
    WHERE pickup_datetime < date_trunc('month', '2025-02-08'::DATE)
   ```
   
   |  Query  | Time (s) | Options |
   | ------- | -------- | -------- |
   |    Q1     |    ~3    |  no cache, optimization enabled |
   |    Q1     |   ~35   |  no cache, optimization disabled |
   |    Q2     |    ~3    |  no cache, optimization enabled |
   |    Q2     |    ~3    |  no cache, optimization disabled |
   
   ## What changes are included in this PR?
   A few additional support functions and additional match arms in the simplifier match expression.
   
   ## Are these changes tested?
   
   Our custom rule has tests of the expression transformations and for correct evaluation results. These will be added to the PR after the implementation is in approximately good shape.
   
   ## Are there any user-facing changes?
   Better performance and occasionally confusing explain plan. In short, a `date_trunc('month', col) = '2025-12-03'::DATE` will always be false (because the truncation result can never be a non-truncated value), which may produce an unexpected expression (`false`).
   
   Explain plan details below (may be overkill but it was fun to figure out):
   
   Initial query:
   ```sql
   SELECT  PULocationID
              ,pickup_datetime
         FROM taxi_view_2025
        WHERE date_trunc('month', pickup_datetime) = '2025-12-03'
   ```
   
   After simplify_expressions:
   ```sql
   logical_plan after simplify_expressions                    | Projection: taxi_view_2025.PULocationID, taxi_view_2025.pickup_datetime                                                                                            |
   |                                                            |   Filter: date_trunc(Utf8("month"), CAST(taxi_view_2025.pickup_datetime AS Timestamp(Nanosecond, None))) = TimestampNanosecond(1764720000000000000, None)          |
   |                                                            |     TableScan: taxi_view_2025
   ```
   
   Before and after `date_trunc_optimizer` (our custom rule):
   ```sql
   logical_plan after optimize_projections                    | Filter: date_trunc(Utf8("month"), CAST(taxi_view_2025.pickup_datetime AS Timestamp(Nanosecond, None))) = TimestampNanosecond(1764720000000000000, None)            |
   |                                                            |   TableScan: taxi_view_2025 projection=[PULocationID, pickup_datetime]                                                                                             |
   | logical_plan after date_trunc_optimizer                    | Filter: Boolean(false)                                                                                                                                             |
   |                                                            |   TableScan: taxi_view_2025 projection=[PULocationID, pickup_datetime]
   ```
   


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   From my experience waiting for PR reviews, it’s often easier to review several smaller PRs than one large one. 
   
   I ended up splitting my [original](https://github.com/apache/datafusion/pull/18789) `date_part` `preimage` PR into two. 
   
   You could keep this one as is and add a new small one with the `preimage` API update.


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   Thanks @drin, I'll take a look tomorrow.


-- 
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] decomposed date_trunc optimization into expr simplifier [datafusion]

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

   @UBarney something I think could use some definite improvement in handling of the source expressions along transformation and failure paths (https://github.com/drin/datafusion/blob/8cba13ceafcf0df047e753f20bf54ad85a02f019/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs#L690-L720).
   
   I try to avoid moving until I know what to return (transformed expression or source expression), but I don't know rust/datafusion well enough to know best practices for when to clone and when to move and how to avoid either until necessary.


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   okay, I can do that.
   
   just so we're clear, the first case can only capture when the right-hand constant is aligned. I agree it's a clear win, but continuing with the date_trunc('month', ...) example, it's applicable to 1 value for every 30 values, and that's not including time and timezone offsets. As far as I can tell, date_trunc truncates time stamps to UTC so any other timezone will only get the optimization if it's pre-normalized to UTC midnight.


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   I hope to find time today to give this a more careful review


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   > just so we're clear, the first case can only capture when the right-hand constant is aligned. I agree it's a clear win, but continuing with the date_trunc('month', ...) example, it's applicable to 1 value for every 30 values, and that's not including time and timezone offsets. 
   
   I am not sure why it is not applicable to timezone offsets
   
   In my mind writing 
   ```sql
   date_trunc(col, 'month') = 2025-12-01
   ```
    is the natural way to write queries that look to bucket date by month (aka to compare date trunc to a date/time with the granulatity of the truncation). 
   
   the expression 
   ```sql
   date_trunc(col, 'month') = 2025-12-03`. -- <-- A value that is not a natural boundary
   ```
   
   Doesn't make sense to me at all (as that will be FALSE for all values)
   
   The expression 
   
   ```sql
   date_trunc(col, 'month') < 2025-12-03    
   ```
   
   Makes slightly more sense as it will actually pass some rows, but I still would be surprised if this was a common epression as the constant doesn't align to the truncation granularity


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   Marking as draft as I think this PR is no longer waiting on feedback and I am trying to make it easier to find PRs in need of review. Please mark it as ready for review when it is ready for another look 


-- 
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] implement `preimage` for date_trunc [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #18648: implement `preimage` for date_trunc
URL: https://github.com/apache/datafusion/pull/18648


-- 
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] decomposed date_trunc optimization into expr simplifier [datafusion]

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

   I will try to push this forward this week


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   Hey @drin, I'll take a look tomorrow.


-- 
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] decomposed date_trunc optimization into expr simplifier [datafusion]

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

   In theory we should be able to use the API added in 
   - https://github.com/apache/datafusion/pull/19722


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   that's maybe a question for a committer? I don't mind it, but if we split it there will be a dependency. Fortunately, expanding the preimage framework is teeny tiny, but it does mean double the review plus an additional merge.
   
   I have no strong opinions either way, except that this one feels just about done already
   
   


-- 
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] implement `preimage` for date_trunc [datafusion]

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


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########


Review Comment:
   I didn't add a Time type, but I do use this instead of the inlined `matches!()` call in `preimage`



-- 
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] implement `preimage` for date_trunc [datafusion]

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

   I'm convinced. We could split the PR into two smaller ones to make review easier:
   1) Apply changes to the `preimage` api and the functions that already implement it.
   2) Implement `preimage` for `date_trunc`
   
   Let me know if you think that's a good idea.


-- 
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] implement `preimage` for date_trunc [datafusion]

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

   Well, `date_trunc('month', date_col) < '2026-02-23'` can be optimized by this framework, and if you fallback on not using `preimage` then you can't optimize it at all. The literal, `'2026-02-23'`, could come from a variable; then, it's not an edge case at all, it's just a typical engineering scenario: `df = ctx.sql(f"SELECT date_trunc('month', date_col) < {date_literal}")`. It seems like an oversight to me to require a user to normalize `date_literal` in this case as a prerequisite to getting faster query performance. It's also likely to lead to tribal knowledge: "if you are using `x` function, then you can get better optimization if you do `y` to align it to a boundary."
   
   The extra complexity is:
   1. An extra comparison (`is_boundary = value == lower`)
   2. An extra bool attribute in the `PreimageResult::Range` enum
   3. A few extra match arms (`Operator::Eq && is_boundary`)
   
   and the optimization potentially:
   1. removes the predicate altogether
   2. removes the operator (and potentially the plan sub-tree)
   
   Considering the complexity of a time type vs timestamp type amplified by the date trunc granularity, I think the extra complexity cost is basically 0 (for `date_part`). So, to me it's a clear that it's worth the cost.
   
   Related:
   - duckdb accommodates this (https://github.com/duckdb/duckdb/pull/18457)
   - This PR accommodates the same change for [floor](https://github.com/apache/datafusion/pull/18648/changes#diff-077176fcf22cb36a0a51631a43739f5f015f46305be4f49142a450e25b152b84)
     - although, its logic would have to be modified to return a proper value instead of None to accommodate these cases


-- 
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] implement `preimage` for date_trunc [datafusion]

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


##########
datafusion/expr/src/preimage.rs:
##########
@@ -23,7 +23,23 @@ use crate::Expr;
 pub enum PreimageResult {
     /// No preimage exists for the specified value
     None,
-    /// The expression always evaluates to the specified constant
-    /// given that `expr` is within the interval

Review Comment:
   I don't fully understand this logic 
   
   For the example `floor(x) < 8.3`  I would expect there to be no preimage as defined here -- specifically there is no range of inputs for which `floor(x)` evaluates to `8.3`
   
   I agree that it is valid simplificaition to rewrite `floor(x) < 8.3` to `x < 9.0`, but it seems different than "preimage" πŸ€” 
   
   Maybe we just need to give it a different name (maybe that is what you have tried to do with `is_boundary`)
   
   



##########
datafusion/expr/src/preimage.rs:
##########
@@ -23,7 +23,23 @@ use crate::Expr;
 pub enum PreimageResult {
     /// No preimage exists for the specified value
     None,
-    /// The expression always evaluates to the specified constant
-    /// given that `expr` is within the interval
-    Range { expr: Expr, interval: Box<Interval> },
+    /// For some UDF, a `preimage` implementation determines that:
+    ///     the result `udf_result` in `udf_result = UDF(expr)`
+    ///     is equivalent to `udf_result = UDF(i)` for any `i` in `interval`.
+    ///
+    /// Then, `is_boundary` indicates a boundary condition where:
+    ///     the original expression `UDF(expr)` is compared to a value `lit` where:
+    ///         `UDF(lit) == lit`
+    /// This condition is important for two scenarios:
+    /// 1. `<` and `>=` operators:
+    ///    if `Some(false)`, expression rewrite should use `interval.upper`
+    /// 2. `=` and `!=` operators:
+    ///    if `Some(false)`, expression rewrite can use constant (false and true, respectively)
+    ///
+    /// if is_boundary is `None`, then the boundary condition never applies.

Review Comment:
   While trying to understand this, I wonder if it might be easier to express by instead of adding a field to `Range`  we could instead add a new variant. Something like this:
   
   ```rust
   enum PreimageResult {
     /// ...
     Range { expr: Expr, interval: Box<Interval> }, 
     // The original expression UDF(lit) = lit
     // 1. `<` and `>=` operators:
     ///    if `Some(false)`, expression rewrite should use `interval.upper`
     /// 2. `=` and `!=` operators:
     ///    if `Some(false)`, expression rewrite can use constant (false and true, respectively)
     Boundary { expr: Expr, interval: Box<Interval> }, 
   }
   ```



##########
datafusion/expr/src/preimage.rs:
##########
@@ -23,7 +23,23 @@ use crate::Expr;
 pub enum PreimageResult {
     /// No preimage exists for the specified value
     None,
-    /// The expression always evaluates to the specified constant
-    /// given that `expr` is within the interval

Review Comment:
   BTW I checked with datafusion-cli and the `floor(x) < 8.3` case is not optimized today (the preimage is not applied here)
   
   ```sql
   > create OR REPLACE table foo(x float) as values (1.0), (8.0), (9.0);
   0 row(s) fetched.
   Elapsed 0.002 seconds.
   
   > select * from foo where floor(x) < 8.3;
   +-----+
   | x   |
   +-----+
   | 1.0 |
   | 8.0 |
   +-----+
   2 row(s) fetched.
   
   > explain select * from foo where floor(x) < 8.3;
   +---------------+-------------------------------+
   | plan_type     | plan                          |
   +---------------+-------------------------------+
   | physical_plan | β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” |
   |               | β”‚         FilterExec        β”‚ |
   |               | β”‚    --------------------   β”‚ |
   |               | β”‚         predicate:        β”‚ |
   |               | β”‚ CAST(floor(x) AS Float64) β”‚ |
   |               | β”‚           < 8.3           β”‚ |
   |               | β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ |
   |               | β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” |
   |               | β”‚       DataSourceExec      β”‚ |
   |               | β”‚    --------------------   β”‚ |
   |               | β”‚         bytes: 112        β”‚ |
   |               | β”‚       format: memory      β”‚ |
   |               | β”‚          rows: 1          β”‚ |
   |               | β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ |
   |               |                               |
   +---------------+-------------------------------+
   1 row(s) fetched.
   Elapsed 0.008 seconds.
   
   > explain format indent select * from foo where floor(x) < 8.3;
   +---------------+------------------------------------------------------+
   | plan_type     | plan                                                 |
   +---------------+------------------------------------------------------+
   | logical_plan  | Filter: CAST(floor(foo.x) AS Float64) < Float64(8.3) |
   |               |   TableScan: foo projection=[x]                      |
   | physical_plan | FilterExec: CAST(floor(x@0) AS Float64) < 8.3        |
   |               |   DataSourceExec: partitions=1, partition_sizes=[1]  |
   |               |                                                      |
   +---------------+------------------------------------------------------+
   2 row(s) fetched.
   Elapsed 0.002 seconds.
   ```



-- 
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] implement `preimage` for date_trunc [datafusion]

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

   Thank you so much for working on this @drin and @sdf-jkl 


-- 
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] implement `preimage` for date_trunc [datafusion]

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


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -502,6 +650,125 @@ fn truncate_time_secs(value: i32, granularity: DateTruncGranularity) -> i32 {
     }
 }
 
+/// Increment time in nanoseconds by the specified granularity
+fn increment_time_nanos(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + NANOS_PER_HOUR,
+        DateTruncGranularity::Minute => value + NANOS_PER_MINUTE,
+        DateTruncGranularity::Second => value + NANOS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + NANOS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + NANOS_PER_MICROSECOND,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in microseconds by the specified granularity
+fn increment_time_micros(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MICROS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MICROS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MICROS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + MICROS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + 1,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in milliseconds by the specified granularity
+fn increment_time_millis(value: i32, granularity: DateTruncGranularity) -> i32 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MILLIS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MILLIS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MILLIS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + 1,

Review Comment:
   What I do instead, is I return the same value (no increment) and then I check if the increment call was a no-op (lower == upper), and if so, I print an appropriate error (e.g. "Millisecond too granular for time in Seconds").



-- 
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] implement `preimage` for date_trunc [datafusion]

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

   I guess the first question is: do we really want to support edge cases like `date_trunc('month', '2026-02-27') < '2026-02-23'`?
   
   Why not fall back to not using preimage, like the `floor` function? What arguments in favor of changing the API?
   
   One argument I can think of is:
   - Right now, it's up to the user to know not to use dates like `2026-02-XX` (where `XX > 01`). Leaving that responsibility to the user is not good UX. I'd be confused if some queries where the RHS day is `01` were faster than otherwise identical queries with a different day value.
   
   On the other hand:
   - API change and extra complexity (not that big of a change and doesn't add much complexity to the interval calculation)


-- 
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] decomposed date_trunc optimization into expr simplifier [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #18648:
URL: https://github.com/apache/datafusion/pull/18648#issuecomment-3736660589

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
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] implement `preimage` for date_trunc [datafusion]

Posted by "sdf-jkl (via GitHub)" <gi...@apache.org>.
sdf-jkl commented on code in PR #18648:
URL: https://github.com/apache/datafusion/pull/18648#discussion_r2849762483


##########
datafusion/sqllogictest/test_files/datetime/timestamps.slt:
##########
@@ -5358,3 +5358,301 @@ SELECT to_timestamp(arrow_cast(100.5, 'Float16'), name) FROM test_to_timestamp_s
 
 statement ok
 drop table test_to_timestamp_scalar
+
+## date_trunc Preimage tests
+
+# Test with timestamp data
+statement ok
+CREATE TABLE t1(ts TIMESTAMP) AS VALUES
+  (NULL),
+  ('2023-01-15T10:30:45'::timestamp),
+  ('2024-06-20T14:25:30'::timestamp),
+  ('2024-12-31T23:59:59'::timestamp),
+  ('2025-03-10T08:15:20'::timestamp);
+
+# Test YEAR granularity - basic comparisons
+
+query P
+SELECT ts FROM t1 WHERE date_trunc('year', ts) = timestamp '2024-01-01T00:00:00' ORDER BY ts;

Review Comment:
   Does your comment about this still hold?
   ```sql
   SELECT  PULocationID
              ,pickup_datetime
         FROM taxi_view_2025
        WHERE date_trunc('month', pickup_datetime) = '2025-12-03'
   ```
   
   Without `preimage` it would always return `False`, but with `preimage`, we create an interval `[2025-12-01, 2026-01-01)` and simplification rule returns `col >= 2025-12-01 and col < 2026-01-01` we could get false positives, because `2025-12-03` falls into that interval.



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -412,6 +415,151 @@ impl ScalarUDFImpl for DateTruncFunc {
         })
     }
 
+    fn preimage(
+        &self,
+        args: &[Expr],
+        lit_expr: &Expr,
+        _info: &SimplifyContext,
+    ) -> Result<PreimageResult> {
+        // Determine what datetime granularity to use for preimage calculation
+        let [trunc_part, col_expr] = take_function_args(self.name(), args)?;
+        let granular_part = trunc_part
+            .as_literal()
+            .and_then(|sv| sv.try_as_str().flatten())
+            .map(part_normalization);
+
+        let granularity = match granular_part {
+            Some(trunc_granularity) => {
+                match DateTruncGranularity::from_str(trunc_granularity) {
+                    Ok(granularity_instance) => granularity_instance,
+                    Err(granularity_err) => {
+                        return Err(granularity_err);
+                    }
+                }
+            }
+            None => {
+                return Ok(PreimageResult::None);
+            }
+        };
+
+        fn trunc_interval_for_ts<TsType: ArrowTimestampType>(
+            ts_val: &i64,
+            ts_tz: &Option<Arc<str>>,
+            ts_granularity: DateTruncGranularity,
+        ) -> Result<Interval> {
+            let parsed_tz = parse_tz(ts_tz)?;
+            let is_calendar_granularity = matches!(
+                ts_granularity,
+                DateTruncGranularity::Year
+                    | DateTruncGranularity::Month
+                    | DateTruncGranularity::Quarter
+                    | DateTruncGranularity::Week
+                    | DateTruncGranularity::Day
+            );
+
+            // general_date_trunc converts to nanoseconds
+            let lower_val =
+                general_date_trunc(TsType::UNIT, *ts_val, parsed_tz, ts_granularity)?;
+            let upper_val = if is_calendar_granularity {
+                increment_timestamp_nanos_calendar(lower_val, parsed_tz, ts_granularity)?
+            } else {
+                increment_time_nanos(lower_val, ts_granularity)
+            };

Review Comment:
   `general_date_trunc` converts the values back to the original `TimeStamp` type, we shouldn't increment in nanos, but use the original `TimeUnit`.



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -412,6 +415,151 @@ impl ScalarUDFImpl for DateTruncFunc {
         })
     }
 
+    fn preimage(
+        &self,
+        args: &[Expr],
+        lit_expr: &Expr,
+        _info: &SimplifyContext,
+    ) -> Result<PreimageResult> {
+        // Determine what datetime granularity to use for preimage calculation
+        let [trunc_part, col_expr] = take_function_args(self.name(), args)?;
+        let granular_part = trunc_part
+            .as_literal()
+            .and_then(|sv| sv.try_as_str().flatten())
+            .map(part_normalization);
+
+        let granularity = match granular_part {
+            Some(trunc_granularity) => {
+                match DateTruncGranularity::from_str(trunc_granularity) {
+                    Ok(granularity_instance) => granularity_instance,
+                    Err(granularity_err) => {
+                        return Err(granularity_err);
+                    }
+                }
+            }
+            None => {
+                return Ok(PreimageResult::None);
+            }
+        };
+
+        fn trunc_interval_for_ts<TsType: ArrowTimestampType>(

Review Comment:
   Could this move out of the `preimage` impl?



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########


Review Comment:
   We should add a guard for `Time` types granularities.
   We could reuse this function.



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -502,6 +650,125 @@ fn truncate_time_secs(value: i32, granularity: DateTruncGranularity) -> i32 {
     }
 }
 
+/// Increment time in nanoseconds by the specified granularity
+fn increment_time_nanos(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + NANOS_PER_HOUR,
+        DateTruncGranularity::Minute => value + NANOS_PER_MINUTE,
+        DateTruncGranularity::Second => value + NANOS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + NANOS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + NANOS_PER_MICROSECOND,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in microseconds by the specified granularity
+fn increment_time_micros(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MICROS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MICROS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MICROS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + MICROS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + 1,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in milliseconds by the specified granularity
+fn increment_time_millis(value: i32, granularity: DateTruncGranularity) -> i32 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MILLIS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MILLIS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MILLIS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + 1,

Review Comment:
   Keep match arms for granularities finer than rhs?
   ```suggestion
           DateTruncGranularity::Millisecond => value + 1,
           DateTruncGranularity::Microsecond => value + 1,
   ```



##########
datafusion/sqllogictest/test_files/datetime/timestamps.slt:
##########
@@ -5358,3 +5358,301 @@ SELECT to_timestamp(arrow_cast(100.5, 'Float16'), name) FROM test_to_timestamp_s
 
 statement ok
 drop table test_to_timestamp_scalar
+
+## date_trunc Preimage tests
+
+# Test with timestamp data
+statement ok
+CREATE TABLE t1(ts TIMESTAMP) AS VALUES
+  (NULL),
+  ('2023-01-15T10:30:45'::timestamp),
+  ('2024-06-20T14:25:30'::timestamp),
+  ('2024-12-31T23:59:59'::timestamp),
+  ('2025-03-10T08:15:20'::timestamp);
+
+# Test YEAR granularity - basic comparisons
+
+query P
+SELECT ts FROM t1 WHERE date_trunc('year', ts) = timestamp '2024-01-01T00:00:00' ORDER BY ts;

Review Comment:
   It was actually covered for `floor preimage` impl by @devanshu0987 in #20059
   Check here:
   https://github.com/apache/datafusion/pull/20059/changes#diff-077176fcf22cb36a0a51631a43739f5f015f46305be4f49142a450e25b152b84R280-R303
   `Floor` is very similar to `date_trunc`, so we could replicate the behavior.



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -502,6 +650,125 @@ fn truncate_time_secs(value: i32, granularity: DateTruncGranularity) -> i32 {
     }
 }
 
+/// Increment time in nanoseconds by the specified granularity
+fn increment_time_nanos(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + NANOS_PER_HOUR,
+        DateTruncGranularity::Minute => value + NANOS_PER_MINUTE,
+        DateTruncGranularity::Second => value + NANOS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + NANOS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + NANOS_PER_MICROSECOND,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in microseconds by the specified granularity
+fn increment_time_micros(value: i64, granularity: DateTruncGranularity) -> i64 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MICROS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MICROS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MICROS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + MICROS_PER_MILLISECOND,
+        DateTruncGranularity::Microsecond => value + 1,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in milliseconds by the specified granularity
+fn increment_time_millis(value: i32, granularity: DateTruncGranularity) -> i32 {
+    match granularity {
+        DateTruncGranularity::Hour => value + MILLIS_PER_HOUR,
+        DateTruncGranularity::Minute => value + MILLIS_PER_MINUTE,
+        DateTruncGranularity::Second => value + MILLIS_PER_SECOND,
+        DateTruncGranularity::Millisecond => value + 1,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,
+    }
+}
+
+/// Increment time in seconds by the specified granularity
+fn increment_time_secs(value: i32, granularity: DateTruncGranularity) -> i32 {
+    match granularity {
+        DateTruncGranularity::Hour => value + SECS_PER_HOUR,
+        DateTruncGranularity::Minute => value + SECS_PER_MINUTE,
+        DateTruncGranularity::Second => value + 1,
+        // Other granularities are not valid for time - should be caught earlier
+        _ => value,

Review Comment:
   return `Err` or `None`?



##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -412,6 +415,151 @@ impl ScalarUDFImpl for DateTruncFunc {
         })
     }
 
+    fn preimage(
+        &self,
+        args: &[Expr],
+        lit_expr: &Expr,
+        _info: &SimplifyContext,
+    ) -> Result<PreimageResult> {
+        // Determine what datetime granularity to use for preimage calculation
+        let [trunc_part, col_expr] = take_function_args(self.name(), args)?;
+        let granular_part = trunc_part
+            .as_literal()
+            .and_then(|sv| sv.try_as_str().flatten())
+            .map(part_normalization);
+

Review Comment:
   We should add a guard for Type families. `col_expr: TimeStamp` needs a `lit_expr: TimeStamp` and the same for `Time` types.



##########
datafusion/sqllogictest/test_files/datetime/timestamps.slt:
##########
@@ -5358,3 +5358,301 @@ SELECT to_timestamp(arrow_cast(100.5, 'Float16'), name) FROM test_to_timestamp_s
 
 statement ok
 drop table test_to_timestamp_scalar
+
+## date_trunc Preimage tests
+
+# Test with timestamp data
+statement ok
+CREATE TABLE t1(ts TIMESTAMP) AS VALUES
+  (NULL),
+  ('2023-01-15T10:30:45'::timestamp),
+  ('2024-06-20T14:25:30'::timestamp),
+  ('2024-12-31T23:59:59'::timestamp),
+  ('2025-03-10T08:15:20'::timestamp);
+
+# Test YEAR granularity - basic comparisons
+
+query P
+SELECT ts FROM t1 WHERE date_trunc('year', ts) = timestamp '2024-01-01T00:00:00' ORDER BY ts;

Review Comment:
   We'd need to change the behavior to cover this.
   
   - One way would be by having a guard checking the `eq Operator` specifically for `date_trunc preimage` and return `PreimageResult::None` if `rhs != date_trunc(granularity, rhs)`. But `preimage` is `Operator` agnostic.
   - Another way is by having an optimization rule to do check this `rhs != date_trunc(granularity, rhs)` and return `False` for the whole column. But that's adding a rule just for one udf.
   - Another way is to only let `date_trunc preimage` work with with `rhs = date_trunc(granularity, rhs)`, but this requires the user to write the date in the right way if they want the query to run faster.
   For example:
   ```diff
   ++WHERE date_trunc('month', pickup_datetime) = '2025-12-01'
   --WHERE date_trunc('month', pickup_datetime) = '2025-12-03'
   ```



-- 
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] decomposed date_trunc optimization into expr simplifier [datafusion]

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

   I tried to reuse existing date_trunc functions where possible and match the structure in date_part::preimage. The calendar duration and sql logic tests were added with the help of an LLM. I reviewed the calendar duration so that should be cohesive with my overall design, but the sql logic tests I have no context in and I would appreciate some extra review (and advice) in that area.
   
   Thanks!


-- 
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] implement `preimage` for date_trunc [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #18648:
URL: https://github.com/apache/datafusion/pull/18648#issuecomment-4376096552

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
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