Skip to content

perf: preserve date_trunc ordering for timezone-aware timestamps at day and coarser granularities - #27732

Open
xudong963 wants to merge 1 commit into
apache:mainfrom
xudong963:xudong963/date-trunc-coarse-tz-ordering
Open

xudong963 wants to merge 1 commit into
apache:mainfrom
xudong963:xudong963/date-trunc-coarse-tz-ordering

Conversation

@xudong963

Copy link
Copy Markdown
Member

Which issue does this PR close?

This follows #27547, which restored the ordering for minute and finer granularities. #25635 covered UTC and 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_trunc from propagating its input ordering for timezone-aware timestamps, because truncating in local time can go backwards across a timezone transition (#25353). After #27547, hour and coarser granularities still drop the ordering for every timezone, including UTC and fixed offsets. So sorting or grouping by date_trunc('day', ts) over input ordered on ts adds 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 day goes backwards there. America/New_York changes its offset at 02:00, away from midnight, so day keeps the order.

What changes are included in this PR?

  • DateTruncFunc::output_ordering also keeps the input ordering for a timezone-aware timestamp when local_truncation_preserves_order holds for the constant granularity.
  • local_truncation_preserves_order finds 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. For day, week, month, quarter and year, it compares the kernel's output 1 ns before and at each transition. hour is only accepted for zones without transitions, such as UTC and fixed offsets.
  • The result is cached per timezone name. In a release build, the first call took 0.6 to 4.6 ms in the zones I timed (America/New_York, 359 transitions: 4.6 ms; UTC: 1.2 ms; +05:30: 0.6 ms). Later calls take about 40 ns.
  • minute and finer granularities are unchanged (perf: preserve date_trunc ordering for timezone-aware timestamps at minute and finer granularities #27547).

What is the testing strategy for this PR?

  • timestamps.slt adds two EXPLAIN cases next to the America/Goose_Bay regression from ORDER BY date_trunc(...) can return incorrectly ordered results for named timezones #25353. date_trunc('day', ...) in America/New_York needs no SortExec, and in America/Goose_Bay the SortExec stays. The New York case fails without this change.
  • The output_ordering_with_timezone_depends_on_granularity unit test also asserts that America/New_York is ordered for day through year and unordered for hour, that UTC and +05:30 are ordered for hour, day and year, and that America/Goose_Bay stays unordered for hour and day.
  • The new timezone_offsets_are_constant_outside_transition_scan_window unit 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 hour through year. 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. For day through year the check and the sampling agreed exactly: 21 zones reverse at day, 7 at month, 4 at quarter and year, and none at week. 43 zones reverse at hour, 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 plan main already 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:

  • day or coarser granularity, in zones where truncation keeps the order
  • hour, in zones without transitions such as UTC and fixed offsets

Results are unchanged. No API changes.

🤖 Generated with Claude Code

… 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, find every transition between 1800 and 2200 (daily steps plus
bisection) and compare the kernel's output just before and at each one.
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.
@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) functions Changes to functions implementation labels Nov 25, 2026
@xudong963 xudong963 added the regression Something that used to work no longer does label Nov 25, 2026

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@alamb

alamb commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

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

@xudong963

Copy link
Copy Markdown
Member Author

@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 target_partitions = 1 both plans run at the same speed (NY GROUP BY day: 1.9 s vs 2.0 s). With 12 partitions, the order-preserving merge drains the sorted file ranges one at a time, so the date_trunc inside the scan runs on one core.

The chrono path for timezone-aware hour and coarser costs about 80 ns per row, and that's where the 3–6x comes from. Over a timezone-less column, the same order-aware plan is actually faster than the sort plan (0.27 s vs 0.57 s).

@xudong963

Copy link
Copy Markdown
Member Author

@jayzhan211 thanks for the reviww, I opened #27883 to address the perf issue for date_trunc

xudong963 added a commit that referenced this pull request Dec 1, 2026
…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.
@jayzhan211

Copy link
Copy Markdown
Contributor

@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 ORDER BY, where dropping the sort takes peak memory from 380 MiB to 120 MiB. The largest slowdowns are the GROUP BY cases (0.22 s to 1.36 s), and on main those run as a hash aggregate over about 5.6k hourly groups with no sort, so there is no buffer to save.

#27883 removes most of the per-row cost, but it also speeds up main (UTC GROUP BY hour drops from 0.208 s to 0.047 s there), while the order-aware GROUP BY plan still runs on one core.

@alamb

alamb commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

With 12 partitions, the order-preserving merge drains the sorted file ranges one at a time, so the date_trunc inside the scan runs on one core.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did it in #27883, after #27883 is merged, we can rebase the PR
f9598fb

alamb pushed a commit that referenced this pull request Dec 1, 2026
…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>
xudong963 added a commit that referenced this pull request Dec 2, 2026
…#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>
adriangb pushed a commit to adriangb/datafusion that referenced this pull request Dec 2, 2026
## 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation regression Something that used to work no longer does sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restore date_trunc ordering propagation for safe timezone-aware timestamps

3 participants