Skip to content

Fix Replicated database recovery for a Remote table over a table function - #118221

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/remote-engine-skip-target-analysis-on-replay
Sep 13, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/remote-engine-skip-target-analysis-on-replay

Conversation

@groeneai

@groeneai groeneai commented Sep 5, 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):

Fixed a bug where a Replicated database could not recover a lost replica if it held a table with the Remote or RemoteSecure engine whose target is a table function, such as merge(...), that no longer resolves because the table it matched was dropped. Recovery re-analyzed the stored target and failed with BAD_ARGUMENTS, so the database's DDLWorker never finished initialization and DDL on that database stopped.

Description

recoverLostReplica re-creates every table from the ZooKeeper snapshot. Nothing registers a dependency edge from Remote to what its target matches, since a table function's matched set cannot be evaluated at attach time, so it can be created first. registerStorageRemote then re-analyzes the persisted target, which legitimately matches nothing, so BAD_ARGUMENTS propagates out of DatabaseReplicatedDDLWorker::initializeMainThread and initialization retries every 5 seconds.

The guard that suppresses that re-analysis, isLoadingFromExistingMetadata(mode) || attach_short_syntax, does not cover recovery, which arrives at SECONDARY_CREATE. Master already carries the flag for this distinction, Context::isRecoveryFromStoredMetadata, added for the same defect in registerStorageMergeTree; this adds it as a third disjunct. A backup RESTORE and ordinary secondary-replica DDL replay are untouched, so their access checks still run.

The same variable also gates the plain local-shard SELECT/INSERT check below it, which recovery therefore stops running; that check was already inert there, since a recovery context has no user and so full access. The other engines sharing this idiom read their target only when the structure was omitted, which a recovered definition never is. The one exception, registerStorageMaterializedPostgreSQL's legacy multi-address branch, could not be observed reproducing without a live PostgreSQL and is left alone.

Validated on a two-replica Replicated database over Keeper: before, the joining replica logged 18 initialization errors in 90 seconds and never reached Initialized DDLWorker thread; after, recovery completes on the first attempt with its persisted columns intact. A fresh CREATE naming an absent target is still BAD_ARGUMENTS and an unprivileged one still ACCESS_DENIED, identically on both arms, and 04341_remote_storage_engine_restore stays green over 50 randomized runs.

CI provenance: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109004&sha=2f038c176c218fde7ebe0fac144caaf5d07cc5fc&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Related: #106189


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

Version info

  • Merged into: 26.9.1.1355 (included in 26.9 and later)

…icated database replays stored metadata

`DatabaseReplicated::recoverLostReplica` re-creates every table from the ZooKeeper
metadata snapshot. `DDLDependencyVisitor::visitTableEngine` does not know `Remote` or
`RemoteSecure`, and nothing registers `merge` as a dependency source, so a table whose
engine is `Remote('127.0.0.1:9000', merge(db, '^src$'))` carries no dependency edge on
`src` and can be scheduled before it. `registerStorageRemote` then re-analyzes the
persisted table function target, because its guard was
`isLoadingFromExistingMetadata(args.mode) || args.query.attach_short_syntax` and recovery
arrives at `SECONDARY_CREATE`. The target legitimately matches nothing, so `BAD_ARGUMENTS`
is thrown, `tolerate_absent_target` does not apply because it requires
`args.is_restore_from_backup`, and the throw propagates out of
`DatabaseReplicatedDDLWorker::initializeMainThread`, which logs
`Error on initialization of <db>` and retries every 5 seconds.

Add `Context::isRecoveryFromStoredMetadata` as a third disjunct. That flag is the tree's
existing replay provenance, set by `recoverLostReplica` and by
`SYSTEM RESTORE DATABASE REPLICA`, and it already serves this exact purpose in
`registerStorageMergeTree`. A `mode`-derived predicate cannot express the distinction:
recovery shares `SECONDARY_CREATE` with an ordinary secondary-replica `CREATE`, which is
not broken and must keep validating.

A backup `RESTORE` is unchanged. It reaches this code with `SECONDARY_CREATE` and
`args.is_restore_from_backup`, which the new disjunct does not touch, so it keeps both its
access checks and its carve-out that leaves `ACCESS_DENIED` fatal while tolerating an absent
target. `SYSTEM RESTART REPLICA` sets the same flag but cannot reach this engine, because
`doRestartReplica` returns early unless the table is a `StorageReplicatedMergeTree`, so it
is not claimed as covered.

Amend the two comments that enumerate which routes count as already-validated metadata.
Leaving the second one alone would have left it stating that only server startup and a
short `ATTACH` skip the analysis, which this change makes false.

Measured on a two-replica `Replicated` database over Keeper, with both servers on one
`tcp_port` bound to `127.0.0.1` and `127.0.1.1` so the target is a local shard on both.
Before the change the second replica logged 18 consecutive initialization errors in 90
seconds and never reached `Initialized DDLWorker thread`, and its database stayed empty;
after it, recovery completes on the first attempt with the persisted columns intact. In one
recovery covering five tables, three recovered before and five after, including a `Buffer`
with an absent destination. A fresh `CREATE` naming an absent target is still rejected with
`BAD_ARGUMENTS`, and an unprivileged `CREATE` over either a plain or a `merge()` local
target is still `ACCESS_DENIED`, identically before and after.

The regression test is added next to `test_alias_with_dropped_target`, which is the same
two-replica construction for the sibling `Alias` defect. It fails on the unfixed binary on
its own assertion, and passes 50 times out of 50 on the fixed one.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 0 blockers, 0 majors. Three informational notes.

💡 loading_from_existing_metadata gates two guards, so recovery also stops running the plain local-shard SELECT/INSERT check below the analysis. That is inert: a recovery context has no user and therefore full access (Context.cpp:2456), and the pre-fix repro logged ACCESS_DENIED 0 times against BAD_ARGUMENTS 18 times. Now stated in the description.

💡 registerStorageRemote is the only user of this idiom that analyses its target even when the columns are present, which is why it alone breaks recovery: everywhere else the target is read only under columns.empty(), and a replayed definition is never columnless. The one exception, registerStorageMaterializedPostgreSQL's legacy multi-address branch, could not be observed reproducing without a live PostgreSQL, so it is disclosed and left alone rather than fixed blind.

⚠️ StorageAlias.cpp:550 still carries the pre-flag idiom, but its check is a bare checkAccess under that same no-user context and its catalog restrictions already exclude SECONDARY_CREATE, so nothing user-visible remains to fix there. Left alone deliberately.

@clickhouse-gh clickhouse-gh Bot closed this Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [053bcf8]

Summary: ✅


AI Review

Summary

This PR makes Remote and RemoteSecure skip table-function target re-analysis only when a Replicated database is replaying already-stored metadata during lost-replica recovery, and adds an integration test that reproduces the stuck-initialization case with a dropped merge(...) target. I did not find any blocking or major issues in the current code: the new isRecoveryFromStoredMetadata disjunct matches the existing replay-only contract, backup RESTORE keeps its separate validation path, and the new test exercises recoverLostReplica through the new-replica recovery path.

Final Verdict

✅ No blocking issues found.

LLVM Coverage Report

Measured on commit 053bcf8.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @alexey-milovidov, could you review this? A Replicated database cannot recover a replica that holds a Remote table whose merge(...) target was dropped, because registerStorageRemote re-analyzes the persisted target on the recovery path. This adds Context::isRecoveryFromStoredMetadata to that guard rather than relaxing tolerate_absent_target, so a backup RESTORE and ordinary secondary-replica DDL replay keep validating.

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 053bcf805 with master 55c256363 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

3 object files changed (+16.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageDistributed.cpp.o 1.12 MiB 1.14 MiB +16.38 KiB (+1.42%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 1999a0f Sep 13, 2026
175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 14, 2026
Resolves the one conflict, in `registerStorageRemote`. Our side deletes that block
(its logic moved into `parseAndValidateRemoteEngineTarget`, shared with the new
initiator-side preflight); master's side keeps it. Took our empty side by editing the
marked region only, rather than `git checkout --ours`, which would also have discarded
master's other, auto-merged changes to the same file: the two
`hasLimitAfter()`/`limitAfter()` guards in `getOptimizedQueryProcessingStage` and the
Mintlify admonition migration in the engine's documentation block. Both verified present
afterwards.

The part that mattered was outside the conflict markers. Master's change to the deleted
block came from ClickHouse#118221, which added a third disjunct to the guard:

    || args.getLocalContext()->isRecoveryFromStoredMetadata()

Without it, a `Replicated` database replaying metadata it stored in Keeper re-analyzes a
persisted `Remote` engine's table function target, and a target that legitimately matches
nothing now fails the replica's initialization. Recovery cannot be recognised from
`args.mode`, which it shares with an ordinary secondary-replica `CREATE` that must keep
validating, so the flag is carried on the context.

`validateRemoteEngineTarget.cpp` exists only on this branch, so git had no reason to
report anything there, and a resolution that only removed the conflicted block would have
reverted ClickHouse#118221 silently while compiling and passing this branch's own tests. Ported the
disjunct into the helper and amended the route enumeration above it, which had claimed
that only server startup and a short `ATTACH` skip the analysis. The second comment
ClickHouse#118221 amended needs no change here: this helper's `analyze_table_function_target`
comment does not enumerate those routes.

Verified on the merged tree with two servers sharing one Keeper and one `tcp_port` across
`127.0.0.1` and `127.0.1.1`, so the target is a local shard on both (`is_local = 1`
measured on each; without that every probe below passes vacuously).

This branch's own fix, under `GRANT CLUSTER ON *.*` so the query reaches the preflight
rather than stopping at the cluster gate: an `ON CLUSTER` `Remote` over a table the user
cannot read is refused with `SELECT ON occ.protected` when the structure is given and
`SHOW COLUMNS ON occ.protected` when it is omitted, matching the local form; with the
grants both succeed, and the omitted form infers `secret_col UInt64, other_col String`.

ClickHouse#118221's invariant, both halves: a fresh `CREATE` naming an absent `merge()` target is
still rejected with `BAD_ARGUMENTS`, while a second replica of the same Keeper path
instantiates the stored definition with its recorded columns, logging no initialization
error and no target re-analysis. The fresh-CREATE rejection is the control proving the
analysis is reachable on that server, so the asymmetry is the evidence.

Submodules were resynced to the merged pins after the ownership gate reported the
worktree's own plumbing; no `contrib` drift against master remains.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants