Skip to content

Fix flaky test_replicated_table_structure_alter - #110030

Closed
groeneai wants to merge 29 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-test_replicated_table_structure_alter
Closed

groeneai wants to merge 29 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-test_replicated_table_structure_alter

Conversation

@groeneai

@groeneai groeneai commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix a bug where a ReplicatedMergeTree replica could keep an outdated table structure indefinitely. If a replica was inactive across an ALTER (for example, its Replicated database was detached) and the corresponding ALTER_METADATA log 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, and SYSTEM SYNC REPLICA could 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_alter was 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:

  • In the test, competing_node is DETACHed across ALTER TABLE rmt ADD COLUMN m. By the time it re-attaches, the active replicas have already executed the ALTER_METADATA entry and it has been cleaned up from zookeeper_path/log - without this replica being marked lost.
  • pullLogsToQueue advances 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 REPLICA only drains the replication queue (waitForProcessingQueue); it never re-reads /metadata. So the local table stays on the pre-ALTER structure indefinitely (confirmed: the on-disk rmt.sql stayed 2-column after ~60 SYNC retries).
  • The machinery that repairs exactly this, cloneMetadataIfNeeded (prepends a dummy ALTER_METADATA built from ZooKeeper /metadata + /columns when the real entry is gone), only runs from cloneReplica, 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 from ReplicatedMergeTreeRestartingThread::tryStartup after 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 authoritative zookeeper_path/metadata + /columns (compared structurally, not by version - fixReplicaMetadataVersionIfNeeded can advance a never-locally-altered replica's metadata_version while its structure is still stale) and no ALTER_METADATA entry with alter_version >= the snapshot version is queued after a log drain, it prepends a dummy ALTER_METADATA sourced from the table root to the replica's own queue, so normal queue processing applies it via setTableStructure. This avoids a strict re-attach (checkTableStructure(strict_check=true)), which would instead throw INCOMPATIBLE_COLUMNS and 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):

  • Alters with a data-mutation stage are ordered correctly. updateMutations treats an alter mutation whose ALTER_METADATA entry is missing from the queue as "metadata already applied" (ReplicatedMergeTreeAltersSequence::addMutationForAlter), making its MUTATE_PART entries 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.
  • No classification races. During tryStartup no background workers touch the queue, and 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). 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.
  • No same-version duplicates. A versioned set on /metadata and the matching /log entry are committed in one atomic multi (see alter), so after taking a consistent /metadata + /columns snapshot 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 greater alter_version).

The fix is 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.

Tests (integration, test_replicated_database):

  • test_replicated_table_structure_alter: deterministically deletes the ALTER_METADATA entries from /log (mimicking the GC window) instead of relying on cleanup-thread timing; back on plain SYNC + SELECT assertions.
  • test_replicated_table_single_missed_alter: exactly one missed metadata ALTER, which is the case where a version-only guard would be fooled by the startup metadata_version fast-forward.
  • test_replicated_table_missed_alter_with_mutation (new): MODIFY COLUMN type 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.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? No standalone deterministic repro on debug (30/30 green); the race is a ~0.05% metadata-convergence window that only surfaces on slow msan/tsan CI builds. CIDB pins the mechanism: 20 days 0 master failures then 4 on 2026-07-10, all retry_ok, no recovery-code change in the window.
b Root cause explained? Yes. competing_node DETACHes the DB before ADD COLUMN m, so its local rmt metadata is pre-ALTER. recoverLostReplica does not rewrite matching-UUID RMT tables ("handled on table replication level"), so the recovered replica gets the column via table-level metadata replication; metadata_version converges asynchronously after SYSTEM SYNC REPLICA returns, leaving a window where SELECT * sees the pre-ALTER columns.
c Fix matches root cause? Yes. The reads depend on asynchronous metadata convergence, so they are retried until the expected state is reached.
d Test intent preserved? Yes. Expected final states are byte-identical (1\t2\t3, 1\t2\t3\t0\n1\t2\t3\t4); the test still asserts the recovered replica ends with the correct structure. Only the read is retried instead of once.
e Demonstrated in both directions? Partial: cannot force the sub-window on debug (passes without change). Fix verified non-regressing (10/10 with change, 30/30 without). Uses the file's existing assert_eq_with_retry idiom for a known async-convergence pattern.
f Fix general, not narrow patch? Yes. All three structure-dependent post-recovery reads in the test were converted, not just the one at line 1421.
g Generalizes across inputs? N/A (flaky-test read-retry fix, not a code bug).
h Backward compatible? N/A (test-only change).
i Invariants preserved? N/A (test-only change; no product code touched).

Session id: cron:clickhouse-worker-slot-3:20260710-162000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix — could you review this? It de-flakes test_replicated_table_structure_alter by retrying the post-recovery structure reads: on recovery, matching-UUID ReplicatedMergeTree tables are not rewritten by recoverLostReplica, so metadata_version converges asynchronously after SYSTEM SYNC REPLICA and SELECT * could briefly read the pre-ADD COLUMN structure (msan/tsan window). Expected states are unchanged.

@groeneai groeneai mentioned this pull request Jul 10, 2026
1 task done
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [51fd2a5]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04305_clickstack_dynamic_routes FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

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

Copy link
Copy Markdown
Collaborator Author

Pushed a follow-up commit (6100665) hardening the fix. The prior commit converted the reads to assert_eq_with_retry, but the Integration tests (amd_asan_ubsan, flaky) job still failed at test.py:1426 ('1\t2\t3' != '1\t2' on competing_node): column m never converged within the retry budget.

Root cause of the residual flakiness: the retry only re-ran the SELECT, while SYSTEM SYNC REPLICA ran once, before the loop. A replica recovering 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, StorageReplicatedMergeTree.cpp). If the single pre-loop SYNC returns before that entry exists, re-reading alone can never force convergence. The follow-up re-runs SYSTEM SYNC DATABASE REPLICA + SYSTEM SYNC REPLICA inside the retry loop (up to 60s) until the structure converges. Exact-equality assertions are unchanged.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The prior committed fix (retry SELECT only) is itself the fails-without-fix evidence: Integration tests (amd_asan_ubsan, flaky) FAIL @ 3ef5a05, test.py:1426, '1\t2\t3' != '1\t2'. Natural rate is ~0.05% (msan/tsan-only convergence window), not on-demand triggerable, but the flaky-check harness reproduced it.
b Root cause explained? Recovered replica converges structure async via table-level metadata replication (cloneMetadataIfNeeded enqueues the metadata entry during recovery). The single pre-loop SYNC could return before that entry existed; retrying only the SELECT then never forces convergence → pre-ALTER column set observed.
c Fix matches root cause? Yes — moves the SYNC (DB + table) INSIDE the retry loop so a later SYNC picks up the eventually-enqueued entry. Directly addresses the async-convergence mechanism.
d Test intent preserved? Yes — the exact-equality checks (1\t2\t3, 1\t2\t3\t0\n1\t2\t3\t4) are unchanged; the test still verifies the recovered replica ends up with the full post-ALTER structure.
e Both directions demonstrated? Fails without fix: the flaky-check FAIL above. Passes with fix: 3/3 local runs (amd_tsan config) after the follow-up.
f Fix is general across code paths? N/A (integration-test synchronization fix, not a code bug). All three structure-dependent post-recovery reads use the same helper.
g Fix generalizes across inputs? N/A (integration-test synchronization fix, not a code bug).
h Backward compatible? N/A (integration-test synchronization fix, not a code bug).
i Invariants and contracts preserved? N/A (integration-test synchronization fix, not a code bug). The helper only adds idempotent SYSTEM SYNC calls; assertions unchanged.

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 5ab3579. The sync/query pair in sync_and_assert_eq_with_retry is now wrapped in try/except inside the retry loop (mirroring assert_eq_with_retry), so an UNKNOWN_IDENTIFIER on the not-yet-applied k column is caught and retried until the schema converges or the 60s timeout expires, instead of exiting on the first iteration. This covers the final SELECT * FROM table_structure.rmt ORDER BY k read.

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

Copy link
Copy Markdown
Collaborator Author

Pushed c52b6df — the 1451 failure (competing_node returning 1\t2 instead of 1\t2\t3) is a distinct root cause from the earlier UNKNOWN_IDENTIFIER point, and is NOT fixed by retrying SYSTEM SYNC REPLICA longer.

