Skip to content

Refreshable MV: apply RANDOMIZE FOR per replica - #112979

Merged
al13n321 merged 11 commits into
ClickHouse:masterfrom
groeneai:refresh-mv-randomize-per-replica
Sep 23, 2026
Merged

al13n321 merged 11 commits into
ClickHouse:masterfrom
groeneai:refresh-mv-randomize-per-replica

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #78410

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Applies RANDOMIZE FOR on 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 on next_refresh_time, so the value reported by system.view_refreshes on 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_time and which one refreshed came down to the race for the ephemeral running znode, 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. Repeated SYSTEM REFRESH VIEW calls 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_time within 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

  • Merged into: 26.10.1.535-master (included in 26.10 and later)

@groeneai
groeneai requested a review from a team as a code owner August 2, 2026 04:31
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 5 rounds, 2 blockers and 8 majors fixed, 1 declined with evidence

An independent cold review plus a second-model gate reviewed this change before each push. Rounds
1 to 4 found 2 blockers and 8 majors, all fixed; round 5 found one major I disagree with, refuted
below. The commit history is the record: each commit after the first is one round's fix.

Fixed during review

❌ A restart moved a pending next_refresh_time (blocker, rounds 1 and 2). The offset was
drawn in the constructor, so it was process-local and unrecoverable, where on master it came back
from Keeper on every read. It is now derived as a hash of the replica name and the coordination
znode's shared token, both recoverable. Pinned by an integration cell that actually restarts a
replica; reverting the derivation to a draw reddens only that cell.

❌ Uncoordinated views froze their offset for the process lifetime (blocker, round 3). A
regression introduced by round 2's own fix: such a view has no replica name to derive from, and
the consumer had switched to reading the derived field unconditionally, so every refresh landed at
the same point in the window. That is the default configuration for a view in a non-Replicated
database. It now follows the shared per-refresh token exactly as before.

❌ The re-roll trigger was absent from older znode writers (blocker, round 1). It keyed on
last_success_end_time, added in 26.6 and read with optional_field, so a znode written by 26.3
to 26.5 yields epoch 0 and a new replica would never re-roll during a rolling upgrade, keeping its
startup draw. It now keys on randomness, which every version requires and re-rolls once per
successful refresh.

⚠️ Also fixed: three test oracles that could not fail for the reason they named (the restart
assertion never restarted anything; the replica-count assertion observed the count that was read
rather than the reshaping's output; the re-roll assertion permitted a switch back to a shared
offset); a helper that accepted the pre-scheduling epoch placeholder as a scheduled time; a
replicas znode read that could throw on the scheduling thread and stop the view permanently; the
system.view_refreshes.next_refresh_time description, which still claimed replicas agree; and the
comment volume, trimmed to at most three lines per block with the rationale moved into the commit
messages.

Declined, with evidence

⚠️ "The multi-round re-roll test cannot detect a losing replica failing to re-roll." The
necessary step is that next_refresh_time moves after each refresh anyway, because the schedule
advances to a new timeslot even with a frozen offset. That step is false for this cell's schedule,
two independent ways.

Arithmetically: the cell drives each round with SYSTEM REFRESH VIEW, an out-of-schedule refresh,
and timeslotForCompletedRefresh then returns floorEvery(start_time) early, before the
advanceEvery line the finding cites. For EVERY 1 YEAR with the EMPTY constructor seeding the
timeslot to now, the base timeslot is 2027-01-01 both before and after the refresh, bit-identical.
With a frozen offset the deadline cannot move at all.

Empirically: the exact mutation described was already built and measured. Moving the re-roll into
the success block, so only the winning replica re-rolls, reddens this cell and nothing else (1
failed, 3 passed). The frozen replica held next_refresh_time at 2026-12-23 08:11:53 through 200
polls over 60 seconds while last_success_time advanced, so the refresh happened and the deadline
did not move.

The finding's other observation, that the replicas could stay unequal on their initial offsets, is
true but is the sibling assertion's job: the per-node moved-value check catches a frozen offset,
the cross-replica inequality check catches a shared one, and each has its own discriminating
mutation.

💡 The rendered system.view_refreshes documentation page still reads as though replicas agree on
next_refresh_time. The source string is updated here; the rendered page sits in an autogenerated
region that cannot be hand-edited without a maintainer-only label, and no job in this repository
regenerates it. The two prose pages this PR does update carry the user-visible half.

Session id: cron:clickhouse-review-slot-51:20260802-040100

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A as a bug: this is a design change requested by the refreshable-MV owner, nothing was broken. The equivalent gate is a deterministic both-directions measurement: the new integration cell test_randomize_for_is_per_replica fails on every run of the pre-fix binary with both replicas scheduled the refresh for <T>, so the random offset is still shared, and passes on every run of the fixed binary.
b Root cause explained? The RANDOMIZE FOR offset was drawn once by whichever replica wrote the coordination znode, persisted into Keeper (toString), and read back by every replica, so all replicas computed the same next_refresh_time and the refresh owner was decided purely by the race to create the ephemeral running znode.
c Fix matches root cause? Yes. It stops SHARING the draw (the actual mechanism) rather than perturbing the schedule or guarding a symptom. No widened bound, no weakened assertion, no defensive check.
d Test intent preserved / new tests added? 6 new gtest cells (gtest_refresh_schedule.cpp) and 5 new integration cells. Three oracles were STRENGTHENED during review because they could not fail: the replica-count cell now asserts the reshaping's OUTPUT (shaped > raw) rather than the count that was read; the re-roll cell also asserts the replicas still disagree AFTER a refresh; and the uncoordinated cell now asserts the offset CHANGES across a refresh instead of only that scheduling happened. One assertion was deliberately DELETED: a stateless cell that compared next_refresh_time across a 1-second sleep in a single un-restarted process with no coordinated state, which passed identically with and without the regression it named. It is replaced by test_randomize_for_survives_restart. No assertion was weakened.
e Both directions demonstrated? Yes. Pre-fix arm (baseline built from the same worktree with only the 4 source files reverted, per-file md5 verified against origin/master) fails the new integration cell; fixed arm passes. Plus 9 mutation arms across the review rounds, each rebuilt with the Build ID asserted to MOVE and each restored with the source md5 re-verified, and a clean-tree control.
f Fix is general across code paths? Yes. The re-roll hook is at BOTH coordination.root_znode assignment sites, which is what makes it reach every replica rather than only the replica that wins the Keeper compare-and-swap (only that one runs executeRefresh); a mutation that moves the re-roll into executeRefresh reddens the multi-refresh cell while the single-scheduling cell stays green, proving the placement is load-bearing. Both writers of the per-replica value are covered (the constructor and the hook), enumerated by grep, so no path can leave it stale; the consumer is the single addRandomSpread call site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Replica counts 0, 1, 2, 3, 5, 8, 16 asserted; the full [-1e9, 1e9] input range swept at 1000-step granularity in three cells; window endpoints asserted to map exactly; both view kinds covered (coordinated, and uncoordinated all_replicas = 1, which is also the default single-node shape).
h Backward compatible? (maintainer-approved exception only) Yes, and this is the load-bearing carrier. randomness STAYS in the coordination znode: toString still writes it and parse still reads it as a required field, so an older server can still parse a znode written by a new one during a rolling upgrade. It was chosen as the re-roll key precisely because it is a required field in every active release, unlike the first candidate, which is absent from three of them. The format version is deliberately NOT bumped. The one residual is disclosed in the description rather than engineered around: mid-rolling-upgrade the distribution is skewed toward the not-yet-upgraded replicas, which is transient, bounded, and biased toward the old replica refreshing. No setting added or changed, so SettingsChangesHistory.cpp needs no entry (confirmed by grep).
i Invariants and contracts preserved? The replica count is read in readZnodesIfNeeded, which already unlocks for Keeper and already runs earlier in the same scheduling pass, so determineNextRefreshTime still does no Keeper I/O under the mutex, and the locked assignment ordering is unchanged. The consumer contains no rng call, and for a coordinated view the hook itself is idempotent (a pure function of two unchanged inputs), so next_refresh_time is stable while a view sits in Scheduled and survives a process restart. A retry chain does not re-roll, because the key advances only inside the success block. An uncoordinated view keeps following the same per-refresh token it followed before, so it keeps re-randomizing every refresh as documented. The new /replicas read is failure-tolerant like its three neighbours in the same function: a missing znode (a real window, since a concurrent DROP removes it) logs one warning and retains the previous count, which biases refreshes later rather than earlier, instead of reaching the catch-all that would stop the view permanently and abort a debug build; verified on the real path by deleting the znode under a live view. The waiting-for-dependencies guard still skips addRandomSpread.

Session id: cron:clickhouse-impl-slot-4:20260801-220600

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach, could you review this? Each replica now applies its own RANDOMIZE FOR offset instead of the one shared through Keeper, derived from the replica name and the coordination znode's per-refresh token so it survives a restart, and reshaped by the replica count so that adding replicas does not pull refreshes earlier.

@al13n321 al13n321 left a comment

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.

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`)."},

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.

Too long, just say something like "[... next refresh is scheduled to start] on this replica (unless another replica starts it first)."

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.

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]>
@groeneai
groeneai force-pushed the refresh-mv-randomize-per-replica branch from a32dc5e to ce5fa1f Compare August 4, 2026 05:34
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

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 next_refresh_time.

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, (last_completed_timeslot, randomness) from the znode. randomness is what makes every replica redraw rather than only the one that refreshed: every version that wrote this znode re-rolls it on exactly one event, a successful refresh, and every replica reads it. It is no longer the offset, just that marker.

Worth knowing, measured on a server: keying on the timeslot alone froze the offset across SYSTEM REFRESH VIEW, which is out of schedule and can leave the timeslot equal (five forced refreshes, one value; with randomness in the key, six distinct). last_success_end_time would have looked cleaner but 25.8, 26.3 and 26.5 do not write it, so a new replica would read epoch zero through a rolling upgrade.

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 all_replicas = 1 across two refreshes.

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.
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@al13n321
al13n321 enabled auto-merge August 20, 2026 01:27
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [545aef1]

Summary: ✅


AI Review

Summary

This PR switches refreshable MV RANDOMIZE FOR from a Keeper-shared offset to a per-replica local draw, keeps the serialized randomness field only for rolling-upgrade compatibility, updates the system.view_refreshes wording, and adds new randomization coverage. The implementation itself looks coherent, but the rewritten integration oracle does not fully prove the per-timeslot fairness behavior the PR now documents, so I left one test-coverage major.

Findings

⚠️ Majors

  • [tests/integration/test_refreshable_mat_view_replicated/test.py:1106-1126] test_randomize_for_is_redrawn_on_every_replica is weaker than the behavior it documents. len(seen) > 1 only shows that each replica changed offset at least once across three rounds, so a mutant that redraws only the winner can still pass if the wins alternate. The test also never checks that the replica with the earlier next_refresh_time is the one recorded in last_refresh_replica.
    Suggested fix: 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.
Tests

⚠️ Not run locally in this review.

Final Verdict

⚠️ Needs a stronger regression for the main per-timeslot fairness contract before I’d treat the new behavior as fully proven.

LLVM Coverage Report

Measured on commit 545aef1.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@al13n321 no test job has ever run on this PR. The three runs before yours all ended action_required; your push started run 32321048892, which stopped in Config Workflow at the can_be_tested pre-hook, so Mergeable Check reads Failed: Config Workflow, Dropped: 169.

That pre-hook wants the can be tested label, since I am a fork author and am neither in ci/defs/trusted_contributors.json nor a ClickHouse org member. My tooling only sets that label when it opens a PR, which postdates this one, and I do not add it to a PR that is already open.

The label alone will not restart this run: the hourly Retry Infrastructure Failures job re-runs a failed Config Workflow at the same SHA, but only for attempt-1 runs created in the last 6 hours, and this is attempt 2 from six days ago. So it needs the label plus a re-run of 32321048892, or a fresh head if you would rather I push one.

I have not touched the branch; head is still your 7a0070c.

@al13n321 al13n321 added the can be tested Allows running workflows for external contributors label Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 545aef1b5 with master 9611ce333 (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-refreshable-materialized-view Refreshable materialized views: scheduled/periodic refresh, refresh state machine, refresh orches... label Sep 4, 2026
al13n321 and others added 3 commits September 14, 2026 22:05
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]>
auto-merge was automatically disabled September 16, 2026 02:58

Head branch was pushed to by a user without write access

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the rewrite. It settles the question I left in #112979 (comment): the redraw test is narrowed to scheduled refreshes and randomness stays retired. I have not touched that choice.

Both rewritten bodies compare the wrong way round, though, so as pushed they assert the opposite of this PR. In test_randomize_for_is_per_replica, break # success fires when the two next_refresh_time values are EQUAL, which is the shared-offset case. In test_randomize_for_is_redrawn_on_every_replica, failed_rounds counts the rounds where they DIFFER. Both then raise "the random offset is still shared" on the path where the observed values differ. Measured on one tree with two binaries, the baseline built from the merge base with only this PR's three source files reverted:

test body master baseline this branch
as pushed (c10c26ae1) 2 passed 2 failed
corrected 2 failed 2 passed

before also became unused, and ruff F841 on it failed Style check; Mergeable Check then reported 148 jobs dropped, so the integration suite never ran on that commit.

Pushed as b6b4ec4:

  • both comparisons flipped, keeping your retry-on-coincidence structure;
  • before dropped, and each replica's own offset is now also asserted to change between timeslots, which is the second property the docstring names;
  • sleep(1) replaced by a wait for a next_refresh_time past the fake clock, because a refresh keeps the deadline it was started for until it completes;
  • the RANDOMIZE FOR documentation paragraph moved out of docs/reference/statements/create/view.mdx into the statement registration it is generated from, which is what the second red check was about;
  • the description paragraph that still described the pre-Simplify per-success key rewritten to match the code.

Happy to change any of it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b6b4ec4

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
Integration tests (amd_asan_ubsan, db disk, 7/8) infra, 0 tests run: pull access denied for minio/mc, repository does not exist on all 3 attempts, so the batch pre-pull aborted the whole shard before any test started (Failed to pre-pull Docker images needed by the test batch). The minio/mc Docker Hub repository was deleted upstream; the two minio/minio tags in the same batch still pulled. #119999 (mine, open)

Mergeable Check and PR are the praktika aggregators. Both report only the shard above
(Failed: Integration tests (amd_asan_ubsan, db disk, 7/8), Dropped: 100) and clear with it.
CH Inc sync succeeded on this head. 54 checks passed, 119 skipped, no test-level failure anywhere.

Session id: cron:our-pr-ci-monitor:20260916-060320

@al13n321
al13n321 enabled auto-merge September 17, 2026 06:17
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.
auto-merge was automatically disabled September 17, 2026 08:33

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - df960fe

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
Stress test (arm_tsan) / assertTypeEquality logical error (STID 2508-4620) Pre-existing trunk bug in Dynamic-subcolumn deserialization: the assertion at IColumn.h:984 fires through IColumn::insertRangeFrom (IColumn.h:287) from SerializationDynamicElement::deserializeBinaryBulkWithMultipleStreams (:279), reached via SerializationVariantElement -> SerializationArray -> SerializationObjectDynamicPath (:196). Nothing in this PR's diff (ParserCreateQuery.cpp, RefreshTask.{cpp,h}, StorageSystemViewRefreshes.cpp, 2 tests) reaches column serialization. My merged #113752 is present at this head (its merge commit aa121aa1a9d8 is an ancestor; the head is 2564 commits ahead of it) and does not cover this shape, so it is not the owner. a fix task is created (investigating at full effort - fixing-PR link to follow here)
BuzzHouse (amd_debug) / Received signal -1 (STID 3782-2f00) std::terminate in MergeTreeData::loadOutdatedDataParts (MergeTreeData.cpp:3637) on a retryable load error. Same signature on 4 unrelated PRs (#117135, #117503, #118246, #115725) and on a master run over the last 30 days, so it is not specific to this branch. #117981 (external, open)

Mergeable Check and PR are the praktika aggregators; they report only the two rows above.
CH Inc sync succeeded on this head, and 178 of 178 checks completed.

Session id: cron:our-pr-ci-monitor:20260917-153132

@al13n321

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Collaborator Author

Merged (not rebased): df960fe to 545aef1b, merging master at 33bd2f8. mergeable is back to MERGEABLE.

Two conflicts:

  • RefreshTask.h: the pending_requests change removed SchedulingState::out_of_schedule_refresh_requested from the exact lines this branch had added randomness_drawn_for_timeslot and randomness to. I took the removal and kept the two fields; no reference to the old flag is left in src/.
  • tests/integration/test_refreshable_mat_view_replicated/test.py: both sides appended tests at the end of the file, so the three new SYSTEM REFRESH VIEW request tests come first and the four randomize ones after them.

On the merged tree the debug build is clean and pytest test_refreshable_mat_view_replicated -k randomize gives 4 passed. All eleven last_completed_timeslot sites in RefreshTask.cpp are unchanged by the merge (the out_of_schedule value now comes from pending_requests, but it still reaches timeslotForCompletedRefresh the same way), so the draw key is still last_completed_timeslot alone.

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.

@al13n321
al13n321 enabled auto-merge September 23, 2026 03:42
Comment on lines +1106 to +1126
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"

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

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.

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.

@al13n321
al13n321 added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 7faa9a0 Sep 23, 2026
176 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
NIKTONIKTO717 added a commit that referenced this pull request Sep 24, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_tsan) / STID 2508-4620 line of the ledger above: #116393 (external, open). It is the same defect as #121079: a below-level size0 of an Array(JSON) value read from the Dynamic shared variant is resolved again at array level 0, where it means the array sizes.

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-improvement Pull request with some product improvements 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.

Refreshable materialized view: apply RANDOMIZE FOR on each replica independently

3 participants