Skip to content

Stop the DDL worker before SYSTEM RESTORE DATABASE REPLICA re-initialises the replica - #118481

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/restore-db-replica-stop-ddl-worker-before-init
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/restore-db-replica-stop-ddl-worker-before-init

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117399

Found by BuzzHouse (amd_tsan), STID 4105-4a50, on an unrelated PR:
report.

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 race between SYSTEM RESTORE DATABASE REPLICA and the DDL worker of a Replicated database. The restore re-initialised the replica while the previous DDL worker was still running its own startup recovery, so the recovery could read a max_log_ptr_at_creation the restore was overwriting and mark the wrong range of replicated-DDL log entries as finished, or move local tables to _broken_replicated_tables. The worker is now stopped before the restore touches Keeper.

Description

restoreDatabaseInKeeper rewrote the Keeper nodes and called initDatabaseReplica(..., CREATE) before
replacing the DDL worker, so the old worker kept running and its startup recovery read the state the
restore was overwriting. recoverLostReplica computes
first_entry_to_mark_finished = new_replica ? max_log_ptr_at_creation : our_log_ptr from that plain
non-atomic field, and it decides which log entries the recovering replica marks finished/synced.

This is a lost fix. 82c08b3156ed5c2 stopped and joined the worker before the restore touched
Keeper, with a SCOPE_EXIT restarting it on failure. bb5a2d19fb88f94 removed both while renaming
restoreDatabaseMetadataInKeeper, on a branch predating the fix and with no mention of the guard in
its message; 26.3-26.8 all contain the removal. Restoring it adds no new blocking: the tail
reinitializeDDLWorker() already joined that thread. SCOPE_EXIT_SAFE rather than SCOPE_EXIT,
because the body runs during exception propagation and reinitializeDDLWorker() can itself throw.

A new integration test parks the worker inside recoverLostReplica with an existing failpoint, then
runs a second restore. It fails without the source change; mutating only the SCOPE_EXIT_SAFE half
reddens it too.

Residuals, deliberately not fixed here. ddl_worker is now null for the whole restore rather than the
~1 ms reinitializeDDLWorker took, so DDL issued during a restore is rejected with
DATABASE_REPLICATION_FAILED, and the pre-existing check-then-use windows in
tryEnqueueReplicatedDDL (:1471 vs :1489) and waitForReplicaToProcessAllEntries (:867 vs
:870) get more exposure. Two concurrent restores are also still unserialised. All three want
#117399's exclusive database DDLGuard.


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

Version info

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

…ises the replica

`restoreDatabaseInKeeper` rewrites the database's Keeper nodes and then calls
`initDatabaseReplica(zookeeper, LoadingStrictnessLevel::CREATE)`, which assigns
`max_log_ptr_at_creation`, and only afterwards calls `reinitializeDDLWorker()`.
The previous DDL worker is therefore still running throughout those mutations,
and its own startup recovery independently reads the same state:
`initializeMainThread` -> `initializeReplication` -> `recoverLostReplica`, where

    UInt32 first_entry_to_mark_finished = new_replica ? max_log_ptr_at_creation : our_log_ptr;

selects which replicated-DDL log entries the recovering replica marks `finished`
and `synced` in Keeper. The field is a plain non-atomic `UInt32`, so the overlap
is both a data race and a logical one: the recovery can mark the wrong entry
range while the state it is recovering from is being replaced underneath it. The
worker's ZooKeeper-reconnect path re-enters `initDatabaseReplica` itself, so
write-vs-write on the same object was reachable too.

Reported by `BuzzHouse (amd_tsan)` as a ThreadSanitizer data race between
`DatabaseReplicated::initDatabaseReplica` and
`DatabaseReplicated::recoverLostReplica`.

This is a lost fix rather than a new defect. 82c08b3 added a block that
stops and joins the worker before the restore touches Keeper, plus a
`SCOPE_EXIT` that reinitialises it if the restore fails. bb5a2d1 removed
both while renaming `restoreDatabaseMetadataInKeeper` to
`restoreDatabaseInKeeper`; that branch was authored before the fix landed and its
message does not mention the guard, so the removal was incidental to the
refactor. Release branches 26.3 through 26.8 all contain the removal.

Stopping the worker removes the other participant instead of protecting one
field: with the worker joined before the mutations and a fresh worker created
after them, both accesses gain a happens-before edge, which also covers
`is_readonly`, `is_probably_dropped`, `tables_metadata_digest` and the Keeper
nodes themselves. It adds no new blocking, because the existing tail call already
waits for that thread: `reinitializeDDLWorker()` calls `DDLWorker::shutdown()`,
which joins `main_thread` and `cleanup_thread`. The change is a reordering of two
operations the function already performs.

Two deliberate differences from 82c08b3:

  * the block sits after the `getZooKeeper()` null check rather than immediately
    after `waitDatabaseStarted()`, so a `NO_ZOOKEEPER` failure no longer stops
    and restarts the worker for nothing;
  * `SCOPE_EXIT_SAFE` instead of `SCOPE_EXIT`, because the guard body runs while
    an exception propagates and `reinitializeDDLWorker()` can itself throw on
    thread creation; plain `SCOPE_EXIT` would call `std::terminate` there, and a
    throwing guard would also replace the restore's own error.

`ddl_worker_initialized` is cleared before `ddl_worker` is reset, both under
`ddl_worker_mutex`, so `canExecuteReplicatedMetadataAlter()` short-circuits
instead of dereferencing a null worker when a ReplicatedMergeTree background
thread calls it during the restore.

Not addressed here: two concurrent `SYSTEM RESTORE DATABASE REPLICA` statements
on the same database, which needs the exclusive database `DDLGuard` proposed in
PR ClickHouse#117399. That change and this one are disjoint.

The new integration test parks the worker inside `recoverLostReplica` with the
existing `database_replicated_pause_after_snapshot_identity_check` failpoint and
then issues a second restore, asserting that the second restore cannot reach its
Keeper writes while the recovery is parked. It fails without the source change,
and mutating only the `SCOPE_EXIT_SAFE` half makes the post-restore DDL fail with
`Database is not initialized or is being dropped`, so both halves of the change
are covered.

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 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 gate findings plus 4 from my own
cold pass; bounded: 1 full pass, 0 fix rounds).

# Sev Finding Verdict Evidence / action
1 ❌ Destroying ddl_worker early can race with users of the raw pointer (:1489, :870), and does not serialise two concurrent restores DISAGREE Severity conceded; my own pass raised the same exposure. Refuted step: the destruction is not new. Master already destroys this worker on this path at :2425 -> reinitializeDDLWorker -> :1132, so both windows are reachable on master through the same statement; this only moves it earlier. In-PR remedies are worse: the exclusive DDLGuard plus shared_ptr is #117399; keeping a joined worker registered turns :1471's clear error into a hang on :1489; an atomic field still leaves two threads in initDatabaseReplica. Disclosed as a residual in the description, no coverage claimed
2 ⚠️ The recovery guard is armed too late (after shutdown) and disarmed too early (before the tail call) DISAGREE Both orderings are 82c08b3156ed5c2 verbatim, including need_reinitialize_ddl_worker = false; immediately before reinitializeDDLWorker(); this diff changes only SCOPE_EXIT to SCOPE_EXIT_SAFE. Both failure modes are base-identical: a throwing DatabaseReplicatedDDLWorker::shutdown (DatabaseReplicatedWorker.cpp:158) leaves the same state at :1129, which master's restore reaches on every call, and a throwing tail call leaves no worker on master too. Neither trigger is reproduced. See the note below
3 ⚠️ The ddl_worker == nullptr audit missed two readers AGREE My own finding. tryEnqueueReplicatedDDL releases ddl_worker_mutex at :1474 and dereferences at :1489; waitForReplicaToProcessAllEntries releases it at :867 and dereferences at :870/:882/:896, looping there in STRICT mode and from createTableRestoredFromBackup (:2912). Both are pre-existing, both now see more of the window. Folded into the description's residual paragraph
4 💡 Two of the three SCOPE_EXIT_SAFE comment lines restate the commit message AGREE Noted, not changed. Measured budget: 7 added comment lines against 17 added code lines in src/. The 4-line block above it is 82c08b3156ed5c2 verbatim and states why the ordering is required, which is the knowledge whose loss let the refactor drop the guard, so it is kept intact

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Open question for the code owner, from finding 2. I deliberately kept 82c08b3156ed5c2's exact
ordering so this reads as the restoration it is. If you would rather have the strictly-more-robust
variant, it is two one-line moves: install the SCOPE_EXIT_SAFE above the stop block, so a throwing
shutdown() still gets a restart attempt, and clear its flag after reinitializeDDLWorker() returns,
so a failed thread start is retried once instead of leaving the database without a worker. Say the
word and I will push it; I did not want to smuggle an improvement into a revert.

