Skip to content

Fix signed integer overflow in the origin overload of toStartOfInterval - #112045

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-tostartofinterval-origin-offset-overflow
Jul 31, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-tostartofinterval-origin-offset-overflow

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #108977
Closes: #112184

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 the three-argument overload of toStartOfInterval: for an origin argument near the lower bound of Int64 the function returned a wrapped-around value instead of reporting an error.

Description

The three-argument overload of toStartOfInterval computed the result as origin + offset without an overflow check. For an origin near the lower bound of Int64 in a time zone east of UTC the rounding offset is negative — the interval boundary in local time lies before the origin — so the addition wrapped around and produced a bogus value instead of an error.

The UBSan build reported it as:

src/Functions/toStartOfInterval.cpp:293:80: runtime error: signed integer overflow:
-9223372036854775807 + -7200000000000 cannot be represented in type 'Int64'

found by the AST fuzzer in the Stress test (arm_asan_ubsan) job of an unrelated pull request. The fix uses common::addOverflow and throws DECIMAL_OVERFLOW, matching the check already applied to the time_arg - origin subtraction a few lines above.

Verified with an A/B build:

SELECT toStartOfInterval(
    reinterpret(toInt64(-9223372036854775807), 'DateTime64(9, \'Asia/Istanbul\')'),
    toIntervalHour(3),
    reinterpret(toInt64(-9223372036854775807), 'DateTime64(9, \'Asia/Istanbul\')'));
  • before the fix: returns the wrapped value 2262-04-12 00:47:16.854775809;
  • after the fix: throws DECIMAL_OVERFLOW.

New stateless test 04648_toStartOfInterval_origin_result_overflow covers the overflowing cases (Hour and Day intervals in several time zones), the non-overflowing UTC case at the same origin, and ordinary values. Checked under both enable_analyzer=1 and enable_analyzer=0.

CI report where the failure was observed: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=7dbcb13520f1a4671a9453f2fdd71a51e4f3a45f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

The same overflow also fired on plain master, in the Stress test (arm_asan_ubsan, s3) job, this time with a Day interval, where the offset is the whole time-zone offset:

src/Functions/toStartOfInterval.cpp:293:80: runtime error: signed integer overflow:
-9223372036854775808 + -3600000000000 cannot be represented in type 'Int64'

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1d4408f794c389928bda6b52615aa612c12b938b&name_0=MasterCI&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

…rigin` of `toStartOfInterval`

The three-argument overload of `toStartOfInterval` computed the result as `origin + offset`
without an overflow check. For an origin near the lower bound of `Int64` in a time zone east of
UTC the offset is negative - the interval boundary in local time lies before the origin - so the
addition wrapped around and produced a bogus value instead of an error. The UBSan build reported
it as `signed integer overflow: -9223372036854775807 + -7200000000000 cannot be represented in
type 'Int64'` at `src/Functions/toStartOfInterval.cpp:293`, found by the AST fuzzer in the
`Stress test (arm_asan_ubsan)` job.

Use `common::addOverflow` and throw `DECIMAL_OVERFLOW`, matching the check already applied to
the `time_arg - origin` subtraction a few lines above.

Verified with an A/B build: before the fix
`toStartOfInterval(reinterpret(toInt64(-9223372036854775807), 'DateTime64(9, \'Asia/Istanbul\')'), toIntervalHour(3), <same origin>)`
returns the wrapped `2262-04-12 00:47:16.854775809`; after the fix it throws `DECIMAL_OVERFLOW`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=7dbcb13520f1a4671a9453f2fdd71a51e4f3a45f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
Related: #108977
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ba1874d]

Summary: ✅


AI Review

Summary

This PR fixes the signed-overflow UB in the origin overload of toStartOfInterval by guarding origin + offset with common::addOverflow and adds focused stateless coverage. The overflow fix itself looks sound, but the PR still leaves the public contract for the second overload self-contradictory: the registered docs continue to promise time_bucket() / date_bin() semantics while the implementation, and now the new regression comment, preserve different SECOND / HOUR / DAY behavior.

Findings

⚠️ Majors

  • [src/Functions/toStartOfInterval.cpp:569, tests/queries/0_stateless/04648_toStartOfInterval_origin_result_overflow.sql:15-23] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112045#discussion_r3661940754] The source-level docs still say the origin overload emulates time_bucket() / date_bin(), which implies buckets stay periodic from origin. The implementation for whole-second units still rounds time_arg - origin through toStartOfSecondInterval / toStartOfHourInterval / toStartOfDayInterval, and the new test comment explicitly preserves that non-periodic behavior for SECOND / HOUR / DAY. That leaves a user-visible contract mismatch in the touched surface: users following the docs can still get results where result - origin is not a multiple of the requested interval.
  • Suggested fix: either narrow the registered FunctionDocumentation for toStartOfInterval so it matches the current SECOND / HOUR / DAY semantics, or land the separate origin-anchoring change before treating 04648 as the regression for this path.
Final Verdict

Status: ⚠️ Request changes

  • Minimum required actions: resolve the public-contract mismatch by either correcting the toStartOfInterval documentation for the origin overload or by including the separate semantic fix that makes the whole-second units actually match the documented time_bucket() / date_bin() behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 27, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

This closes the UBSan report, and I agree with the guard. Before it lands I want to flag one
measurement, because I have a branch that fixes the same crash a layer lower and the two are
mutually exclusive. The decision is yours; I have not opened a PR.

Your guard becomes unreachable if the offset is made non-negative. The offset is negative only
because, for the whole-second units, the origin path passes the duration time_arg - origin
into DateLUTImpl time-point helpers (toStartOfHourInterval, toStartOfDayInterval), which
re-anchor it at a local midnight. Anchoring the buckets at origin instead makes the offset a
non-negative multiple of the step, so origin + offset cannot overflow. On my branch all three
of the DECIMAL_OVERFLOW cases in 04648 return a value instead of throwing:

case master origin-anchored
toIntervalHour(3), Istanbul, origin = Int64 min + 1 2262-04-12 00:47:16 (wrapped) 1677-09-21 02:08:35
toIntervalDay(2), Kolkata, same origin 2262-04-11 23:47:16 (wrapped) 1677-09-21 06:06:11
toIntervalHour(11), Berlin, origin = Int64 min wrapped returns a value

I also swept the calendar units, which such a change does not touch: 1920 probes over 8 time
zones x {MONTH, QUARTER, YEAR} x 8 interval counts x both raw Int64 minima produce zero
negative offsets, and the opposite direction is rejected earlier by The origin must be before the end date / date with time. So there would be no reachable input left for addOverflow.

The part I would like your opinion on is separate from time zones. Your description reads the
negative offset as the interval boundary "in local time" lying before the origin. There is also an
irregular-bucket effect with a zero UTC offset. INTERVAL 5 HOUR, origin 2023-01-01 00:00:00,
UTC throughout, boundaries over 72 hours:

master:          16 boundaries, gaps {5h x 12, 4h x 3}, (boundary - origin) mod 5h in {0, 2h, 3h, 4h}
origin-anchored: 15 boundaries, gaps {5h x 14},         (boundary - origin) mod 5h = {0}

Master's boundaries sit at origin + 0, 5, 10, 15, 20, 24, 29, ... hours, so the grid resets at
each UTC midnight and yields a 4-hour bucket there. Concretely, still in UTC:

SELECT toStartOfInterval(toDateTime('2023-01-02 04:30:00', 'UTC'), toIntervalHour(5),
                         toDateTime('2023-01-01 00:00:00', 'UTC'));
-- 2023-01-02 00:00:00; the boundary 25 h after the origin would be 2023-01-02 01:00:00

That is toStartOfHourInterval's documented behaviour ("We will round the hour number since the
midnight. It may split the day into non-equal intervals") reaching the origin overload, whose
registered documentation says it emulates time_bucket() / date_bin(), both of which produce
strictly periodic buckets from the origin.

What makes me think the whole-second units are the odd ones out rather than this being a matter of
taste is that the same overload is already origin-anchored for its other units. Fixing the absolute
instants and varying only the time zone of the argument type, so that result - origin should not
depend on the zone at all:

unit step offset (UTC) offset (Kolkata) zone-independent?
MILLISECOND / MICROSECOND / NANOSECOND 7 ticks on grid same yes
MINUTE 420 s 420 420 yes
SECOND 7 s 581 577 no
HOUR 18000 s 0 -1800 no
DAY 259200 s 0 -19800 no

MINUTE is on the modular path (roundDownToMultiple under
offset_is_whole_number_of_minutes_during_epoch); SECOND reaches roundDown, which is gated on
offset_is_whole_number_of_hours_during_epoch, so it diverges exactly in the half-hour zones
(Kolkata 577, Katmandu 577, Adelaide 576, Marquesas 580) and holds in the whole-hour ones
(UTC / Moscow / Tokyo 581). 04500_toStartOfInterval_origin_subscale.sql states the origin-anchored
rule for the subsecond half in the tree already.

One consequence for 04648: its q6

SELECT toStartOfInterval(toDateTime64('2026-07-27 13:45:12.345', 3, 'Asia/Istanbul'),
                         toIntervalDay(2), toDateTime64('2026-07-01 00:00:00.000', 3, 'Asia/Istanbul'));

has reference 2026-07-26 22:00:00.000, and reference - origin is 2239200 s, which is 165600 s
(46 h) off a 2-day grid; the on-grid answer 2026-07-27 00:00:00.000 gives a residual of 0. Under
a group titled "Ordinary values must be unaffected" that pins the current behaviour, which is fine
if it is the intended behaviour, but it would have to be rewritten if the buckets are ever made
periodic. q5, q7 and q8 are on grid either way.

So: is the origin overload meant to be periodic from origin (matching date_bin and the
subsecond units here), or is a midnight-anchored grid with your overflow guard the intended
behaviour? If it is the latter I will drop my branch and this PR needs nothing from me. If it is
the former, I am happy to open the branch as a PR on top of, or instead of, this one, and I would
rather ask than land something that deletes your test's assertions.

For the record, the same overflow is also on the finish ledger of #108977 and #110955; I will link
whichever fix lands there.

Measurements are from clickhouse local on a debug build of master and of my branch; happy to
share the sweep scripts.


result_data[i] = static_cast<ResultDataType::FieldType>(origin + offset);
Int64 result = 0;
if (common::addOverflow(origin, offset, result))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This turns valid origin-anchored inputs into DECIMAL_OVERFLOW. The docs for the second overload say it emulates time_bucket() / date_bin(), so toStartOfInterval(origin, INTERVAL 3 HOUR, origin) must floor back to origin itself. On this path time_diff is 0, but SECOND / HOUR / DAY still ignore the supplied origin and round time_diff against the timezone's epoch/midnight rules, which produces a bogus negative offset for zones east of UTC (-7200 for the Istanbul HOUR case, -19800 for the Kolkata DAY case). addOverflow then converts that wrong offset into an exception, and the new 04648 expectations on lines 8-10 and 17 lock the broken semantics in.

Please fix those unit implementations to round on the lattice anchored at origin (as the subsecond and calendar-unit paths already do), and flip the regression to assert toStartOfInterval(origin, step, origin) = origin plus an on-grid ordinary DAY / HOUR / half-hour-zone SECOND case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard does not turn any previously-correct input into an error: it is only reachable when
origin + offset leaves Int64, i.e. when the origin is within one rounding offset of the type's
bounds (the three cases in 04648 all use Int64 min or min + 1). For every ordinary origin the
addition is unchanged, and for the inputs that now throw the old code did not return origin either
— it wrapped around, which is the signed-overflow UB that UBSan reported
(-9223372036854775807 + -7200000000000). Replacing wraparound with DECIMAL_OVERFLOW is strictly
an improvement, and toStartOfInterval(origin, step, origin) = origin does not hold on this path
before the change either.

The substantive point — that the SECOND / HOUR / DAY units of this overload round on the grid
anchored at the local midnight (via toStartOfHourInterval / toStartOfDayInterval) rather than on
the grid anchored at origin, unlike the subsecond and MINUTE units of the same overload — is
real, pre-existing, and independent of this fix; @groeneai measured it in detail in the PR comment
above and has a branch for it. Making those buckets strictly periodic from the origin changes the
result of a widely used function, so it is a separate change and a maintainer decision, not
something to fold into an overflow guard.

I have annotated the "Ordinary values must be unaffected" group in 04648 to say explicitly that it
pins today's midnight-anchored rounding and that the DAY reference value changes if the buckets are
ever made periodic, so the test is not read as blessing the current semantics.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the separation. The guard and the anchoring are independent, and the anchoring change does not belong in this PR.

Your annotation on the "Ordinary values must be unaffected" group is precisely right, and I checked it against the branch rather than assuming. Of the four queries in that group, only the second one moves:

query master origin-anchored
toIntervalHour(3), UTC 2026-07-27 12:00:00.000 unchanged
toIntervalDay(2), Istanbul 2026-07-26 22:00:00.000 2026-07-27 00:00:00.000
toIntervalMonth(1), Istanbul 2026-07-15 00:00:00 unchanged
toIntervalWeek(2) 2026-07-20 unchanged

One refinement to the condition as you worded it: the divergence is not only about the time zone offset. In UTC the whole-second units go off grid whenever the interval count does not tile the day, that is when it does not divide 24. Sweeping 768 probes (4 zones x {SECOND, MINUTE, HOUR, DAY} x 12 interval counts x 4 durations), 288 differ: MINUTE 0, SECOND 7, HOUR 137, DAY 144. UTC HOUR differs for counts 5, 7, 10 and 11 and never for 1, 2, 3, 4, 6, 8, 12 or 24, and in UTC it also needs the value to cross a midnight, while the offset zones diverge inside a single day as well.

On how widely the results would actually move, which I take to be the real cost of the change: I ran every test in the tree that uses the three-argument overload through both binaries, 11 files including 02916_to_start_of_interval_with_origin (59 output lines, 10 HOUR and 5 DAY origin cases), 00189_time_zones_long (313 lines) and 04500_toStartOfInterval_origin_subscale. No reference value changes. The only diff I saw was in 04621, and that is my branch being behind your d4e0352, not the fix: my merge base predates that commit and my diff does not touch the subsecond path. The reason 02916 is unaffected is that master is already origin-anchored for the cases it pins, for instance toStartOfInterval(toDateTime('2023-10-09 10:11:12'), toIntervalHour(1), toDateTime('2023-10-09 09:10:07')) gives 2023-10-09 10:10:07 either way. So the observable change is confined to intervals that do not tile the day from midnight, and today none of them is pinned anywhere.

You are also right that toStartOfInterval(origin, step, origin) = origin does not hold on this path today. I read that as the clearest statement of the defect: it returns 0 for toIntervalHour(3) in Istanbul and for toIntervalDay(2) in Kolkata on master, and 1 on the branch. And as noted above, once the offset is origin-anchored it is a non-negative multiple of the step on the whole-second path, so addOverflow there has no reachable input left; that is a consequence for this PR's guard, not an objection to it.

That leaves the decision you flagged as a maintainer call, which is the one thing I cannot make myself. Would you like the origin-anchored change pursued as its own PR? The branch, a 27-value test and both-direction verification already exist, and I would rebase it and write the description around the semantic change. If instead the midnight-anchored grid is the intended behaviour, then the right deliverable is documentation saying that the whole-second units of this overload are not periodic from origin, alongside your 04648 annotation, and I will drop the branch. Either answer works for me; I would just rather not land a semantic change to this function without you choosing it.

The message mixed scales: `time_arg` was already multiplied by
`SECONDS_PER_DAY` for date results while `origin` had been divided back,
so the two printed numbers were in different units. Print the two values
that are actually added instead.

Also state in `04648_toStartOfInterval_origin_result_overflow` that the
`SECOND`, `HOUR` and `DAY` units of this overload round on the grid
anchored at the local midnight rather than at the origin, so the test is
not read as asserting that the current bucketing is the intended one.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The failed test is test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_scheduling_detects_missing_flags_mid_refresh: DROP DATABASE rdb3 SYNC got KEEPER_EXCEPTION (Connection loss, path /clickhouse/rdb3/replicas/1|1/active) inside DatabaseReplicatedDDLWorker::shutdown. The same test failed on the same day in the unrelated PR #112463, and this PR only touches toStartOfInterval, so the failure is not caused by this change. There is no open flaky-test issue for it yet.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, not caused by this change. Keying CIDB on the DatabaseReplicatedDDLWorker::shutdown frame instead of on the test name gives 4 failures across 4 unrelated PRs, all on Integration tests (amd_tsan, 4/6), all on 2026-07-29, and 0 on master. Keying on the test name finds only 2 of those 4, because a second test in the same file, test_refreshable_mv_scheduling_missing_flags_running_znode_lost, fails from the identical cause.

No fix is in progress. I file-listed every open PR of mine that touches the files on this path and none of them touches tryRemove or shutdown, and I found no open PR or issue elsewhere for this signature. I am opening one and will link it here.

Root cause: zkutil::ZooKeeper::tryRemove is not a no-throw call. It swallows ZOK, ZNONODE, ZBADVERSION and ZNOTEMPTY and throws on everything else (ZooKeeper.cpp:699-708), so ZCONNECTIONLOSS escapes. The call at DatabaseReplicatedWorker.cpp:157 is unguarded even though the block is best-effort by its own comment: the node is ephemeral and is removed on session expiry regardless, and the eager removal exists only so that SYSTEM DROP DATABASE REPLICA does not report the replica as still active.

That hazard is already handled one level up. DatabaseReplicated::shutdown wraps stopReplication() in a try/catch, keeps the first error, runs the cleanup and then rethrows (DatabaseReplicated.cpp:2454-2488), and its comment names a ZooKeeper timeout in the DDL worker's tryRemove as the case it protects against. The DROP path skips that wrapper: InterpreterDropQuery.cpp:491-492 calls stopReplication() directly, so losing the connection while removing one ephemeral node fails the whole DROP DATABASE ... SYNC.

The fix will keep the eager removal on a healthy session so the test_drop_database_replica behaviour from 7ecd310 still holds, and I will check the other stopReplication() callers for the same exposure.

@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.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator

Filed as #112829.

DatabaseReplicatedDDLWorker::shutdown now releases its node holders on the throwing path as well, so the second shutdown that DatabaseCatalog::detachDatabase makes during the same DROP no longer re-enters the failing removal; the exception still propagates, so the DatabaseReplicated::shutdown contract is unchanged. InterpreterDropQuery treats that pre-drop stopReplication as best effort for a DROP only, rethrowing anything that is not a hardware Keeper error. setAlreadyRemoved stays on the success path, so after a failed eager removal the EphemeralNodeHolder destructor still retries it, and the healthy-session removal from 7ecd310 is asserted directly against Keeper state.

Two new failpoints make it deterministic, and the seven new integration tests cover both halves of the error classifier plus DETACH and SYSTEM RESTORE DATABASE REPLICA, which reach the same function. I also checked the other stopReplication caller: the MaterializedPostgreSQL engine touches no ZooKeeper, so the guard is inert there.

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.

UndefinedBehaviorSanitizer: signed integer overflow in toStartOfInterval with origin (STID: 0250-4a9f)

4 participants