Skip to content

Stop refreshable MV gracefully when the Keeper feature-flag check races on attach - #108890

Merged
tuanpach merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/refreshtask-multiread-attach-race-followup
Jul 27, 2026
Merged

tuanpach merged 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/refreshtask-multiread-attach-race-followup

Conversation

@groeneai

@groeneai groeneai commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106737
Related: #108441
Related: #108889

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):

Fixed a coordinated refreshable materialized view (in a Replicated database) getting stuck when it is re-attached on a Keeper that lacks the MULTI_READ feature flag and the feature-flag check races on startup: the scheduling thread hit Unexpected 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 (status Disabled).

Description

Follow-up to #108441, which fixed the same failure (#106737) for the common case but left a residual race.

#108441 made the RefreshTask constructor stop a coordinated refreshable MV gracefully (permanent coordination.unavailable, view Disabled) when it is attached on a Keeper missing MULTI_READ / CREATE_IF_NOT_EXISTS, instead of letting the scheduling thread throw NOT_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_READ as still present. The view then stays coordinated, coordination.unavailable is never set (it was only ever set in the constructor), and the scheduling thread later throws NOT_IMPLEMENTED in readZnodesIfNeeded, which the doScheduling catch-all turns into Unexpected exception in refresh scheduling: a server abort and restart loop in debug and sanitizer builds, and in release builds a thrown LOGICAL_ERROR that 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 flaky test_refreshable_mv_attach_without_multi_read failing assert 'Disabled' in 'Scheduled' on slow integration shards.

This PR fixes the production code: doScheduling re-checks the feature flags on the scheduling thread, right after fetching the coordinated Keeper connection and before readZnodesIfNeeded. If they are missing it enters 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). 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.

Because the fix makes the view converge to Disabled even 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_check makes 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 without MULTI_READ, exactly the post-race state. The new test test_refreshable_mv_attach_feature_flag_propagation_race then asserts the server stays up, the view ends up Disabled, and the catch-all abort count is unchanged across the restart.

Validated in both directions on Build-ID-verified debug binaries:

  • Without the doScheduling re-check: the new test fails with repeated Logical error: 'Unexpected exception in refresh scheduling' followed by abortOnFailedAssertion and a restart loop (the Logical error: 'Unexpected exception in refresh scheduling' (STID: 2508-3e7b) #106737 signature; the abort is debug/sanitizer-only).
  • With the fix: the new test passes 3/3, and the existing test_refreshable_mv_attach_without_multi_read passes 10/10 under CLICKHOUSE_USE_DATABASE_DISK=1.

Version info

  • Merged into: 26.8.1.205 (included in 26.8 and later)

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The timing race does not reproduce on a fast host (debug passes 40/40), so it is forced deterministically: failpoint refresh_mv_skip_attach_feature_flag_check (activated at startup via <fail_points_active> in the no-multi-read Keeper config) makes the constructor's feature-flag check behave as if the flags were present, putting the view in the exact post-race state on a Keeper without MULTI_READ. The new test test_refreshable_mv_attach_feature_flag_propagation_race hits it on demand.
b Root cause explained? The constructor reads the Keeper feature flags once at attach, and coordination.unavailable was only ever set there. On a (re)start the re-attaching view's Keeper connection can negotiate flags before settling on the current (downgraded) Keeper and see MULTI_READ as present, so the view stays coordinated. The scheduling thread then throws NOT_IMPLEMENTED in readZnodesIfNeeded, the doScheduling catch-all raises Unexpected exception in refresh scheduling -> abortOnFailedAssertion (debug/sanitizer) or a caught-but-flapping view (release).
c Fix matches root cause? Yes. doScheduling re-checks the feature flags on the scheduling thread, right after fetching the coordinated Keeper connection and before readZnodesIfNeeded, and converges to the same permanent coordination.unavailable Disabled state the constructor would. It addresses the mechanism (a stale one-shot read) directly, not the symptom.
d Test intent preserved / new tests added? New deterministic regression test added (test_refreshable_mv_attach_feature_flag_propagation_race) plus a startup-config failpoint to force the race. The existing test_refreshable_mv_attach_without_multi_read is unchanged and still exercises the constructor-time graceful stop.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. Without the doScheduling re-check: repeated Logical error: 'Unexpected exception in refresh scheduling' -> abortOnFailedAssertion -> restart loop. With the fix: new test passes 3/3, existing test passes 10/10 under CLICKHOUSE_USE_DATABASE_DISK=1.
f Fix is general across code paths? Yes. The two places that can detect missing flags (constructor at attach, scheduling thread at first pass) now share coordinationFeatureFlagsMissing and markCoordinationUnavailable, so both converge to the identical permanent Disabled stop. readZnodesIfNeeded's own NOT_IMPLEMENTED guard remains as the last-resort path. No symptom-only guard: the bad state (a coordinated view on an incapable Keeper) is detected at its first actionable point and stopped, with coordinated deliberately kept true so it never degrades into an uncoordinated local refresh.
g Fix generalizes across inputs? The condition is binary (the Keeper either advertises MULTI_READ/CREATE_IF_NOT_EXISTS or not); both flags are checked, matching the constructor. No datatype/parameter/wrapper axis applies. The graceful-stop path is the same for attach and restore-from-backup (both keep coordinated true and refuse to resume).
h Backward compatible? Yes. No setting, on-disk, wire, or metadata format change. Behavior only changes for the broken case (a coordinated view on a Keeper missing required flags), which previously aborted/flapped and now stops gracefully. The happy path and the fresh-CREATE NOT_IMPLEMENTED rejection are unchanged.
i Invariants and contracts preserved? Yes. The re-check runs under the doScheduling mutex (lock), like the surrounding code, before any Keeper access. It leaves coordination.coordinated = true (so a non-APPEND coordinated view never degrades into an uncoordinated local refresh that would corrupt the replicated target table) and reaches a terminal Disabled state that start() / finalizeRestoreFromBackup() already refuse to resume. The added failpoint compiles out when FIU is disabled.

Session id: cron:clickhouse-worker-slot-3:20260630-033600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @tuanpach — could you review this? Follow-up to #108441: the refresh task's Keeper feature-flag check (MULTI_READ/CREATE_IF_NOT_EXISTS) is a one-shot read in the constructor, so a view re-attached during a restart can read the flags before its Keeper connection settles on the downgraded Keeper, stay coordinated, and later abort the scheduling thread with Unexpected exception in refresh scheduling. This re-checks the flags in doScheduling and stops the view gracefully (Disabled) instead. It fixes the production race behind the flaky test_refreshable_mv_attach_without_multi_read, so it supersedes the test-only #108889.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ba0700b]

Summary: ✅


AI Review

Summary

This PR hardens RefreshTask against Keeper feature-flag loss during attach/startup and while a coordinated refresh is already in flight, and it adds focused integration coverage for the race windows discussed on the PR. After reviewing the current code and the full prior discussion, I did not find any remaining correctness, compatibility, or state-reconciliation issues in HEAD; the previously raised thread findings appear addressed.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 30, 2026
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch, fixed in 2179fed.

The doScheduling re-check must stay before readZnodesIfNeeded (which itself throws NOT_IMPLEMENTED without MULTI_READ, the original bug), so I went with reconciling the in-flight refresh rather than restricting the check to the pre-refresh path. Before the permanent give-up I now cancel or reset any non-None execution.state, mirroring the existing reconciliation idiom in the else branch a few lines below:

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 doScheduling catch-all, which is the exact server abort this PR removes. Cancelling is enough for correctness: the stale refresh_running flag plus the ephemeral /running znode are reclaimed by the existing crashed-replica grace period (the running_znode_missing_since path), so another replica can take over, same as if this replica had crashed mid-refresh.

For coverage I added a test-only failpoint refresh_mv_force_scheduling_feature_flags_missing and test_refreshable_mv_scheduling_detects_missing_flags_mid_refresh: a coordinated view runs a slow refresh on a healthy (multi-read) Keeper, the failpoint makes the next scheduling pass see the flags as missing while the refresh is Running, and the test asserts the in-flight refresh is cancelled (the target table stays empty) and the view ends Disabled with no scheduling-thread abort. Validated both directions on Build-ID-verified debug binaries:

  • Without the reconciliation: AssertionError: the cancelled refresh leaked 20 rows into the target (the refresh kept running and completed the table exchange outside coordination, exactly this finding).
  • With the fix: the new test passes, and the whole test_refreshable_mv_no_multi_read suite passes 3/3.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for 2179fed (the in-flight reconciliation fix).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The flags cannot flip on a live connection, so the mid-refresh case is forced with the test-only failpoint refresh_mv_force_scheduling_feature_flags_missing: a coordinated view runs a slow refresh on a healthy Keeper and the next scheduling pass is made to see the flags as missing while the refresh is Running. test_refreshable_mv_scheduling_detects_missing_flags_mid_refresh hits it on demand.
b Root cause explained? The doScheduling feature-flag re-check (added in this PR) runs before the local Requested/Running/Finished reconciliation. If it fires while a refresh is in flight, it sets coordination.unavailable and returns without cancelling the refresh, so a non-APPEND refresh keeps running and completes its table exchange locally while Keeper still records refresh_running for this replica, blocking the coordinated view on other replicas until session expiry.
c Fix matches root cause? Yes. Before the permanent give-up, the patch reconciles the local execution: Finished is reset to None, any other non-None state (Requested/Running) is cancelled via interruptExecution(). It does not write to Keeper (that needs the missing multi-read and a throwing write would hit the catch-all abort); the stale refresh_running//running znode is reclaimed by the existing crashed-replica grace period.
d Test intent preserved / new tests added? New regression test added (test_refreshable_mv_scheduling_detects_missing_flags_mid_refresh) plus the supporting failpoint. The two existing tests in the suite are unchanged and still pass.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. Without the reconciliation: AssertionError: the cancelled refresh leaked 20 rows into the target. With the fix: the new test passes and the full test_refreshable_mv_no_multi_read suite passes 3/3.
f Fix is general across code paths? Yes. There is exactly one give-up site on the scheduling thread (the doScheduling re-check); the constructor give-up runs before any refresh can be in flight, so it needs no reconciliation. The reconciliation mirrors the established idiom in the sibling else branch (execution.state != None → reset Finished / interruptExecution), so behavior is consistent across both reconciliation sites.
g Fix generalizes across inputs? The condition is binary (Keeper either advertises MULTI_READ/CREATE_IF_NOT_EXISTS or not) and the reconciliation covers every execution.state value: None (no-op), Finished (reset to None), Requested/Running (cancel). No datatype/parameter/wrapper axis applies. interruptExecution() is idempotent, so it is safe regardless of how the executor got there.
h Backward compatible? Yes. No setting, on-disk, wire, or metadata format change. Behavior changes only for the already-broken case (a coordinated view discovering missing Keeper flags mid-refresh), which previously leaked an uncoordinated refresh and now cancels it. The new failpoint compiles out when FIU is disabled.
i Invariants and contracts preserved? Yes. The reconciliation runs under the held doScheduling mutex (lock), and interruptExecution() requires that mutex (it asserts !mutex.try_lock()) and takes executor_mutex internally — matching the existing call site. It writes nothing to Keeper on this path, preserving the "never touch Keeper when flags are missing" invariant the re-check exists to enforce, and leaves coordination.coordinated = true so the view cannot degrade into an uncoordinated local refresh.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. refresh_mv_pause_before_exchange (pauseable) holds the refresh thread after the insert pipeline finishes and before the exchange; SYSTEM WAIT FAILPOINT ... PAUSE blocks until that point is reached; a scheduling pass with refresh_mv_force_scheduling_feature_flags_missing then cancels it. Fires every run.
b Root cause explained? interruptExecution() only cancels the PipelineExecutor. executeRefreshUnlocked runs with the mutex released and has no cancellation check between the post-executor block (executor already null) and exchangeTargetTable. A cancellation landing in that post-insert window is unobserved, so the non-APPEND exchange proceeds outside coordination while Keeper still records this replica as running -> blocks the coordinated view on other replicas.
c Fix matches root cause? Yes. Re-check execution.interrupt_execution under executor_mutex immediately before the exchange (mirrors the existing pre-executor check). Targets the unobserved-cancellation mechanism directly, not a symptom.
d Test intent preserved / new tests added? New integration test test_refreshable_mv_scheduling_detects_missing_flags_after_insert covering the post-insert window. The three prior tests are unchanged and still pass.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. Without the pre-exchange check: AssertionError: the cancelled refresh leaked 5 rows into the target. With it: new test passes, full suite 4/4 green.
f Fix is general across code paths? The exchange is the single destructive coordinated step in this path. Both give-up cases set the interrupt flag (Running -> interruptExecution; Finished reconciliation keeps it), so the one check covers both. APPEND refreshes do no exchange and are unaffected.
g Fix generalizes across inputs? N/A for input types: the guard is a control-flow cancellation check independent of column types/values. Exercised with the coordinated ReplicatedMergeTree non-APPEND refresh path, which is where the exchange occurs.
h Backward compatible? Yes. No setting, on-disk, wire, or Keeper-format change. Pure in-process cancellation ordering; the new failpoint is test-only (USE_LIBFIU).
i Invariants and contracts preserved? Yes. Throwing QUERY_WAS_CANCELLED enters the existing catch path, which drops the freshly-created temp table and returns nullopt, leaving the real target untouched (same contract as the other two cancellation checks). The check is taken under executor_mutex, the documented lock for interrupt_execution, so it serializes correctly against interruptExecution().

Session id: cron:clickhouse-worker-slot-8:20260630-182100

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 2ac7e82

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.

Check / test Reason Owner / fixing PR
Bugfix validation (integration, amd64+aarch64) / test_refreshable_mv_attach_without_multi_read (6 rows) expected bugfix-validation signal (job-level PASS: this PR's own regression test must FAIL on master to prove it catches the attach-race crash) PR-caused N/A (this PR @ 2ac7e82)
Stateless tests (arm_asan_ubsan, azure, parallel) / 03360_bool_remote flaky (connection-pool desync, Code 102 Unexpected packet; 16 unrelated PRs + 1 master / 30d) #108854 (external, open)
Stress test (amd_debug) / Not-ready Set (STID 0250-424f) trunk logical error (buildOrderedSetInplace; 3 PRs + 2 master / 30d) #102192 (external, open)
Stress test (amd_tsan) / Hung check ×2 deadlock (chronic stress-shutdown) #108212 (ours, merged) / #105905 (ours, open)
Stress test (arm_tsan) / Hung check deadlock #108212 (ours, merged) / #105905 (ours, open)
Unit tests (asan_ubsan, function_prop_fuzzer) / FunctionsStress.stress + AllTests trunk producer-scale bug: reinterpret(... AS Decimal(38,24), 'Decimal128(2)') returns unexpected scale (111 unrelated PRs + 16 master / 30d) #108878 (ours, open)
PR derivative aggregator (fails only due to the above) —
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable by us)

No PR-caused failures: this PR hardens RefreshTask to converge to a graceful Disabled stop when the Keeper feature-flag check races on attach; the Bugfix-validation per-test FAILs are the expected signal (job-level PASS), and every other red check is a pre-existing trunk flake/bug owned above.

Session id: cron:our-pr-ci-monitor:20260701-003000

@tuanpach

tuanpach commented Jul 8, 2026

Copy link
Copy Markdown
Member

@groeneai Check the CI failure and open discussion

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

@tuanpach The only red checks on the current head (2ac7e82f88f9) are two Stress test Hung checks:

  • Stress test (amd_tsan) / Hung check failed, possible deadlock found
  • Stress test (arm_tsan) / Hung check failed, possible deadlock found

These are not caused by this PR:

  1. The stack contains no RefreshTask / MaterializedView frames. The captured hung_check.log backtraces are entirely in generic query paths (QueryAnalyzer, FunctionsConversion, IFunction, SerializationAggregateFunction, aggregate min/max) with zero frames from src/Storages/MaterializedView/RefreshTask.cpp or exchangeTargetTable. Nothing in this PR's diff appears on the hang path.
  2. It is a chronic trunk deadlock, not a regression here. Over the last 30 days the Stress test (*_tsan) Hung check fired on 332 distinct PRs and 169 times on master (965 total). It hits unrelated PRs at the same rate.

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.

@tuanpach

tuanpach commented Jul 8, 2026

Copy link
Copy Markdown
Member

@groeneai Merge master to this branch.

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master, new head 8812c32. Clean auto-merge (master's executing_query_status/interruptExecution changes and the pre-exchange interrupt check integrated without conflict; RefreshTask.cpp compiles). Only this PR's 5 files differ from master, no submodule drift. CI re-running.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the round-4 fix (commit 47be501):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New pauseable failpoint refresh_mv_pause_after_interrupt_check holds the refresh thread in the exact RefreshTask.cpp:1248-1255 gap; a forced scheduling pass (refresh_mv_force_scheduling_feature_flags_missing) then reproduces the premature-disable deterministically.
b Root cause explained? Yes. Missing-flags branch called markCoordinationUnavailable() unconditionally while state==Running. interruptExecution() only cancels the executor; executeRefreshUnlocked() runs with mutex released and can win the interrupt-read -> exchange race. Once coordination.unavailable is set, every later doScheduling bails before reconciling the in-flight attempt -> Finished result never recorded, /running never cleared.
c Fix matches root cause? Yes. When flags are missing and a refresh is in flight (Requested/Running), only interrupt and stay Running; defer markCoordinationUnavailable to the next pass (Finished -> None) which reconciles cleanly. Directly removes the premature permanent-disable.
d Test intent preserved / new tests added? Yes. Added test_refreshable_mv_scheduling_missing_flags_when_exchange_wins_race (asserts not-prematurely-disabled + clean reconcile). Updated ..._after_insert to assert the same invariant. ..._mid_refresh still passes (interrupt outcome unchanged).
e Both directions demonstrated? Yes. Negative control (defer branch reverted, failpoints kept, Build ID 4a5b78dd): both new/updated tests FAIL with assert 'Disabled' == 'Running'. With fix (Build ID 1e1bcd95): all three tests pass (integration runner, amd_tsan config).
f Fix is general across code paths? Yes. markCoordinationUnavailable has exactly two reachable sites: the attach-time constructor path (no in-flight refresh possible) and this doScheduling branch. The in-flight case only exists here. Not a symptom guard: it fixes the state-machine transition at the point the decision is made.
g Fix generalizes across inputs? N/A (coordination state-machine fix, not a datatype/parameter code bug). Covers both in-flight states (Requested and Running) and both exit races (pre-exchange-check-wins and exchange-wins).
h Backward compatible? Yes. No settings, on-disk/wire/Keeper format, or public behavior change. Only reorders when a view that lost coordination becomes Disabled (one scheduling hop later, after the in-flight attempt reconciles).
i Invariants and contracts preserved? Yes. execution.state remains read/written only under mutex. New branch returns while owns_lock() holds (like the other early returns). interruptExecution() precondition (mutex held, not executor_mutex) is satisfied. coordination.unavailable is still set exactly once, on the reconciling pass. Shutdown path unchanged (is_shutdown guard falls through to immediate give-up).

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the round-5 fix (commit e86051b).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT refresh_mv_pause_after_interrupt_check pauses the refresh thread in the post-interrupt-check window; a forced missing-flags scheduling pass then defers give-up; on resume the exchange wins and the attempt reaches Finished. Without the fix, the next missing-flags pass drops the Finished result. Test test_refreshable_mv_scheduling_missing_flags_when_exchange_wins_race.
b Root cause explained? The deferred in-flight attempt reaches Finished; the next missing-flags scheduling pass (RefreshTask.cpp Finished branch) set execution.state = None and called markCoordinationUnavailable() directly, bypassing the ordinary Finished reconciliation (updateCoordinationState). So last_success_*/last_attempt_* were never written back, notifyDependentsIfNeeded never fired, and the /running lock was left dangling while the target table had already been swapped.
c Fix matches root cause? Yes. The Finished-in-missing-flags branch now reconciles execution.znode via updateCoordinationState(running=false) (with the same version-mismatch handling as the normal Finished path) before markCoordinationUnavailable().
d Test intent preserved / new tests? Yes. Existing assertions (view ends Disabled, no scheduling-thread abort, target holds the refreshed rows) are unchanged. Extended the exchange-wins test to also assert last_success_time IS NOT NULL and that the /running znode is cleared.
e Demonstrated both directions? Yes. Negative control (reconciliation reverted, failpoint+test kept, Build ID cc9a174b): test FAILS AssertionError: assert '0' == '1' (last_success_time NULL). With fix (Build ID 748a3d06): all 3 tests pass (80.75s, amd_tsan integration config).
f Fix general, not a narrow patch? Yes. The reconciliation mirrors the single canonical Finished path (updateCoordinationState), covering both the version-match and version-mismatch cases; no sibling give-up path bypasses it.
g Generalizes across inputs? The give-up branch handles all execution.state values: Finished -> reconcile then None; Requested/Running -> defer (interrupt + stay Running); None -> nothing to reconcile.
h Backward compatible? Yes. No setting, on-disk, wire, or Keeper-schema change. updateCoordinationState(running=false) uses only set+remove, which need no extra Keeper feature flags.
i Invariants preserved? Yes. updateCoordinationState runs under mutex (asserted); the write releases and re-acquires the mutex exactly as every other caller does; coordination.root_znode/running_znode_exists are updated consistently; markCoordinationUnavailable still follows, keeping the permanent-stop invariant.

Session id: cron:clickhouse-worker-slot-0:20260708-085600

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e86051b

CI has fully finished on this commit. Every failing check below has an owner. No failure is caused by this PR's diff.

Check / test Reason Owner
Stateless tests (arm_asan_ubsan, targeted): Segmentation fault (STID: 3772-3b00) + Server died crash (pre-existing trunk) Not PR-caused. Segfault is in the ZSTD compression codec (ZSTD_compressBlock_fast -> CompressionCodecZSTD::doCompressData), a MergeMutate read->write heap-corruption family unrelated to this PR's RefreshTask change. 30d: 6 distinct unrelated PRs, 0 master (for this raw STID). Tracked under upstream investigation issue #106370; a full-effort fix task owns it.
Bugfix validation (integration tests, amd64 / aarch64): test_refreshable_mv_attach_without_multi_read expected Check status is PASS. The individual test row shows FAIL because bugfix validation runs the new regression test on master HEAD (without the fix) where it correctly fails; it passes on this PR. This is the intended bugfix-validation outcome, not a failure.
Stateless (amd_llvm_coverage, ... WasmEdge ...) transient server-died rows flaky/transient Shard PASSES at the check level (retry succeeded). Transient server health-check timeout, not PR-caused.

Session id: cron:our-pr-ci-monitor:20260709-020000

@tuanpach

Copy link
Copy Markdown
Member

@groeneai check the CI failure. Any PRs fixing them? Merge master to this branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tuanpach Done, and CI checked.

Merged master into the branch. New head: 4a1485f104597a254696bab004898f11df6dd3ac (was e86051b). Clean auto-merge, no conflicts; net diff vs master is only this PR's 5 files (+544), no submodule drift. Master had rewritten interruptExecution (now also cancels the query via executing_query_status); I rebuilt the full binary against merged master (0 errors) and re-ran the integration suite test_refreshable_mv_no_multi_read -> 5/5 passed, so the coordination fix is still correct on top of the refactor. CI is re-running now.

CI failures on the previous head (e86051b) - none caused by this PR:

Check Failure Classification / owner
Stateless (arm_asan_ubsan, targeted) Segfault STID 3772-3b00 Not PR-caused. ZSTD compression crash in a background MergeTree part write (ZSTD_wildcopy -> MergeTreeDataPartWriterWide::fillDataChecksums); zero RefreshTask frames. Chronic ASan-build crash: 6 unrelated PRs, 0 master in 30d. Matcher issue #105221.
Stateless (amd_llvm_coverage, old analyzer, DatabaseReplicated, ...) 7 tests + "Unknown error" Not PR-caused. All are fallout from one server death on that runner ("shutting down due to a fatal error (ABORTED)", "server died", "Lost connection"), not test-logic failures. e.g. 03915_exchange_tables_race = 55 PRs / 10 master in 30d.
Bugfix validation (integration tests) test_refreshable_mv_attach_without_multi_read FAIL Expected signal, not a real failure: the Bug Fix regression test is required to FAIL on master HEAD (without this fix) and PASS with it. Job-level verdict is PASS.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — af42ce0

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) hung-check deadlock at test 10967/11655 (Hung check failed: server is not responding; server unresponsive at shutdown, connections refused; all refreshable-MV tests passed, no RefreshTask frame in any stack) #105905 (ours, open) / #108212 (ours, merged)
Finish Workflow / Mergeable Check / PR rollup red reflecting the single hung-check job above #105905 (ours, open) / #108212 (ours, merged)

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

@tuanpach

Copy link
Copy Markdown
Member

@groeneai Why does CI have many skipped jobs?

Check them please.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The 124 "skipped" checks are not 124 skipped jobs. Splitting them by what praktika actually recorded for head af42ce0 (report result_pr.json: 42 OK, 22 SKIPPED, 107 DROPPED, 1 ERROR, 1 FAIL):

  • 107 = DROPPED by the failure cascade, not skipped by a filter. Exactly one job failed, and praktika then marks every transitive dependee DROPPED (ci/praktika/hook_html.py:249-282, add_dependees recursion, skipping only run_unless_cancelled jobs). Independently, the generated per-job guard if: !cancelled() && !contains(needs.*.outputs.pipeline_status, 'failure') ... (ci/praktika/yaml_generator.py:270) prevents those jobs from starting, so GitHub reports them as "skipped". In pull_request.yml that one job has 117 transitive dependees (116 gated + finish_workflow, which is always()), which is where the number comes from. All 107 carry the note "Dropped due to previous failure [Stateless tests (amd_asan_ubsan, distributed plan, parallel)]".
  • 17 = genuine config-level skips, each with a reason in the report: "reused from cache" (3 docker builds), "Not affected by the changed files and not required" (Docs check x2, CI Tests), "Skipped, not labeled with 'pr-performance'" (6 perf shards), "Skipped, not labeled with 'ci-toolchain'" (2), "no changes in src/Coordination..." (Keeper Stress), "Skipped, no functional tests updates" (2 functional Bugfix validation). Those are normal.

The single root failure is Stateless tests (amd_asan_ubsan, distributed plan, parallel): at test 10967/11655 the job log records Hung check failed: server is not responding -> Reason: server died -> StopTesting. It is not caused by this PR: in that same job every refreshable-MV test passed (02932_refreshable_materialized_views_1/2/3, 03258_refreshable_mv_misc, 03760_refreshable_mv_local, 03221, 03327, 04201, 04218, 04327, 04329, 04401, 04408 - all [ OK ]), there is no RefreshTask/MaterializedView frame in any crash stack, and this diff is failpoint-gated so it is inert outside the test_refreshable_mv_no_multi_read integration job. This is the chronic hung-check family (fixing PRs #105905 open, #108212 merged), which hit 85 distinct PRs in the 7 days around that run. Report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/108890/af42ce0a94912c7818d2a47800a277936628b524/stateless_tests_amd_asan_ubsan_distributed_plan_parallel/job.log

Finish Workflow FAIL is second-order from the same cascade. new_tests_check.py requires at least one per-arch Bugfix Validation job to have validated the bug; both integration-arch jobs depend on the failed job and were therefore DROPPED, and the two functional-arch ones are legitimately SKIPPED (this PR adds no functional test). On the previous head 4a1485f, with no cascade, the same hook passed: Bugfix validation (integration tests, amd64) and (aarch64) both OK with the expected Failures: 1/5, Finish Workflow OK, 150 OK / 22 SKIPPED / 0 DROPPED.

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.

groeneai and others added 6 commits July 27, 2026 03:49
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

New head: ba0700b5c8b8ca35dcfd03a1777b740b255598ee (master merged in, so this gets a fresh full run instead of the dropped-by-cascade one).

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:

  1. Only ZBADVERSION was terminal, ZNONODE was not. The reconciliation is a multi of a version-checked set plus a remove of /running, ZooKeeper::tryMulti returns user errors instead of throwing, and Coordination::isUserError lists both codes, so both arrive the same way. A Keeper session loss drops the ephemeral /running without necessarily advancing the root version, and on a single replica nothing advances that version at all, so ZNONODE is the likelier shape of the race the ZBADVERSION handling was added for. It escaped to the outer handler, which reschedules; the give-up path returns before readZnodesIfNeeded, so running_znode_exists stayed cached true and the same doomed remove was retried forever.

  2. A multi is atomic, so a failed remove also rolled back a valid root update. Fixing (1) by swallowing ZNONODE was not enough: the root set's own version check had passed, but the rollback discarded the finished attempt's last_success_* and left persistent refresh_running set. For a coordinated APPEND view, whose rows are written directly rather than swapped in, a later retry would then append the same timeslot twice. When the failed operation is the removal, the root update is now redone on its own.

  3. The give-up path could clear another replica's active refresh. The normal path requires refresh_running && last_attempt_replica == our replica before touching coordination state; the give-up path had no such check. A reconnect re-reads the root, so the cached copy can already describe a replica that took the lock over while our execution was in flight. It now applies the same ownership condition and discards the local result instead.

  4. 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 the session expired plus the grace period, blocking the view on every other replica. It now normalizes Requested to Finished first, as the normal path already does.

  5. markCoordinationUnavailable is the first asynchronous writer of coordination.unavailable, which turned a pre-existing unlocked read in finalizeRestoreFromBackup into a real race whose stale false let startReplicated remove the cluster-wide /paused znode. The check now lives inside startReplicated, under the lock it already takes, mirroring the refusal in start; that also removes the time-of-check window rather than narrowing it. startReplicated additionally consults the Keeper connection it just obtained, since the cached flag is only set once the asynchronous recheck has run.

Each of 1-4 is covered by an integration test and verified by reverting only that fix and confirming exactly the corresponding failure: the ZNONODE test hangs in Scheduling, the atomicity test loses last_success_time, the shutdown test finds /running still present, and the replicated-start test finds /paused removed. Suite is 9/9 green. Item 5 ships without a test on purpose: the asynchronous detection pass always wins the race before a client query can be issued, so a test asserting only the cached-flag refusal passes with or without the new check, and I would rather not add a vacuous one.

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 DETACH TABLE ... PERMANENTLY SYNC is what reaches it. And fmt's formatter for Coordination::Error prints errorMessage's prose rather than the enum name, so the log line uses magic_enum::enum_name to keep ZBADVERSION / ZNONODE greppable.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 91.90% 92.00% +0.10%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 103/127 (81.10%) · Uncovered code

Full report · Diff report

@tuanpach
tuanpach added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit 2fc5a8b Jul 27, 2026
178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
@al13n321

Copy link
Copy Markdown
Contributor

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?

@groeneai

Copy link
Copy Markdown
Collaborator Author

No, a transient session loss cannot reach that branch on its own. It is gated on the Keeper itself reporting the flags missing.

doScheduling only enters the give-up path when coordinationFeatureFlagsMissing(*zookeeper) is true (RefreshTask.cpp:830-832). With MULTI_READ and CREATE_IF_NOT_EXISTS present, a lost session falls through to readZnodesIfNeeded and the ordinary ownership handling, which recovers: /running is re-created after a reconnect (:1038), and if another replica took the refresh over meanwhile, the local attempt is discarded and scheduling continues (:1056). Nothing sets coordination.unavailable there.

The two lost-ownership tests are the evidence: they run against a healthy Keeper and have to force the precondition with SYSTEM ENABLE FAILPOINT refresh_mv_force_scheduling_feature_flags_missing (test_refreshable_mv_no_multi_read/test.py:519, :552). Without that failpoint the branch is unreachable. My failpoint comments describe only the inner ZBADVERSION/ZNONODE condition, which is why they read as if a lost session were enough; that is my wording, not the gate.

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 readZnodesIfNeeded on the scheduling thread (:1752), which the catch-all turned into an abort, crash-looping on restart. Retrying inside the give-up path cannot work either, since it returns before the only place a fresh znode version is read, so it would spin on a stale version. #108890 added the doScheduling re-check for the attach-time race and reused that state.

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 coordination.unavailable short-circuits before any Keeper access (:810-817). If the attach-time read can ever report a capable Keeper as incapable (its own comment calls that read non-authoritative), the view stays Disabled with no way back short of re-attaching the table. I have not observed that direction and am not claiming it happens, but that is the case to close if you think the read can false-positive during a rolling Keeper restart.

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 pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants