Skip to content

Fix toUTCTimestamp next to a daylight saving time change - #128744

Merged
yariks5s merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-to-utc-timestamp-dst
Nov 13, 2026
Merged

yariks5s merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-to-utc-timestamp-dst

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128266

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed toUTCTimestamp (to_utc_timestamp) returning a time one hour off for local times in the hours around a daylight saving time change, for both DateTime and DateTime64. It now converts a local time as toDateTime(s, time_zone) does, also a local time that happens twice or does not exist. Closes #128266.

Description

On 26.8.21.12 and 26.10.2.103, toUTCTimestamp(toDateTime('2026-10-25 01:00:00'), 'Europe/Berlin') returns 2026-10-25 00:00:00 instead of 2026-10-24 23:00:00 (session time zone UTC). The window is about 3 hours a year in Berlin, 9 in New York and 21 in Sydney.

toUTCTimestamp reads its argument as a wall clock in time_zone, but took the offset with DateLUTImpl::timezoneOffset, the offset at a UTC instant. It looked at the local time read as UTC, which is |offset| away from the real instant, so next to a change it applied the offset from the other side. parseDateTime had the same bug (#126704).

The fix adds DateLUTImpl::timezoneOffsetAtLocalTime, the offset at a local time resolved as makeDateTime resolves it, and uses it for toUTCTimestamp only; fromUTCTimestamp gets a UTC instant and is unchanged. Behaviour change by design: Berlin 2026-10-25 02:30 (happens twice) was 01:30 UTC and is now 00:30, as toDateTime and Spark; New York 2026-03-08 02:30 (does not exist) was 07:30 UTC and is now 06:30, as toDateTime and parseDateTime (Spark moves a skipped time forward by the gap, which gives 07:30).

03891_utc_timestamp_datetime64_overflow asserted the old value at one New York boundary; it is corrected and gains a line that checks the floor of negative fractions.

Validation: the new test fails on master and passes with the fix. Over all 598 time zones (every 30 minutes, DateTime 1970-2106, DateTime64 1900-1970, plus 20 zones over 1900-2299) the result equals makeDateTime for all 2.3 billion local times (master: 688917 mismatches). Cost on the shapes of tests/performance/utc_timestamp_transform.xml (10M rows, one thread, four runs on two cores): toUTCTimestamp DateTime -9% to -15%, DateTime64 -1% to -9%; fromUTCTimestamp DateTime -1% to +4%, DateTime64 +3% to +11% (its lookup is unchanged; compiling each direction separately was slower still).


Workflow [PR]
Sync PR [sync-upstream/pr/128744]

Version info

  • Merged into: 26.11.1.2207-master (included in 26.11 and later)
  • Backported to: 26.10.11.13, 26.9.37.7, 26.8.45.6

groeneai and others added 3 commits November 2, 2026 14:23
`toUTCTimestamp` reads its argument as a wall clock in the given time zone,
but took the offset with `DateLUTImpl::timezoneOffset`, which is the offset at
a UTC instant. The instant it looked at was the local time read as UTC, which
is |offset| away from the real one, so in the hours around each offset change
the offset from the other side of the change was applied (one hour off in
Europe/Berlin and America/New_York, both for DateTime and DateTime64).
`parseDateTime` had the same bug, fixed in ClickHouse#126704.

Add `DateLUTImpl::timezoneOffsetAtLocalTime`, the offset at a local time,
resolved as `makeDateTime` does (a repeated local time is its first
occurrence, a skipped one is read with the offset after the change), and use
it in the `toUTCTimestamp` direction. The result is now the same as
`toDateTime(s, time_zone)`. `fromUTCTimestamp` converts from a UTC instant and
keeps using `timezoneOffset`.

`03891_utc_timestamp_datetime64_overflow` asserted the old value for
New York local 1969-10-26 05:59:59.999 (EST, so 10:59:59.999 UTC); the floor
of negative fractions is now checked at the 01:59:59.999 boundary instead.

Closes ClickHouse#128266

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t have one

With `t == day * 86400 + time_of_day`, the previous return value
`t - (date + (time_of_day >= time_at ? time_of_day - amount : time_of_day))`
equals `day * 86400 - date + (time_of_day >= time_at ? amount : 0)`, and adding
`amount` when it is 0 is a no-op, so guarding with `amount != 0 &&` changes
nothing. This is the shape of `timezoneOffset`, and it keeps `toUTCTimestamp`
from decoding the offset-change fields on every row.

Also test local times outside the years 1900-2299 (every 15 minutes of 2300 in
Europe/Berlin and America/New_York, and of 1883 in America/New_York), where the
conversion goes through `timezoneOffsetAtLocalTimeOutOfRange`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment in timezoneOffsetAtLocalTimeOutOfRange that restated the code below it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 3 findings) plus my own review (3 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ timezoneOffsetAtLocalTime made toUTCTimestamp slower than the lookup it replaces (DateLUTImpl.h) AGREE, fixed @ 19bc80c the offset-change fields are applied only when the day has a change, as in timezoneOffset; toUTCTimestamp is now faster than master
2 ❌ outside 1900-2299 a repeated local time resolves to its second occurrence DISAGREE the rule is "as toDateTime does", and there toDateTime64 itself gives the second occurrence (2300-11-04 01:30 New York: both 06:30 UTC); the changelog entry does not promise "first occurrence"; a test of that range is added
3 ⚠️ fromUTCTimestamp DateTime64 is slower although its logic is unchanged (UTCTimestampTransform.cpp) DISAGREE a build that compiles each direction separately (so its fromUTCTimestamp loop is master's) was 8-10% slower than master, slower than this PR in the same runs, so the direction dispatch is not the cause; the same two binaries measured +3% to +11% across runs; the range is in the description

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20261102-191000

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET session_timezone = 'UTC'; SELECT toUTCTimestamp(toDateTime('2026-10-25 01:00:00'), 'Europe/Berlin') returns 2026-10-25 00:00:00 on every run of master, 26.8.21.12 and 26.10.2.103 (correct: 2026-10-24 23:00:00); same for the DateTime64 and New York cases of the issue.
b Root cause explained? Yes. toUTCTimestamp reads its argument as a local wall clock but took the offset with DateLUTImpl::timezoneOffset, which is the offset at a UTC instant. It looked at the local time read as UTC, which is |offset| away from the real instant, so next to an offset change it applied the offset from the other side of the change.
c Fix matches root cause? Yes. The offset lookup itself is replaced in the toUTCTimestamp direction by DateLUTImpl::timezoneOffsetAtLocalTime, which resolves a local time with the same LUT fields and rule as makeDateTime, so the result equals toDateTime(s, time_zone) by construction. No guard, no special case.
d Test intent preserved / new tests added? Yes. New 05483_to_utc_timestamp_daylight_saving_time (the issue's cases, half-hour grids around the Berlin and New York changes, DateTime64 before 1970 with a fraction, a 2026 count for 6 zones). 03891 asserted the old value at one boundary; it is corrected and gains a line that checks the floor of negative fractions. Five source mutations (each call site back to the old lookup, no floor, >= to > in the helper, the out-of-range branch sent to the UTC-instant lookup) each turn a test red.
e Both directions demonstrated? Yes. With the test runner and randomized settings: master FAILS 05483 and 03891 (diff is exactly the inverse), the fix passes both; 02812_from_to_utc_timestamp and 01252_weird_time_zone pass on both with unchanged references. 50/50 runs of 05483, 20/20 of 03891 and 02812.
f Fix is general across code paths? Yes. Both loops (DateTime, DateTime64) and the to_utc_timestamp alias. fromUTCTimestamp receives a UTC instant, so timezoneOffset is the right lookup there; it is unchanged and the round trip is in the test. The other timezoneOffset callers pass UTC instants. parseDateTime was fixed the same way in #126704. Local days outside 1900-2299 go through makeDateTimeOutOfRange, as makeDateTime does.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. DateTime and DateTime64 (scale 1 and 3, negative values with a fraction), constant and non-constant arguments, a non-UTC session time zone. Every one of the 598 time zones, every 30 minutes (among them Australia/Lord_Howe with its 30-minute shift and Pacific/Chatham): 2.3 billion local times, 0 differences from makeDateTime (688917 on master). Outside 1900-2299, where another code path runs: lines in the test plus 70 million local times with 0 differences from toDateTime64(s, 3, time_zone) (26530 on master). Nullable/LowCardinality are unwrapped by the default implementations. Extreme values (03891 lines 1-5) and DateTime saturation are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes, as a bug fix: no setting, no format change. Only local times in the hours around an offset change convert differently, now as toDateTime does. This is stated in the PR description and the function documentation.
i Invariants and contracts preserved? Yes. The new helper returns a real offset of the zone (less than one day), so offset * scale_multiplier still fits Int64; the floor split of negative DateTime64 values, the overflow clamp and the DateTime saturation are unchanged. The helper cannot overflow for any Int64 input, and out-of-range input is clamped to the representable calendar before the conversion.

Session id: cron:clickhouse-impl-slot-5:20261102-140100

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov, could you review this and add the can be tested label so CI runs? toUTCTimestamp took the offset at its wall clock read as a UTC instant (DateLUTImpl::timezoneOffset), so it was one hour off next to a daylight saving time change; the new DateLUTImpl::timezoneOffsetAtLocalTime resolves the local time as makeDateTime does with one LUT access, and the per-row cost is in the description.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [47a30c4]

Summary: ✅


AI Review

Summary

The change fixes toUTCTimestamp and to_utc_timestamp near daylight saving time transitions by resolving local times consistently with toDateTime, including fractional DateTime64 values. Review of head 47a30c4f771380448cbe8f7a11c7b3afe5da898f, the full diff, and all prior discussions found no actionable issues. The new DST regression test and existing overflow and UTC conversion tests pass in the current head's Fast test report.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 2, 2026
@yariks5s yariks5s self-assigned this Nov 2, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Nov 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 47a30c4f7 with master 7a987ba24 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.67, programs/clickhouse-keeper ×0.69 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.7 s 14.7 s +10.8 s (+281%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.5 s +5.2 s (+230%)
Compile time of recompiled translation units

2918 translation units recompiled, 17294 s compile time in total, 2918 of them have a recent master baseline.

Job report

@antonio2368
antonio2368 requested a review from yariks5s November 11, 2026 11:19

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai please fix these nits

Comment thread src/Common/DateLUTImpl.h Resolved
Comment thread src/Common/DateLUTImpl.cpp Resolved
Use `%` for the time of day, and look the out-of-range local time up
with cctz directly instead of decomposing it for makeDateTimeOutOfRange.
Both are behaviour-preserving: `t - (t / 86400) * 86400 == t % 86400`,
and the clamped civil time is already within makeDateTimeOutOfRange's
year range, so its year clamp was a no-op here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@yariks5s
yariks5s added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit e465558 Nov 13, 2026
203 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@antonio2368 antonio2368 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 23, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 23, 2026
Backport #128744 to 26.9: Fix `toUTCTimestamp` next to a daylight saving time change
clickhouse-gh Bot added a commit that referenced this pull request Nov 23, 2026
Backport #128744 to 26.8: Fix `toUTCTimestamp` next to a daylight saving time change
clickhouse-gh Bot added a commit that referenced this pull request Nov 23, 2026
Backport #128744 to 26.10: Fix `toUTCTimestamp` next to a daylight saving time change
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

toUTCTimestamp is 1 h off near DST transitions

5 participants