Skip to content

Fix timezoneOffset losing the whole-day component of the UTC offset - #115332

Merged
yariks5s merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-timezone-offset-whole-day-115281
Aug 21, 2026
Merged

yariks5s merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-timezone-offset-whole-day-115281

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 timezoneOffset (alias timeZoneOffset) returning an offset wrong by exactly one day for time zones whose UTC offset differs from their 1970-01-01 offset by a whole day, such as Pacific/Kiritimati and Pacific/Apia after they crossed the international date line, and for most zones before 1970. This also fixes parseDateTime, parseDateTimeOrNull, parseDateTime64, parseDateTimeInJodaSyntax, EXTRACT(TIMEZONE_HOUR / TIMEZONE_MINUTE ...), formatDateTime's %z, toUTCTimestamp and fromUTCTimestamp, which consume that offset. Closes #115281.

Description

Reported by @ PedroTadim in #115281 (comment).

timezoneOffset did not read the offset, it reconstructed it as (lut[index].date - lut[epoch].date) % 86400 plus offset_at_start_of_epoch. That difference is days * 86400 - (offset_now - offset_epoch), so the modulo keeps only the sub-day part of the change since the epoch and discards any whole-day part; the date-line zones stayed pinned at their pre-jump offset, correct before the jump and wrong after. Separately, % takes the sign of the dividend, so on a pre-epoch day the remainder is negative, the res > 43200 wrap never fired, and the result came out near +86400 instead of a small negative offset.

The fix computes the offset directly as day_number * 86400 - lut[index].date: local midnight is that many seconds of local time from the epoch, and date is the UTC instant of the same midnight. Exact for either sign, no modulo, no wrap branches. The same-day amount_of_offset_change correction is unchanged.

All 12 in-tree call sites checked. Seven were wrong and are repaired by this one change: the function itself, the parseDateTime family (including a zone named in the format string), EXTRACT(TIMEZONE_HOUR / TIMEZONE_MINUTE ...), formatDateTime's %z, and toUTCTimestamp / fromUTCTimestamp. The other five reduce the offset modulo a day (CAST ... AS Time / Time64, localtime), so an exact one-day error already cancelled; the test pins those as controls.

Over all 597 rows of system.time_zones at 14 instants from 1900 to 2300, against Python zoneinfo as an independent oracle: 500 wrong samples across 307 zones before, 18 after, all 18 being tzdata differences between the bundled 2025a and the system 2026a. All 488 changed samples differ by exactly one day, so nothing sub-day moved.

Validation

Both directions through tests/clickhouse-test: on the base master debug snapshot (build id 09e3d57a4bbe30cd) 01252_weird_time_zone fails with a 39-line reference diff; with the fix (build id 485b33ed0bf6e99c) it passes, including 50 of 50 randomized runs.

unit_tests_dbms --gtest_filter='*DateLUT*:*DateTime*:*Date*' passes 7906 tests, so no calendar component moved. The timezone stateless suite passes 42 of 42. Six failures in the wider datetime and extract suites are pre-existing gaps in my local environment (no remote() cluster config, no parquet/iceberg fixtures, no test.hits) and reproduce identically on the base binary.

New arms: the seven reported zones after their jump; the same zones before it and Pacific/Chatham (+13:45) as controls that must not move; the pre-1970 class; agreement between parseDateTime* and toDateTime; the other offset consumers; the modulo-a-day consumers as regression controls; DST transition days; agreement between the in-range and out-of-range paths; and a sweep over system.time_zones with no zone list hardcoded, comparing the reported offset to rendering the instant as local text and reading it back as UTC.


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

Version info

  • Merged into: 26.8.1.1888 (included in 26.8 and later)

timezoneOffset did not read the offset, it reconstructed it from the
distance between two start-of-day timestamps:

    res = (lut[index].date - lut[epoch].date) % 86400;
    res = res > 43200 ? (86400 - res) : (0 - res);
    return res + offset_at_start_of_epoch;

