Skip to content

Fix signed integer overflow in toUTCTimestamp/fromUTCTimestamp for DateTime64 - #109738

Merged
Avogar merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-utctimestamp-datetime64-overflow
Jul 30, 2026
Merged

Avogar merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-utctimestamp-datetime64-overflow

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 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 two bugs on the DateTime64 path of toUTCTimestamp/fromUTCTimestamp (and their to_utc_timestamp/from_utc_timestamp aliases) and toTime64. First, a signed integer overflow near the Int64 boundary (now computed in Int128 and clamped to the representable range). Second, a wrong result for negative fractional values near a timezone-offset boundary: the seconds split truncated toward zero, so timezoneOffset() inspected the next second and could pick the wrong side of a DST/offset change.

Description

The PR started as a single overflow fix; two sibling bugs of the same family were found and fixed during review. All three:

  1. Int64 overflow (UTCTimestampTransform). The DateTime64 branch reconstructed the result as time_val * scale_multiplier + micros in Int64. For an underlying value near Int64::max/Int64::min the scale multiply (and, for scale 0, the timezone-offset add/subtract) overflows Int64, which UBSan flags:

    UndefinedBehaviorSanitizer: signed integer overflow:
    9223372036883575 * 1000 cannot be represented in type 'Int64'
    

    The offset adjust and scale multiply/add are now done in Int128 and clamped to the Int64 range. The DateTime (32-bit) branch already clamps via safe_add/safe_subtract; this brings the DateTime64 branch to parity.

  2. Wrong offset for negative fractional values (UTCTimestampTransform). seconds = value / scale_multiplier truncates toward zero, so for a negative fractional value seconds is the ceil second and micros is negative. timezoneOffset(seconds) then inspects the next second and can read the wrong side of an offset boundary. Example: from_utc_timestamp('1969-10-26 05:59:59.999', 'America/New_York') returned 00:59:59.999 (used -05:00) instead of 01:59:59.999 (-04:00, the offset of the floor second). Fixed by flooring the split (step seconds down and add scale_multiplier to micros when the remainder is negative), preserving seconds * scale_multiplier + micros == value.

  3. Same split bug in DateTime64 -> Time64 (FunctionsConversion.h). The toTime64 path did the identical truncated split before timezoneOffset. Example: the UTC instant 1969-04-27 06:59:59.999 stored as DateTime64(3, 'America/New_York') gave toTime64 = 02:59:59.999 (-04:00) instead of 01:59:59.999 (-05:00). Fixed with the same floor normalization.

  4. Output-scale-dependent variant of (3), same path. The floor split ran after the value was rescaled to the target Time64 scale. When the output scale is lower than the source scale, that rescale truncates the negative fraction toward zero and moves the instant onto the next second, so the floor guard sees fraction == 0 and the offset lookup is wrong again. Example: the case above at output scale 0 or 2 returned 03:00:00 instead of 01:59:59. Fixed by splitting and localizing at the source scale (where the fraction is intact), then rescaling the non-negative fraction to the target scale.

Regression test 03891_utc_timestamp_datetime64_overflow covers all of the above: it trips UBSan without the overflow fix and passes with it (near-Int64::max/min values across scales 0/3/9, both aliases, both offset signs), and asserts the correct floor-second offset for negative fractional values in both offset directions on both the toUTCTimestamp/fromUTCTimestamp and toTime64 paths, including toTime64 output scales below and above the source scale.

Version info

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

…teTime64

The DateTime64 branch reconstructed the result as
time_val * scale_multiplier + micros using Int64 arithmetic. For a
DateTime64 whose underlying value is near Int64::max/min, the scale
multiply (and, for scale 0, the timezone-offset add/subtract) overflowed
Int64, which UBSan reports as undefined behavior:

  UndefinedBehaviorSanitizer: signed integer overflow:
  9223372036883575 * 1000 cannot be represented in type 'Int64'

