Skip to content

Fix UBSan signed integer overflow in toStartOfSecond/Millisecond/Microsecond near INT64_MIN - #105482

Merged
al13n321 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-tostartof-subsecond-ubsan-overflow
Jun 19, 2026
Merged

al13n321 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-tostartof-subsecond-ubsan-overflow

Conversation

@groeneai

@groeneai groeneai commented May 21, 2026 •

Copy link
Copy Markdown
Collaborator

Two fixes in toStartOfSecond / toStartOfMillisecond / toStartOfMicrosecond for DateTime64.

  1. UBSan signed integer overflow near INT64_MIN. Each function did datetime64 - fractional_with_sign in signed Int64, which is UB at the boundary. The final subtraction now uses unsigned arithmetic, mirroring the multiplication path fixed in 4154381.

  2. Wrong result for negative pre-epoch values in toStartOfMillisecond / toStartOfMicrosecond. The negative-branch normalization added back a full scale_multiplier instead of the dropped unit (scale_multiplier / 1000 for milliseconds, / 1000000 for microseconds), producing a value off by nearly a full second. For example toStartOfMillisecond(toDateTime64(-123.456789, 6)) returned -124.456000 instead of -123.457000. toStartOfSecond was already correct because its divisor is the full scale_multiplier.

The Time64 overloads in DateTimeTransforms.h are shared template code but are not reachable from SQL: the registered functions use DataTypeDateTime64 and checkArguments rejects Time64 via isDateOrDate32OrDateTimeOrDateTime64. They are corrected for internal consistency only, with no user-visible effect.

Surfaced by the FunctionsStress property fuzzer in Unit tests (asan_ubsan, function_prop_fuzzer) at src/Functions/DateTimeTransforms.h (1 master hit + 3 unrelated PRs in 90 days). Reproduced and verified against an ASan+UBSan build: UBSan no longer fires and negative pre-epoch truncation is correct. Regression test: 04270_toStartOfSubsecond_ubsan_int64_min.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102854&sha=d1d3a9ac7bc28763a2f46268f6fa0918ac096573&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29

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 toStartOfMillisecond and toStartOfMicrosecond returning a result off by nearly a second for negative (pre-epoch) DateTime64 values, and fix UndefinedBehaviorSanitizer signed-integer-overflow in toStartOfSecond, toStartOfMillisecond, and toStartOfMicrosecond for DateTime64 inputs near INT64_MIN.

Documentation entry for user-facing changes

  • Documentation is unchanged.

Version info

  • Merged into: 26.6.1.1032

…osecond near INT64_MIN

`toStartOfSecond`, `toStartOfMillisecond`, and `toStartOfMicrosecond` for
`DateTime64` and `Time64` did `datetime64 - fractional_with_sign` in signed
`Int64`, which triggers UBSan signed-integer-overflow when the input is near
`INT64_MIN`. Use unsigned arithmetic for the final subtraction, matching the
multiplication path already fixed in 4154381.

Surfaced by the `FunctionsStress` property fuzzer at
`src/Functions/DateTimeTransforms.h:954` (1 master hit + 3 unrelated PRs in
the last 90 days).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102854&sha=d1d3a9ac7bc28763a2f46268f6fa0918ac096573&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Session: cron:clickhouse-ci-task-worker:20260520-233000

a) Deterministic repro? Yes. Locally, against build-asan/programs/clickhouse (ASan+UBSan, -DSANITIZE=address,undefined):

clickhouse-local --query "SELECT toStartOfSecond(reinterpret(toInt64(-9223372036854775808), 'DateTime64(3)'))"

fires src/Functions/DateTimeTransforms.h:954:27: runtime error: signed integer overflow: -9223372036854775808 - 192 cannot be represented in type 'long' every single time. Same shape on lines 1017 (toStartOfMillisecond) and 1087 (toStartOfMicrosecond).

b) Root cause explained? getFractionalPartWithScaleMultiplier<DateTime64, true>(datetime64, scale_multiplier) returns datetime64 % scale_multiplier (range [-scale_multiplier+1, scale_multiplier-1]). The if (... < 0) ... += scale_multiplier block shifts it into [0, scale_multiplier-1]. The final return datetime64 - fractional_with_sign; then computes INT64_MIN - p where p > 0 whenever the input has nonzero subsecond part, which is signed overflow UB. The exact pattern was already fixed for the multiplication path of the same three functions in 4154381 (March 2026); this PR applies the identical fix to the subtraction path that commit did not touch.

c) Fix matches root cause? Yes. Replace the signed subtraction with static_cast<DateTime64>(static_cast<UInt64>(datetime64) - static_cast<UInt64>(fractional_with_sign)). Unsigned subtraction is well-defined modulo 2^64 and produces an identical bit pattern to the signed wraparound the existing code unintentionally relied on. For in-range inputs both formulations produce the same value.

d) Test intent preserved? / New tests added? Added tests/queries/0_stateless/04270_toStartOfSubsecond_ubsan_int64_min.sql exercising INT64_MIN reinterpretation for all three functions, plus normal positive and small-negative inputs to lock in the existing semantics. Sibling tests 01269_toStartOfSecond, 03326_toStartOfNanosecond_ubsan, and 03215_toStartOfWeek_with_dateTime64_fix re-run 5x each — all pass unchanged. No assertions were widened.

e) Demonstrated in both directions? Without the fix: UBSan fires immediately on the boundary query above. With the fix: 20/20 --test-runs of the new regression test pass on the rebuilt ASan+UBSan binary; 15/15 cross-runs of the three sibling tests above also pass.

