Skip to content

Fix signed integer overflow in toStartOfSubsecondInterval when rounding near INT64_MIN - #111370

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix/tostartofsubsecondinterval-mul-overflow
Jul 26, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix/tostartofsubsecondinterval-mul-overflow

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

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 a signed integer overflow in toStartOfInterval with subsecond intervals: for DateTime64 values within one interval of the lower bound of Int64, the rounded result silently wrapped to a positive garbage value; now the function throws a DECIMAL_OVERFLOW exception.

In toStartOfSubsecondInterval, the negative-value branches for equal scales and for a value scale smaller than the interval scale computed ((t + 1) / num_units - 1) * num_units without an overflow check, so for values within one interval of INT64_MIN the multiplication wrapped to a positive value (undefined behavior reported by the UBSan build at DateTimeTransforms.h:623). The scale_multiplier > unit_scale branch already guarded the same multiplication with mulOverflow (added in #101032); this applies the same guard to the other two branches, so all three throw DECIMAL_OVERFLOW consistently. This is the incomplete-fix case described in the linked issue.

Found by the AST fuzzer in a stress test run on #97032:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97032&sha=815fbc65e060728ae528de8baab6cf23e00ebe90&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

Closes: #101096
Related: #101032
Related: #97032

Version info

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

…ng near INT64_MIN

In toStartOfSubsecondInterval, the negative-value branches for equal scales
and for a value scale smaller than the interval scale computed
((t + 1) / num_units - 1) * num_units without an overflow check, so for
values within one interval of INT64_MIN the multiplication wrapped to a
positive garbage value (undefined behavior caught by the UBSan build in
DateTimeTransforms.h:623). The scale_multiplier > unit_scale branch already
guarded the same multiplication with mulOverflow; now all three branches
throw DECIMAL_OVERFLOW consistently.

Found by the AST fuzzer in a stress test run:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97032&sha=815fbc65e060728ae528de8baab6cf23e00ebe90&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
(on #97032)
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3116798]

Summary: ✅


AI Review

Summary

This PR closes the remaining signed-overflow cases in toStartOfSubsecondInterval near INT64_MIN and adds focused regression coverage for both the default and origin overloads. I reviewed the current diff, the existing discussion, and the live code paths in toStartOfInterval; the earlier review concern is addressed in the current head, and I did not find any remaining correctness issue in the changed logic.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
@yariks5s yariks5s self-assigned this Jul 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only completed red job, Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6), has two failures unrelated to this PR (which only touches toStartOfSubsecondInterval in src/Functions/DateTimeTransforms.h), both passed on retry (retry_ok):

@groeneai, investigate the failure of test_s3_table_functions/test.py::test_s3_table_functions_timeouts in the report above and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix PR is currently open for test_s3_table_functions/test.py::test_s3_table_functions_timeouts, so I will investigate it and provide a fix in a separate PR, then follow up here with the link (or my findings if it is not actionable).

@groeneai

Copy link
Copy Markdown
Collaborator

Fix in a separate PR: #111506.

Root cause: the test injects a 1200ms network delay and expects the S3 INSERT to time out, but set no explicit S3 timeout. On a fresh connection the adaptive connect timeout (500ms/1000ms) trips reliably, but when the request reuses a pooled keep-alive connection there is no fresh connect, so the only remaining gate is the send/receive idleness timeout (default 3000ms/30000ms, far above 1200ms) and the write completes: the rare DID NOT RAISE. The fix sets s3_request_timeout_ms=500 (with the connect timeout pinned above the delay so the request timeout is the sole mechanism) and asserts the error is a timeout. Reproduced both directions and ran the test 5x.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Both red jobs on commit 3116397 are unrelated to this PR (which only touches toStartOfSubsecondInterval in src/Functions/DateTimeTransforms.h):

Merged master and pushed cc7628b to clear the settings-history red.

Comment thread src/Functions/DateTimeTransforms.h Resolved
The AI review pointed out that the three `origin.has_value()` branches of
`toStartOfSubsecondInterval` subtract the remainder from the (possibly
already scaled) time with a raw signed subtraction.

The concrete examples in the review are not reachable: the only caller,
`FunctionToStartOfInterval`, rejects `origin > time_arg` with
`BAD_ARGUMENTS`, and the remainder of a non-negative difference never
exceeds that difference, so the result is always at least the origin.
Still, the helper should not depend on a precondition enforced by its
caller, so use `common::subOverflow` and throw `DECIMAL_OVERFLOW` there
as well.

Add three-argument regression tests near `INT64_MIN` for all three scale
relations, including the case where the interval start lands exactly on
`INT64_MIN`, and one where scaling the origin up to the interval scale
genuinely overflows and must throw.
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 33/36 (91.67%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 4314fd6 into master Jul 26, 2026
178 of 179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/tostartofsubsecondinterval-mul-overflow branch July 26, 2026 22:06
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 26, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 26, 2026
…ESTORE

A non-APPEND refreshable materialized view is only supported in Atomic and
Replicated databases. CREATE enforced this in validateMaterializedViewColumnsAndEngine,
but the call is gated on mode <= CREATE, so a full-definition ATTACH (mode ATTACH) and
a RESTORE that remaps the view into another database (SECONDARY_CREATE with
is_restore_from_backup) bypassed the check. In a Memory database the view then got a
Nil StorageID UUID, and its refresh (CREATE OR REPLACE of the temp inner table into a
Replicated-db target) wrote the Nil into DDLLogEntry.parent_table_uuid, so
checkParentTableExists(Nil) -> DatabaseCatalog::tryGetByUUID(Nil) tripped
chassert(uuid != Nil && ...) (abort in debug/sanitizer; in release the refresh instead
failed permanently with TABLE_IS_DROPPED "Parent table doesn't exist").

Hoist the engine check out of validateMaterializedViewColumnsAndEngine into createTable,
gated on is_fresh_definition = mode <= CREATE || (mode == ATTACH && !attach_short_syntax)
|| is_restore_from_backup, mirroring the existing is_fresh_definition predicate in
registerStorageMergeTree.cpp. Stored definitions (short ATTACH, ATTACH DATABASE, restart)
and plain Replicated-DDL replay stay exempt; fresh full-definition ATTACH and
RESTORE-with-remap are validated like CREATE. Also add a fail-close Nil guard in
checkParentTableExists (return false, mirroring the existing guard in
getRMVCoordinationInfo) so metadata written by older binaries loads and its refresh
fails cleanly instead of aborting.

Found by BuzzHouse (arm_asan_ubsan on PR ClickHouse#111370, amd_msan on PR ClickHouse#109454; both
unrelated to this code path).

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

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.

toStartOfInterval returns wrong positive result for negative timestamps near INT64_MIN (incomplete fix from #101032)

4 participants