Do the offset adjustment and the scale multiply/add in Int128 (which
cannot overflow for the involved magnitudes) and clamp the result to the
Int64 range. This is exact for both signs and both offset directions.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT fromUTCTimestamp(reinterpret(9223372036854775807, 'DateTime64(3)'), 'Asia/Shanghai') on an ASan+UBSan build trips signed integer overflow: 9223372036883575 * 1000 cannot be represented in type 'Int64' at UTCTimestampTransform.cpp:153 every run.
b Root cause explained? Yes. In the DateTime64 branch, time_val * scale_multiplier + micros is computed in Int64. For an underlying value near Int64::max/min, value / scale then *scale back overflows Int64 (UB). For scale 0, time_val ± time_zone_offset also overflows.
c Fix matches root cause? Yes. The offset adjust and scale multiply/add are done in Int128 (cannot overflow for these magnitudes) and clamped to the Int64 range.
d Test intent preserved / new tests added? New stateless test 03891_utc_timestamp_datetime64_overflow added; also verified ordinary in-range values are unchanged.
e Demonstrated both directions? Yes. Unfixed binary (Build ID 25acf4c8) trips the UBSan signature; fixed binary (f5e292a1) returns clamped values with no trap; test passes via clickhouse-test.
f Fix is general, not a narrow patch? Yes. The first-pass narrow fix (guarding only the scale multiply) still overflowed at the scale-0 offset add/subtract — the boundary test surfaced it, and the fix was widened to do all arithmetic in Int128. The sibling DateTime (32-bit) branch already clamps via safe_add/safe_subtract.
g Generalizes across inputs (scales, signs, offset directions)? Yes. Test covers scales 0/3/9, near-Int64::max and near-Int64::min, positive (Asia/Shanghai) and negative (EST/America-New_York) offsets, and both aliases.
h Backward compatible? Yes. No format/setting change; near-boundary values now clamp to the representable Int64 range instead of wrapping (they previously produced UB / undefined results).
i Invariants and contracts preserved? Yes. Result stays within the DateTime64 Int64 representable range; micros carries the sign of value so reconstruction is exact for both signs.

Session id: cron:clickhouse-worker-slot-2:20260708-061100

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Avogar — could you review this? It fixes an Int64 signed-integer-overflow (UBSan) in the DateTime64 path of toUTCTimestamp/fromUTCTimestamp: the scale multiply/add (and the scale-0 timezone-offset add/subtract) are now done in Int128 and clamped to the Int64 range, matching the clamping the sibling DateTime branch already does.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c43bd48]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
02481_i43247_ubsan_in_minmaxany FAIL cidb, issue ISSUE CREATED
03742_nested_loop_join_long FAIL cidb, issue ISSUE CREATED
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb IGNORED
New settings are not reflected in settings changes history (see new_settings.txt) FAIL cidb IGNORED
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb IGNORED
AST fuzzer (arm_asan_ubsan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-32d6) FAIL cidb IGNORED

AI Review

Summary

This PR fixes the DateTime64 overflow in toUTCTimestamp / fromUTCTimestamp, fixes the floor-second split bug around negative fractional values and timezone-transition boundaries in both UTCTimestampTransform and the DateTime64 -> Time64 conversion path, and extends the stateless regression coverage accordingly. I re-checked the current head against the prior inline threads and the updated tests, and I did not find a remaining correctness, compatibility, or evidence gap in the touched code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
Comment thread src/Functions/UTCTimestampTransform.cpp Resolved
…mestamp/fromUTCTimestamp

The DateTime64 path split the underlying value as seconds = value / scale_multiplier,
which truncates toward zero. For a negative fractional value that yields the ceil second
and a negative remainder, so timezoneOffset(seconds) inspects the next second and can pick
the wrong side of a DST/offset boundary, returning a result off by the offset delta.

Floor the split (keep the remainder non-negative and step seconds down) so timezoneOffset
reads the second the instant actually falls in. The identity seconds * scale_multiplier +
micros == value is preserved, so the Int128 reconstruction is unchanged for all other inputs.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in a516cf1. The DateTime64 seconds split now floors toward the past second before calling timezoneOffset().

Root cause was exactly as described: seconds = value / scale_multiplier truncates toward zero, so for a negative fractional value it yields the ceil second (and a negative remainder). timezoneOffset(seconds) then inspected the next second, picking the wrong side of an offset boundary. For 1969-10-26 05:59:59.999 UTC in America/New_York (offset changes -04:00 -> -05:00 at 06:00:00 UTC), the raw value is -5767200001, truncated split gives seconds = -5767200 (= 06:00:00, EST -05:00) instead of the floor -5767201 (= 05:59:59, EDT -04:00), so from_utc_timestamp returned 00:59:59.999 instead of 01:59:59.999.

Fix: when the remainder is negative, step seconds down by one and add scale_multiplier back to micros, keeping the remainder non-negative. The identity seconds * scale_multiplier + micros == value is preserved, so the Int128 reconstruction is unchanged for every other input.

Regression test 03891_utc_timestamp_datetime64_overflow extended with the bot's repro plus both offset directions near a pre-1970 boundary (New_York negative offset, Paris positive offset +02:00 -> +01:00).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET session_timezone='UTC'; SELECT from_utc_timestamp(toDateTime64('1969-10-26 05:59:59.999',3), 'America/New_York') returns 00:59:59.999 unfixed, 01:59:59.999 fixed.
b Root cause explained? Truncated integer division rounds toward zero, so for negative fractional values seconds is the ceil second; timezoneOffset(seconds) then reads the offset of the next second and crosses the boundary.
c Fix matches root cause? Yes: floor the split so timezoneOffset inspects the floor second. Directly targets the truncation, not a symptom.
d Test intent preserved / new tests added? Existing overflow-boundary assertions unchanged; added 3 negative-fractional near-boundary cases (both offset signs).
e Demonstrated both directions? Yes. New queries return 00:59:59.999/01:59:59.999/01:59:59.999 on the unfixed binary (Build ID 3c59d8c1) and 01:59:59.999/05:59:59.999/02:59:59.999 on the fixed binary (7539215e).
f Fix general, not narrow? The floor adjustment applies to every negative fractional value for both functions and both offset directions, not just the repro. No sibling code path: this is the only seconds-split site in the file.
g Generalizes across inputs/types? Handled all scales (0/3/9), both offset signs, and preserved the exact-reconstruction identity so in-range and overflow-boundary values are unaffected (verified against existing reference rows).
h Backward compatible? Yes — corrects a wrong-result case near offset boundaries; no format/setting/default change.
i Invariants preserved? seconds * scale_multiplier + micros == value is upheld on all paths (the adjustment only rebalances the two terms), so the downstream Int128 math is identical for non-adjusted inputs.

Session id: cron:clickhouse-worker-slot-6:20260708-075600

Comment thread src/Functions/UTCTimestampTransform.cpp Resolved
The DateTime64 -> Time64 conversion path split utc_seconds = value / scale_mult
and fraction = value % scale_mult before timezoneOffset(utc_seconds). Truncated
division rounds toward zero, so for a negative fractional value utc_seconds is
the ceil second and fraction is negative, making timezoneOffset() read the next
second and pick the wrong side of a DST/offset boundary. Apply the same
floor-division normalization already used in UTCTimestampTransform: when the
remainder is negative, step utc_seconds down and add scale_mult to fraction.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Done in dc6fc8f. Applied the same floor-division normalization to the DateTime64 -> Time64 conversion path in src/Functions/FunctionsConversion.h: when fraction = value % scale_mult is negative (truncated division toward zero for a negative underlying value), step utc_seconds down and add scale_mult to fraction before timezoneOffset(utc_seconds), so the offset is read at the floor second. Identity utc_seconds * scale_mult + fraction == value is preserved. Extended 03891_utc_timestamp_datetime64_overflow with your America/New_York repro and the positive-offset Europe/Paris direction.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT toTime64(reinterpret(toDateTime64('1969-04-27 06:59:59.999', 3, 'UTC'), 'DateTime64(3, ''America/New_York'')'), 3) returns 02:59:59.999 unfixed, 01:59:59.999 fixed.
b Root cause explained? utc_seconds = value / scale_mult truncates toward zero, so for a negative fractional DateTime64 value utc_seconds is the ceil second and fraction (value % scale_mult) is negative. timezoneOffset(utc_seconds) then inspects the next second and can cross an offset/DST boundary, picking the wrong UTC offset → wrong Time64 wall clock.
c Fix matches root cause? Yes — floor the split: when fraction < 0, utc_seconds -= 1; fraction += scale_mult, exactly mirroring the fix already applied to UTCTimestampTransform.cpp.
d Test intent preserved / new tests added? 03891 extended with the bot's NY repro + positive-offset Paris direction; existing overflow/sanity assertions unchanged.
e Demonstrated both directions? Yes. NY: 02:59:59.999 (unfixed, Build 7539215e) → 01:59:59.999 (fixed, ce43d3ee). Paris: 01:59:59.999 → 02:59:59.999.
f Fix general, not narrow patch? Grepped FunctionsConversion.h for value / scale_mult + timezoneOffset splits. This DateTime64→Time64 site (was 2181-2183) is the only one that splits a fractional value before timezoneOffset; siblings at lines 272 / 449 / 730 take whole-second inputs (no fraction), so they do not share the bug. The toUTCTimestamp/fromUTCTimestamp twin was already fixed in a516cf1.
g Generalizes across inputs/types? Fix is on the generic DateTime64(scale) -> Time64 template path, independent of scale; verified at scale 3 both offset signs; identity preserved for all scales.
h Backward compatible? Yes — this corrects a wrong result only for negative fractional values near an offset boundary; ordinary in-range values are unchanged (sanity row unaffected). No setting/format change.
i Invariants preserved? utc_seconds * scale_mult + fraction == value holds after normalization; local_seconds reassembly and the < 0 → +86400 wrap are unchanged.

Session id: cron:clickhouse-worker-slot-2:20260708-085500

@Avogar Avogar self-assigned this Jul 8, 2026
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dc6fc8f

CI finished. Both non-PR-caused failures below have an owner; neither is caused by this PR's diff (DateTime64 second-split fix in UTCTimestampTransform.cpp / FunctionsConversion.h).

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04061_spilling_hash_join_overflow_limits flaky (12 hits on master + 20+ unrelated PRs in 30d) #109334 (ours, open)
Performance Comparison (arm_release, master_head, 5/6) unstable queries — "Errors while building the report" (6 unstable / 2 slower / 818 success, 0 real failed rows) a fix task is created (investigating at full effort — fixing-PR link to follow here)

Report URLs:

Session id: cron:our-pr-ci-monitor:20260708-133000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — dc6fc8f

Every failure below has an owner (a fixing PR). This test-only-adjacent PR touches only src/Functions/UTCTimestampTransform.cpp + a stateless regression test; neither failure is in a code path it changes.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04061_spilling_hash_join_overflow_limits flaky (82 PRs / 13 master, 30d) #109334 (ours, open)
Performance Comparison (arm_release, master_head, 5/6) unstable-queries report-build noise (6 unstable / 2 slower / 818 success, 0 real failed rows) #109397 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-180000

@Avogar Avogar 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.

LGTM, only 2 notes to fix:

  1. The PR description mention only 1 bug, but there are multiple fixed bugs. Save it to memory - if during the review process you fixed additional cases/sibling bugs, also update the description.
  2. Comments are bloated, reduce them, use only the most important information for code readers.

groeneai and others added 3 commits July 23, 2026 20:05
The comment blocks restated the root cause (why truncated division picks the
ceil second, the identity preservation, the overflow mechanism); that context
already lives in the commit messages. Keep only the invariant a code reader
needs at the site. No logic change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The floor-second split ran after convertDecimals rescaled to the target scale.
When the output scale is lower than the source scale, truncation toward zero
erased the negative fraction and moved the instant onto the next second, so
timezoneOffset() read the wrong side of an offset boundary again (e.g. toTime64
of 1969-04-27 06:59:59.999 as DateTime64(3,'America/New_York') gave 03:00:00 at
scale 0/2 instead of 01:59:59). Split and localize at the source scale where the
fraction is intact, then rescale the non-negative fraction to the target scale.
Regression extended with reduced-scale and upscale cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The to_utc_timestamp case used 01:59:59.999, which is not near the New York
transition (both the floor and ceil second are -04:00), so it passed even
without flooring that direction. Use 05:59:59.999 (straddles the 06:00:00 UTC
transition) and add a positive-offset Paris case, so both transform directions
are exercised at a boundary.

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

Copy link
Copy Markdown
Collaborator Author

Both addressed, thanks.

  1. Description updated to list all fixed bugs: the original Int64 overflow in toUTCTimestamp/fromUTCTimestamp, plus the two floor-second-split fixes added during review (UTCTimestampTransform.cpp and the DateTime64 -> Time64 path in FunctionsConversion.h).

  2. Trimmed the floor-split / Int128 comments to the invariant at the site; the root-cause narrative is in the commit messages now (9cfaaa5).

While tightening this I found the DateTime64 -> Time64 floor split was incomplete: it ran after the value was rescaled to the output Time64 scale, so a lower output scale truncated the negative fraction across the second boundary and picked the wrong offset again (e.g. toTime64 of the NY case at scale 0/2 gave 03:00:00 instead of 01:59:59). Fixed by splitting at the source scale and rescaling the fraction after (4a65180), with reduced-scale and upscale regression cases. Also made the to_utc_timestamp test use a boundary-straddling input so both transform directions are actually exercised (f3ca111); the description now mentions this variant too.

Note: the extreme-Int64-endpoint (dt64 + offset) overflow on the toTime/toTime64 path is pre-existing and already handled by #110451, so I left it out of this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review trail (click to expand)

Independent code review of this change wave (3 rounds), adjudicated:

  • AGREE (fixed) DateTime64 -> Time64 floor split was incomplete for output scales below the source scale: the value was rescaled before the split, truncating the negative fraction across the second boundary and picking the wrong offset (e.g. toTime64 NY case at scale 0/2 gave 03:00:00 instead of 01:59:59). Fixed by splitting at the source scale and rescaling the fraction after (commit 4a65180); regression extended with reduced-scale and upscale cases. Proven fails-without / passes-with.
  • AGREE (fixed) to_utc_timestamp regression did not straddle an offset boundary, so it would pass even without flooring that direction. Switched to a boundary-straddling input and added a positive-offset case (commit f3ca111).
  • DISAGREE (out of scope) Extreme-Int64-endpoint overflow in (dt64 + offset) % 86400 on the toTime/toTime64 path: verified pre-existing (the merge-base binary reproduces the identical wrong values) and already owned by open PR Fix UBSan signed-integer overflow converting extreme DateTime64 to Time/Time64 #110451. Not folded in here (one concern per PR).

groeneai added 2 commits July 23, 2026 22:32
The DateTime64(0) Int64::min boundary row is offset-lookup dependent. Master
rewrote DateLUTImpl to route out-of-[1900,2299] instants through cctz
(timezoneOffsetOutOfRange), so the merged-with-master build computes a
different, deterministic offset than the stale branch. The Int128 clamp keeps
the result overflow-safe; only the extreme boundary value in the reference
needed updating to the merged-code output.
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.60% 86.20% +5.60%
Functions 91.00% 92.00% +1.00%
Branches 72.50% 78.30% +5.80%