f) Fix is general? Yes. Six call sites have the same *_with_sign -= -then-subtract pattern: three functions × two execute overloads (DateTime64, Time64). All six are patched in this PR. ToStartOfNanosecondImpl does not use this pattern (it uses common::mulIgnoreOverflow on a single multiplication, line 1147) so no change needed there.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @rschu1ze — could you review? Same fix style as 4154381 (the existing unsigned-arithmetic fix for the multiplication path in the same three functions); this PR extends it to the subtraction path that still triggered UBSan near INT64_MIN.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd1e245]

Summary: ✅


AI Review

Summary

This PR fixes DateTime64 subsecond truncation in toStartOfSecond, toStartOfMillisecond, and toStartOfMicrosecond by avoiding signed-overflow UB near INT64_MIN, and also corrects negative pre-epoch millisecond/microsecond rounding to normalize by the dropped unit. The current code addresses the two prior inline review threads, the PR metadata matches the user-visible DateTime64 bug fix, and I found no remaining correctness issues in the changed surface.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 21, 2026
@yariks5s yariks5s self-assigned this May 22, 2026
Comment thread src/Functions/DateTimeTransforms.h Resolved
Comment thread src/Functions/DateTimeTransforms.h Resolved
…crosecond

The negative-value normalization branch added back a full scale_multiplier
instead of the unit that was dropped. getFractionalPartWithScaleMultiplier was
called with scale_multiplier / 1000 (millisecond) or / 1000000 (microsecond),
so the remainder must be normalized by that same divisor, not by the whole
scale_multiplier. Adding the full multiplier shifted negative pre-epoch results
by nearly a full second, e.g. toStartOfMillisecond(toDateTime64(-123.456789, 6))
returned -124.456000 instead of -123.457000.

toStartOfSecond was already correct because its divisor is the full
scale_multiplier. The Time64 overloads are shared template code that is not
reachable from SQL (the registered functions use DataTypeDateTime64 and
checkArguments rejects Time64), but they are corrected here for consistency.

Extends regression test 04270_toStartOfSubsecond_ubsan_int64_min with negative
pre-epoch cases. The INT64_MIN millisecond/microsecond reference values also
change because those inputs hit the same corrected branch.

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

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 4caccaea-88ae-40aa-a970-a1776322f658
  • MIRAI run: 029b8f4a-c284-4d5a-ad95-50adcb8bb954
  • PR check IDs:
    • clickbench_104853_1781865783
    • clickbench_104867_1781865783
    • clickbench_104873_1781865783
    • tpch_adapted_1_official_104880_1781865783
    • tpch_adapted_1_official_104891_1781865783
    • tpch_adapted_1_official_104949_1781865784

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: f4f65c2

CI fully finished on this HEAD: Finish Workflow SUCCESS @ 2026-06-03T16:40:11Z, Mergeable Check SUCCESS, PR aggregator SUCCESS. Zero CIDB FAIL/ERROR rows on this commit. Every Build (amd/arm matrix), Stateless tests, Integration tests, Unit tests (asan_ubsan + tsan + msan + function_prop_fuzzer), AST fuzzer, BuzzHouse, Stress, Performance Comparison, SQLLogic, Compatibility, Install, Docker, Code Review, Fast test, Style — all pass.

Awaiting human re-review from the cc'd reviewers (@ alexey-milovidov, @ rschu1ze) on the unsigned-arithmetic fix for DateTimeTransforms.h (lines 954/965/1017/1039/1087/1109).

Session: cron:our-pr-ci-monitor:20260605-033000

@groeneai groeneai mentioned this pull request Jun 7, 2026
1 task done
@al13n321
al13n321 enabled auto-merge June 19, 2026 00:35
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 11/22 (50.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@al13n321
al13n321 added this pull request to the merge queue Jun 19, 2026
Merged via the queue into ClickHouse:master with commit 6557a74 Jun 19, 2026
166 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 19, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5. 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 added a commit to groeneai/ClickHouse that referenced this pull request Jun 29, 2026
…Time64

The AST fuzzer hit a UBSan signed-integer-overflow on master when an
extreme DateTime64 near INT64_MIN flows into the toStartOf*Interval family
(STID 1421-42cf, Stress test (amd_asan_ubsan)).

toStartOfHourInterval (reached by toStartOfInterval with an N-hour unit,
N > 1) computes the final result as `values.date + time` in signed Int64.
findIndex clamps only the LUT index, not t itself, so for t near INT64_MIN
the raw `time = t - values.date` is hugely negative and `values.date + time`
underflows Int64 -- undefined behavior:

  runtime error: signed integer overflow: -2208988800 + -9223372034645788816
  cannot be represented in type 'long'

The sum is now computed in UInt64 (defined wraparound) and cast back to the
signed type. For every in-range input this is byte-identical to the previous
result; only inputs within a divisor of INT64_MIN -- which have no valid
datetime meaning -- now wrap deterministically instead of invoking UB.

The minute-interval and roundDown fast paths that exhibited the same bug
class were fixed independently on master by the roundDownToMultiple helper
added in PR ClickHouse#107985; this change covers the remaining hour-interval site.
It is the toStartOf*Interval analogue of the subsecond fix in PR ClickHouse#105482
(toStartOfSecond/Millisecond/Microsecond in DateTimeTransforms.h).

The regression test exercises the whole toStartOf*Interval family at the
INT64_MIN boundary so the entire family stays UBSan-clean.

Co-Authored-By: Claude Opus 4.8 <[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 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.

6 participants