Resolve DST-ambiguous and nonexistent local times in string_to_datetime - #11054
Resolve DST-ambiguous and nonexistent local times in string_to_datetime#11054adriangb wants to merge 3 commits into
string_to_datetime#11054Conversation
…amps to a named timezone
Casting `Timestamp(_, None)` to `Timestamp(_, Some(tz))` reads each value as a
wall clock time in `tz`. In an IANA timezone that reading does not always
identify a unique instant:
* When the clocks go back ("fall back") the hour repeats and the reading is
ambiguous.
* When the clocks go forward ("spring forward") an hour is skipped and the
reading never occurs.
`adjust_timestamp_to_timezone` used `LocalResult::single()`, which is `None` for
both cases, so values on either kind of DST boundary failed with "Cannot cast
timezone to different timezone" under `CastOptions { safe: false }` and silently
became NULL under `safe: true`.
Resolve them instead, matching PostgreSQL 17 and DuckDB 1.5:
* Ambiguous readings take the *later* instant, i.e. the offset in effect after
the transition. `2024-11-03T01:30:00` in `America/New_York` becomes
`01:30-05:00` (EST).
* Nonexistent readings are shifted forward by the length of the gap, which is
the same as reading them with the offset in effect *before* the transition.
`2024-03-10T02:30:00` in `America/New_York` becomes `03:30-04:00` (EDT).
The pre-transition offset is recovered by probing the same lookup 24 hours
earlier and taking the earliest result; the timezone database contains no two
transitions within 24 hours of each other, so the probe always lands on the
other side of the transition. `offset_from_utc_datetime` is not usable as a
shortcut here: it returns the post-transition offset, which is wrong for
southern hemisphere gaps such as `Australia/Sydney` `2024-10-06T02:30:00`.
Fixed-offset timezones have no transitions and are unaffected. Unit conversion,
`safe` handling and the error message are unchanged.
Tests live in `arrow-cast`, which now enables `arrow-array/chrono-tz` as a
dev-dependency so its own tests can use IANA timezone names. The one existing
assertion on the "invalid timezone" parser message is relaxed to its common
prefix, since the tail of that message depends on whether `chrono-tz` is on.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ime`
`string_to_datetime` resolves a wall clock reading with `LocalResult::single()`,
which is `None` both when the reading is ambiguous (the repeated hour when the
clocks go back) and when it does not exist (the skipped hour when the clocks go
forward). There are three such call sites:
* a date-only string, which reads local midnight;
* a naive datetime with no trailing offset or zone;
* a datetime with a trailing IANA zone name, e.g.
`'2024-03-10T02:30:00 America/New_York'`.
Every `Utf8`/`LargeUtf8`/`Utf8View` -> `Timestamp(_, Some(tz))` cast goes through
one of them, so such values failed with "error computing timezone offset" under
`CastOptions { safe: false }` and silently became NULL under `safe: true`.
This is the parser-side twin of apache#11038, which fixed the same bug in the cast
kernel's `Timestamp(_, None)` -> `Timestamp(_, Some(tz))` path. Rather than
restate the policy, apache#11038's `resolve_local_offset` moves out of `cast/mod.rs`
into a new private `local_time` module, generalised from `&Tz` to any
`chrono::TimeZone` (`string_to_datetime` is generic over its target timezone),
and both paths now call it. The policy is unchanged: an ambiguous reading takes
the *later* instant, and a nonexistent one is shifted forward by the length of
the gap, recovered by probing the same lookup 24 hours earlier. No two
transitions in the timezone database are closer than 167 hours, so that probe
always lands on the other side of the transition.
A zone named by the string itself is resolved the same way as one taken from the
target type. The zone is spelled out more explicitly, but the wall clock reading
is no less ambiguous for it, and PostgreSQL 17 makes no distinction between the
two spellings either.
Every expectation added here was taken from PostgreSQL 17.11, and covers each of
the three call sites for both an ambiguous and a nonexistent reading: a
whole-hour DST step (`America/New_York`, `America/Los_Angeles`), a thirty minute
step (`Australia/Lord_Howe`, where a gap shifts 02:15 to 02:45 rather than
03:15), a 45 minute offset (`Pacific/Chatham`), a southern hemisphere zone whose
gap falls in October (`Australia/Sydney`), and the two zones whose transitions
land on midnight and so are only reachable from the date-only site
(`America/Sao_Paulo` 2018-11-04, a local midnight that does not exist, and
`America/Havana` 2024-11-03, one that happens twice). Fixed offsets are
unaffected. An array straddling both of a zone's transitions confirms the offset
is resolved per row.
`arrow/tests/timezone.rs` asserted the old error for the two
`America/Los_Angeles` cases; those move from `test_parse_timezone_invalid` to
`test_parse_timezone` with the instants PostgreSQL produces.
Closes apache#11039
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Self-review QA pass — this is our own PR, so treat this as our own adversarial check, not an independent review. No blocking defect. The highest-risk part of this stack is the change of 1. The generalisation does not change the original cast call site — verified byte for byteThis was the item that could regress #11038 silently. I ran the identical battery of cast-path readings on both branches and compared the raw output:
43 rows, and the two files are identical. The cast path on this branch is bit-for-bit the cast path on #11038. The refactor moves One note on the new wrapper. 2. The stated safety argument for the 24-hour probe is not the load-bearing oneThis PR repeats #11038's justification: no two transitions are closer than 167 hours. That figure is correct, and I reproduce it. But it is not the property that makes the probe resolvable. Two separate invariants are at work:
Seven zones have a local gap of exactly 24.00 hours — the dateline changes: The code is correct today. I tested the first instant, the midpoint and the last second of all four surviving dateline gaps through the cast path, and all 13 readings match PostgreSQL 17.11 exactly. But the doc comment in 3. The give-up branch is unreachable, and this PR widens who depends on that
This PR raises the stakes, because the branch now has four callers rather than one. I read all four. All handle
The three parser sites return a 4. The known divergence deserves the same prominence it has in #11038
#11038 carries a full table and a paragraph on why the two must be reconciled. This PR mentions it in one parenthesis inside "What changes are included". I recommend the fuller disclosure here too. This is the PR that creates the single shared helper, so it is the PR that makes the surviving divergence look deliberate. What I checked and found correctBoth paths now share one policy — measured, not assumed. I ran 5,012 boundary readings across 226 zones through the cast path and the string path in the same run. Every DST transition of every zone from 2020 to 2025, sampled at the start and the midpoint of each gap and each repeated interval: 2,506 in a gap, 2,506 ambiguous.
That agreement is the central claim of this PR, and it holds across the whole tzdb, not just the tested zones. Against PostgreSQL. 3,908 of those readings use a zone PostgreSQL 17.11 accepts. 16 disagree, on both paths equally. All 16 are PostgreSQL and DuckDB agree with each other, so chrono-tz is the outlier. Please name Per-row resolution on the string path. One
The four hard zones the PR names. All verified against PostgreSQL independently:
The site-3 argument holds. I confirmed the PostgreSQL claim directly. No call site is missed. After this PR the only remaining local-time resolution in the tree outside Suite. The fixed-offset caveat is over-broad in the body. I measured it. PostgreSQL uses POSIX west-positive signs only when |
The comment gave only one reason the probe is sound: that no two transitions are closer than 24 hours. That is the wrong invariant for the question it was answering. It explains why the offset the probe finds is the *correct* one, but not why the probe lands somewhere *resolvable*. What makes the probe resolvable is a different property: no local gap is longer than 24 hours. Seven zones have a gap of exactly 24 hours -- the dateline changes, such as Pacific/Apia in 2011 and Pacific/Kiritimati in 1994. At the last second of one of those, the probe lands one second before the gap starts. So the real margin is one second, not the 167 hours the old comment implied. Verified against tzdata directly: over 598 zones and 20470 forward transitions between 1900 and 2040, zero gaps exceed 24 hours, seven are exactly 24 hours, and the next largest is 10 hours. Comment only, no behaviour change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Which issue does this PR close?
string_to_datetime(andUtf8→Timestamp(tz)casts) fail on DST-ambiguous and nonexistent local times #11039.Important
This PR stacks on #11038 and must merge after it. The branch sits on
fix-dst-timezone-cast, so the diff here includes #11038's commit. Review the second commit only, or wait for #11038 to merge and this rebases down to one commit.Together, #11038 and this PR close apache/datafusion#25084. Neither closes it alone. See "Are there any user-facing changes?" below.
Rationale for this change
What a user hits today
Parse a timestamp string into a named timezone. Pick a wall clock reading that the zone skips or repeats. The parse fails.
Today:
After this PR:
Every
Utf8/LargeUtf8/Utf8Viewcast toTimestamp(_, Some(tz))goes through that function. UnderCastOptions { safe: true }the error becomes a silent NULL for the whole row.How this reaches a SQL user
A DataFusion user reaches the parser through ordinary SQL. #11038 fixed the cast kernel, so the first line below now works and the other two still fail:
To a user those are the same query, and the last spelling is the most natural one. Merge #11038 alone and an explicit
::timestampin the middle of an expression makes a query start to work. That is harder to explain than the current uniform failure. So this is a blocker for #11038, not a follow-up.Why the parser fails
string_to_datetimeinarrow-cast/src/parse.rsresolves a wall clock reading withLocalResult::single(). That isNonein two distinct cases:There are three such call sites, one per shape of input:
'2018-11-04''2024-03-10 02:30:00''2024-03-10 02:30:00 America/New_York'What changes are included in this PR?
Overview
One shared function now decides every wall clock reading in arrow-cast. The three parser sites and the cast kernel all call it. The policy itself does not change.
Detail
The resolution policy is deliberately shared with #11038, not restated. Two copies of this policy that drift apart is exactly the bug this PR avoids. One such divergence already exists in the tree, and this PR leaves it alone. See the follow-up section below.
So #11038's
resolve_local_offsetmoves out ofcast/mod.rsinto a new privatearrow-cast/src/local_time.rsmodule and becomespub(crate). It generalises from&Tzto anychrono::TimeZone, becausestring_to_datetimeis generic over its target timezone. A thinresolve_local_datetimewrapper returns aDateTime<T>, which is the shape the three parser sites want. All four call sites now go through the one function.The policy is unchanged from #11038:
Two properties of the timezone database make the probe safe:
Both were verified exhaustively for #11038. This PR does not re-derive them.
On site 3, the zone named in the string
Site 3 resolves against a zone the user spelled out, rather than one taken from the target type. So it is fair to ask whether it deserves stricter treatment. It gets the same policy, for two reasons:
'2024-03-10 02:30:00 America/New_York'is exactly as unresolvable as'2024-03-10 02:30:00'read inAmerica/New_York, and the user has no other spelling for what they meant.SET TimeZone='America/New_York'; SELECT '2024-03-10 02:30:00'::timestamptz;andSELECT timestamptz '2024-03-10 02:30:00 America/New_York';both return2024-03-10 07:30:00+00. This was measured, not assumed.A different rule for site 3 would put the "same query, different spelling, different outcome" split back inside a single function. That split is what this PR exists to remove.
Are these changes tested?
Yes. Every expected instant in the new tests came from a real PostgreSQL 17.11 (
postgres:17). None were derived by hand. All three call sites are covered for both an ambiguous and a nonexistent reading:America/New_YorkandAmerica/Los_Angeles— a whole-hour DST step.Australia/Lord_Howe— a thirty minute step, so a gap shifts02:15to02:45, not03:15. This rules out any implementation that assumes a one-hour gap.Pacific/Chatham—+12:45/+13:45, an offset that is not a whole number of hours on either side.Australia/Sydney— southern hemisphere, so the gap falls in October and the repeated hour in April. This catches implementations that reach foroffset_from_utc_datetimeas a shortcut, which returns the post-transition offset and is wrong here.America/Sao_Paulo2018-11-04— local midnight does not exist, because Brazil started DST at 00:00. Result:2018-11-04T03:00:00Z.America/Havana2024-11-03— local midnight happens twice, because Cuba ends DST at 00:00. Result: the later instant,2024-11-03T05:00:00Z.+05:30), which has no transitions and must be unaffected.CastOptions { safe: true }againstsafe: falseat the array level. The former produced a silent NULL and the latter an error. Both now produce the resolved instant, and genuinely unparseable input still nulls or errors as before.StringArray,LargeStringArrayandStringViewArray. This confirms the offset resolves per row, not once for the array.Counterfactually validated. Revert the three call sites and keep the tests, and 9 of the new tests fail. The
safe: truecase fails withleft: 0, which is the silent-NULL mode.arrow-castalready gainedarrow-array/chrono-tzas a dev-dependency in #11038, so no manifest change is needed here.Field research: PostgreSQL 17 and DuckDB
The resolution policy is the one arbitrary decision in this stack, so it needs more than one reference. Both engines were measured directly: PostgreSQL 17.11 in
postgres:17, and the DuckDB 1.5.2 CLI with the ICU extension. All times below are UTC.America/New_York2024-11-03 01:30— ambiguous2024-11-03 06:30:002024-11-03 06:30:002024-11-03 06:30:00America/Havana2024-11-03 00:00— ambiguous local midnight2024-11-03 05:00:002024-11-03 05:00:002024-11-03 05:00:00America/New_York2024-03-10 02:30— gap2024-03-10 07:30:002024-03-10 07:30:002024-03-10 07:30:00America/Sao_Paulo2018-11-04 00:00— local midnight does not exist2018-11-04 03:00:002018-11-04 03:00:002018-11-04 03:00:00Australia/Sydney2024-10-06 02:30— southern hemisphere gap2024-10-05 16:30:002024-10-05 16:30:002024-10-05 16:30:00Australia/Lord_Howe2024-10-06 02:15— 30 minute DST step2024-10-05 15:45:002024-10-05 15:45:002024-10-05 15:45:00Pacific/Chatham2024-09-29 03:00— +12:45 / +13:452024-09-28 14:15:002024-09-28 14:15:002024-09-28 14:15:00The two ambiguous rows carry the argument. A gap has only one sensible answer, so it discriminates nothing. An ambiguous reading has two real answers, and the choice between them is the policy.
2024-11-03 01:30in New York is either05:30Z(EDT) or06:30Z(EST). Both engines give06:30Z. Havana's ambiguous midnight is either04:00Z(CDT) or05:00Z(CST). Both engines give05:00Z. In both cases the answer is the later instant, which is what this PR does.The case neither engine can arbitrate
A fixed-offset string such as
'+05:30'has no agreed reading, so it is recorded here rather than hidden. Measured:SET TimeZone='+05:30'then'2024-01-01 12:00:00'::timestamptz17:30Z'2024-01-01 12:00:00'::timestamp AT TIME ZONE '+05:30'17:30Ztimestamptz '2024-01-01 12:00:00 +05:30'06:30ZPostgreSQL agrees with arrow-rs when the offset sits inside the literal. It disagrees when the offset acts as a zone name. DuckDB 1.5.2 rejects the zone-name spelling outright:
Not implemented Error: Unknown TimeZone '+05:30'.So neither engine settles it. This PR does not change that behaviour. It is tracked downstream in apache/datafusion#25170.
Are there any user-facing changes?
Yes, and the change is intentional. A string that previously failed to parse, or silently became NULL, now parses to the instant PostgreSQL and DuckDB produce. There is no API change.
resolve_local_offsetstays crate-private.Together with #11038 this closes DataFusion #25084
Neither PR closes it alone. #11038 covers the cast kernel. This PR covers the parser. A user hits both through the same SQL, so both must land.
One existing test changes expectation
arrow/tests/timezone.rsasserted the old error for twoAmerica/Los_Angelescases. They move fromtest_parse_timezone_invalidtotest_parse_timezone:2023-03-12 02:05:06 America/Los_Angeleserror computing timezone offset2023-03-12T10:05:06+00:002023-11-05 01:30:06 America/Los_Angeleserror computing timezone offset2023-11-05T09:30:06+00:00Downstream
DataFusion has one matching expectation, at
datafusion/sqllogictest/test_files/datetime/timestamps.slt:2360-2366. It asserts thatSELECT TIMESTAMPTZ '2023-03-12 02:00:00 America/Los_Angeles'errors, and its own comment already notes# postgresql: accepts. On the next arrow upgrade it becomes aquery Pthat returns2023-03-12T10:00:00Z, which is what PostgreSQL returns. This PR includes no DataFusion change.Follow-up:
arrow-arrayresolves ambiguity the opposite wayThis PR creates one shared helper for arrow-cast, but one divergence remains in the tree. It is deliberately untouched here:
arrow-cast::local_time::resolve_local_offsetarrow-array::types::from_naive_datetime(types.rs:347)Ambiguous(dt1, _))NoneMeasured in
America/New_Yorkfor2024-11-03 01:30:00:from_naive_datetimegives05:30Z, and this stack gives06:30Z.This matters downstream. DataFusion calls the
arrow-arrayform directly with aSome(tz)indatafusion/functions/src/datetime/date_part.rs(date_to_scalar, four call sites). Where the local midnight it builds is ambiguous, the earlier instant becomes an upper bound, so valid rows can drop out. The behaviour predates this stack.Changing
from_naive_datetimeaffects every caller ofarrow-array, so it deserves its own review rather than a ride along with a parser fix.🤖 Generated with Claude Code