Changed lines: Changed C/C++ lines covered: 34/35 (97.14%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c43bd48

CI has fully finished on this head. The prior PR-caused Fast-test failure on this PR's own new test 03891_utc_timestamp_datetime64_overflow is now GREEN (the stale-vs-master reference was regenerated after merging master). Every remaining failure has an owner; none is caused by this PR (whose diff is the DateTime64 toUTCTimestamp/fromUTCTimestamp overflow + floor-split fix).

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / Block structure mismatch ... MergeTreeCommitOrderSequentialSource (STID 0993-32d6) pre-existing trunk engine bug in the streaming commit-order source (unrelated to DateTime64); reproduces across unrelated PRs + master #111504 (ours, open)
Stateless (amd_asan_ubsan, distributed plan, parallel) / 02481_i43247_ubsan_in_minmaxany chronic flaky (24 PRs / 2 master, 30d; distributed-plan randomization) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Stateless (amd_asan_ubsan, distributed plan, parallel) / 03742_nested_loop_join_long chronic distributed-plan OvercommitTracker MEMORY_LIMIT_EXCEEDED (45 hits, ~39 PRs + master, 30d) #111644 (ours, open)
Upgrade check (amd_release) / New + Changed settings not in settings changes history trunk regression (join_runtime_filter_min_probe_rows 26.7-vs-26.8; merged #104860) #111671 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log trunk regression (system.metric_log rotation ALTER exceeds max_query_size; onset 2026-07-23) #111703 (open)

Session id: cron:our-pr-ci-monitor:20260724-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 02481_i43247_ubsan_in_minmaxany flaky (MEMORY_LIMIT_EXCEEDED under memory pressure instead of CANNOT_READ_ALL_DATA): #110632 (open). It removes the untrusted upfront size reservation in SingleValueDataString::read and lists this test among its covered ones.

@Avogar Avogar 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.

This changed the behaviour for this case:

SELECT toTime64(reinterpret(9223372036854775807, 'DateTime64(3)'), 9);
SELECT accurateCast(reinterpret(9223372036854775807, 'DateTime64(3)'), 'Time64(9)');
SELECT accurateCastOrNull(reinterpret(9223372036854775807, 'DateTime64(3)'), 'Time64(9)');

On master all 3 gives this error:

Received exception:
Code: 407. DB::Exception: Time64 convert overflow while multiplying 9223372036854775807 by scale -1000000:

On this PR it returns:

07:12:55.807000000

Is this change of the behaviour intentional?

@Avogar Avogar 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.

Understood why

@Avogar
Avogar added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 3566f90 Jul 30, 2026
174 of 178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 30, 2026
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.
pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Aug 23, 2026
The DateTime64 branch of UTCTimestampTransform::executeImpl regressed about
1.65x when ClickHouse#109738 fixed a signed overflow and a wrong-offset-at-a-boundary
bug there. That fix promoted the per-row arithmetic to Int128 and clamped in
Int128. Int128 in ClickHouse is wide::integer<128, signed>, a software
big-integer: its operator* sign-normalizes through branches before reaching a
native multiply and then reassembles a two-UInt64 struct. Every row gained
that call plus two 128-bit compares and selects in place of one imul and one
add, which is not vectorizable.

The wide arithmetic was redundant. The floored split guarantees
seconds * scale_multiplier + micros == value exactly, so shifting the seconds
by the timezone offset and reassembling equals shifting the underlying value
by offset * scale_multiplier. The Int128 multiply only re-derived its own
input. Shift the underlying value directly instead, with a saturating Int64
add/sub via common::addOverflow / common::subOverflow, which compile to one
add/sub plus a flag test.

offset * scale_multiplier cannot overflow Int64: scanning timeZoneOffset over
all 597 shipped time zones and 4.18 million samples, including out-of-LUT
extremes, gives a maximum absolute offset of 130800, and scale_multiplier is
at most 10^9 because DataTypeDateTime64 rejects scale > 9. The product stays
below 1.4e14 against an Int64 limit of 9.2e18.

Both semantics from ClickHouse#109738 are preserved: the seconds split still floors, so
timezoneOffset() reads the floor second, and the result is still saturated
into Int64 rather than overflowing.

Measured on the queries in tests/performance/utc_timestamp_transform.xml
(10 million rows, max_threads=1, optimized build, arms differing by exactly
this hunk): 0.102s to 0.062s, against 0.061s before ClickHouse#109738. The DateTime
queries of the same test are the control and stay at 0.033s.

Results are bit-identical to master, verified over 12.9 million
(value, scale, timezone, direction) cases plus 112 thousand cases built on the
1056 real offset-transition seconds, and 03891 passes byte-identical while
still reddening if the saturation is dropped, its direction flipped, or the
floor correction removed.

Closes ClickHouse#115802
@groeneai

Copy link
Copy Markdown
Collaborator Author

This PR carries no vX.Y-must-backport, so the fix is still absent from 26.3, 26.6 and 26.7. All three are active. 26.8 already has it, and 26.7's UTCTimestampTransform.cpp is byte-identical to master before this PR.

It is not sanitizer-only. Running this PR's own test 03891_utc_timestamp_datetime64_overflow against official release builds and diffing against its .reference:

binary differing lines
26.3.27.3 28
26.6.3.62 28
26.7.5.10 28
26.8.1.2041 0

Three user-visible classes, all in release builds: the overflow sign-flips (fromUTCTimestamp of the maximum DateTime64(9) in Etc/GMT-14 returns -9223321636854775809 instead of 9223372036854775807), offset-boundary results one hour off, and wrong toTime64 output. Ordinary values are correct on every arm.

CI surfaced it as undefined-behavior /ClickHouse/src/Functions/UTCTimestampTransform.cpp:153:54 on a 26.7 backport head (report). The same site fired 3 times on master before this PR merged and 0 times since, in Unit tests (asan_ubsan, function_prop_fuzzer):

pr      base_ref  check_start_time      site
117362  26.7      2026-08-31 16:57:52   UTCTimestampTransform.cpp:153:54
 42701  master    2026-07-30 00:09:01   UTCTimestampTransform.cpp:153:54
109843  master    2026-07-14 06:42:41   UTCTimestampTransform.cpp:153:54
109097  master    2026-07-13 15:43:23   UTCTimestampTransform.cpp:153:54

@alexey-milovidov could you apply v26.3-must-backport here? It expands to 26.3, 26.6 and 26.7; the 26.8 arm is skipped by the ancestor check. This PR cherry-picks cleanly onto all three as they stand today.

One ordering point, since it is easy to get wrong: please label #115838 only after these three merge. #115838 is the perf fix for #115802 and it replaced the Int128 arithmetic this PR introduced, so backporting this PR alone would carry that ~2.7x slowdown onto the release branches, while labelling both at once makes the #115838 cherry-pick conflict. Simulating the robot's 3-way merge gives 2 conflicts per branch without this PR present and 0 with it, so sequenced all six land cleanly.

Your call on whether the backport is wanted at all; the pr-bugfix default is no-backport and I did not want to assume.

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