You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "niebayes (via GitHub)" <gi...@apache.org> on 2026/09/15 08:59:28 UTC

[PR] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   ## What I did
   
   - Optimize date_trunc for fixed-offset timezones (UTC and +HH[:MM]) and coarse granularities binning.
   - Fix eager ok_or error allocation in the per-value chrono path.
   - Extend the criterion bench to cover fixed offsets and DST zones.
   
   After the optimization:
   
   ``` shell
   Gnuplot not found, using plotters backend
   date_trunc_hour_notz_nanos_100000
                           time:   [525.81 µs 527.52 µs 528.95 µs]
                           change: [−2.8681% −2.6375% −2.3945%] (p = 0.00 < 0.05)
                           Performance has improved.
   
   date_trunc_hour_utc_nanos_100000
                           time:   [530.68 µs 530.85 µs 531.06 µs]
                           change: [−96.516% −96.512% −96.507%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 8 outliers among 100 measurements (8.00%)
     6 (6.00%) high mild
     2 (2.00%) high severe
   
   Benchmarking date_trunc_hour_fixed_offset_nanos_100000: Collecting 100 samples in estimated 5.3867 s (10k itera
   date_trunc_hour_fixed_offset_nanos_100000
                           time:   [521.82 µs 523.58 µs 525.67 µs]
                           change: [−96.560% −96.549% −96.540%] (p = 0.00 < 0.05)
                           Performance has improved.
   
   Benchmarking date_trunc_hour_dst_zone_nanos_100000: Collecting 100 samples in estimated 5.7956 s (700 iteration
   date_trunc_hour_dst_zone_nanos_100000
                           time:   [8.3345 ms 8.3677 ms 8.4027 ms]
                           change: [−60.520% −60.351% −60.178%] (p = 0.00 < 0.05)
                           Performance has improved.
   
   date_trunc_day_utc_nanos_100000
                           time:   [466.83 µs 468.50 µs 470.41 µs]
                           change: [−96.919% −96.911% −96.903%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 22 outliers among 100 measurements (22.00%)
     19 (19.00%) low severe
     3 (3.00%) high mild
   
   Benchmarking date_trunc_day_fixed_offset_nanos_100000: Collecting 100 samples in estimated 7.1836 s (15k iterat
   date_trunc_day_fixed_offset_nanos_100000
                           time:   [472.41 µs 472.57 µs 472.75 µs]
                           change: [−96.953% −96.949% −96.944%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 7 outliers among 100 measurements (7.00%)
     7 (7.00%) high mild
   
   date_trunc_minute_notz_nanos_100000
                           time:   [602.10 µs 602.50 µs 602.94 µs]
                           change: [−1.3404% −1.2577% −1.1705%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 1 outliers among 100 measurements (1.00%)
     1 (1.00%) high mild
   
   date_trunc_minute_utc_nanos_100000
                           time:   [601.23 µs 601.58 µs 601.98 µs]
                           change: [−1.6199% −1.5341% −1.4394%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 9 outliers among 100 measurements (9.00%)
     2 (2.00%) low mild
     6 (6.00%) high mild
     1 (1.00%) high severe
   
   Benchmarking date_trunc_minute_dst_zone_nanos_100000: Collecting 100 samples in estimated 6.0929 s (10k iterati
   date_trunc_minute_dst_zone_nanos_100000
                           time:   [601.72 µs 601.99 µs 602.31 µs]
                           change: [−1.5949% −1.5300% −1.4665%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 7 outliers among 100 measurements (7.00%)
     2 (2.00%) high mild
     5 (5.00%) high severe
   
   date_trunc_week_notz_nanos_100000
                           time:   [702.79 µs 703.29 µs 703.94 µs]
                           change: [+1.3167% +1.4981% +1.6598%] (p = 0.00 < 0.05)
                           Performance has regressed.
   Found 11 outliers among 100 measurements (11.00%)
     2 (2.00%) low mild
     3 (3.00%) high mild
     6 (6.00%) high severe
   
   Benchmarking date_trunc_month_notz_nanos_100000: Warming up for 3.0000 s
   Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 6.9s, enable flat sampling, or reduce sample count to 50.
   date_trunc_month_notz_nanos_100000
                           time:   [1.3708 ms 1.3716 ms 1.3724 ms]
                           change: [+2.7066% +2.8029% +2.8938%] (p = 0.00 < 0.05)
                           Performance has regressed.
   Found 6 outliers among 100 measurements (6.00%)
     4 (4.00%) high mild
     2 (2.00%) high severe
   
   Benchmarking date_trunc_quarter_notz_nanos_100000: Collecting 100 samples in estimated 5.0390 s (2300 iteration
   date_trunc_quarter_notz_nanos_100000
                           time:   [2.1888 ms 2.1895 ms 2.1902 ms]
                           change: [−0.2713% −0.2060% −0.1445%] (p = 0.00 < 0.05)
                           Change within noise threshold.
   Found 8 outliers among 100 measurements (8.00%)
     2 (2.00%) low mild
     4 (4.00%) high mild
     2 (2.00%) high severe
   
   Benchmarking date_trunc_year_notz_nanos_100000: Warming up for 3.0000 s
   Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 8.4s, enable flat sampling, or reduce sample count to 50.
   date_trunc_year_notz_nanos_100000
                           time:   [1.6574 ms 1.6583 ms 1.6595 ms]
                           change: [+0.8459% +1.0083% +1.1853%] (p = 0.00 < 0.05)
                           Change within noise threshold.
   Found 11 outliers among 100 measurements (11.00%)
     1 (1.00%) low mild
     4 (4.00%) high mild
     6 (6.00%) high severe
   
   Benchmarking date_trunc_month_fixed_offset_nanos_100000: Warming up for 3.0000 s
   Warning: Unable to complete 100 samples in 5.0s. You may wish to increase target time to 7.0s, enable flat sampling, or reduce sample count to 50.
   Benchmarking date_trunc_month_fixed_offset_nanos_100000: Collecting 100 samples in estimated 6.9700 s (5050 ite
   date_trunc_month_fixed_offset_nanos_100000
                           time:   [1.3531 ms 1.3578 ms 1.3627 ms]
                           change: [−91.250% −91.217% −91.180%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 20 outliers among 100 measurements (20.00%)
     7 (7.00%) low severe
     4 (4.00%) low mild
     6 (6.00%) high mild
     3 (3.00%) high severe
   
   Benchmarking date_trunc_month_dst_zone_nanos_100000: Collecting 100 samples in estimated 5.0534 s (600 iteratio
   date_trunc_month_dst_zone_nanos_100000
                           time:   [8.3957 ms 8.4031 ms 8.4111 ms]
                           change: [−60.986% −60.940% −60.897%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 7 outliers among 100 measurements (7.00%)
     4 (4.00%) high mild
     3 (3.00%) high severe
   ```
   
   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   - Closes #25325.
   
   ## Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   
   Please explain the problem you are trying to solve in terms of the user-visible
   behavior, rather than the implementation.
   
   For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of the
   implementation. "COUNT(DISTINCT) returns wrong results when the column contains
   nulls" is the user-visible problem.
   -->
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here, but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   ## What is the testing strategy for this PR?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   Briefly describe how this PR is tested, and point to the specific tests you added. For example: 'This new feature is covered by the `sqllogictest` cases added in `foo.slt`'.
   
   If this PR does not add tests, explain why. For example, if the change is already covered by existing tests, please mention it.
   
   You should also check the `codecov` bot reply on this PR to confirm the changed code is exercised.
   -->
   
   Added an unit test which compares the fast-path results against the results of the normal path. 
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   
   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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

Posted by "namanjain24-sudo (via GitHub)" <gi...@apache.org>.
namanjain24-sudo commented on code in PR #25326:
URL: https://github.com/apache/datafusion/pull/25326#discussion_r4052937018


##########
datafusion/functions/src/datetime/date_trunc.rs:
##########
@@ -778,26 +817,42 @@ fn general_date_trunc_array_fine_granularity<T: ArrowTimestampType>(
 
     if let Some(unit) = unit {
         let unit = unit.get();
-        // Truncation can only underflow within one `unit` of `i64::MIN`.
-        // Track that possibility while computing the common case so the loop
-        // remains infallible and can be vectorized.
-        let underflow_bound = i64::MIN + unit;
+        // Truncate the value shifted by the (whole-unit) timezone offset and
+        // shift back: `truncate_tz(v) == truncate_naive(v + offset) - offset`.
+        // For fine granularities the offset is a multiple of `unit` and cancels
+        // out; for hour/day it shifts the result as required.
+        let offset_in_unit = offset_nanos / nanos_per_unit(tu);
+        let add_lower = i64::MIN.saturating_sub(offset_in_unit);
+        let add_upper = i64::MAX.saturating_sub(offset_in_unit);
+        // Truncation of the shifted value can only underflow within one `unit`
+        // of `i64::MIN`. Track that (plus a wrapping shift at either extreme)
+        // while computing the common case so the loop remains infallible and
+        // can be vectorized.
+        let underflow_bound = i64::MIN + unit - offset_in_unit.min(0);
         let mut maybe_underflow = false;
         let values: Vec<i64> = array
             .values()
             .iter()
             .map(|value| {
-                maybe_underflow |= *value < underflow_bound;
-                value.wrapping_sub(value.rem_euclid(unit))
+                maybe_underflow |=
+                    *value < add_lower || *value > add_upper || *value < underflow_bound;
+                let shifted = value.wrapping_add(offset_in_unit);
+                shifted.wrapping_sub(shifted.rem_euclid(unit)) - offset_in_unit

Review Comment:
   This `- offset_in_unit` isn't wrapping, and it runs for every value before `maybe_underflow` is checked, so it panics in debug builds near the ends of the range. On this branch, `date_trunc('hour', ...)` over a `Timestamp(Second, "+05:00")` column holding `i64::MIN` or `i64::MAX` panics here with `attempt to subtract with overflow`; on `main` the same input returns `Timestamp ... out of range`.
   
   Since those values already set `maybe_underflow` and go through the checked path, `.wrapping_sub(offset_in_unit)` should be enough. Could be worth adding them to the underflow tests 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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   ## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/25326?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `85.48387%` with `18 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 81.93%. Comparing base ([`133111f`](https://app.codecov.io/gh/apache/datafusion/commit/133111f43a579260df4b0d4e76e2537a46cadda9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`6824b90`](https://app.codecov.io/gh/apache/datafusion/commit/6824b90abc1641ae0d9af0504808792cdc1f41c2?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/25326?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [datafusion/functions/src/datetime/date\_trunc.rs](https://app.codecov.io/gh/apache/datafusion/pull/25326?src=pr&el=tree&filepath=datafusion%2Ffunctions%2Fsrc%2Fdatetime%2Fdate_trunc.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9mdW5jdGlvbnMvc3JjL2RhdGV0aW1lL2RhdGVfdHJ1bmMucnM=) | 85.48% | [12 Missing and 6 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/25326?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@           Coverage Diff            @@
   ##             main   #25326    +/-   ##
   ========================================
     Coverage   81.92%   81.93%            
   ========================================
     Files        1134     1134            
     Lines      426000   426111   +111     
     Branches   426000   426111   +111     
   ========================================
   + Hits       349000   349117   +117     
   + Misses      56304    56289    -15     
   - Partials    20696    20705     +9     
   ```
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/25326?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   Marked as draft after 14 days without activity: merge conflicts.
   
   Please address these items and mark **Ready for review** when ready.


-- 
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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   Some independent numbers on the `ok_or` → `ok_or_else` part of this PR, in case they help it land:
   
   - In a CPU profile of a production query that groups roughly a year of rows (about 83 M) by
     `date_trunc('month', ts)` in a named session time zone (with DST), `alloc::fmt::format` and integer
     `Display::fmt` under `general_date_trunc` were 8–13 % of the samples — all of it the eagerly built error.
   - With **only** that one-line change on `main` (a7c7c08), the existing `date_trunc` bench extended with two cases in
     `America/New_York` (1,000 nanosecond values) went from 309.3 µs to 163.6 µs for `day` and from 311.4 µs to
     165.6 µs for `month`, about −47 %.
   
   Since this PR now conflicts with `main`, would it help if the one-line `ok_or_else` change landed on its own first
   (referencing #25325), leaving the fixed-offset fast path to this PR? Happy to open that small PR if you and the
   maintainers prefer, or to leave it here if this is close to merging.
   


-- 
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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   @niebayes 
   Thank you for your contribution. 
   I would love to review this after you resolve the merge conflicts.


-- 
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] perf(date_trunc): significantly optimize date_trunc for fixed-offset timezones and coarse granularities binning [datafusion]

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

   @niebayes 
   Can you amend the PR description as per .github/pull_request_template.md?


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