Repository navigation
Conversation
A metadata ALTER commits to Keeper and to the local metadata file in two
separate steps: executeMetadataAlter first sets /replicas/<r>/{columns,
metadata,metadata_version} in one multi, and only then writes the local
metadata file. Nothing between the two touches the filesystem, so a SIGKILL,
an OOM kill or a power cut in that window leaves this replica's znodes ahead
of its own metadata file on an otherwise intact filesystem.
On the next start, ReplicatedMergeTreeAttachThread::runImpl runs the
structure check against those advanced znodes with strict_check = true and
throws INCOMPATIBLE_COLUMNS (or METADATA_MISMATCH for projections and the
other mutable fields). run then sets initialization_done, so no retry is
ever scheduled and the replica is readonly across every restart. The throw is
upstream of the queue load in tryStartup, so the ALTER_METADATA entry that
would write the metadata file can never execute, and part reconciliation never
runs either. force_restore_data does not help: it is only consulted by
checkParts, after the throw.
Before the structure check, adopt the replica's own committed Keeper metadata
in memory when an unexecuted ALTER_METADATA entry in its own queue accounts
for it: the entry's alter_version equals the metadata_version znode and its
columns_str/metadata_str are byte-equal to the columns/metadata znodes the
same multi wrote. That way we only ever adopt bytes Keeper already holds for
this replica, a merely lagging replica is excluded, and the entry is a durably
queued instruction to make the local file match. Nothing is written here: the
metadata file is persisted afterwards by the unmodified executeMetadataAlter
once the queue replays the entry, so a kill in the gap simply reproduces the
same recoverable state. When no such entry exists, behaviour is unchanged and
the check throws exactly as before.
The queue is only scanned once a consistency fast path fails, and that fast
path compares columns before metadata. The order matters both ways: the Keeper
metadata can only be parsed against the columns from the same source, and
comparing metadata structurally is safe precisely because it is unreachable
when the columns differ. It also keeps queue parsing out of the attach
thread's non-retrying failure domain for every state that is still
recoverable, and leaves a healthy replica on today's path.
Adoption is in memory only because DatabaseOrdinary::alterTable calls
waitDatabaseStarted, and the database startup job waits on every table
startup job, which is what the attach thread's first try runs inside; the
existing fixReplicaMetadataVersionIfNeeded adjusts metadata in memory for
the same reason. metadata_version is deliberately left untouched:
cloneMetadataIfNeeded returns early when the in-memory version already
equals the source's, so publishing it here would suppress the dummy
ALTER_METADATA entry a lost replica relies on and leave the metadata file
behind with nothing left to update it.
The in-memory half of setTableStructure is extracted into
applyMetadataInMemory so both paths share it, and serialization hints are
reset the same way executeMetadataAlter does, since setNotReadonly
precedes queue activation.
Replicated database tables are out of scope: there the three sets ride inside
a ZooKeeperMetadataTransaction that executeMetadataAlter needs in order to
replay the entry, so adopting one would have to reconstruct that transaction.
That engine keeps the window - DatabaseAtomic::commitAlterTable commits the
transaction and only then renames the local file, with its own NOTE saying the
replica is lost if the server crashes in between - and recovering it there is a
separate change.
The new integration module drives the real torn state through a PAUSEABLE_ONCE
failpoint after the multi, and covers both reported signatures, the case where
the Keeper metadata names a column the local file does not have yet, and four
arms that must still refuse: no entry accounting for the divergence, and an
entry disagreeing with each of the three znodes the predicate compares -
alter_version against metadata_version, columns_str against columns,
metadata_str against metadata. The last three leave the queue intact, so each
pins one authorisation gate: with that gate alone disabled its arm fails while
the other two still pass.
This recovers the crash-window variant. It does not recover the one in which
the local rename was rolled back after executeMetadataAlter had returned and
removeProcessedEntry had already deleted the queue entry: no witness of the
committed metadata survives there, so nothing authorises adoption and the
replica still refuses. ClickHouse#115549 therefore stays open.
Related: ClickHouse#115549
Internal second-model review (independent cold review + adversarial gate, adjudicated)Before publishing I ran an independent cold review of the resulting code on every revision plus a separate Blockers (fixed before this PR was published)
Blocker raised, disagreed with evidence, and disclosed
Majors (fixed before this PR was published)
Noted, not blocking
Checked and found cleanThe predicate is exact by construction (the same Session id: cron:clickhouse-review-slot-8:20260910-131501 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260910-123001 |
|
Workflow [PR], commit [77fdf33] Summary: ❌
AI ReviewSummaryThis PR recovers a Findings❌ Blockers
Tests
Final VerdictChanges required before merge: the adopted schema must not become visible on a readonly startup path until the queue state that supplies the matching read-time conversions has been loaded. LLVM Coverage ReportMeasured on commit 77fdf33.
Changed lines: Changed C/C++ lines covered: 81/83 (97.59%) · Uncovered code |
|
cc @tavplubix @alesapin, could you review this? A metadata ALTER commits to Keeper and to the local metadata file in two separate steps, so a kill in between leaves this replica's znodes ahead of its own file and the attach thread's strict structure check then refuses on every restart, with no retry ever scheduled. This adopts the replica's own committed Keeper metadata in memory when a queued ALTER_METADATA entry in its queue accounts for it byte-for-byte, and leaves the writing of the file to the queue as usual. |
Build profile diff (arm_release)Commit See the job log for details. |
…mmitted-metadata-on-interrupted-alter
CI finish ledger - b383510Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Root cause, measured: #118606 ("Proper partition pruning with dates", merged 13:52:27Z) broke The 124 Session id: cron:our-pr-ci-monitor:20260910-190047 |
CI finish ledger - aea159dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this pull request. The boundary is measurable: A master merge is therefore owed here to re-run CI on a tree that contains the revert; nothing else Session id: cron:our-pr-ci-monitor:20260911-010040 |
…mmitted-metadata-on-interrupted-alter
|
Master merged to pick up #119334, the action the ledger above said was owed: The revert is live in the tree this run builds: My contributed diff is byte-identical across the merge, so there is nothing new to re-read: same zero-context patch-id CI is running on |
| metadata_from_entry, current_metadata->columns, current_metadata->virtuals, getStorageID().getNameForLogs(), getContext()); | ||
| /// Not pending_alter->alter_version: cloneMetadataIfNeeded skips the ALTER_METADATA entry it | ||
| /// creates for a lost replica once the in-memory version already equals the source's. | ||
| applyMetadataInMemory( |
There was a problem hiding this comment.
Publishing the adopted schema under current_metadata->getMetadataVersion() is only safe if the attach path is guaranteed to reach startupImpl() and queue.load() before the table becomes queryable. That is not true here: adoptCommittedMetadataFromPendingAlter runs before checkParts() / createNewZooKeeperNodes(), and any later non-retryable exception makes ReplicatedMergeTreeAttachThread::run set initialization_done = true and return without ever loading the queue.
At that point startup() has already returned from waitFirstTry(), and read() can serve the table in readonly mode. For ALTERs that rely on queued metadata conversions (RENAME COLUMN, DROP COLUMN, MODIFY COLUMN via READ_COLUMN), the adopted schema is now visible with the old metadata_version and an empty mutations snapshot, so selects skip the queued ALTER conversions and read old parts as if they already matched the new schema. Can we keep the adopted metadata local until tryStartup() has loaded the queue, or revert it on any attach-thread failure before then?
CI finish ledger - ad76762Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
This signature has been firing in Session id: cron:our-pr-ci-monitor:20260911-083121 |
…mmitted-metadata-on-interrupted-alter # Conflicts: # src/Storages/StorageReplicatedMergeTree.cpp
CI finish ledger - 77fdf33Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 173 check runs completed, and Session id: cron:our-pr-ci-monitor:20260925-203211 |
|
Fixing PR for the |
|
Fixing PR for the |
…ness's own queries After a clean fuzz run (`Fuzzer exit code is 143`), the post-fuzz liveness probe `clickhouse-client --handshake_timeout_ms=30000 --receive_timeout=5 --query 'SELECT 1'` sometimes never returns. status.tsv is then never written, praktika kills the job at its 18000 s timeout before any artifact is uploaded, and the job reports a bare ERROR with no server log. Five such runs in 45 days: PR ClickHouse#112304 (2026-08-18), PR ClickHouse#98670 (2026-08-19), PR ClickHouse#115530 (2026-08-20), true master 9816d0a `AST fuzzer (amd_release, oracle)` (2026-09-24) and PR ClickHouse#119237 `AST fuzzer (amd_debug, targeted, old_compatibility)` (2026-09-25). Only the last one printed the `1`. Two harness defects make the probe unbounded. (a) The probe is itself fuzzed on the server. query-fuzzer-tweaks-users.xml sets ast_fuzzer_runs=5 and ast_fuzzer_any_query=true on the `default` profile, and no harness-owned client call opted out. The server runs the mutated copies in a query-finish callback, and TCPHandler calls io.onFinish() after sending the data and before EndOfStream, so a fuzzed follow-up that does not finish holds the reply open after the `1` was printed. The same pin was part of ClickHouse#113248, which was closed as already integrated, but its run-fuzzer.sh half never reached master. The stress harness (ClickHouse#114127), the log export (ClickHouse#117996) and tests/clickhouse-test already pin it. (b) --receive_timeout does not bound the probe either. On a receive timeout ClientBase::receiveResult only records TIMEOUT_EXCEEDED and cancels the query; from then on it polls the connection until the server sends a packet, with no bound. A server whose connection thread never gets back to the socket holds the probe forever, which is what the four runs that printed nothing show. Pin --ast_fuzzer_runs=0 on every harness-owned client call through one variable; the fuzzer's own client stays unpinned. Run the two post-fuzz probes (the restart liveness check and the probe loop) under `timeout --signal TERM --kill-after=10 60`. A probe killed by timeout (rc 124, or 137 after the kill) is counted like the client's own "Timeout exceeded while", so a server that stops answering reaches the existing "treating server as hung" verdict after 12 retries (about 14 minutes) and the job keeps its logs. 60 s covers the probe's own worst case (30 s handshake, 5 s receive timeout, the cancel round trip) with room for a slow sanitizer server. The fallback branch now prints the probe's exit code instead of the last grep's. The pre-fuzz probes are not wrapped: the check after attaching gdb waits for gdb to load debug info on purpose, and the server is fresh there. One server-side hang the fuzzer produces, a self-deadlock when one query builds two system.stack_trace sources, is fixed separately in ClickHouse#120216. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
ReplicatedMergeTreereplica staying readonly across every restart withCode: 122, INCOMPATIBLE_COLUMNS(orCode: 342, METADATA_MISMATCH) when the server was killed between the two halves of a metadataALTER. Such a replica now starts up by applying the metadata it already committed to Keeper, and its replication queue finishes writing the local metadata file. Tables in aReplicateddatabase are not covered by this change.Description
Requested by @ zlareb1 in #115549 (comment).
What breaks.
executeMetadataAltercommits a metadataALTERin two steps: a Keepermultion/replicas/<r>/{columns,metadata,metadata_version}, then the local metadata file. A SIGKILL between themleaves the znodes ahead of the file. On restart the attach thread compares the structure with those
znodes, throws, and sets
initialization_done, so nothing retries; the throw precedes the queue load, sothe queued
ALTER_METADATAnever runs.The change. Before that check, adopt this replica's committed Keeper metadata in memory when a queued
ALTER_METADATAentry accounts for it byte-for-byte: samealter_versionas themetadata_versionznode,
columns_str/metadata_strequal to thecolumns/metadataznodes, which excludes a laggingreplica. Nothing is written; the unmodified
executeMetadataAlterpersists the file when the queuereplays the entry. Without a match the replica refuses as today.
Weigh this. That witness is inexact both ways.
removeProcessedEntry's delete is atryRemovewhosefailure is only logged, so a successfully executed ALTER can retain its entry: a locally diverged file
is then overwritten by the queue, where today the replica stays readonly. And if something else consumes
the entry before this replica replays it (another process holding
is_active, manual deletion), startupsucceeds on the adopted metadata but the file stays stale, so the next restart refuses until a later
ALTER.Scope. This recovers the crash-window variant: a SIGKILL or OOM-kill between the Keeper
multiandthe local rename. It does not recover the rename-rollback variant from the issue's original reproducer:
there the entry is already gone, so nothing authorises adoption and the replica still refuses. #111405
prevents that route; a replica already bricked that way needs an owner-level option from #26327, so I am
not closing #115549 here.
Replicateddatabases are excluded: replaying the entry there needs the DDLtransaction
executeMetadataAlterbuilds, so that window stays open there.Validation detail
tests/integration/test_replicated_alter_metadata_interrupted_commit/drives the state through a newPAUSEABLE_ONCEfailpoint placed after the Keepermulti, so it reproduces the reporter's state, not anapproximation. No sleeps:
SYSTEM ENABLE FAILPOINT,ALTER ... SETTINGS alter_sync = 0,SYSTEM WAIT FAILPOINT ... PAUSE, then a SIGKILL restart. Each arm first asserts the torn state exists(
metadata_versionadvanced, queue child present, altered field not visible locally) so it cannotdegrade into a plain-restart test.
test_columns_delta_recovers- theCode: 122report. Also asserts the queue drains to 0 (soexecuteMetadataAlter, not attach, persisted the file) and that a second, plain restart startsclean - what fails if adoption left the file stale.
test_new_column_in_sorting_key_recovers-ADD COLUMN z, MODIFY ORDER BY (x, y, -z), where the Keepermetadata references a column the local table does not have yet.
test_projections_delta_recovers- theCode: 342report (DROP PROJECTION), another throw site.no_pending_entry(queue child deleted), plusentry_{version,payload,metadata}_mismatch, each rewriting one committed znode (metadata_version,columns,metadata) so exactly one of the predicate's three comparisons can refuse; disabling onereddens only its arm.
Without the fix, arm 1 fails on
is_readonlywithCode: 122 ... Table columns structure in ZooKeeper is different from local table structure.The in-memory half of
setTableStructureis now shared; guarded by00754_alter_modify_order_by_replicated_zookeeper_long,00062_replicated_merge_tree_alter_zookeeper_long,test_replicated_database,test_alter_settings_or_comment_on_cluster,test_restore_replica,test_consistent_parts_after_clone_replica,test_fix_metadata_version,test_restore_replica_metadata_version- all green.Workflow [PR]
Sync PR [sync-upstream/pr/119237]