Repository navigation
Stop refreshable MV gracefully when the Keeper feature-flag check races on attach - #108890
Conversation
…es on attach Follow-up to ClickHouse#108441. That PR made the RefreshTask constructor stop a coordinated refreshable materialized view gracefully (permanent coordination.unavailable, view Disabled) when it is attached on a Keeper that lacks the MULTI_READ / CREATE_IF_NOT_EXISTS feature flags, instead of crash-looping the server. But the constructor's check is a one-shot read, and the flag is negotiated once per Keeper connection. When the view is re-attached during a (re)start, its Keeper connection can read the flags before it settles on the current (downgraded) Keeper and see MULTI_READ as still present. The view then stays coordinated, and the scheduling thread later throws NOT_IMPLEMENTED in readZnodesIfNeeded, which the doScheduling catch-all re-raises as a LOGICAL_ERROR and aborts the server (and crash-loops on restart). coordination.unavailable was only ever set in the constructor, so nothing recovered from that raced state. Re-check the feature flags on the scheduling thread, in doScheduling, right after fetching the coordinated Keeper connection and before readZnodesIfNeeded. If they are missing, enter the same permanent "coordination unavailable" Disabled state the constructor would, instead of letting readZnodesIfNeeded throw. This closes the race regardless of when the missing flag becomes visible (constructor time or first scheduling pass). The detection and the state transition are factored into shared helpers (coordinationFeatureFlagsMissing, markCoordinationUnavailable) used by both the constructor and doScheduling. The happy path and the fresh-CREATE NOT_IMPLEMENTED rejection are unchanged. Adds an integration test that reproduces the race deterministically: a new failpoint (refresh_mv_skip_attach_feature_flag_check) makes the constructor's check behave as if the flags were present, so the view attaches as coordinated on a Keeper without MULTI_READ, exactly the post-race state. Without this fix the test reproduces the "Unexpected exception in refresh scheduling" abort and crash-loop; with it the server stays up and the view ends up Disabled. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260630-033600 |
|
cc @al13n321 @tuanpach — could you review this? Follow-up to #108441: the refresh task's Keeper feature-flag check ( |
|
Workflow [PR], commit [ba0700b] Summary: ✅
AI ReviewSummaryThis PR hardens Final Verdict✅ No new findings. |
…flags The doScheduling feature-flag re-check (added in this PR to close the attach-time propagation race) ran before the existing local refresh reconciliation. If a scheduling pass discovered missing MULTI_READ / CREATE_IF_NOT_EXISTS while this replica already had a refresh in flight (Requested/Running/Finished), it set coordination.unavailable and returned without cancelling the refresh or finalizing its Keeper state. A non-APPEND refresh could then keep exchanging/dropping tables locally while Keeper still believed the refresh was running, blocking the coordinated view on other replicas until session expiry. Cancel or reset any non-None execution.state before the permanent give-up, mirroring the existing reconciliation idiom. We cannot finalize the refresh in Keeper here (that needs the multi-read this Keeper lacks, and a throwing write would hit the catch-all and abort the server), so we just cancel it; the stale '/running' ephemeral znode is reclaimed by the existing crashed-replica grace period. Adds a test-only failpoint refresh_mv_force_scheduling_feature_flags_missing and an integration test that runs a slow coordinated refresh on a healthy Keeper, forces the next scheduling pass to see the flags as missing, and verifies the in-flight refresh is cancelled (the target table stays empty) rather than completing the table exchange outside coordination. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch, fixed in 2179fed. The if (execution.state == ExecutionState::State::Finished)
execution.state = ExecutionState::State::None;
else if (execution.state != ExecutionState::State::None)
interruptExecution();
markCoordinationUnavailable();
setState(RefreshState::Disabled, lock);
return;I deliberately do not finalize the refresh in Keeper here: that path needs the multi-read this Keeper lacks, and a throwing write would land in the For coverage I added a test-only failpoint
|
|
Pre-PR validation gate for 2179fed (the in-flight reconciliation fix). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-10:20260630-154000 |
The doScheduling missing-flags give-up branch calls interruptExecution() to cancel an in-flight refresh, but interruptExecution() only cancels the PipelineExecutor. executeRefreshUnlocked() runs with the mutex released and has no cancellation check between the post-executor check and exchangeTargetTable(): once the insert pipeline finished, the executor is gone, so a cancellation that lands in that post-insert window is not observed and the non-APPEND refresh proceeds to exchange the target table outside coordination, while Keeper still records this replica as running the refresh. Re-check execution.interrupt_execution (under executor_mutex, mirroring the existing pre-executor check) right before the exchange. A cancellation in the post-insert window now throws QUERY_WAS_CANCELLED, which the existing catch path turns into a cancelled outcome and drops the freshly-created temp table, leaving the real target untouched. Add a deterministic integration test for that window: a pauseable failpoint (refresh_mv_pause_before_exchange) holds the refresh thread after the insert and before the exchange, a scheduling pass forced to see the flags missing cancels it, and the test asserts the target table is not swapped (stays empty). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260630-182100 |
CI finish ledger — 2ac7e82Every 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
No PR-caused failures: this PR hardens Session id: cron:our-pr-ci-monitor:20260701-003000 |
|
@groeneai Check the CI failure and open discussion |
|
@tuanpach The only red checks on the current head (
These are not caused by this PR:
Owner / fixing PRs for the stress-shutdown hung-check family: #108212 (merged) and #105905 (merged). Everything else in the earlier CI finish ledger has since gone green on re-run; only the chronic TSAN hung-check remains, and it does not gate this change. From this PR's side the change is functionally clean and ready for review/merge. Happy to dig further if you're seeing a specific failure I've missed. |
|
@groeneai Merge master to this branch. |
…k-multiread-attach-race-followup
|
Merged master, new head 8812c32. Clean auto-merge (master's |
The doScheduling missing-flags branch called markCoordinationUnavailable() unconditionally, even while a refresh was Running. interruptExecution() only cancels the pipeline executor, and executeRefreshUnlocked() runs with the mutex released: the pre-exchange interrupt re-check reads the flag under executor_mutex, releases it, then exchanges. A scheduling pass landing in that gap set coordination.unavailable while the refresh thread still exchanged the target table, and because every later doScheduling pass then bailed at the top before the in-flight attempt was reconciled, the Finished result was never recorded and '/running' was never cleared, leaving Keeper believing this replica was still running. Fix: when the flags are missing and a refresh is still in flight (Requested or Running), only interrupt it and stay Running; do not declare coordination unavailable yet. The attempt reaches Finished, and the next scheduling pass (Finished -> None) gives up coordination cleanly. On shutdown there is no next pass, so give up immediately as before. New failpoint refresh_mv_pause_after_interrupt_check reproduces the exchange-wins gap deterministically; the two integration tests now assert the view is not prematurely disabled while the refresh is in flight. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pre-PR validation gate for the round-4 fix (commit 47be501): Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260708-062100 |
…n give-up When doScheduling detects missing Keeper feature flags while a refresh is in flight, it defers giving up coordination and lets the attempt reach Finished. The next scheduling pass hit the missing-flags branch again, converted Finished to None, and called markCoordinationUnavailable directly, skipping the ordinary Finished path that records the attempt and clears the /running lock. If the exchange won the pre-exchange interrupt race, the target table was already swapped, but Keeper and system.view_refreshes stayed on the pre-refresh state (last_success_* not written, dependents not notified) and /running was left dangling until another replica reclaimed it as a crash. Reconcile execution.znode via updateCoordinationState before entering the permanent unavailable state. That write only does set plus optional remove, so it needs neither MULTI_READ nor CREATE_IF_NOT_EXISTS and works on the downgraded Keeper. The exchange-wins test now asserts last_success_time is recorded and /running is cleared. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pre-PR validation gate for the round-5 fix (commit e86051b). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260708-085600 |
CI finish ledger — e86051bCI has fully finished on this commit. Every failing check below has an owner. No failure is caused by this PR's diff.
Session id: cron:our-pr-ci-monitor:20260709-020000 |
|
@groeneai check the CI failure. Any PRs fixing them? Merge master to this branch. |
…k-multiread-attach-race-followup
|
@tuanpach Done, and CI checked. Merged master into the branch. New head: CI failures on the previous head (e86051b) - none caused by this PR:
I did not find an open fixing PR for the 3772-3b00 ZSTD segfault (matcher #105221 was closed 2026-05-19 but it recurs on ASan builds); it is an ASan-build background-merge crash unrelated to this PR. The llvm_coverage server-death is a chronic-cluster infra event, also unrelated. Both are being re-rolled by the fresh CI run on the merged head. |
…ure-flags-missing give-up path The feature-flags-missing give-up path reconciles a Finished in-flight refresh in Keeper with a version-checked set(). If this replica lost its Keeper session while the refresh was running, another replica can advance the coordination znode first (reclaim the stale '/running' lock via the crashed-replica grace period, or start the next refresh), so the reconciling set() is rejected with ZBADVERSION. This path returns before readZnodesIfNeeded, the only place should_reread_znodes is consumed, and updateCoordinationState converts version mismatches into a re-read for the running=true acquire path only. So retrying reuses the same stale version and loops in Scheduling forever instead of converging to Disabled. A lost-ownership conflict is terminal: another replica now owns the coordination state, the ephemeral '/running' was already dropped by the session loss, and this replica is giving up coordination permanently anyway. Swallow the ZBADVERSION and converge to Disabled. Adds refresh_mv_force_coordination_version_conflict failpoint and an integration test (test_refreshable_mv_scheduling_missing_flags_lost_ownership_race) that forces the conflict deterministically: without the fix the view stays in Scheduling forever; with it the view converges to Disabled with no scheduling-thread abort. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — af42ce0Every failure below has an owner. Only
Chronic hung-check family (leaked local ThreadPool at GlobalThreadPool shutdown): 85 distinct PRs / 124 hits in the last 7 days; not caused by this PR (failpoint-gated diff, inactive in this job). CIDB report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108890&sha=af42ce0a94912c7818d2a47800a277936628b524&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 |
|
@groeneai Why does CI have many skipped jobs? Check them please. |
|
The 124 "skipped" checks are not 124 skipped jobs. Splitting them by what praktika actually recorded for head af42ce0 (report
The single root failure is
So nothing here needs a code change: one unrelated hung-check killed one job and the dependency cascade greyed out the rest. "Re-run failed jobs" on run 29634912448 would unwind it while keeping the 42 already-green jobs, but I do not have the rights for that (the API returns 403 "Must have admin rights"). The branch is now 3152 commits behind master, so I am merging master and pushing instead, which gives a fresh full run; I will confirm the new head here. |
…k-multiread-attach-race-followup
…ags are missing The doScheduling feature-flags-missing give-up path had three defects that the earlier rounds of this PR left behind. 1. Only ZBADVERSION was treated as a terminal lost-ownership conflict. The reconciliation is a multi of a version-checked set() plus a remove() of the ephemeral '/running' znode, and ZooKeeper::tryMulti returns user errors rather than throwing, so Coordination::isUserError routes both ZBADVERSION and ZNONODE through KeeperMultiException::check identically. A Keeper session loss drops '/running' without necessarily advancing the root znode version, and on a single replica nothing advances that version at all, so ZNONODE is the more likely shape of the race the ZBADVERSION handling was added for. The escaping ZNONODE reached the outer handler, which reschedules; the give-up path returns before readZnodesIfNeeded, so running_znode_exists stayed cached true, the same doomed remove was retried, and the view spun in Scheduling forever. 2. Under shutdown, a Requested attempt was only interrupted. execution_task is already deactivated at that point, so interruptExecution() sets a flag nobody reads and the give-up returned having written nothing to Keeper. refresh_running and '/running' then dangled until this replica's Keeper session expired plus the crashed-replica grace period, blocking the view on every other replica. The normal path already normalizes Requested to Finished under shutdown; do the same here so the reconciliation runs. 3. markCoordinationUnavailable() is the first asynchronous writer of coordination.unavailable, which is documented as mutex-protected. That turned the pre-existing unlocked read in finalizeRestoreFromBackup into a real race whose stale false let startReplicated() remove the global '/paused' znode, unpausing the view on every replica while this one stays permanently Disabled. Check it inside startReplicated() under the lock it already takes, mirroring the refusal in start(), instead of racily duplicating the check in the caller. Each fix is covered by an integration test and verified by reverting only that fix and observing exactly the corresponding failure: the ZNONODE test hangs in Scheduling, the shutdown test finds '/running' still present, and the replicated start test finds '/paused' removed. Co-Authored-By: Claude Fable 5 <[email protected]>
A Keeper multi is atomic, so when the reconciliation's remove() of '/running' failed with ZNONODE, the version-checked root update was rolled back too - even though its own version check had passed. The previous commit then treated the whole multi as terminal lost ownership, so the finished attempt's result (last_success_*/last_attempt_*) was never recorded and persistent refresh_running stayed set. For a coordinated APPEND view, whose rows are written directly rather than swapped in, the unchanged attempt metadata would make a later retry append the same timeslot a second time. '/running' being absent is the state the reconciliation wanted anyway, so when the failed operation is the removal (failed_op_index > 0) redo the root update on its own. A ZBADVERSION on the root operation itself still means another replica owns the coordination state, so there is nothing of ours left to write. Co-Authored-By: Claude Fable 5 <[email protected]>
The missing-feature give-up path reconciled the local attempt without first checking that this replica still owns the coordination state. The normal path requires refresh_running && last_attempt_replica == our replica before touching it, precisely because a Keeper reconnect re-reads the root znode: the cached copy can already describe another replica that took the refresh lock over while our execution was still in flight. Reconciling then would clear that replica's refresh_running and remove its '/running' znode, cancelling an active refresh elsewhere in the cluster. Apply the same ownership condition here. When it does not hold, the local result is worthless anyway (the lock was taken from us), so discard it and continue to the permanent coordination-unavailable state. Co-Authored-By: Claude Fable 5 <[email protected]>
coordination.unavailable is only set once doScheduling has re-checked the Keeper feature flags, and that pass is scheduled asynchronously. A resume arriving first (SYSTEM START REPLICATED VIEW, or restore finalization, which calls startReplicated directly) therefore sees the cached flag still false, and removing '/paused' would unpause the view on every replica moments before this one is disabled permanently. The connection is already in hand at that point, so check it too. No test accompanies this: the asynchronous detection pass always wins the race before a client query can be issued, so the window is not reachable from an integration test, and a test that only asserts the cached-flag refusal passes with or without this check. Co-Authored-By: Claude Fable 5 <[email protected]>
Per `.claude/CLAUDE.md`, literal names of classes, functions and log messages belong in inline code blocks, and a function is written `f` rather than `f()`. This only rewrites comments added by the preceding commits of this branch; `gcc -fpreprocessed` output is byte-identical, so no code changed. Co-Authored-By: Claude Fable 5 <[email protected]>
|
New head: Merging master was not the only change. Reviewing the give-up path again before pushing turned up five real defects in it, three of them in code this PR itself added, so this round fixes those too:
Each of 1-4 is covered by an integration test and verified by reverting only that fix and confirming exactly the corresponding failure: the Two notes on the test work, since they cost me a wrong first attempt each. A server restart cannot exercise the shutdown path here at all: the harness stops the process right after connections close, so per-table shutdown never runs, and |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 103/127 (81.10%) · Uncovered code |
|
Seems that this silently permanently (until server restart) disabled refreshing on a replica on normal transient error (losing keeper connection for long enough for another replica to take over)? @tuanpach what's the idea behind it? Wouldn't all replicas (maybe except one) eventually get into this state, on a sufficiently long-running cluster? |
|
No, a transient session loss cannot reach that branch on its own. It is gated on the Keeper itself reporting the flags missing.
The two lost-ownership tests are the evidence: they run against a healthy Keeper and have to force the precondition with The permanent stop itself is from #108441: a coordinated view re-attached on a Keeper that had lost MULTI_READ (downgrade) threw NOT_IMPLEMENTED out of So on your third question: no induction from transient losses, and when the flags really are missing every replica converges to Disabled rather than all but one, which is the intent since coordination is impossible on that Keeper. One asymmetry is worth a second look, because it is the only way a healthy cluster could drift into this: the re-check can only go present -> missing, never back, since |
Related: #106737
Related: #108441
Related: #108889
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a coordinated refreshable materialized view (in a
Replicateddatabase) getting stuck when it is re-attached on a Keeper that lacks theMULTI_READfeature flag and the feature-flag check races on startup: the scheduling thread hitUnexpected exception in refresh scheduling(a server abort and restart loop in debug and sanitizer builds; a repeatedly logged error and a never-stopping view in release builds). The view now stops gracefully (statusDisabled).Description
Follow-up to #108441, which fixed the same failure (#106737) for the common case but left a residual race.
#108441 made the
RefreshTaskconstructor stop a coordinated refreshable MV gracefully (permanentcoordination.unavailable, viewDisabled) when it is attached on a Keeper missingMULTI_READ/CREATE_IF_NOT_EXISTS, instead of letting the scheduling thread throwNOT_IMPLEMENTED(which aborts the server in debug/sanitizer builds and leaves the view stuck in release builds).The constructor check is a one-shot read, and the flag is negotiated once per Keeper connection. When the view is re-attached during a (re)start, its Keeper connection can read the flags before it settles on the current (downgraded) Keeper and see
MULTI_READas still present. The view then stays coordinated,coordination.unavailableis never set (it was only ever set in the constructor), and the scheduling thread later throwsNOT_IMPLEMENTEDinreadZnodesIfNeeded, which thedoSchedulingcatch-all turns intoUnexpected exception in refresh scheduling: a server abort and restart loop in debug and sanitizer builds, and in release builds a thrownLOGICAL_ERRORthat is caught but leaves the view flapping (rescheduling and re-logging the error every pass) instead of stopping. This is reported on #100394 and shows up as the flakytest_refreshable_mv_attach_without_multi_readfailingassert 'Disabled' in 'Scheduled'on slow integration shards.This PR fixes the production code:
doSchedulingre-checks the feature flags on the scheduling thread, right after fetching the coordinated Keeper connection and beforereadZnodesIfNeeded. If they are missing it enters the same permanentcoordination.unavailableDisabledstate the constructor would, instead of lettingreadZnodesIfNeededthrow. This closes the race regardless of when the missing flag becomes visible (constructor time or first scheduling pass). Detection and the state transition are factored into shared helpers (coordinationFeatureFlagsMissing,markCoordinationUnavailable) used by both the constructor anddoScheduling. The happy path and the fresh-CREATENOT_IMPLEMENTEDrejection are unchanged.Because the fix makes the view converge to
Disabledeven when the constructor loses the race, it also removes the flakiness that the test-only #108889 targets, so this PR supersedes it.Reproduction and validation
The race is timing-dependent and does not reproduce on a fast host (a debug build passes 40/40), so the new integration test forces it deterministically. A new failpoint
refresh_mv_skip_attach_feature_flag_checkmakes the constructor's feature-flag check behave as if the flags were present; the no-multi-read Keeper config activates it via<fail_points_active>, so the view attaches as coordinated on a Keeper withoutMULTI_READ, exactly the post-race state. The new testtest_refreshable_mv_attach_feature_flag_propagation_racethen asserts the server stays up, the view ends upDisabled, and the catch-all abort count is unchanged across the restart.Validated in both directions on Build-ID-verified debug binaries:
doSchedulingre-check: the new test fails with repeatedLogical error: 'Unexpected exception in refresh scheduling'followed byabortOnFailedAssertionand a restart loop (the Logical error: 'Unexpected exception in refresh scheduling' (STID: 2508-3e7b) #106737 signature; the abort is debug/sanitizer-only).test_refreshable_mv_attach_without_multi_readpasses 10/10 underCLICKHOUSE_USE_DATABASE_DISK=1.Version info
26.8.1.205(included in26.8and later)