Skip to content

Fix UBSan signed-integer overflow converting extreme DateTime64 to Time/Time64 - #110451

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-totime-datetime64-int64min-overflow
Aug 1, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-totime-datetime64-int64min-overflow

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 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):

Fix a signed-integer overflow (UBSan) when converting an extreme DateTime64 value (e.g. INT64_MIN) to Time/Time64 in a timezone with a negative offset.

Description

toTime/toTime64 computed the local seconds-of-day as (dt64 + offset) % 86400. For an extreme input in a timezone with a negative offset the addition overflows Int64 before the modulo (UBSan: signed integer overflow: -9223372036854775808 + -18000).

Fix: reduce the timestamp modulo 86400 before adding the offset. This is mathematically identical ((a + b) mod m == ((a mod m) + b) mod m, negatives normalized with += 86400), but the intermediate sum is now bounded by 86400 + max timezone offset, so it cannot overflow. Applied to both Int64 sites (DateTime64 -> Time at FunctionsConversion.h:273 and DateTime64 -> Time64); the UInt32 sites cannot overflow Int64.

Repro (UBSan build):

SELECT toTime(reinterpret(CAST(-9223372036854775808 AS Int64), 'DateTime64(0, ''America/New_York'')'));

Regression test: 04512_totime_datetime64_extreme_overflow. No related open issue (found by a private fuzzer; 0 public CIDB hits for this site in 30d).

Version info

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

…me/Time64

toTime/toTime64 computed the local seconds-of-day as (dt64 + offset) % 86400.
For an extreme input (dt64 = INT64_MIN) in a timezone with a negative offset the
addition overflows Int64 before the modulo, tripping UBSan.

Reduce the timestamp modulo 86400 before adding the offset. Mathematically
identical since (a + b) mod m == ((a mod m) + b) mod m and the negative case is
normalized with += 86400, but the intermediate sum is now bounded by
86400 + max timezone offset, so it cannot overflow.

Applied to both Int64 sites (DateTime64 -> Time at FunctionsConversion.h:273 and
DateTime64 -> Time64). The UInt32 sites cannot overflow Int64 and are left as is.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toTime(reinterpret(CAST(-9223372036854775808 AS Int64), 'DateTime64(0, ''America/New_York'')')) fires FunctionsConversion.h:273:37: runtime error: signed integer overflow on every UBSan run.
b Root cause explained? (dt64 + offset) % 86400 adds a negative timezone offset to dt64 = INT64_MIN before the modulo, overflowing Int64.
c Fix matches root cause? Yes. Reduce mod 86400 before adding the offset, bounding the intermediate sum to 86400 + max tz offset.
d Test intent preserved / new test added? New test 04512_totime_datetime64_extreme_overflow (extreme bounds + ordinary-value sanity).
e Demonstrated in both directions? Pre-fix binary: UBSan runtime error; post-fix (same query): 03:29:52.
f Fix general, not a narrow patch? Applied to both Int64 sites (DateTime64->Time at :273 and DateTime64->Time64). UInt32 sites cannot overflow Int64, left as-is.
g Generalizes across inputs? Verified at INT64_MIN and INT64_MAX, negative-offset (America/New_York) and positive-offset (Europe/Moscow) timezones; ordinary values unchanged.
h Backward compatible? Yes. Output for all representable inputs is identical (algebraic equivalence); only the previously-UB extreme path changes from UB to a defined value.
i Invariants/contracts preserved? Yes. Same local_seconds in [0, 86399] postcondition; the < 0 -> += 86400 normalization is unchanged.

Session id: cron:clickhouse-worker-slot-4:20260714-203900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @rschu1ze — could you review this? It fixes a UBSan signed-integer overflow in the DateTime64 -> Time/Time64 conversion: (dt64 + offset) % 86400 overflows Int64 for extreme inputs (INT64_MIN) with a negative timezone offset. The fix reduces modulo 86400 before adding the offset (algebraically identical, sum now bounded).

@yariks5s yariks5s self-assigned this Jul 14, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4f1986e]

Summary: ✅


AI Review

Summary

This PR is back to the intended narrow fix: both DateTime64 -> Time and DateTime64 -> Time64 now reduce the whole-second value modulo 86400 before adding the timezone offset, which removes the signed-overflow path on extreme Int64 inputs without changing the time-of-day result. The regression file covers both conversion sites, pins use_legacy_to_time = 0 so the toTime rows stay on the new implementation under randomized compatibility settings, and current Praktika CI is fully green. I did not find any remaining correctness, coverage, or metadata issues in the current three-file diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
The extreme DateTime64 (INT64_MIN/MAX) reproducer used America/New_York /
Europe/Moscow, whose timezoneOffset() returns a tzdata-version-dependent
LMT-era offset for out-of-range inputs. CI produced 03:33:50 (EST, -5:00)
while a local build produced 03:29:52 (NY LMT, -4:56:02) for the same
commit, so the exact wall-clock reference was not portable.

Switch the extreme cases to fixed-offset Etc/GMT zones, which have no
historical transitions and therefore a constant offset even at INT64_MIN/
MAX. The overflow is still triggered (INT64_MIN with a negative offset,
INT64_MAX with a positive offset) and the buggy vs fixed results still
differ (buggy 03:30:08/22:29:51 vs fixed 20:29:52/05:30:07), so the test
remains a valid regression test while being deterministic on every arch
and tzdata version.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 1ff078c: made the extreme-value reference deterministic.

Root cause of the red Fast test: the INT64_MIN/MAX cases used America/New_York, whose timezoneOffset() returns a tzdata-version-dependent LMT-era offset for out-of-range inputs. CI got 03:33:50 (EST -5:00) vs a local build's 03:29:52 (NY LMT -4:56:02) for the same commit -> non-portable reference. The new_tests_check.py FAIL was downstream: the FT Bugfix Validation jobs were DROPPED behind the red Fast test.

Fix: switch the extreme cases to fixed-offset Etc/GMT zones (no historical transitions -> constant offset even at INT64_MIN/MAX). The overflow is still triggered and buggy vs fixed still differ (verified by A/B rebuild: buggy 03:30:08/22:29:51 vs fixed 20:29:52/05:30:07), so it stays a valid regression test but is now deterministic on every arch/tzdata.

Comment thread src/Functions/FunctionsConversion.h Resolved
…h values

The DateTime64 -> Time64 path rescaled the full epoch value with convertDecimals
before applying the day modulo, so an extreme input (e.g. INT64_MIN) threw
DECIMAL_OVERFLOW even though the wall-clock time-of-day is always representable.
It also split the value with truncation toward zero, so a pre-epoch fractional
value landed on the wrong wall-clock day (a negative Time64).

Split the original DateTime64 into floor-aligned whole seconds plus a
non-negative sub-second fraction first, apply the timezone/day modulo to the
whole part, then rescale only the bounded fraction and reassemble. convertDecimals
never sees the full out-of-range epoch value, and pre-epoch fractions round toward
the floor second so the wall-clock day is correct.

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 584045d. The DateTime64 -> Time64 path now splits the original value into floor-aligned whole seconds plus a non-negative sub-second fraction first, applies the day/timezone modulo to the whole part, and only then rescales the bounded fraction and reassembles. convertDecimals is no longer called on the full epoch value, so the extreme input no longer throws DECIMAL_OVERFLOW, and pre-epoch fractions round toward the floor second (correct wall-clock day).

  • CAST(reinterpret(CAST(-9223372036854775808 AS Int64),'DateTime64(0,''Etc/GMT+12'')') AS Time64(9)) now returns 20:29:52.000000000 (was DECIMAL_OVERFLOW).
  • CAST(toDateTime64('1969-12-31 23:59:59.250', 3, 'Etc/GMT+0') AS Time64(9)) now returns 23:59:59.250000000 (was -00:00:00.750000000).
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_time_time64_type=1; SELECT CAST(reinterpret(CAST(-9223372036854775808 AS Int64),'DateTime64(0,''Etc/GMT+12'')') AS Time64(9)); throws DECIMAL_OVERFLOW on the baseline every run; the pre-epoch fractional cast returns a negative wrong-day Time64.
b Root cause explained? The scale-changing branch called convertDecimals on the full epoch value (rescaling INT64_MIN overflows Int64/decimal), then split with / and % (truncate toward zero), so pre-epoch fractions produced a negative fraction on the wrong day.
c Fix matches root cause? Yes. Split the ORIGINAL value into floor-aligned whole seconds + non-negative fraction before any rescale; apply day/tz modulo to the whole part; rescale only the bounded fraction; reassemble via multiplyAdd. convertDecimals never sees the out-of-range epoch.
d Test intent preserved / new tests? Extended 04512_totime_datetime64_extreme_overflow with scale-changing extreme cases (Time64(9)) and pre-epoch fractional cases (Time64(3)/Time64(9)). Existing assertions unchanged.
e Both directions demonstrated? Baseline (Build ID 72dd29): DECIMAL_OVERFLOW / -00:00:00.750000000 / -00:00:00.500000000. Fixed (Build ID 3d4503): 20:29:52.000000000 / 23:59:59.250000000 / 23:59:59.500000000, stable across 3 runs.
f Fix general, not narrow? Covers equal-scale and scale-changing (up and down), positive and negative offsets, extreme INT64_MIN/INT64_MAX, and pre-epoch fractions. The accurateOrNull path uses tryMultiplyAdd so it nulls (not throws) on genuine out-of-range.
g Generalizes across inputs/wrappers? Exercised scales 0/1/3/9, Etc/GMT+12/Etc/GMT-14/Etc/GMT+0/Etc/GMT+-3, epoch extremes and pre-epoch fractional.
h Backward compatible? Yes. Output for in-range values is unchanged; only extreme (previously erroring) and pre-epoch fractional (previously wrong) results change to correct values. No setting/format change.
i Invariants preserved? whole_seconds*scale + fraction == value holds with a non-negative fraction; multiplyAdd preserves the overflow contract (throw / null-on-accurateOrNull).

Session id: cron:clickhouse-worker-slot-2:20260714-233500

groeneai and others added 2 commits July 15, 2026 00:38
clang-tidy/-Werror flagged 'to_fraction' as used-uninitialized in the
DateTime64->Time64 branch. It is assigned on both branches before use;
initialize to 0 at declaration to satisfy the check.

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

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_asan_ubsan, distributed plan, parallel) failures on this PR (dozens of unrelated tests, all Code 241 (total) memory limit exceeded / OvercommitTracker, clustered in the 2026-07-15 01:00-04:45 UTC window) are a fleet-wide host-OOM co-scheduling burst on that shard, not caused by this PR (7-day baseline for the lane is 2-10 Code-241 fails/day; the burst was ~1959 then self-resolved). Fixing PR: #110503 (retry-on-server-(total)-memory-error).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 002ffd5

CI is fully finished on this head. Every failure has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) — 104 unrelated tests fleet-wide host-OOM (Code 241, MEMORY_LIMIT_EXCEEDED (total) OvercommitTracker), transient 01:00-04:45 UTC window; none of these tests are in this PR's diff (which touches FunctionsConversion.h + 04512_totime_datetime64_extreme_overflow) #110503 (ours, open)
Finish Workflow / Post Hooks (new_tests_check.py) downstream cascade — the Bugfix-validation jobs were DROPPED behind the fleet-OOM red Mergeable Check, so the new-tests hook could not observe them #110503 (ours, open)

The earlier Fast test (04512 reference, on aa6dff4), Build (arm_tidy) (-Werror, on 584045d) and Style check (04402 blocker, on a094dd1) failures are all on pre-fix/pre-merge heads and are gone on the current head 002ffd5.

Session id: cron:our-pr-ci-monitor:20260715-070000

@yariks5s

Copy link
Copy Markdown
Member

@groeneai investigate the CI failures. Why do you need that much changes in the code while you were fixing only the UBSan?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both questions answered below.

1. The CI failures

Current head is 002ffd57 (pushed 2026-07-15). It has 171 check runs, exactly 2 with a failure conclusion, and the second is a cascade of the first:

Check Verdict What it actually is
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL 104 / 11260 passed 83 of the 104 are Code: 241. (total) memory limit exceeded, 15 more are ConnectionResetError after the server was killed, 6 are profile-event / part-log reference diffs from the same starved run (01946_profile_sleep, 03255_merge_mutation_start_entry_in_the_part_log, ...). Nothing in the list touches Time, Time64 or DateTime64.
Finish Workflow FAIL new_tests_check.py: "No per-arch Bugfix Validation job validated the bug". Both Bugfix validation (functional tests, amd64/aarch64) jobs are DROPPED behind the red job above, so the check never got a verdict. Not an independent problem.

The host OOM was a fleet-wide event that day, not something this branch caused. In that one check, (total) memory limit exceeded appeared in 181 of 360 runs on 2026-07-15 (master and unrelated PRs included); today it is 1 of 229.

The branch is also 4966 commits behind master, and the two changes that addressed that cohort are not on it:

git merge-base --is-ancestor bb9c5e5a3032 002ffd57   -> false   (#110503, merged 2026-07-15 21:37Z)
git merge-base --is-ancestor 21efe2da0a9e 002ffd57   -> false   (#110574, merged 2026-07-18)

A GitHub re-run would reuse this same build, so it cannot pick those up. I will merge master into the branch and push, so the next run is real signal rather than a 12-day-old snapshot.

The test added by this PR is not implicated either: in the CI database it is 416 OK against 1 FAIL since 2026-07-14, and the single FAIL is the old Fast test on aa6dff4a, before I made its reference independent of the tzdata version. I also re-ran it just now against this head's own prebuilt debug binary (build id ED0C8489DA20ABBC695D9059CDD421E0FDAB9782) and the output is byte-identical to the committed .reference.

2. Why the diff is larger than the UBSan fix

Fair question. The real diff against the merge base is 3 files, +82/-26, and FunctionsConversion.h is +40/-26 of which 12 added lines are comments.

The UBSan fix proper is 2 changed lines, in the first commit aa6dff4a:

-        Int64 local_seconds = (dt64 + offset) % 86400;
+        Int64 local_seconds = (dt64 % 86400 + offset) % 86400;

plus the same reorder at the DateTime64 -> Time64 site. That is all the overflow needed.

Everything else is one later commit, 584045d, which I pushed after the automated review pointed out that the DateTime64 -> Time64 scale-changing cast was still wrong in two ways on the same code path:

  • convertDecimals rescaled the whole epoch value before the day modulo ran, so an extreme input threw Code: 407 DECIMAL_OVERFLOW instead of returning a time-of-day.
  • the utc_seconds / fraction split truncated toward zero, so a pre-epoch value landed on the wrong wall-clock day.

The second one is reachable with an ordinary value and no settings at all. On master today:

SELECT CAST(toDateTime64('1969-12-31 23:59:59.250', 3, 'UTC') AS Time64(3));
-- master:   -00:00:00.750
-- this PR:  23:59:59.250

So 584045d is a second defect on the path I was already touching, not extra scope I chose. I also ran a 13-case matrix of ordinary values (DST and standard time, scale up, scale down with truncation, epoch zero, 1900, accurateCastOrNull) on master and on this head: identical everywhere except the two intended changes above.

That said, you are the assignee and you are entitled to a smaller PR. I am happy to split it:

  • keep only the 2-line modulo reorder and its 3 extreme-value test cases here, and
  • move the DateTime64 -> Time64 rework and its 5 test cases into a separate PR.

Or, if you would rather not have the second fix at all, say so and I will drop it; the automated review comment is not binding. Tell me which you prefer and I will do it in one push. Until then I am not restructuring the diff, only merging master so CI gives a usable answer.

Pick up the fleet-wide stateless-test host OOM mitigations (ClickHouse#110503, ClickHouse#110574)
so CI on this branch produces real signal.

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

Copy link
Copy Markdown
Collaborator Author

Master merged and pushed: head is now 6b44de7b (was 002ffd57, which was 4966 commits behind). That build now contains both host-OOM mitigations that were missing (bb9c5e5a from #110503 and 21efe2da from #110574), so this CI run should be usable signal rather than a 12-day-old snapshot.

The merge changed nothing in the fix itself. Against origin/master the diff is still exactly 3 files, +82/-26 (FunctionsConversion.h, plus the test and its reference), with no submodule movement. FunctionsConversion.h had no upstream change overlapping either hunk; master's edits to that file are all several thousand lines below, around line 3627 onward.

Verified locally after the merge: the tree builds clean with clang-21 (-Werror), and 04512_totime_datetime64_extreme_overflow is 50/50 OK under randomized settings against build id 31d459db2425d414009cda597bbc81112a1769df, which is the build id the test server reported.

Still waiting on your call about splitting the DateTime64 -> Time64 rework out; I have not touched the diff shape.

FunctionFactory resolves toTime to the legacy toTimeWithFixedDate whenever
use_legacy_to_time = 1, and the stress runner injects a random
compatibility='NN.N' client option that restores that value for versions
before 26.7. In that mode the toTime statements of this test return a
DateTime instead of a Time, and the values are byte-identical with and
without the DateTime64 -> Time fix, so that half of the fix is no longer
covered. Pinning the setting keeps the statements on
ToTimeImpl::execute(Int64) regardless of the injected compatibility value.

The pin is a no-op on the default path: the reference file is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110451&sha=6b44de7be8d0a0d1cf5e21a972c708353e729a77&name_0=PR
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — da3a6b7

CI fully finished on this head (Finish Workflow pass, Mergeable Check pass, 0 checks queued or in progress): 160 pass, 17 skipped, 0 failures. Nothing to own.

The reds recorded on earlier heads are all gone here: the Fast test reference mismatch on 04512_totime_datetime64_extreme_overflow (head aa6dff4a), Build (arm_tidy) -Werror (head 584045d), the Style check blocker (head a094dd11), and the fleet-wide host-OOM Stateless tests (amd_asan_ubsan, distributed plan, parallel) window plus its new_tests_check.py cascade (head 002ffd57).

Session id: cron:our-pr-ci-monitor:20260727-220000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts and update the branch.

Master picked up the floor-aligned seconds split for DateTime64 -> Time64
through ClickHouse#109738, which rewrote the same block this branch touched. Resolved
by taking master's structure (it already carries that split and the
accurateCastOrNull representability gate) and re-applying only the overflow
reorder on top, at both Int64 sites.

The Time64 reassembly no longer needs DecimalUtils::multiplyAdd: Time64 caps
at scale 9, so the widest value is 86399 * 1e9 + 999999999 = 8.64e13, five
orders of magnitude below INT64_MAX. That guard was dead code and is dropped.

What remains against master is the 2 line fix the branch exists for.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, the branch is updated and the conflict is resolved: head is now 4f1986e29b683339257e1ec12d04c18ae48a2f2d and GitHub reports the PR mergeable again.

The conflict was against my own PR #109738, which merged 38 minutes before your comment and rewrote the same DateTime64 -> Time64 block. Master already carries the floor-aligned seconds split from it, so I took master's structure for that block and re-applied only the overflow reorder on top.

That shrank this PR to what it was always meant to be, which also answers @ yariks5s's earlier question about the size of the diff. Against master it is now 2 changed lines of code:

-        Int64 local_seconds = (dt64 + offset) % 86400;
+        Int64 local_seconds = (dt64 % 86400 + offset) % 86400;

and the same reorder at the DateTime64 -> Time64 site. Reducing modulo 86400 first is mathematically identical and keeps the intermediate sum bounded, so INT64_MIN + offset no longer overflows.

I also dropped the DecimalUtils::multiplyAdd guard the earlier version added for the reassembly. Time64 caps at scale 9, so the widest representable value is 86399 * 1e9 + 999999999 = 8.64e13, five orders of magnitude below INT64_MAX. It was dead code.

The fix is still needed on master: with the reorder reverted, the two extreme cases return 03:30:08 and 22:29:51 instead of 20:29:52 and 05:30:07, so it is silently wrong results in release builds on top of the UBSan report. Verified locally on a debug build, 5 of the 10 assertions in the regression test move when the reorder is reverted; the 3 pre-epoch rows do not, since they now cover the split that #109738 landed without tests, and I left a comment in the test saying so. 50 consecutive runs pass.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

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

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

While it may make the conversion slower, it is unlikely to be important.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 8d9b7fd Aug 1, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
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 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.

4 participants