Session id: cron:clickhouse-review-slot-10:20260906-214700

@clickhouse-gh clickhouse-gh Bot closed this Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One command: python3 -m ci.praktika run "integration" --test "test_restore_db_replica/test.py::test_restore_db_replica_stops_ddl_worker_before_touching_keeper". The overlap is constructed with a PAUSEABLE_ONCE failpoint that parks the reader inside recoverLostReplica, so the unfixed arm fails on the first oracle tick every run, not at some low rate.
b Root cause explained? Yes. restoreDatabaseInKeeper rewrites the Keeper nodes and calls initDatabaseReplica(..., CREATE) (which assigns max_log_ptr_at_creation) and only afterwards replaces the DDL worker, so the previous worker's startup recovery reads that field at DatabaseReplicated.cpp:1913 while the restore is writing it. That value chooses which replicated-DDL log entries the recovering replica marks finished/synced.
c Fix matches root cause? Yes. It restores the ordering whose absence is the root cause: stop and join the worker before the restore touches Keeper. No atomic on the symptom field, no widened bound, no no-random-* tag, no guard at the failure site. It is the block 82c08b3156ed5c2 added for this exact race, re-placed in the function bb5a2d19fb88f94 renamed.
d Test intent preserved / new tests added? Yes. No existing test was weakened; the only edits to the existing file are one additive LIKE-based log-count helper and one new test function. All 13 tests in test_restore_db_replica/test.py pass, as do all 45 in test_replicated_database/test.py.
e Both directions demonstrated? Yes. Reverting only the source hunk rebuilds to a binary byte-identical to pristine HEAD (Build-ID bf62fdb7…) and the test fails with 'Metadata was restored previously%' count moved 1 -> 2; with the change (Build-ID b54f7a9a…) it passes, 20 consecutive runs green. A second, independent mutation that neuters only the SCOPE_EXIT_SAFE half fails on the post-restore DDL with Code: 571 Database is not initialized, so each half of the diff has its own reddening arm.
f Fix is general across code paths? Yes, enumeration is closed. restoreDatabaseInKeeper has exactly one caller (InterpreterSystemQuery.cpp:1391); initDatabaseReplica has exactly three entry points (startup, the worker's ZK-reconnect path, and this restore); max_log_ptr_at_creation has two writers (:753, :977, both inside that call tree) and one reader (:1913). The single join/create edge covers all of them, including the write-vs-write case where the worker re-enters initDatabaseReplica itself.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A in the type sense: the defect has no column, expression, format or parameter axis. The one input-shaped dimension is the recovery branch, and the test forces new_replica == true (log_ptr = 0), which is exactly the branch that reads the racing field; the other branch reads a local (our_log_ptr) and is not exposed.
h Backward compatible? Yes. No setting, no SettingsChangesHistory.cpp entry, no format, versioning, on-disk or Keeper layout change. The only behaviour change is when the worker is stopped during a restore, and it restores the behaviour that shipped in 82c08b3156ed5c2.
i Invariants and contracts preserved? Partly, and the exception is disclosed in the description rather than claimed away. Lock ordering is unchanged: the new block takes ddl_worker_mutex alone and calls shutdown() under it, exactly as reinitializeDDLWorker() and stopReplication() already do. The window where ddl_worker is null widens from roughly 1 ms to the whole restore, so every reader was checked. Safe: canExecuteReplicatedMetadataAlter() (called from background threads), because setting ddl_worker_initialized = false before ddl_worker = nullptr makes its && short-circuit; and a client DDL that arrives during the window gets the null-guarded throw at :1471, measured rather than argued (the guard-neutered mutant produced Code: 571 from :1472 on a Debug binary with chassert active instead of aborting). Not covered by that guard, and therefore listed as residuals: tryEnqueueReplicatedDDL releases the mutex at :1474 and dereferences at :1489, and waitForReplicaToProcessAllEntries releases it at :867 and dereferences at :870/:882/:896, looping there in STRICT mode and from createTableRestoredFromBackup (:2912). Both windows exist on master, where the same restore destroys the same worker at :2425, so this change widens them rather than creating them. Exactly one worker restart happens on every path, and a throw from the explicit tail call still propagates.

Row (i) was amended during pre-publication review, which found the two readers listed there; the
answers are otherwise as recorded when the change was implemented.

Session id: cron:clickhouse-impl-slot-6:20260906-203045

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @tuanpach, could you review this? restoreDatabaseInKeeper assigns max_log_ptr_at_creation and only afterwards replaces the DDL worker, so the previous worker's startup recovery reads that field while the restore writes it. It restores the guard 82c08b3156ed5c2 added, which bb5a2d19fb88f94 dropped during the rename to restoreDatabaseInKeeper.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3cac22]

Summary: ✅


AI Review

Summary

This PR restores the lost ordering that stops the local DDLWorker before SYSTEM RESTORE DATABASE REPLICA rewrites Keeper state, which addresses the reported max_log_ptr_at_creation race. The review is still negative, because moving that shutdown to the start of the restore stretches an existing ddl_worker lifetime bug from the old tail reinitializeDDLWorker() gap to the whole restore window, so concurrent replicated DDL or SYSTEM SYNC DATABASE REPLICA can still run against a reset worker.

Findings

❌ Blockers

  • [src/Databases/DatabaseReplicated.cpp:2391, 1470-1489, 863-896] restoreDatabaseInKeeper now destroys ddl_worker before any Keeper work, but both tryEnqueueReplicatedDDL and waitForReplicaToProcessAllEntries still drop ddl_worker_mutex before they dereference that member. A request that passes the null check just before line 2391 can now observe ddl_worker after reset for the entire restore instead of only the old tail reinitialization gap, which keeps the null/use-after-free race alive and makes it materially easier to hit. Suggested fix: either serialize SYSTEM RESTORE DATABASE REPLICA with every ddl_worker user, or take a stable worker reference under ddl_worker_mutex and use that reference after unlocking.
Final Verdict

Changes requested. The original restore-vs-recovery race is fixed, but the widened ddl_worker lifetime race still needs to be closed before this is safe to merge.

LLVM Coverage Report

Measured on commit e3cac22.

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: 18/19 (94.74%) · 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 6, 2026
if (ddl_worker)
{
LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper.");
ddl_worker->shutdown();

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 shutdown now happens at the start of the restore, but the other ddl_worker entrypoints still drop ddl_worker_mutex before their dereference (tryEnqueueReplicatedDDL() at :1469-1489, waitForReplicaToProcessAllEntries() at :863-896). Because SYSTEM RESTORE DATABASE REPLICA is still not serialized with those paths, a concurrent replicated DDL or SYSTEM SYNC DATABASE REPLICA can pass its null check, then this block shuts the worker down and resets it, and the later call becomes a null/use-after-free on ddl_worker. On master that window was only the tail reinitializeDDLWorker() gap; moving the shutdown here stretches it to the whole restore. I think this needs either serialization with every ddl_worker user or a stable worker reference across the unlocked calls before the earlier stop is safe.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed on the mechanism, and it is in the description as a deliberate residual: ddl_worker is null for the whole restore instead of the ~1 ms reinitializeDDLWorker took, so the check-then-use windows in tryEnqueueReplicatedDDL (:1471 vs :1489) and waitForReplicaToProcessAllEntries (:867 vs :870/:882/:896) see more of it.

Both remedies you name already exist, in #117399, which the description links as the owner of this residual:

  • stable worker reference: std::unique_ptr becomes std::shared_ptr (DatabaseReplicated.h:279), a local copy is taken under ddl_worker_mutex in both functions, and every unlocked dereference uses the copy, including the STRICT loop.
  • serialization with the other users: getDDLGuard(database_name, "", nullptr) plus getExclusiveDDLGuardForDatabase(database_name) in InterpreterSystemQuery::restoreDatabaseReplica, before restoreDatabaseInKeeper.

Two measurements on "before the earlier stop is safe", which is why I am not sequencing this revert behind that PR:

  1. The restore still destroys the worker exactly once. With the stop in place, reinitializeDDLWorker's if (ddl_worker) (:1126) is false, so :1129/:1132 do not run and only initDDLWorkerUnlocked() does. A thread already past its null check meets one destruction either way, across the same unlocked span, and that span is long on master too: tryEnqueueAndExecuteEntry waits for the worker thread up to database_replicated_initial_query_timeout_sec and then runs processTask on the client thread.

  2. For a replicated DDL or SYSTEM SYNC DATABASE REPLICA that arrives while the restore runs, the widened interval is exactly the interval in which the guards fire: :1472 throws DATABASE_REPLICATION_FAILED, :866 returns false, both before any dereference. On master, with the database not is_probably_dropped, those arrivals pass the check because the worker is still registered, and the tail destruction lands inside their unlocked span; in STRICT mode that span runs to timeout_ms in the :880-:897 loop. So for arrivals this change removes a dereference rather than adding one.

What does get worse is the thread already past its check when the restore starts: on master it re-read a freshly created worker after ~1 ms, and now it reads nullptr for the restore's duration. That is the residual, and #117399's copy under the mutex is what closes it. I am not duplicating those hunks here: they are the same two functions in a PR that is already open, and this one restores a fix that is absent from 26.3-26.8, where the failure needs a single restore and no concurrency at all.

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e3cac220d 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.

Compile time of recompiled translation units

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

Job report

@tuanpach tuanpach self-assigned this Sep 7, 2026
/// tables to `_broken_replicated_tables`.
{
std::lock_guard lock{ddl_worker_mutex};
if (ddl_worker)

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.

How about DDLWorker of another replica?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Another replica's worker cannot see the state this block protects, and it cannot see a half-written metadata set either.

The comment is verbatim from 82c08b3156ed5c2, and it was accurate for that shape: the restore ran tryConnectToZooKeeperAndInitDatabase(CREATE) first, which created the database root with an empty /metadata, and restoreTablesMetadataInKeeper() wrote the per-table nodes only afterwards. In that window any worker, local or remote, could snapshot zero tables and detach its local ones, so the question would have found a real gap there. Your bb5a2d19fb88f94 ("Restore DB nodes on Keeper atomically") closed it: restoreDatabaseNodesInKeeper now puts buildDatabaseNodesInZooKeeper() (:1084) and one create request per local table into a single tryMulti (:1108), so the root, /metadata, /max_log_ptr and every /metadata/<table> node appear together or not at all, and a ZNODEEXISTS on any of them leaves Keeper untouched (the "Metadata was restored previously" path).

After that multi the restore only writes under this replica's own replica_path: createReplicaNodesInZooKeeper (:960-969, with a check request pinning /max_log_ptr's version), and the FORCE_AUTO_RECOVERY_DIGEST set at :2422. The only shared thing it adds is the empty entries createEmptyLogEntry appends (:852), which other replicas take through the normal log path.

What is left is process-local, and that is what the stop covers: initDatabaseReplica writes max_log_ptr_at_creation (:753, and :977 through createReplicaNodesInZooKeeper) and is_readonly (:778), restoreDatabaseNodesInKeeper recomputes tables_metadata_digest (:1105), and the worker's own recovery reads max_log_ptr_at_creation at :1913 while comparing the Keeper snapshot against the local table set. The reported race is exactly that pair, the client thread inside initDatabaseReplica against the worker main thread inside recoverLostReplica in the same server. A remote replica has its own DatabaseReplicated object, so no local stop could reach it and none is needed for this window.

A remote worker also does not reach recovery during a restore of a lost root, because the multi recreates only the shared subtree and createReplicaNodesInZooKeeper registers this host alone: its own /log_ptr read (DatabaseReplicatedWorker.cpp:195) throws ZNONODE and it retries every 5 s (:133), or, if its database is already readonly, initializeMainThread concludes "the database was probably dropped" and exits the thread. It stays that way until that replica runs the command itself.

The one cross-replica case that is genuinely not covered is two replicas restoring at the same time. One multi wins; the other takes the "Metadata was restored previously" path and then forces its own recovery against the winner's metadata, so a table that only it has is detached (reading recoverLostReplica, I have not run this case). That is pre-existing and this PR does not change it, and I should sharpen what the description says about it: #117399's getExclusiveDDLGuardForDatabase orders two restores inside one server, but it is per process, so it does not order restores issued on different replicas. That would need a lock in Keeper. Do you want it tracked separately?

One thing I would change here, since your refactor is what made the Keeper write atomic: the comment names a window that no longer exists, which is exactly what the question points at. I would reword it to name the local state instead.

/// Stop this replica's DDL worker before the calls below re-initialize replication state:
/// its recovery reads `max_log_ptr_at_creation` and compares the Keeper metadata with the
/// local table set, which those calls rewrite, and a recovery running against a half-updated
/// view detaches local tables into `<db>_broken_replicated_tables`.

I have not pushed that, because the code would not change and CI on this head is green. Tell me to go ahead, or fold it in with anything else you want changed, and it goes in one commit.

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.

Update it in one commit.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Pushed as e3cac220d12160b5db61f90fddc1660054eacf35, one commit, comment only. The diff totals are unchanged at +159 / -0 in two files, because the replacement is also four lines.

The commit message records why the old text no longer applies, so the reasoning is not only in this thread.

alexey-milovidov and others added 2 commits September 8, 2026 05:45
The comment was 82c08b3's text, and it described a Keeper-visible
window: at that commit the restore created the database root with an empty
`/metadata` and wrote the per-table nodes only afterwards, so any worker, local
or remote, could snapshot zero tables and detach its local ones.

bb5a2d1 ("Restore DB nodes on Keeper atomically") closed that window.
`restoreDatabaseNodesInKeeper` puts `buildDatabaseNodesInZooKeeper()` and one
create request per local table into a single `tryMulti`, so the root,
`/metadata`, `/max_log_ptr` and every `/metadata/<table>` node appear together
or not at all, and a `ZNODEEXISTS` on any of them leaves Keeper untouched.

What the stop protects is process-local: `initDatabaseReplica` assigns
`max_log_ptr_at_creation` and `is_readonly`, `restoreDatabaseNodesInKeeper`
recomputes `tables_metadata_digest`, and this replica's own worker recovery
reads `max_log_ptr_at_creation` while comparing the Keeper metadata against the
local table set. The comment names that state now, instead of a window that no
longer exists.

Comment only, no behaviour change.

Co-Authored-By: Claude Opus 5 <[email protected]>

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

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 3551ffe Sep 13, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 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 15, 2026
Only conflict: src/Common/FailPoint.cpp, where master added
database_replicated_pause_after_database_name_fetch at the same place in the
failpoint list as this branch added
database_replicated_pause_before_initial_entry_execution. Both entries kept.

Master meanwhile landed ClickHouse#118481, which stops the DDL worker at the top of
DatabaseReplicated::restoreDatabaseInKeeper. That fixes a different window (the
worker's own startup recovery racing the restore's Keeper rewrite) and does not
subsume this branch: SYSTEM RESTORE DATABASE REPLICA still takes no DDL guard,
ddl_worker is still a unique_ptr on master, and tryEnqueueReplicatedDDL still
executes the entry through a raw pointer after releasing ddl_worker_mutex.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
`test_restore_db_replica_waits_for_database_sync` measured the database-level
`DDLGuard` the restore takes by watching this replica's `digest` node in Keeper
during the window in which `SYSTEM SYNC DATABASE REPLICA` holds that guard.
ClickHouse#118481 then moved the DDL worker stop to the top of `restoreDatabaseInKeeper`,
before every Keeper write, so an unguarded restore now blocks joining the parked
worker thread before it can rewrite the digest: measured on the merged tree, the
guard-removed control passed every in-window assertion and only failed after
the failpoint was released, on the expected-refusal assertion (the restore
succeeded, `{'ok': True}`, instead of refusing a healthy replica).

Watch that stop instead, which is what the guard has to prevent: with the guard
the trace line never appears while the sync waits; without it the line is logged
0.14 ms into the restore. Re-measured on this head: control red inside the
window, fix green, full module 15/15 green.
alexey-milovidov added a commit that referenced this pull request Nov 7, 2026
Resolve conflicts against 26.3:
- `FailPoint.cpp`: add only `database_replicated_pause_before_initial_query_execution`; the other
  failpoints from master's context are not used in 26.3.
- `DatabaseReplicated.cpp`: keep the 26.3 structure of `waitForReplicaToProcessAllEntries` (STRICT mode)
  and `tryEnqueueAndExecuteEntry(entry, context, flags.internal)`, but use the local `worker` reference,
  and return early when the worker is stopped. Keep `assert` (26.3) with the new `isDDLWorkerCurrentlyActive`.
- `restoreDatabaseInKeeper`: 26.3 lacks #118481
  (stop the DDL worker before `SYSTEM RESTORE DATABASE REPLICA` re-initialises the replica), which
  this fix builds on. Include it inline (stop the worker before restore, `SCOPE_EXIT_SAFE` reinitialize
  on failure, `need_reinitialize_ddl_worker = false` on success).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 7, 2026
Resolve conflicts in `src/Databases/DatabaseReplicated.cpp`:
- `tryEnqueueReplicatedDDL`: use the worker reference from `tryGetDDLWorker`
  with the 26.8 signature of `tryEnqueueAndExecuteEntry` (`flags.internal`).
- `restoreDatabaseInKeeper`: 26.8 does not have
  #118481 (stop the DDL worker
  before `SYSTEM RESTORE DATABASE REPLICA` re-initialises the replica), on top
  of which #128824 waits for admitted initial queries. Keep the master version of
  this block, which brings in that small prerequisite: stop the worker before
  the restore, reinitialize it in `SCOPE_EXIT_SAFE` on failure, and set
  `need_reinitialize_ddl_worker = false` before the final `reinitializeDDLWorker`.
  Add the `Common/scope_guard_safe.h` include it needs.

Co-Authored-By: Claude Opus 5.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-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. 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.

4 participants