Repository navigation
Fix signed integer overflow in refreshable materialized view RANDOMIZE FOR - #113673
PedroTadim merged 6 commits into
Conversation
RANDOMIZE FOR accepts an unbounded UInt64 and the random factor is a signed Int64, but RefreshSchedule::addRandomSpread computed the random offset in double and then pushed it through three unchecked domains in one expression: the double to Int64 conversion, the milliseconds to microseconds widening, and the time_point addition. system_clock::duration is microseconds, so a representable milliseconds value is not automatically safe, and each of the three has its own threshold and its own frame. Compute the offset in Int128, the narrowest width that holds the widest possible product of the two unbounded operands (UInt64_MAX * Int64_MIN fits with 2^63 to spare; after the division the final sum has a factor of 2000), then saturate the result strictly inside the time_point range. Strictly inside matters because time_point::max() is the "no refresh scheduled" sentinel; producing it would make a view read as waiting indefinitely. Operand order is load-bearing: dividing before scaling back up is what keeps the product inside Int128, whereas the naive order overflows it. The same change covers the coordination znode, which deserializes the random factor with no range check, so any Int64 a znode holds reaches this function rather than only the range the scheduler draws from. This is not exactly behaviour-preserving. The intermediate product leaves the exact range of double above a spread of about five hours, and above about 100 days that rounding changes the result the old path returned; the Int128 form returns the exact value instead, a difference of a few milliseconds (measured bound 4 ms) in a deliberately randomized jitter. The changelog entry says so rather than describing the change as a no-op. Two adjacent overflows in the same subsystem are deliberately left alone and tracked separately: CalendarTimeInterval's own arithmetic, whose months field wraps, and the delay this schedule hands to BackgroundSchedulePool. The stateless test has one arm per domain plus a control with an ordinary spread, and a sign-independent oracle, since the random factor is drawn over both signs and a wide window legitimately yields a past-due instant. Only a positive draw overflows in the third domain, so that arm is probabilistic and uses enough views to make a miss negligible; the deterministic pin for that domain is in the gtest, which drives the addition to both ends of the range with a fixed randomness. The gtest also covers what the stateless test cannot see: two of the guards fail inside the wide-integer arithmetic, where the sanitizer emits no check and the result is silently wrong rather than aborting.
Internal second-model review (click to expand)Two review rounds, each with an independent second-model pass over the whole change. Six findings
|
Pre-PR validation gate (click to expand)
Five mutants of the fix were built, each with its own build id, and each reddens at least one test: Session id: cron:clickhouse-review-slot-48:20260806-123800 |
|
cc @al13n321 @tuanpach, could you review this? RANDOMIZE FOR takes an unbounded UInt64 and the random factor is a signed Int64, so addRandomSpread had three unchecked domains in one expression, the double to Int64 conversion, the milliseconds to microseconds widening and the time_point addition, each of which aborts a sanitizer build; the offset is now computed in Int128 and saturated strictly inside the time_point range, which also corrects a few-millisecond rounding error for windows wider than about 100 days. |
|
Workflow [PR], commit [71dcb49] Summary: ✅
AI ReviewSummaryThe PR fixes overflow from very large Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 6 s compile time in total, 6 of them have a recent master baseline. |
Every arm of 04757 passed a window expressed in seconds, so `months` was zero in all of them and the months term of CalendarTimeInterval::minSeconds was never exercised. Add a YEAR and a MONTH arm to the stateless test, and months-only cases to the unit test. The stateless arms are deterministic rather than probabilistic like arm C: escaping the milliseconds-to-microseconds widening pre-fix needs |randomness| <= 1015 for the YEAR arm and <= 6044 for the MONTH arm, out of the 1e9 the scheduler draws. Measured on a pristine ASan+UBSan master build, each arm run alone aborts at RefreshSchedule.cpp:73:51, and both are clean on the fixed build. The unit cases are what pin the calendar term itself: with only the existing seconds-based cases, replacing spread.minSeconds with spread.seconds inside addRandomSpread left every assertion passing in both tests. Their windows (1, 12 and 24 months) do not wrap in minSeconds, so the expected offsets are exact. Verified against that mutant: it fails only the new unit case. Also add the atomic-database tag. Every view here is non-APPEND with a Memory target, and in a Replicated database StorageMaterializedView forces refresh_coordinated and then refuses that combination, so the test cannot pass under --replicated-database. The runner only acts on the tag when the database engine is not Atomic, so no passing run is skipped, and the sibling refreshable-view tests already carry it. The wrap in the unsigned calendar conversion itself is pre-existing and out of scope: CalendarTimeInterval.cpp is byte-identical between this branch and master, and an input whose wrap does collapse the window to a small value schedules identically on both.
CI finish ledger - 5ce7325Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: 175/175 check-runs completed, 157 success / 17 skipped,
Not caused by this PR. The diff is confined to The three failing rows are one server abort, not three defects: the Session id: cron:our-pr-ci-monitor:20260807-153000 |
| @@ -0,0 +1,117 @@ | |||
| #include <gtest/gtest.h> | |||
|
|
|||
| #include <Storages/MaterializedView/RefreshSchedule.h> | |||
There was a problem hiding this comment.
@groeneai this gtest is not needed, when you have sql ones
There was a problem hiding this comment.
Deleted in cccc9d8.
It was there because the shell test only asserted the server stayed up, which cannot pin a
one-sided overflow. Reading next_refresh_time back from system.view_refreshes makes the shell
test a value oracle instead, so the gtest is redundant. Concretely: mutating spread.minSeconds()
to the bare spread.seconds field passed both the old shell arms and the old gtest, and fails the
new assertion 4 of 4.
Two things the gtest pinned are not reachable from SQL and are now uncovered: the exact ordinary
offset (still bounded by 02932's <29: randomize>) and the full Int64 factors the coordination
znode accepts, which the scheduler's own draw cannot reach. Say the word if you want either back.
| # Arms E and F: a calendar-unit window reaches the offset through the months term of | ||
| # CalendarTimeInterval::minSeconds instead of its seconds term, which every arm above uses. | ||
| # Deterministic pre-fix: escaping needs |randomness| <= 1015 (E) or <= 6044 (F) out of 1e9. | ||
| $CLICKHOUSE_CLIENT -q " |
There was a problem hiding this comment.
@groeneai, this test is too long, can you trim it to just one RMV with randomization in milliseconds?
There was a problem hiding this comment.
Trimmed to two views in cccc9d8, 42s to 7s.
Two rather than one because the window reaches the offset through two different terms of
CalendarTimeInterval::minSeconds: seconds for a clock unit, months for a calendar one. One
view covers only its own term.
Milliseconds are rejected before they get there: RANDOMIZE FOR 1000 MILLISECOND is
Code: 36 ... Sub-second intervals are not supported here (CalendarTimeInterval.cpp:22), so
SECOND is the finest unit that parses.
Thirty views were only needed because the old assertion was liveness, so one view caught a one-sided
overflow half the time. The assertion now reads the value back, and a single view aborts on every
run pre-fix rather than half of them.
The stateless test asserted only that the server stayed up, so it needed thirty views to make one of its three domains abort with high probability, and the deterministic pin for that domain lived in a gtest. Reading next_refresh_time back from system.view_refreshes turns the shell test into a value oracle instead. A window wide enough to saturate makes the assertion hold for every random factor the scheduler can draw except a vanishing few, so one view per term of CalendarTimeInterval::minSeconds covers the arithmetic and the gtest is redundant. Measured on the pre-fix snapshot, a single view aborts on every run rather than half of them: the offset leaves the representable range for all but |randomness| <= 1844 out of 1e9. The value oracle is also stronger than the liveness one it replaces, since replacing minSeconds() with the bare seconds field passes the old arms and fails this one. The assertion is against the two constants the saturated ends reduce to, not a wall-clock date that would have expired in 2034, and the wait for the background scheduler polls for those constants rather than for any non-NULL value, since the column holds the epoch until scheduling runs. Runtime drops from about 42s to about 7s.
CI finish ledger - cccc9d8Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: 175/175 check-runs completed, 157 success / 17 skipped,
Not caused by this PR. The diff is This PR's own test Session id: cron:our-pr-ci-monitor:20260809-040000 |
|
🕵️ Holding this one. The saturation direction is wrong at the low end and my test does not catch it.
So this trades a view that hangs forever for one that spins forever, which is worse for a typo in My reference constant Three ways out, and I would rather agree the shape before pushing again:
I lean towards 2 with 1 as the fallback for already-attached views. Separately, the |
|
Not worth fixing |
|
Understood, and I will not reopen this or refile it elsewhere. One question, because it governs more than this PR. The sibling #113007 came out of a real CI hit, a UBSan signed overflow in the refresh scheduler on a BuzzHouse arm_asan_ubsan run of an unrelated PR, so a sanitizer build will keep aborting there whenever a fuzzer reaches those magnitudes. Is the ruling that UBSan-reachable arithmetic overflow in cold paths like this is not worth changing code for at all, or that these two fixes were not shaped the way you want? If it is the former I will stop opening PRs for that class and treat future occurrences of it as not actionable. |
|
We have to fix this |
|
@groeneai 🕵️ The
|
Clamping the resulting time_point to the Int64 range left both ends meaningless: a negative draw landed ~292,000 years in the past, so the view refreshed immediately, and a positive one never refreshed, and both handed a ~292,000-year delay to BackgroundSchedulePool::scheduleAfter. Cap |offset| at 3e9 seconds (about 95 years, the same bound as the retry backoff in ClickHouse#113007), so an absurd RANDOMIZE FOR behaves like the widest supported jitter and the scheduled instant stays near its timeslot. Build a std::chrono::milliseconds and let chrono convert it to system_clock::duration instead of assuming microseconds. The test now uses REFRESH EVERY 200 YEAR, whose first timeslot is 2170-01-01, so both signs of the capped offset stay in the future: it asserts the view is Scheduled without refreshing and that next_refresh_time is exactly the timeslot plus or minus the cap. Under the previous clamp it saw a saturated end, and on master the out-of-range conversion. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, done in 4370179 (description updated to match): 1-2. Left as is: a period within 95 years of the |
CI finish ledger - 4370179Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261022-003004 |
Backport #113673 to 26.9: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
Backport #113673 to 26.10: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
Backport #113673 to 26.8: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
…materialized view `RANDOMIZE FOR`
…materialized view `RANDOMIZE FOR`
… materialized view `RANDOMIZE FOR`
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix undefined behavior when a refreshable materialized view uses a very large
RANDOMIZE FORwindow. The random offset was converted fromdoubletoInt64milliseconds and widened to microseconds without range checks, so such a window produced a meaningless next refresh time or aborted a sanitizer build. The offset is now capped at about 95 years, so an absurd window behaves like the widest supported jitter.Description
Related: #113007
On 26.8,
REFRESH EVERY 1 HOUR RANDOMIZE FOR 10000000000000000000 SECONDcomputes the offset ofRefreshSchedule::addRandomSpreadthrough an out-of-rangedoubletoInt64conversion: the release build (26.8.18.2) silently drops the jitter, and an ASan+UBSan build aborts.The offset is computed in
Int128(RANDOMIZE FORis an unboundedUInt64, the factor is up to1e9) and|offset|is capped at3e12ms, the 95-year bound #113007 uses for the retry backoff. The scheduled instant then stays within 95 years of its timeslot, so the delay handed toBackgroundSchedulePool::scheduleAfterstays representable, and aRANDOMIZE FORof less than 190 years is unaffected. Thechronoconversion of the cappedstd::chrono::millisecondsno longer assumessystem_clock::durationis microseconds.The test uses
REFRESH EVERY 200 YEAR, whose first timeslot is 2170-01-01, so both signs of the capped offset stay in the future: it asserts the view isScheduled, has not refreshed, and thatnext_refresh_timeis exactly the timeslot plus or minus the cap (compared modulo 2^32, since the column is aDateTime). It fails on master and on the previous revision of this PR, which clamped the timestamp, and passes 20/20 on both a debug and an ASan+UBSan build.A schedule within 95 years of the
time_pointlimit still overflows the addition, but such a period already overflows withoutRANDOMIZE FORwhen it is converted to atime_point(REFRESH AFTER 9223372036855 SECOND), so that bound belongs to the period.Workflow [PR]
Sync PR [sync-upstream/pr/113673]
Version info
26.11.1.545-master(included in26.11and later)