Repository navigation
Refreshable MV: apply RANDOMIZE FOR per replica - #112979
Conversation
Internal second-model review: 5 rounds, 2 blockers and 8 majors fixed, 1 declined with evidenceAn independent cold review plus a second-model gate reviewed this change before each push. Rounds Fixed during review❌ A restart moved a pending ❌ Uncoordinated views froze their offset for the process lifetime (blocker, round 3). A ❌ The re-roll trigger was absent from older znode writers (blocker, round 1). It keyed on
Declined, with evidence
Arithmetically: the cell drives each round with Empirically: the exact mutation described was already built and measured. Moving the re-roll into The finding's other observation, that the replicas could stay unequal on their initial offsets, is 💡 The rendered Session id: cron:clickhouse-review-slot-51:20260802-040100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260801-220600 |
|
cc @tuanpach, could you review this? Each replica now applies its own |
al13n321
left a comment
There was a problem hiding this comment.
Ah, number of replicas wasn't already available, needed a new zk request. Not worth it, please remove the randomness shaping altogether, just draw delay uniformly and remove unnecessary code.
Also remove the "DERIVED from the replica name and root_znode.randomness, not drawn, so it survives a restart" logic, not worth the complexity, just have a field for next refresh time and remove more code.
| "Time when the latest refresh attempt finished (if known) or started (if unknown or still running). NULL if no refresh attempts happened since server startup or table creation."}, | ||
| {"last_refresh_replica", std::make_shared<DataTypeString>(), "If coordination is enabled, name of the replica that made the current (if running) or previous (if not running) refresh attempt."}, | ||
| {"next_refresh_time", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeDateTime>()), "Time at which the next refresh is scheduled to start. NULL if the next refresh time is not currently known, e.g. when waiting for dependencies (status `WaitingForDependencies` or `MissingDependencies`)."}, | ||
| {"next_refresh_time", std::make_shared<DataTypeNullable>(std::make_shared<DataTypeDateTime>()), "Time at which the next refresh is scheduled to start. With `RANDOMIZE FOR` on a coordinated replicated view this is the time at which this replica would refresh; each replica picks its own time, so another replica may refresh earlier and this refresh then doesn't happen. NULL if the next refresh time is not currently known, e.g. when waiting for dependencies (status `WaitingForDependencies` or `MissingDependencies`)."}, |
There was a problem hiding this comment.
Too long, just say something like "[... next refresh is scheduled to start] on this replica (unless another replica starts it first)."
There was a problem hiding this comment.
Done in ce5fa1f, using your wording verbatim.
The random offset was drawn once, written to the coordination znode, and read back by every replica, so all replicas computed the same next_refresh_time and which one refreshed came down to the race to create the ephemeral running znode. In practice that favours the same replica repeatedly. Each replica now draws its own delay uniformly and the earliest one refreshes. The draw is kept across scheduling passes rather than made afresh in each one: the pass reruns on every Keeper watch and every timer tick, so redrawing each time would keep moving next_refresh_time and nothing could tell when a refresh is due. It is redrawn when the timeslot moves, when any replica's refresh succeeds, and when the schedule is altered. The success trigger is what stops a replica holding an early draw and winning every race, and it has to fire on replicas that did not perform the refresh, so it is keyed on the znode's shared randomness: parse has required that field since long before this change, every supported version re-rolls it on exactly one event, a successful refresh, and every replica reads it. Both key components come from the znode rather than from the computed deadline, which a retry or a zero-period dependency refresh derives from the wall clock. The schedule case resets the key in alterRefreshParams, so it covers every schedule field. Two consequences, both deliberate. The earliest of several independent draws is earlier than a single draw on average, so refreshes land slightly earlier inside the RANDOMIZE FOR window the more replicas there are. And the draw is process-local, so restarting a replica moves its pending next_refresh_time within the window. Earlier revisions cancelled the first by reshaping the offsets by the replica count and avoided the second by deriving the offset rather than drawing it; both were dropped in review, the reshaping because it needed a new Keeper request on the scheduling path. While a rolling upgrade is in progress, replicas that are not upgraded yet still apply the shared offset, so the refresh is skewed toward them and lands somewhat earlier in the window. This resolves itself once every replica is upgraded. Closes: ClickHouse#78410 Co-Authored-By: Claude Opus 4.8 <[email protected]> Co-Authored-By: Claude Fable 5 <[email protected]>
a32dc5e to
ce5fa1f
Compare
|
Both removed in ce5fa1f (+68/-442 against the previous head): the shaping helper, the replica-count read and its gtest are gone, and so is the derived offset. Each replica just draws its delay uniformly. The description is rewritten rather than trimmed, since it argued for machinery that no longer exists, and now states both behaviours you accepted: refreshes land slightly earlier in the window the more replicas there are, and a restart moves a pending One thing I kept, because a plain field alone broke the per-refresh redraw. The scheduling pass reruns on every watch and timer tick, so a value recomputed there never settles. The draw is therefore retained and invalidated by a key, Worth knowing, measured on a server: keying on the timeslot alone froze the offset across Two test gaps I left open, in case you want them first: nothing asserts the earliest replica is the one that refreshes, only that the candidates differ, and no live cell covers uncoordinated |
Master removed the legacy Docusaurus tree docs/en (9440ca7, "Docs: remove legacy Docusaurus documentation"), which conflicted modify/delete with this branch's note in docs/en/sql-reference/statements/create/view.md. Master's deletion is taken: the note already exists in the Mintlify replacement page docs/reference/statements/create/view.mdx, which this branch also edits and which auto-merged cleanly, so the documentation change is preserved without resurrecting the removed path or duplicating the note. The three source carriers (RefreshTask.cpp, RefreshTask.h, StorageSystemViewRefreshes.cpp) and both test files are byte-unchanged on master since the previous merge base, so no semantic reconciliation was needed.
|
Workflow [PR], commit [545aef1] Summary: ✅
AI ReviewSummaryThis PR switches refreshable MV Findings
TestsFinal VerdictLLVM Coverage ReportMeasured on commit 545aef1.
Changed lines: Changed C/C++ lines covered: 43/43 (100.00%) · Uncovered code |
|
@al13n321 no test job has ever run on this PR. The three runs before yours all ended That pre-hook wants the The label alone will not restart this run: the hourly I have not touched the branch; head is still your 7a0070c. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units36 translation units recompiled, 276 s compile time in total, 36 of them have a recent master baseline. |
Both tests treated replica agreement as success, so they passed without the per-replica draw and failed with it. Measured on one tree with two binaries, the baseline built from the merge base with only this PR's three source files reverted, both test bodies run against both: test body master baseline this branch as pushed (c10c26a) 2 passed 2 failed corrected 2 failed 2 passed test_randomize_for_is_per_replica left the retry loop when the two next_refresh_time values were EQUAL, which is the shared-offset case, and then raised "the random offset is still shared" on the path where they differ. test_randomize_for_is_redrawn_on_every_replica counted the rounds where they differ, so with the change it reached failed_rounds == 2 on round 1. Drop the unused `before` dict. ruff F841 rejects it, and the resulting Style check failure gated every other job in the run. Keep the second property the docstring asks for. The fake clock advances a timeslot per round, so disagreement between the replicas also holds for an offset drawn once at construction and never redrawn; assert that each replica's own offset changes between timeslots as well. Wait for a next_refresh_time past the fake clock instead of sleeping for a second. A refresh keeps the deadline it was started for until it completes, so a fixed sleep can read the previous timeslot's value. Move the RANDOMIZE FOR paragraph from the generated Mintlify page to the statement registration it is generated from. The docs check rejects direct edits inside the AUTOGENERATED region of docs/reference/statements/create/view.mdx. Co-Authored-By: Claude Opus 5 <[email protected]>
Head branch was pushed to by a user without write access
|
Thanks for the rewrite. It settles the question I left in #112979 (comment): the redraw test is narrowed to scheduled refreshes and Both rewritten bodies compare the wrong way round, though, so as pushed they assert the opposite of this PR. In
Pushed as
Happy to change any of it. |
CI finish ledger - b6b4ec4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260916-060320 |
Replicas running a version from before per-replica RANDOMIZE FOR apply the serialized `randomness` field of the coordination znode as the shared offset. This branch stopped drawing that field in the constructor, so a znode created by an upgraded replica carried `randomness: 0` until the view's first successful refresh, and every not-yet-upgraded replica scheduled that first refresh at the exact timeslot with no spread at all. The PR description says such replicas keep applying the shared offset from Keeper, which only held after the first refresh. Measured on two servers sharing one Keeper, one built from this branch and one from the merge base, joined as replicas of the same Replicated database, with 12 coordinated `EVERY 1 DAY RANDOMIZE FOR 1 HOUR` views per arm (offsets in seconds against the un-randomized deadline, window +/-1800): znode written by znode randomness offset applied by the old replica this branch 0 x12 0 x12 merge base non-zero x12 -1775 .. +1268 this branch + draw non-zero x12 1800 * randomness / 1e9, exact x12 The field stays unread by this version, so nothing about per-replica randomization changes: in the last arm the upgraded replica kept applying its own draw, unrelated to the value it wrote to the znode. The regression covers both halves of what an old reader needs: a random value at the first znode write, and a fresh one after every successful refresh. Verified red on this branch without the draw and against a mutant that keeps the draw but drops the update after a refresh.
Head branch was pushed to by a user without write access
randomness_drawn_for_timeslot and CoordinationZnode::last_completed_timeslot are both zero-initialized, so determineNextRefreshTime's redraw check compares equal and leaves scheduling.randomness at 0 for a view that has not completed a refresh yet. A REFRESH AFTER ... RANDOMIZE FOR ... DEPENDS ON ... view reaches its first finite deadline in exactly that state: it reports no next_refresh_time at all until the dependency refreshes, so every replica then schedules its first refresh at the un-randomized deadline. Measured on one server, 8 such views, RANDOMIZE FOR 300 DAY (window +/-12960000 seconds), offsets against the un-randomized deadline every view shares: branch without this change 0 x8, one distinct value master 8 distinct, spread over the window with this change 8 distinct, spread over the window Reading the same view class before and after one successful refresh of its own, same window and same probe, isolates the cause to the zero timeslot rather than to DEPENDS ON: 0 before, spread after. An EMPTY view, whose last_completed_timeslot is seeded to now(), randomizes normally on all three. Regression: test_randomize_for_is_applied_before_the_first_refresh in test_refreshable_mat_view_replicated. It fails without this change (both replicas pick the same second) and passes with it; the three pre-existing randomize tests pass either way.
CI finish ledger - df960feEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260917-153132 |
|
@groeneai , please merge master. |
…e-per-replica Conflicts, both resolved in favour of keeping both sides: * src/Storages/MaterializedView/RefreshTask.h: master replaced SchedulingState::out_of_schedule_refresh_requested with Coordination::pending_requests, in the same lines where this branch added randomness_drawn_for_timeslot and randomness. Took master's removal and kept the two new fields. * tests/integration/test_refreshable_mat_view_replicated/test.py: both sides appended new tests at the end of the file. Kept master's three SYSTEM REFRESH VIEW request tests followed by this branch's four randomize tests.
|
Merged (not rebased): Two conflicts:
On the merged tree the debug build is clean and Auto-merge is still off: my 17 September push cleared the arming and I have not touched it since, so it needs re-arming if you want it. |
| coinciding_rounds = 0 | ||
| offsets = {n.name: set() for n in nodes} | ||
| for round_number in range(3): | ||
| fake_time = f"20{45+round_number}-07-04 00:00:00" | ||
| for n in nodes: | ||
| n.query(f"SYSTEM TEST VIEW randomize_multi_rmv SET FAKE TIME '{fake_time}'") | ||
|
|
||
| times = { | ||
| n.name: _next_refresh_time(n, "randomize_multi_rmv", after=fake_time) for n in nodes | ||
| } | ||
| for name, t in times.items(): | ||
| # The schedule is yearly, so everything after the year is the offset that was drawn. | ||
| offsets[name].add(t.split("-", 1)[1]) | ||
|
|
||
| if len(set(times.values())) == 1: | ||
| coinciding_rounds += 1 | ||
| # Ignore if there's only one coincidence. | ||
| assert coinciding_rounds == 1, f"both replicas scheduled the refresh for {times} on round {round_number}, so the random offset is still shared" | ||
|
|
||
| for name, seen in offsets.items(): | ||
| assert len(seen) > 1, f"{name} drew offset {sorted(seen)} in every timeslot, so its offset is frozen rather than redrawn" |
There was a problem hiding this comment.
This oracle is weaker than the contract the docstring names. len(seen) > 1 only proves that each replica changed offset at least once across three rounds; a mutant that redraws only the winner still passes if the wins alternate. The test also samples next_refresh_time only after the refresh has already completed, so it never checks that the replica with the earlier deadline is the one recorded in last_refresh_replica.
Because the user-visible promise here is "every replica redraws for every timeslot, and the earlier deadline wins", I think this needs a stronger regression: keep the previous per-replica offset and assert it changes on every round, then add one round that captures both pending deadlines before they fire and checks last_refresh_replica against the earlier one.
There was a problem hiding this comment.
This is the class of finding I take seriously, so I measured it instead of arguing. I built exactly the mutant described, a redraw restricted to the replica that performed the refresh:
- if (znode.last_completed_timeslot != scheduling.randomness_drawn_for_timeslot)
+ if (znode.last_completed_timeslot != scheduling.randomness_drawn_for_timeslot
+ && znode.last_attempt_replica == coordination.replica_name)1. len(seen) > 1 catches that mutant, 8 runs out of 8, every time at that assertion and always naming the same replica:
AssertionError: node1_2 drew offset ['01-10 07:14:19'] in every timeslot, so its offset is frozen rather than redrawn
The same test passes 3/3 on the unmutated binary. The alternating wins the escape needs do not happen here: the round jumps the fake clock a full year past the deadline, so both deadlines are already overdue by the time the loop reaches the second node, and the refresh goes to whichever one moved first. That was node1_1 in every round I measured on both binaries, including the three rounds where node1_2 held the earlier deadline. Under a winner-only redraw node1_2 is then visibly frozen: its next_refresh_time stays at 12-26 10:30:08 across all rounds, with only the year advancing.
2. The last_refresh_replica arm does not discriminate the two binaries, and as described it would be incorrect. "Earlier deadline wins" is false under the year-long jump, because by then both deadlines are in the past: on the correct binary I measured node1_2 holding 2047-12-26 03:16:50 against node1_1's 2048-01-05 03:07:25, and last_refresh_replica came back as node1_1. Added to the existing rounds, that assertion would red on correct code whenever the first-moving node holds the later deadline. It does hold if the clock is instead set to one second past the earlier deadline only, but then it holds on the mutant too, 4 rounds out of 4 on each binary, because replica selection is pre-existing coordination that this PR does not change. (last_refresh_replica is also the Replicated database replica name, 1 or 2, not the instance name.)
So I am leaving both tests as they are. The per-round form of the offset-changed assertion was dropped in c10c26a when the trigger became a fake-clock jump, and the set-based form that replaced it is what catches the mutant above.
The only master change in this PR's files is #112979 (`RANDOMIZE FOR` per replica); it auto-merged in `RefreshTask`. The conflict was in `test_refreshable_mat_view_replicated/test.py`: this branch had moved `test_takeover_waits_for_recreated_request` to `test_refreshable_mv`, and master appended its new `RANDOMIZE FOR` tests right after it. The resolution keeps the move and master's new tests. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ed-rmv-refresh-schedule Conflicts in RefreshTask.h and RefreshTask.cpp, both against ClickHouse#112979 (per-replica RANDOMIZE FOR) and ClickHouse#121037 (startup/shutdown race). SchedulingState: kept both sides, the fields are independent. startup(): took master's shape, which does every view-dependent step under `mutex` and returns early when shutdown() has already nulled `view`. The local-state resolve/load/save moved inside that lock and now reads the captured `context`/`view_id` rather than dereferencing `view` unlocked, which is the access ClickHouse#121037 made safe. DatabaseCatalog does not reach back into RefreshTask, so the catalog lookup under `mutex` cannot invert a lock order. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes: #78410
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Applies
RANDOMIZE FORon each replica of a refreshable materialized view independently, so that a random replica performs each refresh instead of the same one every time. Replicas no longer agree onnext_refresh_time, so the value reported bysystem.view_refresheson one replica is the time that replica would refresh at, not necessarily when the refresh happens. Closes #78410.Description
Previously the offset was drawn once, written to the coordination znode, and read back by every replica, so all replicas computed the same
next_refresh_timeand which one refreshed came down to the race for the ephemeralrunningznode, which in practice favours the same replica repeatedly. Each replica now draws its own delay uniformly and the earliest one refreshes.The draw is kept across scheduling passes rather than made afresh in each one: the pass reruns on every Keeper watch and timer tick, so redrawing each time would keep moving
next_refresh_time. It is redrawn when the timeslot the view last completed moves, which every scheduled refresh advances; that timeslot comes from the coordination znode, so replicas that did not perform the refresh redraw too and none keeps an early draw and wins every race. RepeatedSYSTEM REFRESH VIEWcalls inside one timeslot keep the draw, which does not decide them: such a refresh is performed by the replica that received the query.Two deliberate consequences: the earliest of several independent draws is earlier than a single draw on average, so refreshes land slightly earlier in the window the more replicas there are; and the draw is process-local, so restarting a replica moves its pending
next_refresh_timewithin the window.An earlier revision cancelled the first by reshaping the offsets by the replica count and avoided the second by deriving the offset rather than drawing it. Both were dropped in review: the reshaping needed a new Keeper request on the scheduling path, and neither was judged worth the complexity.
While a rolling upgrade is in progress, replicas that are not upgraded yet still apply the shared offset from Keeper, so the refresh is skewed toward them and lands somewhat earlier in the window. This resolves itself once every replica is upgraded.
Workflow [PR]
Sync PR [sync-upstream/pr/112979]
Version info
26.10.1.535-master(included in26.10and later)