Repository navigation
Conversation
After a Replicated database replica loses metadata and restarts, recoverLostReplica does not rewrite matching-UUID ReplicatedMergeTree tables (their metadata is handled at table-replication level). The recovered replica therefore picks up the post-DETACH ADD COLUMN via table-level metadata replication, whose metadata_version converges asynchronously after SYSTEM SYNC REPLICA returns. The exact-equality reads of SELECT * right after recovery could observe the pre-ALTER column set in the narrow convergence window (surfaced on slow msan/tsan builds). Use assert_eq_with_retry for the structure-dependent reads, matching the idiom already used throughout this file. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260710-162000 |
|
cc @tavplubix — could you review this? It de-flakes |
|
Workflow [PR], commit [51fd2a5] Summary: ❌
|
The previous fix retried only the SELECT, but SYSTEM SYNC REPLICA ran once before the retry loop. A replica that recovered from lost metadata converges its table structure asynchronously: recoverLostReplica does not rewrite matching-UUID ReplicatedMergeTree tables, and their structure is picked up by table-level metadata replication, which enqueues the metadata-update entry during recovery (cloneMetadataIfNeeded). If the single pre-loop SYNC returned before that entry existed, re-reading alone could never force convergence within the retry budget, so the flaky-check still observed the pre-ALTER column set (1,2 instead of 1,2,3). Re-run SYSTEM SYNC DATABASE REPLICA + SYSTEM SYNC REPLICA inside the retry loop until the structure converges, keeping the exact-equality assertions unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed a follow-up commit (6100665) hardening the fix. The prior commit converted the reads to Root cause of the residual flakiness: the retry only re-ran the Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-9:20260710-210200 |
While a recovered replica is still on the old table structure, the sync+read pair can raise (e.g. the read references a not-yet-applied column -> UNKNOWN_IDENTIFIER), not only return the wrong rows. The loop did not catch that, so it exited on the first iteration and never retried. Wrap the pair in try/except inside the loop, like assert_eq_with_retry, so the helper keeps retrying until the schema converges or the timeout expires. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed in 5ab3579. The sync/query pair in |
…lper
SYSTEM SYNC REPLICA only syncs the replication queue; it does not re-read
the table structure from ZooKeeper. When a recovered replica's DDLWorker
skips a local ADD COLUMN ("already executed by another replica of the same
shard"), the local table stays on the old structure and no amount of SYNC
converges it. SYSTEM RESTART REPLICA re-runs the attach thread, which
re-reads /metadata via checkTableStructure and applies the up-to-date
structure. Retry restart + sync + read until the structure converges.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed c52b6df — the Root cause (from the flaky-check logs of the previous head 5ab3579, RUN 29125441442, gw1+gw2): on the failing runs, Fix: add Local reproduction (debug build, praktika Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260710-223800 |
|
clickhouse-gh[bot] is right: Root cause (confirmed from the failing flaky-check CI logs + a local debug-build repro):
So plain Since this was requested as a de-flake on #101273, the scope call is yours @alexey-milovidov:
Either way I will not leave the server-side convergence gap unfiled. |
|
Correction and definitive root cause (with on-disk proof). My earlier claim that The RESTART-in-loop head ( Proof this is a real server-side convergence gap, not a read-timing window. On the failing Column Why So the test is asserting a convergence that the server does not currently guarantee for a matching-UUID replica whose database was detached across the ALTER. That is the bug behind #110036. Scope call is yours @alexey-milovidov, since a robust fix touches core Replicated-DB recovery:
I can implement either, but I do not have a deterministic local repro of the non-convergence (debug passes 3/3; it is a ~4% sanitizer-timing race), so I do not want to push a core-recovery change on approach I am guessing at. Which do you prefer for this PR? |
|
@groeneai, look not fixed. |
tiandiwonder
left a comment
There was a problem hiding this comment.
The in-thread root-cause work here is excellent — the on-disk proof and the self-correction pin this as a server-side convergence gap, not a read-timing window. But the current head can't land: the restart-in-loop helper trips the strict attach check and leaves the table readonly (details inline). One more thing: the PR description still describes the superseded first approach ("by-design eventual consistency" / plain assert_eq_with_retry) that your correction comment refutes, and links neither Closes: nor Related: to #110036 — future readers and the private sync will read the description, not the comment thread. Please update it once the A/B call is made.
| # retrying, like assert_eq_with_retry, so a transient error does not exit early. | ||
| for _ in range(retry_count): | ||
| try: | ||
| node.query(f"SYSTEM RESTART REPLICA {database}.{table}") |
There was a problem hiding this comment.
your correction comment is right, and I verified the chain in source: the attach thread calls checkTableStructure(..., strict_check = true) (ReplicatedMergeTreeAttachThread.cpp:194), which throws INCOMPATIBLE_COLUMNS on a local-vs-ZK mismatch instead of applying the ZK structure — so this restart leaves the stale replica readonly and the next SYNC REPLICA in the loop fails with TABLE_IS_READ_ONLY, exactly what the flaky lane shows on this head. Since nothing outside cloneReplica ever re-syncs a matching-UUID replica's metadata, no test-level retry can converge this case; the helper shouldn't land in its current form — it needs your option A (recreate competing_node's replica so recovery takes the fresh-replica path, keep #110036 open) or option B (server-side re-sync via cloneMetadataIfNeeded when metadata_version is behind).
There was a problem hiding this comment.
Went with option B, generalized: the server-side resync landed as StorageReplicatedMergeTree::syncTableStructureFromZooKeeperIfNeeded, now called from ReplicatedMergeTreeRestartingThread::tryStartup (before the replica leaves readonly mode), so any replica that missed a cleaned-up ALTER_METADATA without being marked lost is repaired at startup - the recovery case included. The test-level helper this thread reviewed is gone; the test is back to plain SYSTEM SYNC REPLICA + SELECT assertions with a deterministic /log deletion to force the missed-entry state.
| # local table can stay on the old structure indefinitely. SYSTEM RESTART | ||
| # REPLICA re-runs the attach thread, which re-reads /metadata from ZooKeeper | ||
| # (checkTableStructure) and applies the up-to-date structure. Retry the |
There was a problem hiding this comment.
this states the opposite of the verified behavior — per your own follow-up, the strict attach check throws on mismatch rather than applying the ZK structure. Whatever approach lands, the comment needs to match it.
There was a problem hiding this comment.
The comment (and the whole RESTART REPLICA-based helper it described) was removed when the fix moved server-side; the current test has no claims about RESTART REPLICA re-reading /metadata.
The previous approach ran syncTableStructureFromZooKeeperIfNeeded from DatabaseReplicated::recoverLostReplica, i.e. after the table had already started: mutations were loaded and background queue processing was running. As the review pointed out, that is too late for an ALTER with a data-mutation stage: updateMutations treats an alter mutation whose ALTER_METADATA entry is missing from the queue as "metadata already applied" (ReplicatedMergeTreeAltersSequence::addMutationForAlter), so a recovered replica could execute MUTATE_PART against the stale pre-ALTER structure before the repair entry was reconstructed. Running with active workers also forced the repair to classify ZooKeeper-only /queue znodes (orphan vs just-finished) under pull_logs_to_queue_mutex, which was subject to V/V+1 and multi-candidate classification races. Now the repair runs from ReplicatedMergeTreeRestartingThread::tryStartup after queue.load() and the initial pullLogsToQueue(LOAD), while the replica is still readonly and no background workers are active: - The repair entry is queued before background processing starts, so the alters sequence keeps MUTATE_PART blocked until the metadata stage is applied (inserting an ALTER_METADATA flips an already-registered mutation with the same alter_version back to waiting-for-metadata). - queue.load() has already materialized every /queue znode into the in-memory queue, including a repair entry created by a previous incarnation that died before using it, so the in-memory queue is a complete picture and the whole orphan classification disappears. - The suppression check (drain the log after taking the /metadata + /columns snapshot, then look for a queued ALTER_METADATA with alter_version >= the snapshot version) keeps the guarantee that the repair entry can never duplicate a real entry with the same alter_version. The repair is also no longer specific to Replicated database recovery: any replica that missed a cleaned-up ALTER_METADATA entry without being marked lost is repaired at startup (the lost path was already covered by cloneMetadataIfNeeded). Adds test_replicated_table_missed_alter_with_mutation: MODIFY COLUMN type change (ALTER_METADATA + MUTATE_PART) missed across a detach, which must converge structure first and mutation second on recovery. Co-Authored-By: Claude Fable 5 <[email protected]>
…ta resync As pointed out in the review, checkEquals parses the ZooKeeper-side indices and projections under the local column set, so a missed ALTER_METADATA that adds a column together with an index or a projection referencing it raised UNKNOWN_IDENTIFIER in the structure probe instead of reporting a mismatch. Propagating the exception from tryStartup would wedge the replica permanently in readonly mode (every startup retry rethrows), which is worse than the stale structure itself. Treat a comparison failure as "differs" and proceed with the repair: the repair path never parses the ZooKeeper metadata under the stale local columns (the repair entry carries the raw strings, and executeMetadataAlter parses them under the entry's own column set), so it converges for this shape. Keeper errors still propagate: they mean the structures could not be compared, not that they differ. Extends test_replicated_table_structure_alter with a missed ADD INDEX on the missed column to pin this shape. Co-Authored-By: Claude Fable 5 <[email protected]>
contrib/base64 and contrib/libpng were removed on master; the leftover checked-out directories were staged by mistake in the previous commit. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Pushed a redesign that addresses the outstanding review verdict: the repair moved from What this changes:
On the relation to #110145 (which we previously deferred to as the canonical server-side fix): the startup-time placement here resolves the points that are still open there, so the two should be consolidated - decision to @alexey-milovidov:
Verification: full debug build; the three integration tests pass locally (see CI for the sanitizer matrix). The Bugfix-validation job is expected to show the new tests failing against the master binary, by design. |
|
Agreed on the consolidation: from our side we withdraw the earlier deferral to #110145 - the Verified against the current head diff:
One unrelated thing before CI runs: the head still carries 4 contrib gitlink changes that are not part of this fix - |
|
pr #111029 fixes it with real root cause. |
|
@tiandiwonder Agreed, #111029 is the right fix. It removes the source: the comment/settings ALTER was committing a query-scoped metadata snapshot pinned before |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a bug where a
ReplicatedMergeTreereplica could keep an outdated table structure indefinitely. If a replica was inactive across anALTER(for example, itsReplicateddatabase was detached) and the correspondingALTER_METADATAlog entry was already cleaned up from ZooKeeper by the time it came back, the replica never picked up the schema change without being marked lost, andSYSTEM SYNC REPLICAcould not repair it, since it only drains the replication queue. The replica now detects this at startup and forces a metadata resync from ZooKeeper before background queue processing starts.Description
Closes: #110036
test_replicated_table_structure_alterwas clean on master for 20+ days, then started flaking on 2026-07-10 across several unrelated PRs. Investigation (with @tiandiwonder and the automated reviewer) established that this is a genuine server-side convergence gap, not a test read-timing window.Root cause:
competing_nodeisDETACHed acrossALTER TABLE rmt ADD COLUMN m. By the time it re-attaches, the active replicas have already executed theALTER_METADATAentry and it has been cleaned up fromzookeeper_path/log- without this replica being marked lost.pullLogsToQueueadvances the replica's log pointer past the missing entry without applying it, and the recovered replica's DDLWorker treats the DB-level DDL as "already executed by another replica of the same shard" and skips it.SYSTEM SYNC REPLICAonly drains the replication queue (waitForProcessingQueue); it never re-reads/metadata. So the local table stays on the pre-ALTERstructure indefinitely (confirmed: the on-diskrmt.sqlstayed 2-column after ~60 SYNC retries).cloneMetadataIfNeeded(prepends a dummyALTER_METADATAbuilt from ZooKeeper/metadata+/columnswhen the real entry is gone), only runs fromcloneReplica, i.e. for a replica marked lost. A replica that missed an entry without being marked lost never triggers it.Fix: a new
StorageReplicatedMergeTree::syncTableStructureFromZooKeeperIfNeeded, called fromReplicatedMergeTreeRestartingThread::tryStartupafter the queue is loaded and the log is drained, but before the replica leaves readonly mode and background queue processing starts. If the local structure differs from the authoritativezookeeper_path/metadata+/columns(compared structurally, not by version -fixReplicaMetadataVersionIfNeededcan advance a never-locally-altered replica'smetadata_versionwhile its structure is still stale) and noALTER_METADATAentry withalter_version>= the snapshot version is queued after a log drain, it prepends a dummyALTER_METADATAsourced from the table root to the replica's own queue, so normal queue processing applies it viasetTableStructure. This avoids a strict re-attach (checkTableStructure(strict_check=true)), which would instead throwINCOMPATIBLE_COLUMNSand leave the table readonly.Running the repair at this exact point of startup is essential (this addresses the review findings on earlier revisions, which hooked the repair into
DatabaseReplicated::recoverLostReplica, i.e. after table startup):updateMutationstreats an alter mutation whoseALTER_METADATAentry is missing from the queue as "metadata already applied" (ReplicatedMergeTreeAltersSequence::addMutationForAlter), making itsMUTATE_PARTentries runnable. Since the repair entry is queued before background processing starts, the alters sequence keeps the mutation blocked until the metadata stage is applied, so a recovered replica can no longer mutate data against a stale structure.tryStartupno background workers touch the queue, andqueue.load()has already materialized every/queueznode into the in-memory queue (including a repair entry created by a previous incarnation that died before using it). The previous revision's orphan-vs-just-finished classification of ZooKeeper-only queue entries - and its V/V+1 and multi-candidate races - is gone entirely./metadataand the matching/logentry are committed in one atomic multi (seealter), so after taking a consistent/metadata+/columnssnapshot and draining the log, the real entry is either in the in-memory queue (repair suppressed) or gone for good (all future log entries carry a strictly greateralter_version).The fix is no longer specific to
Replicateddatabase recovery: any replica that missed a cleaned-upALTER_METADATAentry without being marked lost is repaired at startup.Tests (integration,
test_replicated_database):test_replicated_table_structure_alter: deterministically deletes theALTER_METADATAentries from/log(mimicking the GC window) instead of relying on cleanup-thread timing; back on plainSYNC+SELECTassertions.test_replicated_table_single_missed_alter: exactly one missed metadataALTER, which is the case where a version-only guard would be fooled by the startupmetadata_versionfast-forward.test_replicated_table_missed_alter_with_mutation(new):MODIFY COLUMNtype change, i.e.ALTER_METADATA+MUTATE_PART; the recovered replica must apply the metadata stage first and the mutation on top of it, in that order.Requested by @alexey-milovidov on #101273.