Repository navigation
Converge kept matching-UUID table structure on Replicated database recovery - #110145
alexey-milovidov wants to merge 8 commits into
Conversation
After `DatabaseReplicated::recoverLostReplica` keeps a matching-UUID `ReplicatedMergeTree`, its structure is expected to converge "on table replication level". If the replica was detached across an `ALTER` whose `ALTER_METADATA` log entry was already cleaned up from `zookeeper_path/log` by the time it re-attaches, recovery advances the replica log pointer past the missing entry, and `SYSTEM SYNC REPLICA` only drains the queue without re-reading `zookeeper_path/metadata`, so the table stays on the old structure indefinitely (e.g. `SELECT *` returns fewer columns than exist). Add `StorageReplicatedMergeTree::syncTableStructureFromZooKeeperIfNeeded`, called from `recoverLostReplica`, which mirrors `cloneMetadataIfNeeded`: if the local metadata version is behind `zookeeper_path/metadata`, it prepends a dummy `ALTER_METADATA` (built from a consistent `zookeeper_path/metadata` + `zookeeper_path/columns` snapshot) to the queue via `ReplicatedMergeTreeQueue::insert`. The replication log is drained to its head first and the injection is skipped when a real `ALTER_METADATA` is pending (injecting a duplicate `alter_version` would corrupt the alters sequence); a `check` on the metadata version closes the concurrent-`ALTER` race. This avoids reloading the whole queue on a running table. Fixes the flaky integration test `test_replicated_database/test.py::test_replicated_table_structure_alter`, a regression on master since 2026-07-10. Closes: #110036 Related: #110030 CI reports of the failure on master: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8b6d09cfbd638c3b41942152c6d85137effa75ec&name_0=MasterCI&name_1=Integration%20tests%20%28amd_msan%2C%207%2F8%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ab8535b3ab0f127a359ba889d9bd26b9456f1897&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=525f0f4d99e60564dd118cc0effea3e8383c3beb&name_0=MasterCI&name_1=Integration%20tests%20%28amd_msan%2C%207%2F8%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ec064681ee99d6f2c0153607a0cb49bb190c30cc&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=aacade522213d270d3b20378747021e2152b7e00&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [a2ccfd9] AI ReviewSummaryThis PR teaches Findings❌ Blockers
Final VerdictNeeds changes before merge: the recovery repair is still not idempotent against a persisted current-version |
…SYNC REPLICA FROM Two follow-ups to `syncTableStructureFromZooKeeperIfNeeded`, from the AI review of the PR. - The "skip repair if a metadata alter is already pending" check used `metadata_alters_in_queue != 0`, which is too coarse. A recovering replica can carry an older `ALTER_METADATA` in its own `/queue` (that state survives detach and is reloaded by `ReplicatedMergeTreeQueue::load`) while a newer metadata change was later cleaned up from `/log`. `pullLogsToQueue` cannot pull the missing newer entry, the old branch returned early, and once the stale alter executed it advanced the structure only partway, so the replica stayed behind `zk_metadata_version` forever. Compare the highest queued `ALTER_METADATA` `alter_version` (new `ReplicatedMergeTreeQueue::getMaxMetadataAlterVersionInQueue`) against `zk_metadata_version` and skip the synthetic repair only when a queued entry already reaches the current ZooKeeper version. This still avoids injecting a duplicate `alter_version` and stays idempotent across recovery retries. - The synthetic repair entry was tagged with `source_replica = replica_name`, but `SYSTEM SYNC REPLICA FROM '<other>'` filters its wait set by `entry->source_replica` in `ReplicatedMergeTreeQueue::addSubscriber`, and an entry from our own (existing) replica is neither a specified nor an unknown/empty source, so such a query could return before the repair applies the missed metadata. Build the entry with an empty `source_replica` (it is sourced from the ZooKeeper snapshot, not any replica); empty sources are always waited for. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit made `syncTableStructureFromZooKeeperIfNeeded` call
`ReplicatedMergeTreeQueue::pullLogsToQueue` with the `SYNC` reason to drain the
replication log before deciding whether to inject a repair `ALTER_METADATA`.
But this runs from `DatabaseReplicated::recoverLostReplica` while the replica is
still readonly (its `ReplicatedMergeTreeRestartingThread` has not finished
startup yet), and `pullLogsToQueue` throws a `LOGICAL_ERROR`
("Tried to pull logs to queue (reason: {}) on readonly replica {}, it's a bug")
for any reason other than `LOAD` or `FIX_METADATA_VERSION` on a
not-completely-initialized readonly replica. That aborted the server during
recovery and cascaded into `Connection refused` failures across the whole
`test_replicated_database` suite (`test_recover_staled_replica`,
`test_replicated_table_structure_alter`, etc.).
Add a dedicated `RECOVER_METADATA` pull reason that - like the
`FIX_METADATA_VERSION` drain in
`ReplicatedMergeTreeRestartingThread::fixReplicaMetadataVersionIfNeeded`, which
runs in the same readonly-startup situation - is allowed to pull logs on a
not-completely-initialized readonly replica, and use it at the recovery call
site.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110145&sha=62e7e7b1168ad6ce34baefcf5e1cd457ee482a33&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
Related: #110145
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The recovery repair added in this PR injects a synthetic `ALTER_METADATA` with an empty `source_replica` so that `SYSTEM SYNC REPLICA ... FROM '<replica>'` waits for it (`ReplicatedMergeTreeQueue::addSubscriber` always waits for entries with an empty `source_replica`). Sync the recovered replica via `FROM '<source replica>'` instead of a plain `SYSTEM SYNC REPLICA` in `test_replicated_table_structure_alter`, so the empty-`source_replica` branch is covered end to end: had the synthetic entry carried our own replica name, `FROM` would skip waiting for it and the structure could still be stale at the assert. Related: #110145 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Revert the previous commit. `SYSTEM SYNC REPLICA <table> FROM '<replica>'` is not valid syntax: the parser (`ParserSystemQuery`) only accepts `FROM` after the `LIGHTWEIGHT` keyword, so the added query would fail to parse. And even `SYSTEM SYNC REPLICA <table> LIGHTWEIGHT FROM '<replica>'` would not exercise the `source_replica` behavior, because `LIGHTWEIGHT` restricts the wait set in `ReplicatedMergeTreeQueue::addSubscriber` to part-level entries (`GET_PART` / `ATTACH_PART` / `DROP_RANGE` / `REPLACE_RANGE` / `DROP_PART`), which excludes `ALTER_METADATA` by type before `source_replica` is ever considered. The recovery-path decision on this additional coverage is left to the author, as already discussed on the review thread. Related: #110145 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The CI red on
Fixed in I also tried the requested |
…ecovery-metadata-convergence
Keep the `user_files_policy` branch current with master (was 320 commits behind). The merge is clean (no conflicts). This refreshes CI on a current base; the two prior reds were unrelated flakes: - AST fuzzer '!part.empty()' (STID 2508-2ef2): a widespread pre-existing analyzer/AST roundtrip issue under EXPLAIN QUERY TREE, hitting many unrelated PRs; not caused by this PR. - Integration test_replicated_database::test_replicated_table_structure_alter: known flake tracked by #110036 (fix #110145 still open), labeled retry_ok.
…rsion `syncTableStructureFromZooKeeperIfNeeded` decided whether the kept matching-UUID replica lagged by reading the in-memory metadata version via `getInMemoryMetadataPtr(...)->getMetadataVersion()`. `DatabaseReplicated::recoverLostReplica` runs this before the table's `ReplicatedMergeTreeRestartingThread` finishes startup (the replica is still readonly - that is why the earlier `RECOVER_METADATA` pull-reason fix was needed), and for a table of a `Replicated` database the in-memory `metadata_version` stays `0` for a while regardless of the actual structure (see the "metadata_version will be 0 for a while" note in the constructor; `ReplicatedMergeTreeRestartingThread::fixReplicaMetadataVersionIfNeeded` restores the in-memory version from the persisted node during startup). So an already up-to-date replica could be misdetected as stale and get an unnecessary synthetic `ALTER_METADATA` injected. Because `fixReplicaMetadataVersionIfNeeded` then sees `metadata_alters_in_queue != 0` and keeps the in-memory version at `0` until that entry executes, any queued fetch/clone work ahead of it would write fresh parts with `metadata_version = 0`, polluting the schema-version tracking that mutations and snapshots rely on. Read the persisted `replica_path/metadata_version` node instead - the version this replica has actually applied (`executeMetadataAlter` writes it atomically with the structure change and it survives detach/reattach), the same authoritative, startup-safe signal `fixReplicaMetadataVersionIfNeeded` uses. In the target scenario (a replica detached at an older version) the persisted node equals the in-memory version throughout the readonly recovery window, so the repair still fires; for an up-to-date replica the persisted node correctly reports the applied version and no bogus entry is injected. Fall back to skipping the check when the node is absent, matching the compatibility caveat in `cloneMetadataIfNeeded`. The now-redundant post-drain in-memory recheck is dropped: the `getMaxMetadataAlterVersionInQueue` guard already covers a pending alter and the persisted version cannot change on a readonly replica. Addresses AI Review finding at StorageReplicatedMergeTree.cpp:4018. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| entry->source_replica = ""; | ||
| entry->metadata_str = zk_metadata; | ||
| entry->columns_str = zk_columns; | ||
| entry->alter_version = zk_metadata_version; |
There was a problem hiding this comment.
If recovery skips more than one metadata version, this single synthetic ALTER_METADATA at zk_metadata_version can violate the metadata -> data ordering that ReplicatedMergeTreeAltersSequence enforces.
updateMutations() will still register any older alter-mutation from /mutations with metadata_finished = true when its original ALTER_METADATA entry has already been cleaned, so that older version becomes the head of queue_state (ReplicatedMergeTreeAltersSequence::addMutationForAlter). That means canExecuteDataAlter() can let the older MUTATE_PART run before this synthetic entry, while MutateFromLogEntryTask::prepare() still reads the stale in-memory table metadata.
A concrete case is a replica detached across ALTER MODIFY COLUMN ... (version N-1, with a mutation still active) and then a later metadata-only ALTER (version N). Recovery here only injects version N, so version N-1 can start mutating parts while the table is still on version N-2.
Can we either synthesize metadata stages for every missing alter version that still has an active alter-mutation, or otherwise stop treating a missing metadata stage as already finished when the local metadata_version is still behind it?
There was a problem hiding this comment.
Thanks — the mechanism you describe is exactly right and I traced it end to end. When an intermediate ALTER_METADATA (version N-1) has been cleaned from zookeeper_path/log but its alter-mutation is still active in /mutations, ReplicatedMergeTreeQueue::updateMutations calls alter_sequence.addMutationForAlter(N-1) (ReplicatedMergeTreeQueue.cpp:1268-1272), and since no addMetadataAlter(N-1) ever ran, ReplicatedMergeTreeAltersSequence::addMutationForAlter emplaces {metadata_finished=true, data_finished=false}. So canExecuteDataAlter(N-1) returns true at the head and the MUTATE_PART can run while the in-memory structure is still at N-2.
But this is a pre-existing property of the alters sequence, not something this PR introduces or worsens, and I don't think it can be fixed within the scope of this recovery repair:
-
It is not caused by this PR, and it is shared verbatim with
cloneMetadataIfNeeded. Themetadata_finished=truedefault inaddMutationForAlterfires for any replica whose intermediateALTER_METADATAwas cleaned — that is the normal cleanup path.cloneMetadataIfNeeded(StorageReplicatedMergeTree.cpp:3892) — in ClickHouse for years — repairs the very same lag by prepending a single dummyALTER_METADATAat the latestsource_metadata_version, built from the current/metadata+/columnssnapshot; it does not synthesize intermediate versions either. Its own comment acknowledges "some entries are probably cleaned up from the log" and relies on "ALTER_METADATA seems to be idempotent, and older entries of such type can be replaced with newer entries."syncTableStructureFromZooKeeperIfNeededdeliberately mirrors that established behavior. -
The primary suggested fix — synthesize a metadata stage for every skipped version — is infeasible. ZooKeeper keeps only the current structure in
zookeeper_path/metadataandzookeeper_path/columns(a single versioned node each, no per-version archive). Once theN-1ALTER_METADATAentry is cleaned from/log, theN-1structure snapshot is gone — there is nothing left to reconstruct it from (the/mutationsentry carries the mutation commands, not the base structure). That is precisely why both this repair andcloneMetadataIfNeededconverge in one entry straight to the latest version. -
This PR is a strict improvement, not a regression. Without it, the kept matching-UUID replica never converges at all — the structure stays at the pre-detach version indefinitely, so in exactly your scenario the
N-1mutation would run against stale metadata and the table would stay behind forever. With it, the structure converges to the latest versionN; theN-1ordering is unchanged relative to before. -
The synthetic entry does not corrupt the sequence. Head stays
N-1until its data alter finishes and it is erased, after whichcanExecuteMetaAlter(N)/finishMetadataAlter(N)see head== N(nochassertviolation), and the structure lands onN.
What remains is a genuine, broader design question that is out of scope for this recovery fix and that I'd like to leave to @alexey-milovidov: whether the alters sequence should stop assuming metadata_finished for a cleaned intermediate stage while the local replica_path/metadata_version is still behind it (i.e. block canExecuteDataAlter for such a version until the structure has caught up). That is a cross-cutting change to the core replicated-ALTER machinery — it would affect normal operation and cloneMetadataIfNeeded alike, not just this recovery path — so it belongs in a dedicated change rather than here.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 39/71 (54.93%) · Uncovered code |
…ecovery-metadata-convergence
| /// ReplicatedMergeTreeRestartingThread::fixReplicaMetadataVersionIfNeeded - is allowed to pull logs on | ||
| /// a not-completely-initialized readonly replica. Any other reason would throw "it's a bug". | ||
| queue.pullLogsToQueue(zookeeper, {}, ReplicatedMergeTreeQueue::RECOVER_METADATA); | ||
| if (queue.getMaxMetadataAlterVersionInQueue() >= zk_metadata_version) |
There was a problem hiding this comment.
ReplicatedMergeTreeRestartingThread::tryStartup() is the code that loads persisted /queue entries into RAM via queue.load(), and this recovery hook explicitly runs while that startup is not guaranteed to have finished yet. getMaxMetadataAlterVersionInQueue() only inspects the in-memory queue, so it misses a current-version ALTER_METADATA that already exists under replica_path/queue but has not been loaded yet.
In that case this branch still injects a second synthetic ALTER_METADATA with the same alter_version, even though the comment above correctly notes that duplicates corrupt ReplicatedMergeTreeAltersSequence. Could we either call this helper only after queue.load() has populated RAM, or inspect/load replica_path/queue directly before deciding whether a current-version metadata alter is already pending?
|
Fixed by pr #110145 |
|
@tiandiwonder, sorry, fixed by what exact PR? |
|
You meant #111029 |
Closes: #110036
Related: #110030
When a
Replicateddatabase replica recovers viaDatabaseReplicated::recoverLostReplica, a table with a matching UUID is kept as is and is expected to converge its structure "on table replication level". This breaks if the replica was detached across anALTER ... ADD COLUMN(for example, because itsReplicateddatabase was detached) and the correspondingALTER_METADATAlog entry was already cleaned up from the table'szookeeper_path/logby the time it re-attaches: recovery advances the replica's log pointer past the missing entry without applying it, andSYSTEM SYNC REPLICAonly drains the replication queue and never re-readszookeeper_path/metadata. So the recovered replica keeps serving the pre-ALTERstructure indefinitely —SELECT *returns fewer columns than the table actually has.This is exactly the situation
cloneMetadataIfNeededalready repairs for a cloned (lost) replica. This change does the same repair for a kept matching-UUID replica. During recovery, if the local metadata version is behindzookeeper_path/metadata, the newStorageReplicatedMergeTree::syncTableStructureFromZooKeeperIfNeededprepends a dummyALTER_METADATA(built from a consistentzookeeper_path/metadata+zookeeper_path/columnssnapshot) to the replication queue, so normal queue processing appliessetTableStructureandSYSTEM SYNC REPLICAnow waits for it.To stay safe on a running queue:
ALTER_METADATAis then pending, no synthetic entry is injected — the structure will converge on its own, and injecting a second entry with the samealter_versionwould corrupt the alters sequence. This also makes the operation idempotent across recovery retries.checkon thezookeeper_path/metadataversion, so a concurrentALTERmakes the request retry instead of injecting a duplicatealter_version.ReplicatedMergeTreeQueue::insert(not by reloading the whole queue on a running table).The bug was surfaced by the flaky integration test
test_replicated_database/test.py::test_replicated_table_structure_alter, which regressed onmastersince 2026-07-10 (0 failures for two weeks, then ~4% on sanitizer builds). The test is kept on plainSYSTEM SYNC REPLICA+SELECT; the fix is server-side.CI reports of the failure on
master:Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
Replicateddatabase replica keeping an outdated table structure (for example, missing columns added byALTERwhile it was detached) after recovery, when the correspondingALTER_METADATAentry had already been cleaned up from the replication log.