Repository navigation
Stop the DDL worker before SYSTEM RESTORE DATABASE REPLICA re-initialises the replica - #118481
Conversation
…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]>
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
Severity: ❌ blocker / Open question for the code owner, from finding 2. I deliberately kept Session id: cron:clickhouse-review-slot-10:20260906-214700 |
Pre-PR validation gate (click to expand)
Row (i) was amended during pre-publication review, which found the two readers listed there; the Session id: cron:clickhouse-impl-slot-6:20260906-203045 |
|
cc @alesapin @tuanpach, could you review this? |
|
Workflow [PR], commit [e3cac22] Summary: ✅
AI ReviewSummaryThis PR restores the lost ordering that stops the local Findings❌ Blockers
Final VerdictChanges requested. The original restore-vs-recovery race is fixed, but the widened LLVM Coverage ReportMeasured on commit e3cac22.
Changed lines: Changed C/C++ lines covered: 18/19 (94.74%) · Uncovered code |
| if (ddl_worker) | ||
| { | ||
| LOG_TRACE(log, "Stopping DDL worker before restoring database metadata in Keeper."); | ||
| ddl_worker->shutdown(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_ptrbecomesstd::shared_ptr(DatabaseReplicated.h:279), a local copy is taken underddl_worker_mutexin both functions, and every unlocked dereference uses the copy, including theSTRICTloop. - serialization with the other users:
getDDLGuard(database_name, "", nullptr)plusgetExclusiveDDLGuardForDatabase(database_name)inInterpreterSystemQuery::restoreDatabaseReplica, beforerestoreDatabaseInKeeper.
Two measurements on "before the earlier stop is safe", which is why I am not sequencing this revert behind that PR:
-
The restore still destroys the worker exactly once. With the stop in place,
reinitializeDDLWorker'sif (ddl_worker)(:1126) is false, so:1129/:1132do not run and onlyinitDDLWorkerUnlocked()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:tryEnqueueAndExecuteEntrywaits for the worker thread up todatabase_replicated_initial_query_timeout_secand then runsprocessTaskon the client thread. -
For a replicated DDL or
SYSTEM SYNC DATABASE REPLICAthat arrives while the restore runs, the widened interval is exactly the interval in which the guards fire::1472throwsDATABASE_REPLICATION_FAILED,:866returnsfalse, both before any dereference. On master, with the database notis_probably_dropped, those arrivals pass the check because the worker is still registered, and the tail destruction lands inside their unlocked span; inSTRICTmode that span runs totimeout_msin the:880-:897loop. 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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 16 s compile time in total, 7 of them have a recent master baseline. |
| /// tables to `_broken_replicated_tables`. | ||
| { | ||
| std::lock_guard lock{ddl_worker_mutex}; | ||
| if (ddl_worker) |
There was a problem hiding this comment.
How about DDLWorker of another replica?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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]>
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.
`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.
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]>
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]>
Related: #117399
Found by
BuzzHouse (amd_tsan), STID 4105-4a50, on an unrelated PR:report.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a race between
SYSTEM RESTORE DATABASE REPLICAand the DDL worker of aReplicateddatabase. The restore re-initialised the replica while the previous DDL worker was still running its own startup recovery, so the recovery could read amax_log_ptr_at_creationthe 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
restoreDatabaseInKeeperrewrote the Keeper nodes and calledinitDatabaseReplica(..., CREATE)beforereplacing the DDL worker, so the old worker kept running and its startup recovery read the state the
restore was overwriting.
recoverLostReplicacomputesfirst_entry_to_mark_finished = new_replica ? max_log_ptr_at_creation : our_log_ptrfrom that plainnon-atomic field, and it decides which log entries the recovering replica marks
finished/synced.This is a lost fix.
82c08b3156ed5c2stopped and joined the worker before the restore touchedKeeper, with a
SCOPE_EXITrestarting it on failure.bb5a2d19fb88f94removed both while renamingrestoreDatabaseMetadataInKeeper, on a branch predating the fix and with no mention of the guard inits message;
26.3-26.8all contain the removal. Restoring it adds no new blocking: the tailreinitializeDDLWorker()already joined that thread.SCOPE_EXIT_SAFErather thanSCOPE_EXIT,because the body runs during exception propagation and
reinitializeDDLWorker()can itself throw.A new integration test parks the worker inside
recoverLostReplicawith an existing failpoint, thenruns a second restore. It fails without the source change; mutating only the
SCOPE_EXIT_SAFEhalfreddens it too.
Residuals, deliberately not fixed here.
ddl_workeris now null for the whole restore rather than the~1 ms
reinitializeDDLWorkertook, so DDL issued during a restore is rejected withDATABASE_REPLICATION_FAILED, and the pre-existing check-then-use windows intryEnqueueReplicatedDDL(:1471vs:1489) andwaitForReplicaToProcessAllEntries(:867vs: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
26.9.1.1323(included in26.9and later)