Root cause (from the flaky-check logs of the previous head 5ab3579, RUN 29125441442, gw1+gw2): on the failing runs, competing_node's recovery leaves table_structure.rmt permanently on 2 columns (n, v) — the final on-disk rmt.sql after the whole test still lacks m, despite the full 60-iteration / 150s sync loop. Its DDLWorker logged Task query-0000000006 (ADD COLUMN m) has already been executed by replica (shard1|replica1) of the same shard and skipped the local ALTER; the digest matched (unsynced_after_recovery=false), so no lost-replica recovery ran; and SYSTEM SYNC REPLICA only syncs the replication queue (waitForProcessingQueue/pullLogsToQueue) — it does not re-read /metadata structure from ZooKeeper. So the local table stays on the old structure and no amount of sync converges it. (Passing runs are the ones where the DDLWorker executed ADD COLUMN m locally during recovery.)

Fix: add SYSTEM RESTART REPLICA {db}.{table} inside the retry loop. RESTART REPLICA re-runs the attach thread, which re-reads /metadata via checkTableStructure and applies the up-to-date structure. Kept inside the try/except so a transient error still retries.

Local reproduction (debug build, praktika integration runner): pre-fix code reproduced 1/40; with the fix, 90/90 pass (40 + 50).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Race, ~4% in CI; locally reproduced 1/40 with the pre-fix head. Not on-demand deterministic, but reproduced and root-caused from CI logs (final on-disk metadata stuck at 2 cols).
b Root cause explained? Yes. DDLWorker dedups ADD COLUMN m on the recovered replica ("already executed by replica1 of same shard") → local ALTER skipped; SYSTEM SYNC REPLICA only syncs the replication queue, never re-reads /metadata → structure stays 2-col forever → SELECT * returns 1\t2.
c Fix matches root cause? Yes. SYSTEM RESTART REPLICA re-runs the attach thread → checkTableStructure re-reads /metadata from ZK → applies the current structure. It is exactly the primitive that forces a structure re-read, which SYNC does not do.
d Test intent preserved? Yes. The test still asserts the recovered replica converges to the full 1\t2\t3 / 1\t2\t3\t0,1\t2\t3\t4 structure+data. No assertion weakened, no data reduced, no no-* tag added.
e Both directions demonstrated? Yes. Pre-fix: 1/40 fail ('1\t2\t3' != '1\t2', line 1451). With fix: 90/90 pass.
f Fix is general across code paths? N/A (integration-test synchronization helper, not a C++ code bug). The helper is applied at all three recovered-replica read sites in the test.
g Fix generalizes across inputs? N/A (test-helper fix, not a code bug).
h Backward compatible? N/A (test-only change).
i Invariants and contracts preserved? N/A (test-only change). RESTART REPLICA is permitted on Replicated-DB tables (InterpreterSystemQuery has explicit digest handling for it) and does not alter table data.

Session id: cron:clickhouse-worker-slot-2:20260710-223800

@groeneai

Copy link
Copy Markdown
Collaborator Author

clickhouse-gh[bot] is right: SYSTEM RESTART REPLICA re-reads /metadata from ZooKeeper (attach thread -> checkTableStructure -> setTableStructure) and therefore repairs the table rather than closing a read-timing window. Our own root-cause analysis reaches the same conclusion: this is a real server-side convergence gap, not a flaky read window.

Root cause (confirmed from the failing flaky-check CI logs + a local debug-build repro):

  • After DatabaseReplicated::recoverLostReplica, the recovered replica keeps its matching-UUID ReplicatedMergeTree and relies on structure converging "on table replication level" (src/Databases/DatabaseReplicated.cpp:1550-1553).
  • The follow-up ALTER TABLE ... ADD COLUMN is a DB-level DDL entry. On the recovered replica the DDLWorker sees it as already executed by another replica of the same shard (src/Interpreters/DDLWorker.cpp:881) and skips local execution; the DB digest matches, so no lost-replica recovery re-runs.
  • SYSTEM SYNC REPLICA only waits on the replication queue (waitForProcessingQueue); it does not re-read /metadata. So the matching-UUID RMT stays on the old structure permanently (verified: on-disk rmt.sql remained 2-column after ~60 SYNC retries / 150s).
  • Only SYSTEM RESTART REPLICA re-runs ReplicatedMergeTreeAttachThread -> checkTableStructure and applies the ZK structure.

So plain SYNC + SELECT genuinely cannot converge this state, and RESTART REPLICA does mask the underlying recovery bug.

Since this was requested as a de-flake on #101273, the scope call is yours @alexey-milovidov:

  • (A) keep the test-level RESTART REPLICA de-flake now and track the recoverLostReplica convergence gap as a separate issue/PR (I will file it with the analysis above), or
  • (B) expand this PR to fix the server side: after recovery, a recovered matching-UUID RMT should re-check its structure against ZK (equivalent to what the attach thread does), keeping the test assertion on plain SYNC + SELECT.

Either way I will not leave the server-side convergence gap unfiled.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction and definitive root cause (with on-disk proof). My earlier claim that SYSTEM RESTART REPLICA re-reads /metadata and applies the new structure was wrong; verified against source and against this PR's own red CI.

The RESTART-in-loop head (c52b6dfd) is worse, not a fix. SYSTEM RESTART REPLICA re-runs the attach thread, which calls checkTableStructure(..., strict_check = true) (ReplicatedMergeTreeAttachThread.cpp:194). With strict_check = true, checkTableStructureAttempt throws INCOMPATIBLE_COLUMNS on a local-vs-ZK mismatch (StorageReplicatedMergeTree.cpp:1804); it does not apply the ZK structure. So restarting a replica whose local metadata is stale forces a failing re-attach and the table stays readonly. The amd_asan_ubsan, flaky run on c52b6dfd fails with Code: 242 ... Table is in readonly mode in waitForProcessingQueue -> assertNotReadonly on the SYSTEM SYNC REPLICA inside the retry loop.

Proof this is a real server-side convergence gap, not a read-timing window. On the failing c52b6dfd run, competing_node's final on-disk metadata after the whole test (full 60-iteration / 150s restart+sync loop) is still 2 columns:

$ cat .../competing_node/database/store/.../rmt.sql
ATTACH TABLE _ UUID '...'
( `n` Int32, `v` UInt64 COMMENT 'version' )
ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{uuid}/{shard}', '{replica}', v) ORDER BY n

Column m never arrives. No test-level primitive converges it: SYSTEM SYNC REPLICA only drains the replication queue (waitForProcessingQueue), it never re-reads /metadata; SYSTEM RESTART REPLICA throws under the strict attach check.

Why dummy_node converges but competing_node does not. dummy_node detached before rmt existed, so on ATTACH DATABASE recovery creates rmt fresh from ZK metadata (3 cols) and converges immediately. competing_node created rmt (matching UUID, 2 cols) before detaching; recoverLostReplica keeps matching-UUID ReplicatedMergeTree tables ("handled on table replication level", DatabaseReplicated.cpp:1551) and relies on the RMT's own replication to converge. The startup path allows the mismatch ("metadata_version will be 0 for a while", StorageReplicatedMergeTree.cpp:656) and expects cloneMetadataIfNeeded to catch up, but cloneMetadataIfNeeded only runs for a lost replica (via cloneReplica). competing_node's RMT replica is not lost, so nothing ever forces its metadata to re-sync, and it sits on the pre-ALTER structure indefinitely.

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?

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, look not fixed.

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +101 to +103
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

alexey-milovidov and others added 4 commits July 19, 2026 00:29
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a redesign that addresses the outstanding review verdict: the repair moved from DatabaseReplicated::recoverLostReplica to ReplicatedMergeTreeRestartingThread::tryStartup, right after queue.load() + pullLogsToQueue(LOAD), while the replica is still readonly and before background queue processing starts.

What this changes:

  • The ALTER_METADATA -> MUTATE_PART ordering blocker is fixed for the missed version: the repair entry is queued before background_operations_assignee/mutations_updating_task start, so the alters sequence keeps the alter mutation blocked until the metadata stage applies. New regression: test_replicated_table_missed_alter_with_mutation (MODIFY COLUMN type change missed across a detach).
  • The orphan-vs-just-finished classification is gone entirely (and with it the V/V+1 and multi-candidate races): at startup queue.load() has materialized every /queue znode into RAM (including a repair entry from a dead incarnation, which then just applies idempotently), and no workers run during tryStartup. The function shrank accordingly, which also addresses the comment-density point.
  • The UNKNOWN_IDENTIFIER wedge is fixed: a failure to compare the structures (ZK metadata referencing a column the stale replica does not know, e.g. a missed ADD COLUMN + ADD INDEX on it) is treated as "differs" and repaired instead of propagating and leaving the replica readonly forever. Regression added to test_replicated_table_structure_alter (missed ADD INDEX on the missed column).
  • The fix is no longer specific to Replicated database recovery: any replica that missed a cleaned-up ALTER_METADATA without being marked lost is repaired at startup (the lost path was already covered by cloneMetadataIfNeeded).

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:

  1. Converge kept matching-UUID table structure on Replicated database recovery #110145 hooks recoverLostReplica, which is unordered with respect to the restarting thread, so its repair can land after updateMutations already made the missed alter's mutation runnable - the same mechanism confirmed in its open review thread. tryStartup placement makes the same-version ordering deterministic. (The intermediate-version case remains out of scope in both PRs for the reason stated there: the intermediate structure snapshot no longer exists anywhere to reconstruct.)
  2. Converge kept matching-UUID table structure on Replicated database recovery #110145 keys the decision off the persisted replica_path/metadata_version. fixReplicaMetadataVersionIfNeeded fast-forwards that node (0 -> table version, for a replica that never applied an alter locally, when no ALTER_METADATA is queued - exactly the single-missed-ALTER state) from the restarting thread; if that bump runs before the recovery hook probes, the version guard reports "up to date" and the stale structure is never repaired. test_replicated_table_single_missed_alter pins this shape; the structural compare used here is immune to it (and treats a compare failure as "differs", so it does not inherit the wedge from point 3 above).
  3. Converge kept matching-UUID table structure on Replicated database recovery #110145's create-then-insert has a crash window: recoverLostReplica retries do not reload the queue, and getMaxMetadataAlterVersionInQueue only sees RAM, so a retry after a crash between the two steps creates a second entry with the same alter_version; both later load together on restart and corrupt the alters sequence (finishMetadataAlter head invariant). At startup this cannot happen - queue.load() picks up the leftover znode before the repair decision.

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.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed on the consolidation: from our side we withdraw the earlier deferral to #110145 - the tryStartup placement is the right vehicle and points 1-3 hold.

Verified against the current head diff:

  • Repair now runs from ReplicatedMergeTreeRestartingThread::tryStartup() after queue.load() + pullLogsToQueue(LOAD) and before background processing, so the orphan-vs-just-finished classification (and with it the V/V+1 and the create-then-insert idempotency findings we had raised) is gone.
  • The compare-failure -> "differs" path removes the UNKNOWN_IDENTIFIER wedge.
  • All three regressions are present: test_replicated_table_missed_alter_with_mutation, test_replicated_table_single_missed_alter, and the missed ADD INDEX shape in test_replicated_table_structure_alter.

One unrelated thing before CI runs: the head still carries 4 contrib gitlink changes that are not part of this fix - contrib/clickstack, contrib/krb5, contrib/silk, contrib/sysroot. master has not moved these since the PR base, so pull/110030/merge keeps the head's pins; krb5/silk/sysroot roll back below master (sysroot to 2025-12-01). git checkout origin/master -- contrib/clickstack contrib/krb5 contrib/silk contrib/sysroot drops them.

@tiandiwonder

Copy link
Copy Markdown
Contributor

pr #111029 fixes it with real root cause.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tiandiwonder Agreed, #111029 is the right fix. It removes the source: the comment/settings ALTER was committing a query-scoped metadata snapshot pinned before lockForAlter by the #107491 access check, overwriting a concurrently applied ALTER_METADATA and dropping the column. #110030 and #110145 only repaired the resulting divergence after the fact; reading the commit base fresh under the alter lock (bypass=true) is the correct minimal fix, and test_alter_comment_races_replicated_alter_metadata pins the exact mechanism. Standing down; #111029 owns #110036.

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 manual approve Manual approve required to run CI pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_replicated_database/test.py::test_replicated_table_structure_alter (regression since 2026-07-10)

4 participants