Repository navigation
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260708-061100 |
|
cc @rschu1ze @Avogar — could you review this? It fixes an Int64 signed-integer-overflow (UBSan) in the DateTime64 path of |
|
Workflow [PR], commit [c43bd48] Summary: ❌
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve |
…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]>
|
Fixed in a516cf1. The DateTime64 seconds split now floors toward the past second before calling Root cause was exactly as described: Fix: when the remainder is negative, step Regression test Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-6:20260708-075600 |
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]>
|
Done in dc6fc8f. Applied the same floor-division normalization to the Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260708-085500 |
CI finish ledger — dc6fc8fCI finished. Both non-PR-caused failures below have an owner; neither is caused by this PR's diff (DateTime64 second-split fix in
Report URLs:
Session id: cron:our-pr-ci-monitor:20260708-133000 |
CI finish ledger — dc6fc8fEvery failure below has an owner (a fixing PR). This test-only-adjacent PR touches only
Session id: cron:our-pr-ci-monitor:20260708-180000 |
Avogar
left a comment
There was a problem hiding this comment.
LGTM, only 2 notes to fix:
- 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.
- Comments are bloated, reduce them, use only the most important information for code readers.
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]>
|
Both addressed, thanks.
While tightening this I found the Note: the extreme- |
Internal second-model review trail (click to expand)Independent code review of this change wave (3 rounds), adjudicated:
|
…estamp-datetime64-overflow
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/35 (97.14%) · Uncovered code |
CI finish ledger — c43bd48CI has fully finished on this head. The prior PR-caused Fast-test failure on this PR's own new test
Session id: cron:our-pr-ci-monitor:20260724-050000 |
|
Fixing PR for the |
Avogar
left a comment
There was a problem hiding this comment.
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?
3566f90
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.
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
|
This PR carries no It is not sanitizer-only. Running this PR's own test
Three user-visible classes, all in release builds: the overflow sign-flips ( CI surfaced it as @alexey-milovidov could you apply 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 Your call on whether the backport is wanted at all; the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed two bugs on the
DateTime64path oftoUTCTimestamp/fromUTCTimestamp(and theirto_utc_timestamp/from_utc_timestampaliases) andtoTime64. First, a signed integer overflow near theInt64boundary (now computed inInt128and clamped to the representable range). Second, a wrong result for negative fractional values near a timezone-offset boundary: the seconds split truncated toward zero, sotimezoneOffset()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:
Int64 overflow (
UTCTimestampTransform). TheDateTime64branch reconstructed the result astime_val * scale_multiplier + microsinInt64. For an underlying value nearInt64::max/Int64::minthe scale multiply (and, for scale 0, the timezone-offset add/subtract) overflowsInt64, which UBSan flags:The offset adjust and scale multiply/add are now done in
Int128and clamped to theInt64range. TheDateTime(32-bit) branch already clamps viasafe_add/safe_subtract; this brings theDateTime64branch to parity.Wrong offset for negative fractional values (
UTCTimestampTransform).seconds = value / scale_multipliertruncates toward zero, so for a negative fractional valuesecondsis the ceil second andmicrosis 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')returned00:59:59.999(used-05:00) instead of01:59:59.999(-04:00, the offset of the floor second). Fixed by flooring the split (stepsecondsdown and addscale_multipliertomicroswhen the remainder is negative), preservingseconds * scale_multiplier + micros == value.Same split bug in
DateTime64->Time64(FunctionsConversion.h). ThetoTime64path did the identical truncated split beforetimezoneOffset. Example: the UTC instant1969-04-27 06:59:59.999stored asDateTime64(3, 'America/New_York')gavetoTime64=02:59:59.999(-04:00) instead of01:59:59.999(-05:00). Fixed with the same floor normalization.Output-scale-dependent variant of (3), same path. The floor split ran after the value was rescaled to the target
Time64scale. 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 seesfraction == 0and the offset lookup is wrong again. Example: the case above at output scale 0 or 2 returned03:00:00instead of01: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_overflowcovers all of the above: it trips UBSan without the overflow fix and passes with it (near-Int64::max/minvalues 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 thetoUTCTimestamp/fromUTCTimestampandtoTime64paths, includingtoTime64output scales below and above the source scale.Version info
26.8.1.449(included in26.8and later)