lut[i].date is the UTC instant of local midnight of day i, so the
difference of two such instants is days * 86400 - (offset_now -
offset_epoch). Taking it modulo 86400 keeps only the sub-day part of the
offset change since the epoch and discards any whole-day part, which the
added offset_at_start_of_epoch cannot restore. The zones that
permanently shifted their offset by 24 hours when they crossed the
international date line therefore stayed pinned at their pre-jump
offset, which is why each of them reported correctly before its jump and
wrongly after it.

The wrap on the second line also handles only one sign. In C++ the
remainder takes the sign of the dividend, so for a day before the epoch
res is negative, the res > 43200 test can never fire, and 0 - res yields
a value near +86400 rather than a small negative offset. That is a
second, independent defect affecting most zones at pre-1970 instants,
not just the seven date-line ones from the report.

Compute the offset directly instead. The UTC offset at local midnight of
a day is day_number * 86400 - lut[index].date, since local midnight is
that many seconds of local time from the epoch while date is the UTC
instant of the same midnight. This is exact for either sign and any
magnitude, needs no modulo and no wrap branches. The existing correction
for an offset change later in the same day is kept as it was, and
offset_at_start_of_epoch is no longer added here because the new base
term is absolute rather than epoch-relative. The member itself stays, it
still has other users.

Measured over all 597 rows of system.time_zones at 14 instants spanning
1900 to 2300, against Python zoneinfo as an independent oracle, wrong
samples drop from 500 across 307 zones to 18, and each of those 18 is a
tzdata version difference between the bundled 2025a and the system
2026a. Every one of the 488 samples this changes differs by exactly one
day, so nothing sub-day moved and no previously correct sample
regressed.

The same offset feeds parseDateTime and its OrNull, OrZero, 64 and Joda
variants, a zone named inside a Joda format string,
EXTRACT(TIMEZONE_HOUR / TIMEZONE_MINUTE ...), the %z specifier of
formatDateTime, and toUTCTimestamp / fromUTCTimestamp, all of which were
wrong by a day on the affected zones and are fixed here. The remaining
consumers reduce the offset modulo a day, so an exact one-day error
already cancelled for them; they were correct before and remain so, and
the test pins them as controls.

Reported by PedroTadim.

Closes ClickHouse#115281.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding fixed, 3 declined with evidence)

Before publishing I reviewed the resulting code cold, then ran an independent second-model review of the full diff, then adjudicated both sets against the recorded validation. No source file changed during review.

# Finding Verdict
❌ 1 The description miscounted the affected call sites as "six wrong / six modulo-a-day". AGREED, fixed
⚠️ 2 The toUTCTimestamp / fromUTCTimestamp arms leave the input DateTime untyped, so the instant depends on the CI-randomized session_timezone. Declined
⚠️ 3 The whole-zone sweep samples only post-1970 instants, and no arm sits exactly on a date-line jump boundary. Declined
💡 4 Make Closes: an active standalone line instead of leaving it in the linked-issues comment block. Declined

1 (fixed). The real split of the 12 call sites is seven wrong and five that reduce the offset modulo a day. The recorded per-site A/B probe agreed with that; only the description prose was wrong. Corrected, and "consumers" became "call sites" so the 12 has one unambiguous unit (seven sites, but six user-facing functions).

2 (declined). The dependency is real but the reference is invariant across the whole randomization list by construction, not by luck: every zone that setting can take here has a fixed offset across 2025-06-14..16, so the 14-hour shift lands on the same wall-clock text in all of them. The 50-run randomized pass confirms it.

3 (declined). The four pre-1970 arms already fail on the base binary, so the class is covered and only its breadth is narrower. Extending the sweep below 1970 would pull in the tzdata 2025a-vs-2026a LMT disagreement that accounts for all 18 residual mismatches, making the arm fail on a tzdata bump. The jump-boundary degeneracy lives in the day-lookup helper, is untouched here, and the pre-existing arms in this file already sample those seven zones a million instants each.

4 (declined). The rendered body already carries a live Closes #115281, which is a keyword GitHub's auto-close parser accepts, so the behaviour the finding asks for is already in place. In the current upstream template the prescribed Closes: line is itself inside the linked-issues comment block, so leaving the populated line there follows the template rather than departing from it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT timeZoneOffset(toDateTime('2025-06-15 12:00:00','Pacific/Kiritimati')), timeZoneOffset(toDateTime64(-1900000000,0,'Africa/Abidjan')) returns -36000 / 85432 on every run before the fix and 50400 / -968 after. Fixed zones, fixed instants, no dependence on randomization or timing.
b Root cause explained? Yes. timezoneOffset reconstructed the offset as (lut[index].date - lut[epoch].date) % 86400 + offset_at_start_of_epoch. That difference equals days * 86400 - (offset_now - offset_epoch), so the modulo keeps only the sub-day part of the change since the epoch and discards any whole-day part, leaving date-line zones pinned at their pre-jump offset. Separately % takes the sign of the dividend, so on a pre-epoch day the remainder is negative, the res > 43200 wrap never fired, and the result came out near +86400.
c Fix matches root cause? Yes. The offset is now computed directly at its origin in DateLUTImpl::timezoneOffset as day_number * 86400 - lut[index].date, which is exact for either sign. Not a guard at a consumer and not a widened modulo. Adding only the missing negative wrap was rejected: it leaves the reported date-line zones broken.
d Test intent preserved / new tests added? Yes. The seven pre-existing arms of 01252_weird_time_zone produce byte-identical output on both binaries and the reference change is purely additive (+38 lines). Ten new arm groups were added, including negative controls that must not move.
e Both directions demonstrated? Yes, through tests/clickhouse-test with the build id of each server asserted against its binary. Base (master debug snapshot, build id 09e3d57a4bbe30cd): FAILS with a 39-line reference diff. Fixed (build id 485b33ed0bf6e99c): passes, and passes 50 of 50 randomized runs.
f Fix is general across code paths? Yes. All 12 in-tree call sites of the offset were enumerated and probed individually. Seven were wrong and all seven are repaired by this single source change: the function itself, parseDateTime and its OrNull / OrZero / 64 / Joda variants (including a zone named inside the format string), EXTRACT(TIMEZONE_HOUR / TIMEZONE_MINUTE ...), formatDateTime's %z, and toUTCTimestamp / fromUTCTimestamp. The other five reduce the offset modulo a day, so an exact one-day error already cancelled there; they are correct before and after and the test pins them as controls.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Checked all 597 rows of system.time_zones at 14 instants from 1900 to 2300 against Python zoneinfo as an independent oracle: 500 wrong samples across 307 zones before, 18 after, all 18 being a tzdata version difference between the bundled 2025a and the system 2026a. Positive and negative offsets, whole-day and sub-day, DST transition days, the epoch and epoch minus one second, and the LUT boundary instants all verified with no undefined behaviour. timezoneOffset takes a scalar, so Nullable / LowCardinality / Const / Array are handled generically by FunctionDateOrDateTimeToSomething and have no separate path.
h Backward compatible? (maintainer-approved exception only) The returned value changes for the affected zones, which is the bug fix itself, so the category is Bug Fix. No setting default changes, no serialization or format change, and no signature change, so no SettingsChangesHistory.cpp entry is required.
i Invariants and contracts preserved? Yes. The postcondition "returns the true UTC offset at t" now holds where it previously did not. The out-of-range escape still runs first, so lut[index] is always in range, and the in-range and out-of-range paths now agree (an arm asserts this). Overflow is bounded: (index - daynum_offset_epoch) * 86400 is computed in Int64 from a value below DATE_LUT_SIZE, so about 1.3e10, far from the type limits, and no sanitizer suppression was added. offset_at_start_of_epoch is retained for its three other users. The method is const and reads a preallocated table, so no locking or lifetime contract is touched.

