Skip to content

Upgrade check: recover the read-only replicas that refuse KILL MUTATION - #121409

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/upgrade-check-recover-readonly-replica-before-kill
Sep 27, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/upgrade-check-recover-readonly-replica-before-kill

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120978
Related: #119425

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Upgrade check: report why a pre-upgrade KILL MUTATION failed, and recover the read-only replicas that refused it.

Description

Upgrade check (amd_release) reds with 1 mutations could not be killed before the upgrade:
4 failures against 331 OK runs of the counterpart assertion since #120978 landed, on 4 unrelated
pull requests, the only red in 3.
https://github.com/ClickHouse/ClickHouse/actions/runs/35581391859/job/106309904192

Root cause. 04070_truncate_all_tables_skip_views.sql runs TRUNCATE ALL TABLES FROM {CLICKHOUSE_DATABASE:Identifier}, in stress mode the runner's shared test_N database, holding
earlier tests' leftovers. On the previous release the unfiltered form still calls
flushAndPrepareForShutdown() on each table, which for ReplicatedMergeTree stops the restarting
thread and sets the replica permanently read-only; the truncate then throws TABLE_IS_READ_ONLY,
leaving the mutations. killMutation also begins with assertNotReadonly(), so every KILL MUTATION throws Code: 242, which ||: discards. #119425 fixed the product half on
master, but the stress phase runs the previous release's binary and queries (today
v26.8.10.6-lts, where I reproduced this), so only this script can act. A 26.9 release removes
that trigger; the fault-injection route and the reporting half do not depend on it.

Change, in the kill step only: each KILL MUTATION keeps its stderr in
unkilled_mutation_errors.txt, now named in the FAIL line, since the survivor is reported with an
empty latest_fail_reason; if one survives, SYSTEM RESTART REPLICA the read-only replicas still
holding it and kill again; and a restart that fails, or that leaves its replica read-only, writes
its own FAIL row whatever the count says, since system.mutations reports only what an attached,
initialized replica holds.

Validation. No harness runs upgrade_runner.sh, so I rebuilt the state on 26.8.10.6 and ran the
block. One fixture, both directions: FAIL with the old block, OK with the new. It still FAILs when
the count reaches zero: restart detaching the table (failpoint), or leaving the replica read-only
(Keeper stopped). On a clean server it does nothing; shellcheck unchanged.


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

Version info

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

The pre-upgrade kill loop added in ClickHouse#120978 reds with "N mutations could not be killed before
the upgrade" on pull requests unrelated to mutations: 4 failures against 331 OK runs of the
counterpart assertion since it landed on 2026-09-20, on 4 unrelated pull requests, in 3 of
them the job's only red.

In the three occurrences whose job logs I read, the kill threw Code: 242 TABLE_IS_READ_ONLY
and the deliberate `||:` discarded it. The chain: 04070_truncate_all_tables_skip_views.sql
runs TRUNCATE ALL TABLES FROM currentDatabase(), which in stress mode is the runner's shared
test_N database, so it covers every table earlier tests left behind (--upgrade-check implies
--fake-drop, so their DROPs were no-ops). On the previous release the unfiltered form still
calls flushAndPrepareForShutdown() on every table in the database;
StorageReplicatedMergeTree::flushAndPrepareForShutdown does
restarting_thread.shutdown(part_of_full_shutdown = true), which sets need_stop, deactivates
the task and calls setReadonly(), so the replica is read-only permanently with no thread left
to re-activate it. The per-table truncate then throws, because truncate() begins with
assertNotReadonly(), so the tables are left read-only and un-truncated with their mutations
intact. Thirteen minutes later the kill loop reaches killMutation(), which also begins with
assertNotReadonly().

ClickHouse#119425 fixed the product half on master, the `if (!truncate || !query.has_tables)` guard in
InterpreterDropQuery, but it is not backported and the stress phase runs the previous
release's binary and queries, so only this script can act. Reproduced on v26.8.10.6-lts,
which find_previous_release picks today.

Three changes, all in the kill step:

- Each KILL MUTATION keeps its stderr in unkilled_mutation_errors.txt, and the FAIL line
  names it. Today the survivor is reported with an empty latest_fail_reason, so the artifact
  says nothing about why the kill did not happen, and attributing one occurrence cost a whole
  investigation.

- If a mutation survives, SYSTEM RESTART REPLICA the read-only replicas that still hold one,
  then run the same kill pass again. Re-attaching the table builds it from its metadata and
  starts a replica that can remove the mutation's ZooKeeper node. Waiting instead cannot work
  for this cause: the restarting thread is deactivated, so no session-expiry check
  re-activates the replica. The no-argument SYSTEM RESTART REPLICAS is unusable here because
  restartReplicas() passes throw_on_error = false, so a table it fails to restart is left
  detached and its mutation silently disappears from system.mutations.

- A restart that does not report success, that changes the number of rows in system.replicas,
  or that leaves its own replica read-only, writes its own FAIL row whatever the count says.
  Without this the change would be fail-open, which is worse than the red it removes, and it
  is fail-open in two distinct ways. doRestartReplica() detaches before rebuilding, so a
  failure after that point leaves the table detached; and because it re-creates the table with
  LoadingStrictnessLevel::ATTACH the storage always goes through
  ReplicatedMergeTreeAttachThread, whose startup() only waits for the first initialization
  attempt and never rethrows, so a restart whose first attempt fails returns success and
  leaves the replica read-only with a retry scheduled initialization_retry_period later.
  system.mutations reports only what an attached, initialized replica holds, because the
  mutation queue is filled by pullLogsToQueue(..., LOAD) on the same success path that later
  calls setNotReadonly(). Either state would otherwise drive the count to zero and report
  success for a mutation still in ZooKeeper. That load order is also why the per-replica check
  is race-free: is_readonly = 0 implies the mutations are already loaded.

Validated against a real v26.8.10.6-lts server, since no harness executes upgrade_runner.sh.
On one fixture of two bricked replicated tables the old block reports FAIL and the new one
OK; on a clean server it does nothing, leaves no artifact, and never enters the recovery
block. Both fail-open shapes were injected and both produce the new FAIL row while
system.mutations has already reached zero: the restart_replica_fail_after_detach failpoint for
the detached table, and a stopped Keeper for the replica that stays read-only, where the
unguarded block reported "The stress phase left no unfinished mutation to the upgrade" for a
mutation whose znode was still there and which executed as soon as the replica came back.
shellcheck reports the same findings as before.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 21, 2026
@groeneai

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

Reviewed cold against the resulting code, then with an independent second model (engine: codex), then
adjudicated against the recorded evidence. 1 blocker and 7 nits over 1 full pass, 1 fix round and 1
delta recheck; the delta recheck returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ❌ A SYSTEM RESTART REPLICA that exits 0 without initializing the replica turned the assertion into a false OK: startup() waits only for the first initialization attempt and never rethrows, and is_readonly is cleared only after the mutations are loaded, so an uninitialized replica reports no mutations, the count reached zero, and the step reported success for a mutation still held in Keeper that the upgraded server then resumes AGREE, fixed @ ac0b31d Each restarted replica must now show count() = 1 over system.replicas with NOT is_readonly, keyed on the restarted names rather than on the mutation predicate, which vanishes in exactly that state, and fail-closed on an unreadable count. Checked in source on v26.8.10.6-lts, the release this step runs, as well as on master. Negative control with Keeper stopped: the old block reports OK while the mutation's znode is still present, the new one names the table and FAILs
2 💡 The replica-count guard's comment said a restart "leaves fewer replicas than it found" while the code compares "different" AGREE, fixed @ ac0b31d Prose corrected to "changes the number of replicas it found, or that leaves its replica still read-only"; the fail-closed comparison stays
3 💡 The validation-gate comment claimed the pre-upgrade log is "scanned by nothing" AGREE, fixed Not true: check_logs_for_critical_errors globs clickhouse-server*.log. The conclusion holds, since its only two patterns are Code: 499 ... The specified key does not exist and it is lost forever filtered on SharedMergeTreePartCheckThread, and a mutation error produces neither. Corrected before posting, because this change is what newly lets a revived mutation execute before the upgrade
4 💡 Each kill's stderr now reaches only the new artifact, not the job log AGREE, noted Not blocking: /test_output is uploaded and both FAIL rows name the file
5 💡 The surviving-mutation row names unkilled_mutation_errors.txt unconditionally, and that file is removed when empty AGREE, noted Reachable only when a kill matches no row yet the final count is non-zero; the row also names unkilled_mutations.txt, written in that path
6 💡 The post-restart kill pass swallows a listing failure that the first pass reports AGREE, noted Not a fail-open: the mutations stay in place, so the count below reports either the survivors or its own failure. Only attribution is lost
7 💡 The two clients inside the here-string loop inherit its stdin AGREE, noted Measured at two rows on v26.8.10.6-lts: both replicas restarted, and the flag set inside the loop was still readable after it
8 💡 The fix round hoisted the base64 -d decodes into plain assignments, which under set -e abort the runner on a failed decode AGREE, noted Unreachable: the input is server-produced base64Encode output. The failure direction is red rather than a false OK, and a bare x=$(...) is this file's existing style

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by the fix round are auto-dropped.

One property bounds the change: the recovery block is entered only when the unfinished-mutation count
is already non-zero, the same measurement, at the same point in the script, that decides today's red.
So it cannot turn a currently green run red, and its new FAIL rows only ever replace an existing one.

Session id: cron:clickhouse-review-slot-8:20260921-171300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on a v26.8.10.6-lts server: a ReplicatedMergeTree table, SYSTEM STOP MERGES, ALTER ... UPDATE ... SETTINGS mutations_sync = 0, then TRUNCATE ALL TABLES FROM <db>; the truncate throws TABLE_IS_READ_ONLY and the following KILL MUTATION throws Code: 242 on every run.
b Root cause explained? Yes, see the PR description: flushAndPrepareForShutdown() stops the restarting thread and sets the replica permanently read-only, and truncate and killMutation both start with assertNotReadonly(), so the tables keep their mutations and `
c Fix matches root cause? Yes: the cause is a replica that cannot service a kill, so the fix restores the replica and re-kills. No widened bound, no tolerated survivor, no suppressed assertion; the FAIL semantics of #120978 are untouched.
d Test intent preserved / new tests added? Preserved: both CIDB test_name strings stay byte-identical apart from the added and unkilled_mutation_errors.txt. No test file is added because no harness executes upgrade_runner.sh, so I ran the changed block verbatim against a real previous-release server.
e Both directions demonstrated? Yes, one fixture of two bricked replicated tables: the old block FAILs with latest_fail_error_code_name and latest_fail_reason both empty, matching the CI artifact, the new block reports OK with 0 unfinished mutations and 0 read-only replicas; the read-only guard has its own pair on that fixture with Keeper stopped.
f Fix is general across code paths? Yes: stress_runner.sh and stress_tests.lib have no kill-mutations step, stress.py::_kill_random_mutation tolerates failure by design, StorageMergeTree::killMutation has no read-only gate, and both routes to a read-only replica in this job are covered, the released-truncate one and the ZooKeeper fault injection.
g Fix generalizes across inputs? Yes: names travel base64-encoded over TSV and are substituted server-side as {...:Identifier}, so a space, tab, newline, quote or backtick is neither word-split by the shell nor parsed as SQL, and the kill still addresses mutations by cityHash64; cardinality exercised at 0, 1 and 2.
h Backward compatible? N/A in the usual sense: no setting, no SettingsChangesHistory.cpp, no header, no product code. The only externally visible surface is the two CIDB test_name strings, both pinned, plus one new artifact file written only when a kill failed.
i Invariants and contracts preserved? Yes: a failed listing is still reported instead of silently becoming an empty list, and a restart that fails, that changes the number of rows in system.replicas, or that leaves its replica read-only writes its own FAIL row, both fail-open shapes having been injected while the mutation count had already reached zero. A revived mutation's errors land in the pre-upgrade log, which the strict <Error> scan does not read and the two clickhouse-server*.log patterns do not match.

Session id: cron:clickhouse-impl-slot-4:20260921-162900

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2c15f0]

Summary: ✅


AI Review

Summary

This PR tightens the upgrade-check mutation cleanup path by recording KILL MUTATION errors, restarting only the read-only replicas that still hold unfinished mutations, and then reissuing the kills before the upgrade proceeds. On the current head, the earlier false-red paths raised in review are addressed: the restart validation is now per restarted table instead of comparing the global system.replicas count, the post-restart check matches the product-side startup sequence, and the PR's current CI report is fully green, including Upgrade check (amd_release). I did not find any new correctness or reliability issues in the current diff.

Final Verdict

✅ No actionable findings on the current head.

Comment thread tests/docker_scripts/upgrade_runner.sh Resolved
The kill step compares `system.replicas` before and after the restart pass to
catch a restart that detaches a table and leaves it detached: the count that
decides the red reports only what an attached replica holds, so that state would
report success for a mutation the upgraded server then resumes.

The comparison also ran when the selection of read-only replicas came back empty
and the pass restarted nothing. Such a run has none of those failures to answer
for, yet an unreadable or changed count still wrote `Cannot restart a read-only
replica ...`. Measured on 26.8.10.6, with the post-loop count timing out: the
step reds a run that killed every mutation and reported `The stress phase left
no unfinished mutation to the upgrade` in the same file, pointing at an errors
artifact that was never created.

Gate the comparison on the number of replicas the pass actually restarted. The
per-table check inside the loop, and the same clause for a run that did restart
something, are unchanged: with `restart_replica_fail_after_detach` enabled the
step still FAILs while the mutation count reads zero.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 21, 2026
Comment thread tests/docker_scripts/upgrade_runner.sh Resolved
The recovery pass compared `count() FROM system.replicas` before and after its
restarts, which answers for every replicated table on the server rather than for
the ones it restarted. An unrelated table attaching, or being dropped, inside
that window made the step write `Cannot restart a read-only replica holding a
mutation left unfinished by the stress phase` on a run where every restart it
issued had succeeded and every mutation it targeted was killed. The stress phase
leaves other replicated tables behind, so the window is not quiet.

Measured on v26.8.10.6-lts, the release the job downloads, with two bricked
ReplicatedMergeTree tables and one independent replica changing inside the
window: `recovered_replica` returned 1 for both targets, no unfinished mutation
and no read-only replica was left, and the FAIL row was written anyway - in both
directions, 2 rows to 3 and 3 rows to 2.

The per-table check inside the loop is what the pass is accountable for, and it
is strictly stronger for those tables: a table left detached and a replica whose
initialization failed both return 0 from `... WHERE database = ... AND table =
... AND NOT is_readonly`. The global count was blind exactly where that check is
needed - with Keeper stopped the restart exits 0, the replica stays read-only,
`system.mutations` reads 0 and the replica count does not move - so scoping the
comparison to the restarted pairs would only restate the per-table check.
Removing it also retires the `restarted_replicas` gate, which existed to keep
the comparison from firing when the pass restarted nothing.

Re-measured on the same rig after the change: the `restart_replica_fail_after_detach`
failpoint still reds while the mutation count reads 0, Keeper stopped still reds
with both tables named in the errors file, and a clean server still issues no
restart at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-testing Test content only (no production code). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect manual approve Manual approve required to run CI pr-ci 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.

3 participants