Repository navigation
Conversation
…date_trunc` For a timezone-aware timestamp, `date_trunc` to `hour` or a coarser granularity converted every value to a chrono `DateTime`, truncated it field by field and resolved the truncated local time back to UTC, at 100 to 170 ns per value. The result depends only on the truncated local time and the input's UTC offset, and it is `truncated local time - offset` whenever that instant still has the offset. So find the UTC offset transitions of each zone once, between 1800 and 2200 by daily steps and bisection, cache them per timezone name, and truncate with integer arithmetic. A value whose bucket starts before a transition, such as a July value truncated to the year in New York, still takes the chrono path, which reuses its last result for sorted input.
alamb
left a comment
There was a problem hiding this comment.
Thanks @xudong963
My only real concern about this PR is the global cache, but given the measurements it seems like that is reasonable overhead (1MB if we stored all timezones). It could be less if we called shrink_to_fit too
I wonder if you looked at the pre-existing PR from @niebayes that also tries to solve the same problem?
I had my agent test with all 597 chrono-tz zones and this PR produces correct results
cc @mhilton as I think you are into timezone esotera and perhaps will have some better ideas about this idea than I
| transitions.push(after); | ||
| offsets.push(offset); | ||
| day = after; | ||
| } |
There was a problem hiding this comment.
Since these vectors never change, a shrink_to_fit here would save some memory (agent says 30% for NYC)
|
|
||
| /// [`UtcOffsetSpans`] of `tz`, computed once per timezone name. | ||
| fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option<Arc<UtcOffsetSpans>> { | ||
| static CACHE: LazyLock<Mutex<HashMap<String, Option<Arc<UtcOffsetSpans>>>>> = |
There was a problem hiding this comment.
I am not sure putting a global variable here is a great idea
That being said, I had my agent measure the size, and it was:
┌──────────────────┬─────────────┬──────────────────────────┬──────────────────────────┬─────────────────┐
│ Zone │ Transitions │ transitions (i64) │ offsets (i32) │ Allocated total │
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
│ UTC │ 0 │ 0 bytes │ 4 bytes │ 4 bytes │
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
│ +05:30 │ 0 │ 0 bytes │ 4 bytes │ 4 bytes │
├──────────────────┼─────────────┼──────────────────────────┼──────────────────────────┼─────────────────┤
│ America/New_York │ 359 │ 4,096 bytes (2,872 used) │ 2,048 bytes (1,440 used) │ 6,144 bytes │
└──────────────────┴─────────────┴──────────────────────────┴──────────────────────────┴─────────────────┘
- Largest zone: Africa/Cairo and New York tie at the 6,144-byte maximum.
- Whole cache: if every one of the 597 zones were cached, the total would be about 1.2 MB.
| } | ||
|
|
||
| /// [`UtcOffsetSpans`] of `tz`, computed once per timezone name. | ||
| fn cached_utc_offset_spans(tz_name: &str, tz: Tz) -> Option<Arc<UtcOffsetSpans>> { |
There was a problem hiding this comment.
Another idea from the 🤖 during testing would be to special case UTC and fixed offset timezones (e.g. +8:00 as now they have to go through this code to discover they have no transistions
`UTC` and fixed offsets such as `+05:30` have no transitions, so build their single span directly instead of scanning 1800 to 2200 for the offset changes and caching the result per timezone name.
The per-timezone transition table and its cache now live in `datafusion-common`, so other timezone code can share it instead of keeping its own global. The module is hidden from the docs and is for internal use only. The spans are stored as boxed slices, which drops the vectors' spare capacity (New York: 6,144 to 4,312 bytes). Names that fail to parse are not cached, so the cache holds at most one entry per tz database name.
yeah, I saw it; it hasn't been updated for months, so I directly opened the PR |
| pub mod stats; | ||
| pub mod test_util; | ||
| #[doc(hidden)] | ||
| pub mod timezone; |
There was a problem hiding this comment.
Small question: only date_trunc uses this so far. Is it in datafusion-common so #27732 can reuse it for the ordering check? If not, it could live next to date_trunc in datafusion-functions.
There was a problem hiding this comment.
+1. The API policy reserves #[doc(hidden)] pub for items shared across crates, and both users are in datafusion-functions: this file, and #27732, which still has its own utc_offset_transitions and cache in the same file. A pub(crate) module such as datafusion/functions/src/datetime/timezone.rs keeps it out of datafusion-common's API and drops the new chrono-tz dev-dependency there.
mhilton
left a comment
There was a problem hiding this comment.
It seems to me that the bulk of these changes are intended to work around awkwardness in the chrono-tz API. Since chrono is no longer being maintained we would be better off transitioning toward jiff as the presumed successor.
The performance improvement for date_trunc comes from the observation that consecutive timestamps in a batch will likely have the same offset, so if that can be checked cheaply then we need less processing. That being the case I think we'd be better of finding a way to make arrow's Tz API provide that information to datafusion rather than have datafusion grow an unusual global cache.
|
|
||
| [dev-dependencies] | ||
| chrono = { workspace = true } | ||
| chrono-tz = "0.10.4" |
There was a problem hiding this comment.
Since RUSTSEC-2026-0543 having more dependency on chrono feels like going in the wrong direction.
There was a problem hiding this comment.
We might need to deprecate and intro jiff in arrow-rs as the first step
| /// Finds every UTC offset transition of `tz` between 1800 and 2200 by | ||
| /// stepping a day at a time and bisecting to the second. Steps of a day catch | ||
| /// every transition, since tz database transitions are days apart. | ||
| fn scan(tz: &Tz) -> Option<Self> { |
There was a problem hiding this comment.
This seems like a labour intensive way to find the transitions. jiff::tz::TimeZone::following() would just tell you them.
jayzhan211
left a comment
There was a problem hiding this comment.
@xudong963 thanks for the kernel! I compared it with the chrono path on 174M values across all 597 chrono-tz zones and 7 fixed offsets, in every unit and granularity. It found no mismatches, and the error cases matched too. Your benchmark numbers reproduce here, and none of my worst cases (random quarter/year input, values from 1800 to 2200, 1-row batches) is slower than main. One test request is inline.
| } | ||
| match last_chrono_result.get() { | ||
| Some((offset, truncated_local, result)) | ||
| if offset == current.offset && truncated_local == local => |
There was a problem hiding this comment.
Removing offset == current.offset from this match still passes every test in the PR, but it returns wrong results. In America/Creston, year on [1944-08-18T19:39:14Z, 1944-11-08T00:10:20Z] gives 1944-01-01T06:00Z twice instead of 06:00Z and 07:00Z. Creston fell back at 00:01 on 1944-01-01, so that midnight happened twice, and the chrono path picks the instant with the input's offset. Could you add this test so the offset stays in the key?
/// America/Creston fell back at 1944-01-01 00:01, so midnight that day is
/// ambiguous. August (UTC-6) and November (UTC-7) both truncate to it on the
/// chrono path, which picks the instant with the input's offset.
#[test]
fn date_trunc_with_spans_reuses_chrono_result_only_for_same_offset() {
let tz: Tz = "America/Creston".parse().unwrap();
let spans = UtcOffsetSpans::for_timezone("America/Creston").unwrap();
// 1944-08-18T19:39:14Z and 1944-11-08T00:10:20Z
let array =
PrimitiveArray::<TimestampSecondType>::from(vec![-800_598_046, -793_583_380]);
let actual =
date_trunc_coarse_with_spans(&array, DatePart::Year, tz, &spans).unwrap();
// 1944-01-01T00:00-06:00 and 1944-01-01T00:00-07:00
assert_eq!(actual.values(), &[-820_519_200, -820_515_600]);
}| let tz: Tz = "America/New_York".parse().unwrap(); | ||
| let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); | ||
| for granularity in [DatePart::Hour, DatePart::Day, DatePart::Year] { |
There was a problem hiding this comment.
Optional: this test still passes if the truncation fallback in the kernel returns Some(0) instead of taking the chrono path. Near i64::MIN, New York's negative offset already overflows in checked_add, so the truncation's own overflow is never reached. Adding a zone east of UTC covers it:
| let tz: Tz = "America/New_York".parse().unwrap(); | |
| let spans = UtcOffsetSpans::for_timezone("America/New_York").unwrap(); | |
| for granularity in [DatePart::Hour, DatePart::Day, DatePart::Year] { | |
| // Near `i64::MIN`, adding a west offset overflows, while an east zone | |
| // reaches the truncation and overflows there. | |
| for (zone, granularity) in ["America/New_York", "Asia/Tokyo"] | |
| .into_iter() | |
| .flat_map(|zone| { | |
| [DatePart::Hour, DatePart::Day, DatePart::Year].map(|g| (zone, g)) | |
| }) | |
| { | |
| let tz: Tz = zone.parse().unwrap(); | |
| let spans = UtcOffsetSpans::for_timezone(zone).unwrap(); |
Which issue does this PR close?
date_trunckeeps the ordering of timezone-aware timestamps. This is that kernel.Rationale for this change
For a timezone-aware timestamp,
date_trunctohouror a coarser granularity goes through chrono for every value. It builds aDateTime<Tz>, clears the fields of its local time one at a time, and resolves the result back to UTC withand_local_timezone. In the benchmarks below that costs 110 to 165 ns per value. Timezone-lessweekthroughyeartake 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 - offsetwhenever that instant still has the offset. So:UtcOffsetSpansfinds 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_spanshandles arrays with a timezone. For each value it:_date_trunc_coarse_without_tz;truncated - offsetif 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_tzis now#[inline]. It has a second caller, and without the attribute timezone-lessweekwas 6% slower.Scalars and timezone-less arrays are unchanged.
What is the testing strategy for this PR?
date_trunc_with_spans_matches_chrono_pathcompares 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_pathchecks that values outside the nanosecond range, or truncated below it, get the same error as before.utc_offset_spans_find_transitionschecks two known New York transitions, and checks thatUTCand+05:30have none.timezone_offsets_are_constant_outside_transition_scan_windowchecks that no chrono-tz zone changes its offset outside the scan window, so a chrono-tz upgrade that adds one fails it.datafusion-clionmainand on this branch over 13.7M values in 13 zones, for every granularity fromhourtoyear, 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_trunccover 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:maindate_trunc_hour_new_york_random_nanos_1000date_trunc_day_new_york_random_nanos_1000date_trunc_month_new_york_random_nanos_1000date_trunc_year_new_york_random_nanos_1000date_trunc_hour_new_york_sorted_nanos_1000date_trunc_day_new_york_sorted_nanos_1000date_trunc_month_new_york_sorted_nanos_1000date_trunc_year_new_york_sorted_nanos_1000date_trunc_hour_utc_random_nanos_1000date_trunc_day_utc_random_nanos_1000date_trunc_hour_utc_sorted_nanos_1000date_trunc_day_utc_sorted_nanos_1000date_trunc_minute_1000(unchanged path)date_trunc_week_nanos_1000(unchanged path)date_trunc_month_nanos_1000(unchanged path)date_trunc_year_nanos_1000(unchanged path)yearon 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-cliover 20M rows, one Parquet file declaredWITH ORDER (ts ASC), 12 partitions, median of 5. The data is the setup from #27547; the 6.3-year file has one row every 10 seconds. Plans are unchanged:mainGROUP BY date_trunc('hour', ts)GROUP BY date_trunc('day', ts), 6.3 yearsEXPLAIN ANALYZE ... ORDER BY date_trunc('day', ts)EXPLAIN ANALYZE ... ORDER BY date_trunc('hour', ts)GROUP BY date_trunc('day', ts),target_partitions = 1date_trunc('day', ts)on unsorted input,target_partitions = 1ORDER BY date_trunc('minute', ts)(unchanged path)Are there any user-facing changes?
date_trunctohouror coarser on timezone-aware timestamps is faster. Results are unchanged. No API changes.🤖 Generated with Claude Code