Session id: cron:clickhouse-impl-slot-5:20260818-151000

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c35cc8b]

Summary: ✅


AI Review

Summary

This PR fixes DateLUTImpl::timezoneOffset by deriving the UTC offset directly from the local-day start instead of reconstructing it modulo one day, which correctly preserves whole-day date-line shifts and pre-epoch negative offsets. I checked the changed hot path against the out-of-range escape path and the unchanged consumers that rely on timezoneOffset, and the added stateless coverage matches the bug being fixed; with the current code and all-green CI, I did not find a remaining review issue in this diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 18, 2026
@yariks5s yariks5s self-assigned this Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @alexey-milovidov, could you review this? timezoneOffset reconstructed the offset as (lut[index].date - lut[epoch].date) % 86400 plus the epoch offset, so the modulo discarded any whole-day change since 1970 (the date-line zones stayed pinned at their pre-jump offset) and the res > 43200 wrap mishandled the negative remainder on pre-epoch days; it now computes day_number * 86400 - lut[index].date directly, which repairs parseDateTime, %z, EXTRACT(TIMEZONE_HOUR) and toUTCTimestamp at the source.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c35cc8b90 with master 84688bbff (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
Binary Master PR Δ
programs/clickhouse-stripped 701.97 MiB 698.94 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +1439.1 s (+10%) in total before that adjustment.

Job report

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c35cc8b

CI is fully finished on this head: 178 check-runs, none queued or in progress, Config Workflow and Finish Workflow both green.

No failures, so there is nothing to own.

One note on the record so it is not misread later: CIDB holds a single Config Workflow / Pre Hooks / FAIL row at 18:03:07 for this commit. That attempt was superseded by a re-run at 18:07:20 in which Pre Hooks and every subsequent step report OK, and the check-run itself concluded success at 18:08:09. The stale row is bookkeeping from the first attempt, not a live failure.

The bugfix validation actually ran and passed rather than being skipped: Bugfix validation (functional tests, amd64) and (aarch64) are both green, so the regression test does fail on master HEAD on both architectures. (unit tests) is green; the two integration tests legs are correctly skipped since the diff adds no integration test.

Session id: cron:our-pr-ci-monitor:20260819-020000

@yariks5s
yariks5s enabled auto-merge August 20, 2026 17:41
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 35 queries analysed

This PR is a correctness fix to timeZoneOffset in DateLUTImpl, adjusting how the whole-day UTC offset is computed for international-date-line and pre-epoch zones. The two flagged queries are TPC-H Q7 (+20.9%) and Q17 (+62.5%), both of which run in UTC where the changed offset path returns 0 unchanged, so neither can be affected by this diff. The deterministic gates already marked both as unstable baselines and left them as not_sure; the underlying measurements were noisy (especially Q17), so these deltas are baseline instability rather than a real regression. No action is needed on the perf numbers.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 81 +20.9% <0.0001 This PR only fixes timeZoneOffset for whole-day offset zones (date-line/pre-epoch); TPC-H runs in UTC where that path returns 0 unchanged. The +20.9% is baseline instability, not a PR effect.
⚠️ 17 not_sure 64 104 +62.5% <0.0001 Same story: the timeZoneOffset fix cannot touch a UTC query, and both runs are very noisy, so the +62.5% is run-to-run variance on an unstable baseline, not this change.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 741f545c-4b15-4d95-b5f2-c0aab9bd27b4
  • MIRAI run: c6ed2cd1-98f5-46d2-9fa3-d0bf1e3e483e
  • PR check IDs:
    • clickbench_6444_1787334518
    • clickbench_6455_1787334519
    • clickbench_6462_1787334518
    • tpch_adapted_1_official_6474_1787334518
    • tpch_adapted_1_official_6491_1787334518
    • tpch_adapted_1_official_6516_1787334519

@yariks5s
yariks5s added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 8290f87 Aug 21, 2026
363 of 365 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 25.8, 26.3, 26.5, 26.6, 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

Copy link
Copy Markdown
Collaborator Author

@yariks5s you merged this, so asking you: could you apply v25.8-must-backport?

I verified the request rather than relaying it. All five branches named are active release branches, the fix is absent from each, and the bug reproduces on each published binary (builds.clickhouse.com/<X.Y>/amd64/clickhouse):

branch version timeZoneOffset(toDateTime('2025-06-15 12:00:00', 'Pacific/Kiritimati')) 597-zone sweep mismatches
master 26.8.1.1921 50400 (correct) 0
26.7 26.7.6.8 -36000 19
26.6 26.6.4.13 -36000 19
26.5 26.5.8.14 -36000 19
26.3 26.3.22.4 -36000 19
25.8 25.8.33.4 -36000 19

Two arms that are already correct before the fix stay identical on every branch (Pacific/Apia at 2010-01-01, pre-jump, -39600; Pacific/Chatham, 45900), so the probe is discriminating and not simply red everywhere. The error is exactly -86400 on the affected arm.

One label is enough: select_backport_branches with the real caller arguments expands v25.8-must-backport to exactly ['25.8', '26.3', '26.5', '26.6', '26.7'], since a version-specific label marks the oldest release and picks up every newer active branch.

The port applies cleanly. git merge-tree --write-tree --merge-base=91e2361457881453 origin/<B> c35cc8b90ce3 returns 0 on all five and yields the same 3 files, +97/-10, as on master. Both test files are blob-identical to the PR base on every branch, and the resolved timezoneOffset body carries the new formula on each, so nothing lands as a half no-op.

One caveat before the robot runs: the source fix ports correctly everywhere, but the test does not pass unmodified on four of the five.

Test portability per branch, measured
branch test as-is why
26.7 passes only the arms the fix changes differ pre-port
26.6 1 line off use_legacy_to_time defaults to 1 there, so the toTime control arm renders 1970-01-02 12:00:00
26.5, 26.3 aborts EXTRACT(TIMEZONE_HOUR ...) is Code: 62 (parser support landed in da62a32, present from 26.6)
25.8 aborts same Code: 62, plus enable_time_time64_type defaults to 0 so CAST(... AS Time) is Code: 44, and that arm reads 22:00:00 there once enabled

The 26.6 difference is setting-driven, not fix-driven: master with the fix and SET use_legacy_to_time=1 prints the same 1970-01-02 12:00:00.

Adaptations, if you want the test on the older branches: replace the EXTRACT line with intDiv(timeZoneOffset(...), 3600) (-10 pre-fix, 14 after), use the legacy toTime cell on 26.6 and earlier, and set enable_time_time64_type=1 with a 22:00:00 cell on 25.8. Happy to supply the exact hunks if that is useful.

If you would rather keep it narrow, v26.6-must-backport covers ['26.6', '26.7'] and v26.7-must-backport covers 26.7 alone.

Algunenano added a commit that referenced this pull request Nov 11, 2026
…d file, test from 1900

On this branch `DateLUT` loads zones that are not embedded (`libc:` names, the host database), so the ORC reader and writer threw `LOGICAL_ERROR` for them. `DateTime64` starts at 1900 here, so the test uses values between 1900 and the first transition, and checks the day shift fixed by #115332.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…d file, test from 1900

On this branch `DateLUT` loads zones that are not embedded (`libc:` names, the host database), so the ORC reader and writer threw `LOGICAL_ERROR` for them. `DateTime64` starts at 1900 here, so the test uses values between 1900 and the first transition, and checks the day shift fixed by #115332.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

timeZoneOffset and parseDateTime are wrong by 24 hours for timezones that crossed the international date line

4 participants