Skip to content

Fix signed integer overflow in refreshable materialized view RANDOMIZE FOR - #113673

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-refresh-randomize-for-overflow
Oct 22, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-refresh-randomize-for-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

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 undefined behavior when a refreshable materialized view uses a very large RANDOMIZE FOR window. The random offset was converted from double to Int64 milliseconds 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 SECOND computes the offset of RefreshSchedule::addRandomSpread through an out-of-range double to Int64 conversion: the release build (26.8.18.2) silently drops the jitter, and an ASan+UBSan build aborts.

The offset is computed in Int128 (RANDOMIZE FOR is an unbounded UInt64, the factor is up to 1e9) and |offset| is capped at 3e12 ms, 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 to BackgroundSchedulePool::scheduleAfter stays representable, and a RANDOMIZE FOR of less than 190 years is unaffected. The chrono conversion of the capped std::chrono::milliseconds no longer assumes system_clock::duration is 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 is Scheduled, has not refreshed, and that next_refresh_time is exactly the timeslot plus or minus the cap (compared modulo 2^32, since the column is a DateTime). 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_point limit still overflows the addition, but such a period already overflows without RANDOMIZE FOR when it is converted to a time_point (REFRESH AFTER 9223372036855 SECOND), so that bound belongs to the period.


Workflow [PR]
Sync PR [sync-upstream/pr/113673]

Version info

  • Merged into: 26.11.1.545-master (included in 26.11 and later)

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.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds, each with an independent second-model pass over the whole change. Six findings
across both rounds, three of which changed the PR. No finding was about the fix itself: the
RefreshSchedule.cpp diff is byte-identical to what round one produced.

⚠️ Corrected before publishing

Round one found three countable claims in the PR text that were wrong, each on a sentence carrying
the safety or the honesty argument:

  • Int128 was described as holding the widest product with a factor of 2000 to spare. The true
    relative margin on the product is 5.4e-20 - UInt64_MAX * Int64_MIN sits exactly 2^63 above
    Int128_MIN, so Int128 is the exact minimum width for it. The factor of 2000 belongs to the
    final sum, after the division; That sentence is the justification for the chosen width, so it now states both margins separately.
  • The rounding onset was given as 208 days. Two different thresholds had been merged into one
    number: the intermediate product leaves the exact range of double at about five hours, while
    about 100 days is where that rounding changes the truncated result. The 208-day figure was the
    five-hour threshold multiplied by 1e3, and the text's own adjacent counterexample at 115 days
    contradicted it.
  • The behavioural delta was given as up to one millisecond. Measured bound is 4 ms, with a
    fully-defined, non-saturating 3 ms case (spread 73485847263779, factor 250189397: the old path
    returns 9192689907479486 ms where the exact value is ...483). The widening only requires
    |ms| <= 9.2234e15, where one double ulp is already 2 ms. Since that sentence exists to disclose
    a non-behaviour-preserving change honestly, understating it was the defect.

Round two found two more, both created by round one's own fix: the validation paragraph still claimed
50 runs of the new test after its third arm had been widened from 10 views to 30 (the 50-run
measurement predates that edit; the shipped size has 20 runs, 86.6-96.5 s each), and the changelog
entry still carried the merged 2^53 threshold that had been corrected everywhere else.

❌ Not accepted - the second model's blocker rested on a false premise

It reported that system_clock::duration is nanoseconds on this toolchain, which would make every
jitter 1000x too small and also invalidate the third test arm and the saturated values. Refuted four
ways: contrib/llvm-project/libcxx/include/__chrono/system_clock.h:28 is typedef microseconds duration; the compile line for this translation unit carries -nostdinc++ and includes that
libcxx, so libstdc++ is not visible to it; a probe built with the build's own compiler and includes
reports period = 1/1000000 (the same probe against the default toolchain reports 1/1000000000,
which is where the figure came from); and the measured pre-fix sanitizer report reads
9200000000000000000 + 292248531000000000, which is 9.2e12 seconds times exactly 1e6, emitted
from that libcxx's own duration.h. The existing randomize for 4 day 1 hour assertion in
02932_refreshable_materialized_views_2 also checks the jitter in real seconds and passes, which a
nanosecond representation would break.

💡 Noted, not changed

The saturated instant is outside what system.view_refreshes.next_refresh_time can display, since
that column is a DateTime. This is pre-existing and independent of the overflow: any schedule past
2106 already exceeds the column's range, refresh after 9200000000000 second included. Before this
change those inputs were undefined behaviour, so the change replaces UB with a deterministic value
at that boundary. Widening the column is a separate, user-visible decision.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on an ASAN+UBSAN build with the CI amd_asan_ubsan flags. Three DDLs, one per unchecked domain: REFRESH EVERY 1 YEAR RANDOMIZE FOR 10000000000000000 SECOND (aborts for 99.8% of draws), ... RANDOMIZE FOR 10000000000000000000 SECOND (99.9998%), and REFRESH AFTER 9200000000000 SECOND RANDOMIZE FOR 18000000000000 SECOND. The third is one-sided by construction, since only a positive draw overshoots the range: it aborted 3 of 6 single-view runs, so the shipped arm creates thirty views, leaving a 9.3e-10 chance of no abort, and the deterministic pin for that domain is in the gtest, which drives the addition to both ends of the range with a fixed factor.
b Root cause explained? RANDOMIZE FOR takes an unbounded UInt64 and the random factor is a signed Int64, but RefreshSchedule::addRandomSpread computed the offset in double and then pushed it through three unchecked domains in one expression: the double to Int64 conversion, the milliseconds to microseconds widening (system_clock::duration is microseconds, so a representable millisecond value is not automatically safe), and the time_point addition. Each has its own threshold and its own measured frame.
c Fix matches root cause? Yes. The offset is computed 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, and the final sum with a factor of 2000), then saturated strictly inside the time_point range. No test bound was widened, no randomization was disabled, nothing is guarded at the crash site.
d Test intent preserved / new tests added? No existing test was modified. Added 04757_refreshable_mv_randomize_for_overflow.sh (one arm per domain plus a control with an ordinary spread, and a sign-independent oracle since the factor's sign is random) and gtest_refresh_schedule.cpp (3 tests, 15 assertions on the returned instant).
e Both directions demonstrated? Yes. On a server running unpatched master the new test fails and the server exits 134 with one sanitizer report in addRandomSpread and no unrelated fatal; on the patched build it passes. Re-confirmed for the thirty-view arm: unpatched master aborts on the second view, symbolized operator+ in duration.h:403 under determineNextRefreshTime, one report and no unrelated fatal, and the patched build passes twenty consecutive runs.
f Fix is general across code paths? addRandomSpread is the only place the spread and the random factor meet, and it has exactly one call site, so the retry, schedule and dependency instants it serves are all covered by the one change. minSeconds() appears in four other places, none of which combines it with the random factor. Two adjacent overflows in the same subsystem, in CalendarTimeInterval and in the delay handed to BackgroundSchedulePool, are deliberately out of scope and tracked separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? The gtest covers spreads of 0, ordinary values, the band where the old double path began rounding, 1e19, and UInt64_MAX; random factors of 0, plus and minus 1, half scale, full scale, and both Int64 extremes, which is what the coordination znode can hold since it deserializes the value with no range check; and instants at mid-range and at both ends of the representable range. No type wrappers apply, the operands being plain integers and a time_point.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry, and the diff touches one source file. No serialization or coordination format change, and no DDL is accepted or rejected differently. The only behavioural delta is inside the previously undefined range, plus a rounding correction of up to a few milliseconds (measured bound 4 ms) for windows wider than about 100 days, which the changelog entry states.
i Invariants and contracts preserved? time_point::max() is the "no refresh scheduled" sentinel. It is never an input, because the caller tests for it before calling, and it is never an output, because the saturation stops one microsecond short; a mutant that saturates to the sentinel instead reddens the gtest. time_point::min() is not a sentinel anywhere in this subsystem. The comparator's static_assert on the struct size is unaffected, no member being added. The function is a non-virtual const method with no early returns and no error paths.

Five mutants of the fix were built, each with its own build id, and each reddens at least one test:
reverting the operand order, computing the product in Int64, clamping after the widening instead
of before it, dropping the saturation, and saturating to the sentinel. Two of them are invisible to
the stateless test because they fail inside the wide-integer arithmetic, where the sanitizer emits
no check and the result is silently wrong rather than aborting, which is why the gtest is included
rather than left out. The control arm with an ordinary spread stays green for every mutant, so each
abort is attributable. Fifty runs of the new test and of three sibling REFRESH tests, plus five of the fourth
(it is long-tagged, so the runner scales its repeats by 0.1), all pass with no sanitizer report,
and twenty further runs of the new test after its third arm was widened to thirty views: twenty of
twenty, longest 96.5 seconds against the runner's 600 second per-test default.

Session id: cron:clickhouse-review-slot-48:20260806-123800

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [71dcb49]

Summary: ✅


AI Review

Summary

The PR fixes overflow from very large RANDOMIZE FOR windows by computing the offset in Int128, capping its magnitude at approximately 95 years, and using std::chrono::milliseconds for conversion. Review of head 71dcb49a74d690f4a9e13177d9d6f63878301231, the scheduler callers, regression coverage, and all prior discussion found no actionable findings.

Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 71dcb49a7 with master 31d10e5ef (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 915c5e7f3; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 6 s compile time in total, 6 of them have a recent master baseline.

Job report

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.
@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5ce7325

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 175/175 check-runs completed, 157 success / 17 skipped,
Finish Workflow = success, one failing job.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6444) crash: a set skip-index granule decoded with a type its on-disk data was not written with #112484 (ours, open), with #106988 (ours, open) covering the sibling pending-mutation path
Stress test (amd_tsan) / Cannot start clickhouse-server same event as the row above; the server aborted at 15:22:33, the readiness loop reported it at 13:22:43 UTC job time same owner as above
Stress test (amd_tsan) / Check failed job-level roll-up of the two rows above same owner as above

Not caused by this PR. The diff is confined to RefreshSchedule::addRandomSpread plus its own
gtest and one stateless test; it touches no serialization, skip-index or MergeTree read code. The
abort stack is SerializationNullable::deserializeBinaryBulkWithMultipleStreams <-
MergeTreeIndexGranuleSet::deserializeBinary <- MergeTreeIndexReader::read, reached from a
background read thread on a stress-workload part, with no frame in anything this PR changes.

The three failing rows are one server abort, not three defects: the Cannot start row is the
readiness probe observing the process that had already died, and Check failed is the job
roll-up.

Session id: cron:our-pr-ci-monitor:20260807-153000

@@ -0,0 +1,117 @@
#include <gtest/gtest.h>

#include <Storages/MaterializedView/RefreshSchedule.h>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai this gtest is not needed, when you have sql ones

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai, this test is too long, can you trim it to just one RMV with randomization in milliseconds?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cccc9d8

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 175/175 check-runs completed, 157 success / 17 skipped,
Config Workflow and Finish Workflow both success, one failing job.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04357_distributed_alias_same_expression wrong results: an un-merged GROUP BY group under two-level distributed aggregation, 300 300 2 read back as two 300 300 1 rows #108855 (ours, open)

Not caused by this PR. The diff is src/Storages/MaterializedView/RefreshSchedule.cpp plus one
stateless test of its own, and it touches no planner, aggregation or Distributed code. The failing
row is the duplicate-ALIAS two-level aggregation defect that #108855 fixes: its diff carries the
planner change (Planner.cpp, PlannerJoinTree.{cpp,h}, buildQueryTreeForShard.{cpp,h}) and
owns 04357_distributed_alias_same_expression itself. The runner's own randomized-settings
diagnosis on this row reports 26 of 83 reruns failing, and the failing settings include
group_by_two_level_threshold_bytes 1, which forces the two-level path the defect lives in.

This PR's own test 04757_refreshable_mv_randomize_for_overflow passed everywhere it ran,
including 50 of 50 in each of the four flaky-check flavours and 50 of 50 in
Stateless tests (arm_asan_ubsan, targeted).

Session id: cron:our-pr-ci-monitor:20260809-040000

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ Holding this one. The saturation direction is wrong at the low end and my test does not catch it.

randomness is uniform_int_distribution<Int64>(-1e9, 1e9) (RefreshTask.cpp:2056), signed, re-drawn after every successful refresh (:1271). So about half of cycles produce a negative spread, which this patch pins to INT64_MIN + 1. The caller's guard is else if (start_time < when || waiting_for_dependencies) (:1129), and a when in the past fails it and falls through to refreshing immediately. Refresh completes, randomize() draws again, ~50% chance of another immediate refresh, indefinitely — running the query, writing the target table, and writing znodes per attempt when replicated.

So this trades a view that hangs forever for one that spins forever, which is worse for a typo in randomize for.

My reference constant 2217714954 is that state: INT64_MIN + 1 microseconds is -9223372036854 seconds, and mod 2^32 that is 4294967296 - 2077252342. The test asserts only that next_refresh_time is an endpoint, so it passes while the view hammers. A system.query_log count over the poll window would show it.

Three ways out, and I would rather agree the shape before pushing again:

  1. Clamp the spread rather than the timestamp — bound the offset by the period, so EVERY 1 HOUR cadence survives an absurd randomize for.
  2. Reject an overflowing randomize for at DDL, gated so ATTACH of an existing view still works. Better UX than silently scheduling year 294000, and consistent with how codec-chain length is handled in Fix out-of-bounds write on a long codec chain #113877.
  3. Minimal: keep the saturation but never let the low end move when earlier than the unrandomized time.

I lean towards 2 with 1 as the fallback for already-attached views. Separately, the * 1000 hard-codes system_clock::duration == microseconds; the old code added std::chrono::milliseconds(...), which converted for any period. Right on libc++, off by 1000x on libstdc++. I will add a static_assert on system_clock::period::den either way.

@PedroTadim PedroTadim removed their assignment Aug 10, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Not worth fixing

@PedroTadim PedroTadim closed this Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim

Copy link
Copy Markdown
Member

We have to fix this

@PedroTadim

PedroTadim commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

@groeneai 🕵️ The Int128 computation is right, but clamping the resulting timestamp is not. The latest commit only merges master, so this is still open:

  1. The low end lands in the far past. randomness is drawn uniformly from ±1e9 (drawRandomness), so half of the draws saturate when to about 292,000 years ago, and the caller refreshes immediately because start_time >= when. The value is redrawn only when last_completed_timeslot changes, and an early refresh advances it by one period, so the view refreshes immediately until a positive draw (about twice on average), then saturates at the high end and never refreshes again. Neither end is meaningful, and both hand a ~292,000-year delay to BackgroundSchedulePool::scheduleAfter, the overflow the description leaves out of scope.
  2. Clamp the offset, not the timestamp. Cap |offset| at a fixed bound that is clearly representable, for example the 95-year max_delay_ms of Fix signed integer overflow in refreshable materialized view retry backoff #113007, so both fixes follow one convention. An absurd RANDOMIZE FOR then behaves like the widest jitter we support, when stays near the schedule, and the scheduleAfter overflow is no longer reachable from here. A RANDOMIZE FOR that does not overflow today is unaffected.
  3. spread_ms * 1000 assumes system_clock::duration is microseconds. It is with libc++, but the old code was unit-agnostic. Build a std::chrono::milliseconds and let chrono convert it, or add a static_assert on system_clock::period.
  4. The test accepts the bad state. It passes when next_refresh_time modulo 2^32 is either saturated end: 2077252342 is the high one and 2217714954 the low one, i.e. exactly the outcome in point 1. With an offset cap it can assert that next_refresh_time is within the cap of now() and that the view did not refresh more than once during the poll window.

@clickhouse-gh clickhouse-gh Bot added the comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... label Oct 21, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, done in 4370179 (description updated to match):

1-2. addRandomSpread no longer clamps the timestamp: it caps |offset| at 3e12 ms, the 95-year max_delay_ms of #113007. An absurd RANDOMIZE FOR stays within 95 years of its timeslot, and a window under 190 years is unaffected.
3. The capped value is a std::chrono::milliseconds added to when, so chrono does the conversion.
4. next_refresh_time is a UInt32 DateTime, so "within the cap of now()" (a 190-year window) wraps and accepts any value, the old saturated ends included. The test uses REFRESH EVERY 200 YEAR instead: the first timeslot is 2170-01-01, both signs of the offset stay in the future, and it asserts the view is Scheduled, has not refreshed, and next_refresh_time is exactly the timeslot plus or minus the cap. It fails on master (UBSan in addRandomSpread) and on the previous revision, and passes 20/20 on debug and ASan+UBSan builds.

Left as is: a period within 95 years of the time_point limit still overflows the addition, but REFRESH AFTER 9223372036855 SECOND without RANDOMIZE FOR already overflows when the schedule is converted to a time_point, so that bound belongs to the period.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4370179

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 05407_distributed_plan_exchange_compression_default flaky, not from this PR (it changes only RefreshSchedule::addRandomSpread and its test): 05407_default, 05407_empty_lz4 and 05407_zstd_exchange_level print 1 0 instead of 1 1 under the randomized group_by_two_level_threshold = 1; it failed the same way on master and on 27 other PRs in 30 days. The fix merged after this run had started #127186 (mine, merged)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05407_merge_tree_max_rows_to_use_cache_max_value flaky, not from this PR: 05407_large_value prints 0 when the remote replicas do all the reads, because the check reads only the initiator's query_log row (2 of 243 reruns failed); it failed in the same job on master and on 4 other PRs #127290 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127186, #127290 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-003004

@PedroTadim PedroTadim added pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Oct 22, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 22, 2026
Merged via the queue into ClickHouse:master with commit 406082d Oct 22, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 22, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #113673 to 26.9: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
PedroTadim added a commit that referenced this pull request Nov 2, 2026
Backport #113673 to 26.10: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
clickhouse-gh Bot added a commit that referenced this pull request Nov 2, 2026
Backport #113673 to 26.8: Fix signed integer overflow in refreshable materialized view `RANDOMIZE FOR`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
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 comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants