Skip to content

Fix SYSTEM RESTORE REPLICA bumping the metadata version once per replica - #125796

Closed
dbackeus wants to merge 4 commits into
ClickHouse:masterfrom
dbackeus:fix-restore-replica-metadata-version-bump
Closed

dbackeus wants to merge 4 commits into
ClickHouse:masterfrom
dbackeus:fix-restore-replica-metadata-version-bump

Conversation

@dbackeus

@dbackeus dbackeus commented Oct 14, 2026 •

Copy link
Copy Markdown

Related: #96351

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 SYSTEM RESTORE REPLICA raising a table's metadata version on every restored replica instead of only the first. After restoring more than one replica of a table that had been altered, every later ALTER could fail with CANNOT_ASSIGN_ALTER.

Details

restoreMetadataInZooKeeper (added in #96351) raises the /metadata znode version to the parts' highest metadata_version by issuing that many SETs, and every restored replica ran it. The first replica creates /metadata and brings it to N. The next replica, restored one by one or ON CLUSTER, added its own maximum again, so the shared version ended at 2N while the replicas held N, and every later ALTER failed with Metadata on replica is not up to date with common metadata in Zookeeper (CANNOT_ASSIGN_ALTER). Restoring a lagging replica first failed the same way: a later replica with newer parts raised the shared version past it.

Now only the first replica bumps the version. The others are created as lost replicas and clone the metadata version from a restored replica, as any new replica does.

Reproduced on 26.3.22.7 with two replicas: after ADD COLUMN and DROP COLUMN the version is 2; after deleting the table's Keeper path, restoring replica 1 leaves it at 2, restoring replica 2 makes it 4, and the next ALTER fails with code 517. test_alter_after_restoring_every_replica follows these steps and checks that the version stays at 2 and that an ALTER then succeeds on both replicas. test_alter_after_restoring_lagging_replica_first, from review, restores the replica with older parts first and checks that both replicas end at the shared version and can ALTER. The existing test in that file also restores both replicas, but only checks a TTL merge, which passes with the doubled version.

We hit this in production on 26.3.22.7 when moving a two-replica cluster from ZooKeeper to Keeper: 19 tables with earlier ALTERs refused every ALTER until each replica's metadata_version node was set to the shared version and the table was detached and attached again.


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

@CLAassistant

CLAassistant commented Oct 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Oct 14, 2026
restoreMetadataInZooKeeper raised the /metadata znode version by issuing
max_parts_metadata_version SETs, and every restored replica runs it. The
first replica creates /metadata and bumps it to N; restoring the next one
(one by one or ON CLUSTER) added N again, leaving the shared version at 2N
while the replicas hold N, so every later ALTER failed with
CANNOT_ASSIGN_ALTER.

Bump only while the version is below the target, each SET conditional on
the version just read, so further and concurrent restores leave it at N.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@dbackeus
dbackeus force-pushed the fix-restore-replica-metadata-version-bump branch from 58c3a03 to a9aeda6 Compare October 14, 2026 14:44
@george-larionov george-larionov added the can be tested Allows running workflows for external contributors label Oct 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ea89b7]

Summary: ✅


AI Review

Summary

Reviewed head 2ea89b767aa533493b452e446e013c3a70926a82. This fixes the repeated metadata-version bump during sequential SYSTEM RESTORE REPLICA operations and adds regression tests. The acknowledged concurrent-restore failure remains unresolved.

Missing context / blind spots
  • ⚠️ No local runtime tests were run. The inspected CI report has pending integration jobs; passing results for the modified module would close this validation gap.
Findings

❌ Blockers

  • src/Storages/StorageReplicatedMergeTree.cpp:7666: Concurrent restoration can leave a replica's metadata version permanently behind the shared version. [dismissed by author -- https://github.com/Fix SYSTEM RESTORE REPLICA bumping the metadata version once per replica #125796#discussion_r4312886434] The current clone and startup paths still allow the intermediate version to persist without an entry that advances it.

    For target version 2, the first replica is published with is_lost = 0 and replica version 0 before the shared version finishes increasing. After the first increment, a second restore skips this block, clones version 0, and queues no ALTER_METADATA because both replica versions match. Its startup repair can then persist shared version 1. When the first restore finishes at 2, the second stays at 1: subsequent schema ALTER operations fail with CANNOT_ASSIGN_ALTER, and restart repair accepts the nonzero version unchanged. The author's latest reply explicitly leaves this case to maintainers. Make clone eligibility wait for completed version initialization, while preserving recovery from interrupted initialization.

Tests
  • ⚠️ Add deterministic concurrent-restore coverage that holds the first restore at an intermediate shared metadata version, completes the second, then resumes the first. Check final versions and execute a schema ALTER from each replica. The added tests restore replicas sequentially and cannot exercise this interleaving.
Final Verdict

❌ Block — complete safe version initialization for concurrent restores, add the focused regression case, and obtain passing results for the modified integration module. No new inline comments were posted: the remaining finding already has a thread, and the two findings specific to the reverted implementation no longer apply.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default external Author is not a member of the ClickHouse organization labels Oct 14, 2026
@george-larionov george-larionov self-assigned this Oct 16, 2026
/// Every replica runs this and the first one to restore has already bumped the version, so bump only
/// up to the target: restoring the replicas one by one or ON CLUSTER must not add it once per replica.
/// Each SET is conditional on the version just read, so concurrent restores cannot overshoot either.
if (max_parts_metadata_version > 0)

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 fix looks right, thanks. There is a similar issue when a lagging replica is restored first. Let's say replica1 is at version 1 and replica2 is at version 2. If replica1 is restored first, it will get its version set to 1, but when replica2 is restored it will get its version set to 2 since that is the max version it can see. Then an ALTER will fail just like in your example. Here's a reproducer:

  def test_alter_after_restoring_lagging_replica_first(start_cluster):
      zk = cluster.get_kazoo_client("zoo1")
      table = "test_restored_lagging_first"

      for node in [node_1, node_2]:
          node.query(f"DROP TABLE IF EXISTS {table} SYNC")
      for node in [node_1, node_2]:
          node.query(
              f"CREATE TABLE {table}(n UInt32) "
              f"ENGINE = ReplicatedMergeTree('/clickhouse/tables/{table}/', '{node.name}') ORDER BY n"
          )

      node_1.query(f"ALTER TABLE {table} ADD COLUMN a1 UInt32", settings={"alter_sync": 2})
      node_1.query(f"INSERT INTO {table} (n) VALUES (1)")
      node_2.query(f"SYSTEM SYNC REPLICA {table}")
      node_1.query(f"ALTER TABLE {table} ADD COLUMN a2 UInt32", settings={"alter_sync": 2})

      # node_2 lags: its newest part is at metadata version 1, node_1 has one at version 2
      node_2.query(f"SYSTEM STOP FETCHES {table}")
      node_1.query(f"INSERT INTO {table} (n) VALUES (2)")

      zk_rmr_with_retries(zk, f"/clickhouse/tables/{table}")

      for node in [node_2, node_1]:
          node.query(f"SYSTEM START FETCHES {table}")
          node.query(f"SYSTEM RESTART REPLICA {table}")
          node.query(f"SYSTEM RESTORE REPLICA {table}")
      for node in [node_1, node_2]:
          node.query(f"SYSTEM SYNC REPLICA {table}")

      _, stat = zk.get(f"/clickhouse/tables/{table}/metadata")
      for node in [node_1, node_2]:
          version, _ = zk.get(f"/clickhouse/tables/{table}/replicas/{node.name}/metadata_version")
          assert int(version) == stat.version

      for i, node in enumerate([node_2, node_1]):
          node.query(f"ALTER TABLE {table} ADD COLUMN b{i} UInt32", settings={"alter_sync": 2})

      for node in [node_1, node_2]:
          node.query(f"DROP TABLE IF EXISTS {table} SYNC")

The suggested fix:

Suggested change
if (max_parts_metadata_version > 0)
if (is_first_replica && max_parts_metadata_version > 0)

This will then rely on the clone of not-first replicas to set their versions from the original replica. A pre-existing issue is that in such a scenario as above some data may be lost, but I think that is out of the scope of this PR.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Applied, and added your test. Thanks!

The replicas restored after the first are created as lost replicas and clone
their metadata version from a restored one, so only the first should raise the
shared /metadata version. Raising it on each of them doubled it when the
replicas were restored one by one, and pushed it past the first replica's when
a replica with newer parts was restored after a lagging one. Either way every
later ALTER failed with CANNOT_ASSIGN_ALTER. This replaces the bounded bump of
the previous commit, so the loop is master's again.

The condition and the lagging-replica test come from George Larionov's review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// Only the first replica bumps it. The others are created as lost replicas and clone the metadata
/// version from a restored replica; bumping it again for each of them, or to their own newer parts,
/// would leave the shared version ahead of the replicas and every later ALTER would fail.
if (is_first_replica && max_parts_metadata_version > 0)

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.

[P1] Finalize the first replica's version before allowing it to be cloned

Concurrent SYSTEM RESTORE REPLICA (including ON CLUSTER) can still leave a restored replica unable to execute ALTER. createTableIfNotExistsAttempt publishes the first replica with is_lost = 0 before this block, and cloneReplicaIfNeeded can select it before initialization finishes.

For example, with a target version of 2, pause the first restore after its first SET: the shared version is 1 and its replica's metadata_version is still 0. A second restore now skips this block, clones the first replica (both in-memory/source versions are 0, so cloneMetadataIfNeeded adds no ALTER_METADATA), and fixReplicaMetadataVersionIfNeeded persists the intermediate shared version 1. When the first restore finishes at 2, the second replica remains at 1, so its subsequent ALTER fails with CANNOT_ASSIGN_ALTER. There is no metadata log entry to catch it up, and the startup repair skips nonzero versions.

Please keep the first replica ineligible for cloning until both versions are finalized, or publish the initialized state atomically. Add coverage for concurrent restores that checks the versions and executes ALTER on each replica.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in d8f9a1b: the first replica is now created with its final metadata version. Covered by test_alter_after_restoring_replicas_concurrently.

@dbackeus dbackeus Oct 19, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Reverted in 2ea89b7: publishing the final version early broke recovery from an interrupted restore. Leaving the concurrent case to the maintainers.

The first replica to restore registered itself, not lost and at metadata
version 0, before bumping the shared /metadata version. A replica restored at
the same time (ON CLUSTER) could clone it in between: with both at version 0 it
queued no ALTER_METADATA, and the startup repair copied the intermediate shared
version, so it stayed behind once the bump finished and every ALTER on it
failed. The first replica is now created with the version the bump reaches, so
a replica cloning it at any point catches up to that version.

The new pausable failpoint stops the bump after its first SET, so the test can
restore the second replica in that window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rsion"

This reverts commit d8f9a1b.

Publishing the first replica with the final version before the shared
/metadata node reached it left a persistent mismatch when the restore was
interrupted mid-bump, and a retried creation could no longer adopt its own
replica. The simpler first-replica-only bump is kept; concurrent restores keep
the narrow race it had.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@dbackeus

Copy link
Copy Markdown
Author

@george-larionov After applying your suggested fix, the review bot flagged a race with concurrent restores (ON CLUSTER). Fixing it by registering the first replica with its final version broke recovery from an interrupted restore, so I reverted that. We're now back to having the narrow race condition, but seemed better than my attempt at a fix which surfaced even worse issues.

Let me know what you think.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ea89b767 with master 870f00581 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7d062c274; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 35 s compile time in total, 7 of them have a recent master baseline.

Job report

@filimonov

Copy link
Copy Markdown
Contributor

See #127656

@dbackeus

Copy link
Copy Markdown
Author

Superseded by #127656, which covers this case too. Closing, thanks!

@dbackeus dbackeus closed this Oct 26, 2026
@dbackeus
dbackeus deleted the fix-restore-replica-metadata-version-bump branch October 26, 2026 08:58
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-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants