Repository navigation
perf: preserve date_trunc ordering for timezone-aware timestamps at day and coarser granularities - #27732
perf: preserve date_trunc ordering for timezone-aware timestamps at day and coarser granularities#27732xudong963 wants to merge 2 commits into
date_trunc ordering for timezone-aware timestamps at day and coarser granularities#27732Conversation
jayzhan211
left a comment
There was a problem hiding this comment.
@xudong963 thanks for the PR! The ordering check is exact as far as I can test, but removing the sort makes the target queries 2.7–6.2x slower than main on sorted Parquet at the default 12 partitions: GROUP BY date_trunc('hour', ts) in UTC goes from 0.22 s to 1.36 s, and ORDER BY date_trunc('day', ts) in America/New_York from 0.54 s to 1.73 s. It's the effect from #25635 (#25635 (comment)): the merge now drains the sorted ranges one at a time, and the chrono path these granularities take runs on one core. minute and timezone-less day stay at 0.27 s because their kernels are arithmetic, so the trade-off from #27547 doesn't carry over here.
Could this land after a cheaper kernel for these cases? For example #25326 for fixed offsets, and for named zones, arithmetic between the transitions this PR already computes.
Numbers and setup (release-nonlto, M-series laptop, median of 5)
| Query | main |
This PR |
|---|---|---|
NY EXPLAIN ANALYZE ... ORDER BY date_trunc('day', ts) |
0.54 s, 380 MiB | 1.73 s, 120 MiB |
UTC EXPLAIN ANALYZE ... ORDER BY date_trunc('hour', ts) |
0.56 s | 1.50 s |
UTC GROUP BY date_trunc('hour', ts) |
0.22 s | 1.36 s |
UTC GROUP BY hour ORDER BY h LIMIT 1 |
0.21 s | 1.36 s |
NY GROUP BY day, target_partitions = 1 |
1.86 s | 1.80 s |
NY ORDER BY date_trunc('minute', ts) (control) |
0.27 s | 0.27 s |
Data is the setup from #27547 (20M rows, one per second), written once with America/New_York and once with UTC:
CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION 'utc.parquet' WITH ORDER (ts ASC);
SELECT count(*), max(c) FROM (SELECT date_trunc('hour', ts) AS m, count(*) AS c FROM t GROUP BY m);In the UTC GROUP BY hour plan, the partial AggregateExec reports elapsed_compute=1.42s against 1.36 s of wall time: the 12 partitions run one after another.
|
@jayzhan211 do you think the issue here is that the order aware operators are slower in general than the non order aware ones? I think that was true before this PR as well -- and there is a tradeoff between CPU usage and memory for example (your numbers show the tradeoff I think -- 5x slower runtime but 1/3 the ram (380MB --> 120MB) |
Thanks @alamb. I don't think it's the order-aware operators themselves. With The chrono path for timezone-aware |
|
@jayzhan211 thanks for the reviww, I opened #27883 to address the perf issue for |
…imestamps at minute and finer granularities (backport #27547) (#27848) ## Which issue does this PR close? - Backport of #27547 to `branch-56`, for #24463, which lists it as a regression in 56. - Part of #25464. ## Rationale for this change #25409, new in 56, stopped `date_trunc` from propagating its input ordering for every timezone-aware timestamp. So since 56.0.0, sorting or grouping by `date_trunc('minute', ts)` over input ordered on `ts` adds a sort and loses clustered aggregation, where 55 did not. #27547 restores the ordering for `minute` and finer granularities, where truncation is arithmetic on the epoch value and cannot reorder values. ## What changes are included in this PR? A clean cherry-pick of #27547 (`477c7b9`) with `-x`. No conflicts. ## What is the testing strategy for this PR? The `date_trunc` unit tests and `datetime/timestamps.slt` pass on this branch. Applied on `branch-56` together with the other backports, #27846 (#27021), #27847 (#27150), #27849 (#27732) and #27850 (#26261), the full sqllogictest suite, `cargo fmt --check` and clippy on the touched crates also pass. ## Are there any user-facing changes? Plans only: no `SortExec`, and clustered aggregation, for `date_trunc` at `minute` and finer over ordered timezone-aware input. Results are unchanged. No API changes.
|
@alamb Yes, the one-core part was there before this PR, and it's tracked as #27003: when sorted inputs cover separate key ranges, the merge reads them one at a time. I don't think the memory trade-off explains these numbers, though. It holds for #27883 removes most of the per-row cost, but it also speeds up |
That seems like something we should consider fixing (like we should use one core for merging and then also be buffering at least one batch for each input of we have cores available 🤔 Update: I see #27003 now |
| tz: Tz, | ||
| granularity: DatePart, | ||
| ) -> bool { | ||
| static CACHE: LazyLock<Mutex<HashMap<String, LocalTruncationOrder>>> = |
There was a problem hiding this comment.
I think we could special case UTC and fixed timezone offsets here (+00:00 etc) as they have no transitions and thus preserve granularity
|
|
||
| /// Granularities coarser than minute whose local-time truncation keeps the order | ||
| /// in one zone. Day and longer buckets outlast any offset change, so only the | ||
| /// instants around each transition can go backwards; `hour` needs no transitions. |
There was a problem hiding this comment.
Also I had my agent test all the chrono timezones (597 of them) and all their transitions are more than a day
FWIW it seems jiff has a API to enumerate the timezone transitions -- so if we ever moved that library we could remove this assumption and just enumemerate the transitions directly
| ) -> bool { | ||
| static CACHE: LazyLock<Mutex<HashMap<String, LocalTruncationOrder>>> = | ||
| LazyLock::new(Default::default); | ||
| let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); |
There was a problem hiding this comment.
Also, this global along with the proposed global state / cache in #27883 makes me think we should perhaps centralize the timezone related functionality.
Perhaps we can put it in datafusion-common as a timezone module src/timezone.rs
That way we could have a cached per-zone transition table and share between this PR and #27883
…ue` (backport #27150) (#27847) ## Which issue does this PR close? - Backport of #27150 to `branch-56`, for #24463. - Closes #27149 for the 56 line. ## Rationale for this change Without an `ORDER BY`, `first_value` has no `GroupsAccumulator`, so grouped aggregation keeps one boxed accumulator per group. Every `DISTINCT ON` without `ORDER BY` plans unordered `first_value`. #27150 measured 6x to 18x faster queries and up to 2.7x lower peak memory on ClickBench queries with 17.6M groups. ## What changes are included in this PR? A clean cherry-pick of #27150 (`26de352`) with `-x`. No conflicts. ## What is the testing strategy for this PR? The `first_last` unit tests from #27150 pass on this branch, as do `aggregate*.slt`, `group_by.slt` and `window*.slt`. Applied on `branch-56` together with the other backports, #27846 (#27021), #27848 (#27547), #27849 (#27732) and #27850 (#26261), the full sqllogictest suite, `cargo fmt --check` and clippy on the touched crates also pass. ## Are there any user-facing changes? No API changes. `first_value` without `ORDER BY`, including `DISTINCT ON`, is faster. The intermediate state layout is unchanged (`[first_value, is_set]`), so partial and final aggregation see the same schema as before. Co-authored-by: Rohan Krishnaswamy <47869999+rkrishn7@users.noreply.github.com>
…#27021) (#27846) ## Which issue does this PR close? - Backport of #27021 to `branch-56`, for #24463. - Closes #27020 for the 56 line. ## Rationale for this change arrow-csv maps CSV columns by position. When files in one table have different column layouts, values land in the wrong columns or parsing fails. #27021 adds an opt-in `match_columns_by_header` option that maps each file's columns to the table schema by header name. Users on 56 who read CSV files whose layout changed over time need this before 57. ## What changes are included in this PR? A cherry-pick of #27021 (`3f837ad`) with `-x`. The only conflict was in `docs/source/library-user-guide/upgrading/56.0.0.md`: on `main` that file also has a section from an unrelated PR (`CreateFunction` field types), so I kept only the `match_columns_by_header` section. ## What is the testing strategy for this PR? The tests from #27021 pass on this branch: the `datafusion-datasource-csv` unit tests, the CSV tests in `core_integration`, the proto round-trip tests, `csv_files.slt` and `information_schema.slt`. Applied on `branch-56` together with the other backports, #27847 (#27150), #27848 (#27547), #27849 (#27732) and #27850 (#26261), the full sqllogictest suite, `cargo fmt --check` and clippy on the touched crates also pass. ## Are there any user-facing changes? - New opt-in `format.match_columns_by_header` option, default `false`. Existing reads are unchanged. - API: `CsvOptions` and `CsvReadOptions` gain a public `match_columns_by_header` field. Neither struct is `#[non_exhaustive]`, so code that builds them with an exhaustive struct literal stops compiling until it adds the field or uses `..Default::default()`. This is noted in the 56.0.0 upgrade guide. Please weigh this for a minor release. - Proto: `CsvOptions` (field 23) and `CsvScanExecNode` (field 10) gain the same field, with the same field numbers as `main`. Co-authored-by: Wyatt Herkamp <wyatt.herkamp@massive.com> Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
## Which issue does this PR close? - N/A — found while reviewing apache#27732 ## Rationale for this change `with_return_type` in `datetime/common.rs` unecessarily clones the array's `DataType` only to compare it against the requested type ## What changes are included in this PR? Borrow the `DataType` instead of cloning it. ## What is the testing strategy for this PR? No behavior change; covered by existing tests. ## Are there any user-facing changes? No Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
## Which issue does this PR close? - N/A — found while reviewing apache#27732 ## Rationale for this change `with_return_type` in `datetime/common.rs` unecessarily clones the array's `DataType` only to compare it against the requested type ## What changes are included in this PR? Borrow the `DataType` instead of cloning it. ## What is the testing strategy for this PR? No behavior change; covered by existing tests. ## Are there any user-facing changes? No Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
… day and coarser granularities `date_trunc` truncates day and coarser granularities in local time, and DataFusion stopped propagating its input ordering for every named zone because a transition can move local time back across a bucket boundary. While the UTC offset is constant, truncating to a day or longer is monotone: consecutive buckets start at least 24 hours apart and no offset change is that large. So the order can only break at a transition. For each zone, compare the kernel's output just before and at each of the transitions that the arithmetic kernel already finds. Hour stays limited to zones without transitions. The result is cached per timezone name. An all-zone cross-check against dense sampling around every transition agreed exactly for day through year: 21 zones reverse at day (for example America/Goose_Bay), while America/New_York and UTC keep the order.
`UTC`, fixed offsets and other zones without UTC offset transitions keep the order at every granularity, so return before computing and caching a `LocalTruncationOrder` for them.
b32121f to
58199ee
Compare
…date_trunc` (apache#27883) ## Which issue does this PR close? - Related to apache#25464. In the [review of apache#27732](apache#27732 (review)), @jayzhan211 asked for a cheaper kernel before `date_trunc` keeps the ordering of timezone-aware timestamps. This is that kernel. ## Rationale for this change For a timezone-aware timestamp, `date_trunc` to `hour` or a coarser granularity goes through chrono for every value. It builds a `DateTime<Tz>`, clears the fields of its local time one at a time, and resolves the result back to UTC with `and_local_timezone`. In the benchmarks below that costs 110 to 165 ns per value. Timezone-less `week` through `year` take 4 to 11 ns. ## What changes are included in this PR? The chrono path returns the instant that has the truncated local time and the input's UTC offset. Its result depends only on those two values, and it is `truncated local time - offset` whenever that instant still has the offset. So: - `UtcOffsetSpans` finds the UTC offset transitions of a zone between 1800 and 2200. It steps a day at a time and bisects to the second, continuing from each transition it finds. The spans are cached per timezone name, and the scan runs outside the lock. In a release build the first call took 0.6 to 4.6 ms in the zones I timed. - `date_trunc_coarse_with_spans` handles arrays with a timezone. For each value it: 1. takes the offset from the current span, and looks it up again only when the value leaves that span; 2. truncates the local time with the existing `_date_trunc_coarse_without_tz`; 3. returns `truncated - offset` if that instant is in the same span. Otherwise a transition lies between the bucket start, for example 1 January in New York, and the value, so the value takes the chrono path, which reuses its last result. - `_date_trunc_coarse_without_tz` is now `#[inline]`. It has a second caller, and without the attribute timezone-less `week` was 6% slower. Scalars and timezone-less arrays are unchanged. ## What is the testing strategy for this PR? - `date_trunc_with_spans_matches_chrono_path` compares the kernel with the chrono path at 7 points around every transition of 26 zones. The zones include transitions at midnight (Sao_Paulo, Havana, Santiago), a skipped day (Apia, Kiritimati), Goose_Bay's 00:01 fall-back, sub-hour offsets, and Casablanca's closely spaced transitions. It covers seconds and nanoseconds, all six granularities, and input in ascending and descending order. The same test over all 597 chrono-tz zones also passes, but takes 17 s unoptimized, so the committed list is shorter. With the span check removed, the test fails. - `date_trunc_with_spans_reports_out_of_range_like_chrono_path` checks that values outside the nanosecond range, or truncated below it, get the same error as before. - `utc_offset_spans_find_transitions` checks two known New York transitions, and checks that `UTC` and `+05:30` have none. - `timezone_offsets_are_constant_outside_transition_scan_window` checks that no chrono-tz zone changes its offset outside the scan window, so a chrono-tz upgrade that adds one fails it. - Outside the test suite, I compared `datafusion-cli` on `main` and on this branch over 13.7M values in 13 zones, for every granularity from `hour` to `year`, in second and nanosecond units. The values were spread from 1850 to 2100, in 10-minute steps over 1970 to 2030, and in 15-second steps over 1987 to 1988 and 2023 to 2024. The results were identical. ### Benchmarks The new criterion cases in `date_trunc` cover random and sorted input in America/New_York and UTC. Numbers are medians of 3 interleaved runs per binary, `release-nonlto`, on an M-series laptop: | Benchmark (1000 rows) | `main` | This PR | Change | |---|---|---|---| | `date_trunc_hour_new_york_random_nanos_1000` | 157.99 µs | 11.10 µs | -93.0% | | `date_trunc_day_new_york_random_nanos_1000` | 161.33 µs | 12.24 µs | -92.4% | | `date_trunc_month_new_york_random_nanos_1000` | 162.91 µs | 24.42 µs | -85.0% | | `date_trunc_year_new_york_random_nanos_1000` | 163.07 µs | 138.63 µs | -15.0% | | `date_trunc_hour_new_york_sorted_nanos_1000` | 140.33 µs | 6.14 µs | -95.6% | | `date_trunc_day_new_york_sorted_nanos_1000` | 143.80 µs | 7.11 µs | -95.1% | | `date_trunc_month_new_york_sorted_nanos_1000` | 142.70 µs | 15.31 µs | -89.3% | | `date_trunc_year_new_york_sorted_nanos_1000` | 143.39 µs | 29.19 µs | -79.6% | | `date_trunc_hour_utc_random_nanos_1000` | 114.52 µs | 3.86 µs | -96.6% | | `date_trunc_day_utc_random_nanos_1000` | 115.30 µs | 3.58 µs | -96.9% | | `date_trunc_hour_utc_sorted_nanos_1000` | 110.26 µs | 3.85 µs | -96.5% | | `date_trunc_day_utc_sorted_nanos_1000` | 111.67 µs | 3.58 µs | -96.8% | | `date_trunc_minute_1000` (unchanged path) | 1.35 µs | 1.38 µs | +1.8% | | `date_trunc_week_nanos_1000` (unchanged path) | 3.67 µs | 3.70 µs | +0.7% | | `date_trunc_month_nanos_1000` (unchanged path) | 7.36 µs | 7.46 µs | +1.3% | | `date_trunc_year_nanos_1000` (unchanged path) | 9.13 µs | 9.28 µs | +1.6% | `year` on random New York input gains least. Every value from March to October starts its bucket before the spring transition, so it takes the chrono path, and random input rarely repeats the last result. End to end, with `datafusion-cli` over 20M rows, one Parquet file declared `WITH ORDER (ts ASC)`, 12 partitions, median of 5. The data is the setup from apache#27547; the 6.3-year file has one row every 10 seconds. Plans are unchanged: | Query | `main` | This PR | |---|---|---| | UTC `GROUP BY date_trunc('hour', ts)` | 0.208 s | 0.047 s | | America/New_York `GROUP BY date_trunc('day', ts)`, 6.3 years | 0.246 s | 0.056 s | | America/New_York `EXPLAIN ANALYZE ... ORDER BY date_trunc('day', ts)` | 0.569 s | 0.369 s | | UTC `EXPLAIN ANALYZE ... ORDER BY date_trunc('hour', ts)` | 0.561 s | 0.419 s | | America/New_York `GROUP BY date_trunc('day', ts)`, `target_partitions = 1` | 1.938 s | 0.274 s | | America/New_York `date_trunc('day', ts)` on unsorted input, `target_partitions = 1` | 1.726 s | 0.148 s | | America/New_York `ORDER BY date_trunc('minute', ts)` (unchanged path) | 0.268 s | 0.273 s | ## Are there any user-facing changes? `date_trunc` to `hour` or coarser on timezone-aware timestamps is faster. Results are unchanged. No API changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
#27883 is merged, and I rebased this PR on it. Same setup as your review (20M rows, sorted Parquet, 12 partitions), with
That slowdown isn't specific to timezones, though. On Would you be OK with landing this and treating #27003 as the fix for both? Or would you rather this wait until #27003 is fixed? |
Which issue does this PR close?
This follows #27547, which restored the ordering for
minuteand finer granularities. #25635 coveredUTCand fixed offsets and has been closed. This PR covers those zones too, because a zone without transitions keeps the order at every granularity.Rationale for this change
#25409 stopped
date_truncfrom propagating its input ordering for timezone-aware timestamps, because truncating in local time can go backwards across a timezone transition (#25353). After #27547,hourand coarser granularities still drop the ordering for every timezone, includingUTCand fixed offsets. So sorting or grouping bydate_trunc('day', ts)over input ordered ontsadds a sort, or keeps every group in the hash table until the input ends.Most zones never reverse at these granularities. While the UTC offset is constant, truncating to a day or longer is monotone, because consecutive buckets start at least 24 hours apart and no offset change is that large. So the order can only break at a transition, and checking the instants around each transition is exact. For example, America/Goose_Bay fell back from 00:01 to 23:01 the previous day, so
daygoes backwards there. America/New_York changes its offset at 02:00, away from midnight, sodaykeeps the order.What changes are included in this PR?
DateTruncFunc::output_orderingalso keeps the input ordering for a timezone-aware timestamp whenlocal_truncation_preserves_orderholds for the constant granularity.local_truncation_preserves_orderfinds every UTC offset transition of the zone between 1800 and 2200. It steps a day at a time and bisects to the second. Steps of a day catch every transition, since tz database transitions are at least several days apart; the closest pair in chrono-tz 0.10.4 is 6.9 days apart. Forday,week,month,quarterandyear, it compares the kernel's output 1 ns before and at each transition.houris only accepted for zones without transitions, such asUTCand fixed offsets.America/New_York, 359 transitions: 4.6 ms;UTC: 1.2 ms;+05:30: 0.6 ms). Later calls take about 40 ns.minuteand finer granularities are unchanged (perf: preservedate_truncordering for timezone-aware timestamps at minute and finer granularities #27547).What is the testing strategy for this PR?
timestamps.sltadds twoEXPLAINcases next to the America/Goose_Bay regression fromORDER BY date_trunc(...)can return incorrectly ordered results for named timezones #25353.date_trunc('day', ...)in America/New_York needs noSortExec, and in America/Goose_Bay theSortExecstays. The New York case fails without this change.output_ordering_with_timezone_depends_on_granularityunit test also asserts that America/New_York is ordered fordaythroughyearand unordered forhour, thatUTCand+05:30are ordered forhour,dayandyear, and that America/Goose_Bay stays unordered forhourandday.timezone_offsets_are_constant_outside_transition_scan_windowunit test checks every chrono-tz zone, so a chrono-tz upgrade that adds transitions outside the scan window fails it.As a check outside the test suite, I compared the new check with dense sampling of the kernel around every transition, for all 597 chrono-tz zones and
hourthroughyear. The sampling covered ±3 s, every minute for ±2 h, every 30 min for ±2 days and every 12 h for ±40 days. No zone that the check reports as ordered reverses. The daily-step transitions matched an independent hourly scan in every zone. Fordaythroughyearthe check and the sampling agreed exactly: 21 zones reverse atday, 7 atmonth, 4 atquarterandyear, and none atweek. 43 zones reverse athour, the same count as the sweep in #27547.The plan change is the same one #27547 makes for
minute: no sort, and clustered aggregation. So the trade-off measured there applies here too. It is also the planmainalready picks for timezone-less timestamps.Are there any user-facing changes?
Queries that sort or group timezone-aware timestamps by
date_trunc, over input ordered on the timestamp, no longer add a sort and use clustered aggregation in these cases:dayor coarser granularity, in zones where truncation keeps the orderhour, in zones without transitions such asUTCand fixed offsetsResults are unchanged. No API changes.
🤖 Generated with Claude Code