Skip to content

Serialize SYSTEM RESTORE DATABASE REPLICA against in-flight replicated DDL - #117399

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-restore-database-replica-inflight-ddl
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-restore-database-replica-inflight-ddl

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 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):

Fixes a use-after-free when SYSTEM RESTORE DATABASE REPLICA replaces the DDL worker of a Replicated database while another session is still executing a replicated DDL query through it. In debug and sanitizer builds the same window also produces a Digest does not match logical error.

Description

Related: #114819
Related: #117235 (comment)

Reported there by @ zlareb1.

Root cause. tryEnqueueReplicatedDDL reads ddl_worker under ddl_worker_mutex, releases the lock, then executes the entry through the raw pointer. tryEnqueueAndExecuteEntry runs processTask on the calling client thread, and DDLWorker::shutdown joins only the worker's own threads. SYSTEM RESTORE DATABASE REPLICA is the one database-lifecycle entrypoint that takes no DDL guard, so it destroys that worker while a client thread is inside a member function: a use-after-free in every build type. Since #118481 that happens at the top of restoreDatabaseInKeeper, before its first Keeper write, and again in reinitializeDDLWorker.

Fix. Take the two guards DROP DATABASE and CREATE DATABASE already take, in their order, across the restore. A table-level DDLGuard holds the same database mutex shared for its whole lifetime, and every tryEnqueueReplicatedDDL call site runs on a thread that holds one, so the restore cannot overlap an executing entry. ddl_worker also becomes a shared_ptr, with a local strong reference at both client-thread call sites, because createTableRestoredFromBackup waits on the worker from a RestorerFromBackup thread holding no DDL guard. SYSTEM SYNC DATABASE REPLICA and the backup-restore wait share those call sites and are fixed too.

Behavior change. A replicated DDL query concurrent with a restore fails with TIMEOUT_EXCEEDED on the database lock instead of racing; DROP DATABASE already does this on master (measured). It also serializes against SYSTEM SYNC DATABASE REPLICA, which takes the same guard.

Two reported items I deliberately do not change, reasoning in the thread: the DatabaseReplicated::shutdown half is not reachable (every live-server caller already holds that exclusive guard, and shutdown force-exits via safeExit while any connection remains), and the three digest assertions missing the !ddl_worker || guard need none (not evaluated outside DEBUG_OR_SANITIZER_BUILD, no remaining unsynchronized read can observe a reset after this fix, and locking them deadlocks against stopReplication).

Validation and notes

One new stateless test, 05442_restore_database_replica_waits_for_in_flight_ddl. It parks a replicated CREATE TABLE at a new failpoint and deletes the replica's Keeper node. Until the restore is seen waiting for the exclusive database lock (a no-op DROP TABLE IF EXISTS on the database is refused with Code: 159), it must neither complete nor recreate the node, and once released the entry must fail with Code: 159. A SYSTEM SYNC DATABASE REPLICA started while the restore waits isolates the database-level guard: it must wait for the restore and succeed.

Binary Result
fix pass, 30/30; the sync waited for the restore in every run
fix minus getExclusiveDDLGuardForDatabase fail, 3/3: the restore goes ahead
fix minus getDDLGuard(db, "") fail, 5/5: the sync fails with KEEPER_EXCEPTION on the missing log_ptr
master plus the failpoint hunks fail, 3/3; one run segfaults in DDLWorker::processTask

test_replicated_database/ full: identical to unmodified master.

initializeReplication calls checkDigestValid unconditionally, so one unsynchronized ddl_worker read is not debug-only; it runs on the worker's own main thread, which both reset sites join before assigning nullptr. The other five are chassert only.

Every strong reference is taken through a DatabasePtr its caller holds, so it never outlives the database; ~DDLWorker joins if nothing else did.

Unlike DROP DATABASE, the restore joins the worker under the exclusive guard; the join is bounded because a starved table guard gives up after a second.

The backup-restore waiter has no independent test; parking it needs scaffolding.


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

…ted DDL

`DatabaseReplicated::tryEnqueueReplicatedDDL` reads `ddl_worker` under
`ddl_worker_mutex`, releases the lock, and then executes the entry through the
raw pointer. `tryEnqueueAndExecuteEntry` runs `processTask` on the calling
client thread, and `DDLWorker::shutdown` joins only `main_thread`,
`cleanup_thread` and `worker_pool`, so no join covers that thread.

`SYSTEM RESTORE DATABASE REPLICA` is the one database-lifecycle entrypoint that
takes no DDL guard: on master `getExclusiveDDLGuardForDatabase` has only two
callers, `InterpreterCreateQuery.cpp:415` and `InterpreterDropQuery.cpp:807`. It
therefore reaches `reinitializeDDLWorker` and destroys the worker while a client
thread is inside one of its member functions. That is a use-after-free in every
build type; the `Digest does not match` `LOGICAL_ERROR` is the same window's
debug/sanitizer symptom, because `DatabaseWithOwnTablesBase::shutdown` clears
`tables` while `tables_metadata_digest` keeps its value.

Take the two guards `DROP DATABASE` and `CREATE DATABASE` already take, in their
order (database-level guard, then the exclusive one, with the startup wait
before it so the async startup job can still acquire table guards), and hold
them across `restoreDatabaseInKeeper`. A table-level `DDLGuard` holds
`database_ddl_mutex` shared for its whole lifetime -- `releaseTableLock`
releases only the table mutex -- and every `tryEnqueueReplicatedDDL` call site
runs on a thread that holds one, so the restore can no longer overlap an
executing entry. Six of the seven pass it to the entry; `InterpreterDropQuery`
may pass none on its `no_ddl_lock` path, and there relies on the guard its
caller already holds (`InterpreterDropQuery.cpp:894`,
`InterpreterCreateQuery.cpp:2315`, `DatabaseCatalog.cpp:1548`).

One asymmetry with `DROP DATABASE`, which this fix follows otherwise: it stops
the worker at `InterpreterDropQuery.cpp:494`, before taking the exclusive guard,
whereas the restore reaches `reinitializeDDLWorker` already holding it, so the
worker cannot restart in between. The join stays bounded because
`DDLWorker::shutdown` sets `stop_flag` and signals `queue_updated_event` before
joining, and a worker thread starved of a table guard throws after
`MAX_TRY * INTERVAL_MS`, so `initializeMainThread` leaves its retry loop instead
of waiting for the guard the restore holds.

Also make `ddl_worker` a `shared_ptr` and take a local strong reference at both
client-thread call sites. Serialization alone cannot cover
`createTableRestoredFromBackup`, which polls
`waitForReplicaToProcessAllEntries` on a `RestorerFromBackup` thread that holds
no DDL guard. A strong reference only delays destruction, and never outlives the
database: each one is taken in a member function reached through a `DatabasePtr`
its caller holds, and `~DDLWorker` performs the join if nothing else did. It
cannot leave a second worker running either, because `reinitializeDDLWorker`
stops the old worker, drops it and starts the replacement inside a single
`ddl_worker_mutex` critical section.

`SYSTEM SYNC DATABASE REPLICA` and the backup-restore wait share those call
sites and are fixed too.

Two findings from the report are deliberately not changed. The
`DatabaseReplicated::shutdown` half is not reachable: every live-server caller
already holds that exclusive guard, and server shutdown force-exits via
`safeExit` while any connection remains, so `DatabaseCatalog::shutdownImpl`
never runs with an in-flight entry. And the three digest assertions that lack
the `!ddl_worker ||` guard need no change. There are six such unsynchronized
reads, not five: five sit inside `chassert` and are not evaluated outside
`DEBUG_OR_SANITIZER_BUILD`. The sixth, the live `if` in `checkDigestValid`, is
not one of those. An earlier revision of this description called it debug-only,
and that was wrong: besides `assertDigestWithProbability`, whose body is
entirely `DEBUG_OR_SANITIZER_BUILD`, `checkDigestValid` is also called by
`DatabaseReplicatedDDLWorker::initializeReplication` with no `#if` at all, which
throws `LOGICAL_ERROR` on failure in every build type. That read is safe for a
different reason: it runs on the worker's own main thread, and
`ddl_worker->shutdown()` joins that thread before either reset site assigns
`nullptr` -- `reinitializeDDLWorker` in the same critical section,
`DatabaseReplicated::shutdown` earlier, in `stopReplication`, which only the
`database_replicated_throw_on_stop_replication` fault injection skips. Making
`ddl_worker` a `shared_ptr` does not weaken that, since the site uses only
`operator bool` and `operator->`. After this fix none of those sites can observe
a reset, and locking them would deadlock against `stopReplication`, which holds
`ddl_worker_mutex` while joining the very threads that reach them.

The background `ALTER_METADATA` path is the one `ddl_worker` reader the
serialization above does not cover, because it reaches
`DatabaseReplicated::commitAlterTable` from a `ReplicatedMergeTree` background
thread that holds no catalog DDL guard. Its assertion now tests `txn` first, so
it short-circuits before either `ddl_worker` read on that path: for a table in a
`Replicated` database, `setTableStructure` is always reached through a context
that already carries a `ZooKeeperMetadataTransaction`. Both operands are pure
and `||` is commutative over its truth value, so the assertion accepts and
rejects exactly the same states as before.

A replicated DDL query concurrent with a restore now fails with
`TIMEOUT_EXCEEDED` on the database lock instead of racing, because executing the
entry locally re-enters `getDDLGuard` and `SharedMutex` is writer-preferring.
`DROP DATABASE` already behaves exactly this way on unmodified master, at the
same two frames. The new test pins that outcome by error code (`Code: 159`) as
well as by the message, so a reword of the `DDLGuard` text cannot silently turn
the assertion into a message-shaped one.

The new `PAUSEABLE_ONCE` failpoint is what makes the client-thread window
testable: on master no failpoint parks a client thread inside the worker, since
`database_replicated_stop_entry_execution` fires in `initAndCheckTask`, which
only the worker's main thread reaches. A second test covers the database-level
guard on its own, driving that pre-existing failpoint from the other replica so
that no query thread on the restoring replica holds a table guard: without the
guard the restore rewrites this replica's digest to force recovery while
`SYSTEM SYNC DATABASE REPLICA` is still waiting.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Aug 31, 2026
@groeneai

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

Reviewed cold against the resulting code before reading the implementation's own evidence, then
re-reviewed by an independent model (engine: codex). Six review rounds, five fix rounds; the final
round found 0 findings. Only the findings that changed the change, plus the declines, are listed.

# Sev Finding Verdict Evidence / action
1 ❌ The background ALTER_METADATA path reaches commitAlterTable from a ReplicatedMergeTree thread that holds no catalog DDL guard, so serialization cannot cover its unsynchronized ddl_worker reads AGREE, fixed Assertion operands reordered so txn is tested first and short-circuits both reads. On that path txn is non-null unconditionally, by an exact predicate on the database engine name. Both operands are pure, so the predicate is unchanged
2 ⚠️ The sync test used process-list visibility as its ordering barrier, which precedes the guard acquisition it stands for; an elapsed threshold does not repair it AGREE, fixed Raised in two rounds. Now latched on a <Trace> line the server emits after taking the guard and immediately before it waits, matched for that query's own query_id. Measured 285 ms ahead of the restore's start
3 ⚠️ An assertion on the order in which two independent clients return is racy AGREE, fixed Removed. Both controls were then re-measured red, to show the arm lost no sensitivity
4 ⚠️ The database-level guard had no test of its own, only the exclusive one AGREE, fixed Second test added, driving the entry from the other replica so no query thread on the restoring replica holds a table guard. Its control (this fix minus that one guard) is red on the digest znode
5 ⚠️ The description claimed every remaining unsynchronized ddl_worker read is debug-only; initializeReplication calls checkDigestValid with no #if AGREE, corrected Both the body and the commit message now state the correction, with the reason that read is safe: it runs on the worker's own main thread, which both reset sites join before assigning nullptr
6 ⚠️ The commit message claimed all seven tryEnqueueReplicatedDDL call sites pass a table-level guard; InterpreterDropQuery passes none on its no_ddl_lock path AGREE, corrected The property is about the thread, not the argument: all three guard-elision producers leave the calling thread holding an equivalent guard. Wording fixed, and the three producers are cited in the message
7 💡 A teardown assertion on system.fail_points cannot fail for a PAUSEABLE_ONCE point, because libfiu reports a fired one-time point as disabled AGREE, fixed Deleted from that test only. The identical assertion in the other test is live, its failpoint being PAUSEABLE, and stays
8 💡 The DROP DATABASE asymmetry paragraph in the commit message will go stale if another open PR lands a third getExclusiveDDLGuardForDatabase caller DISAGREE The clause is prefixed "on master" and is true at publication: master has exactly two callers today, InterpreterCreateQuery.cpp:415 and InterpreterDropQuery.cpp:807. A commit message is a dated record whose line numbers drift regardless
9 💡 The commit message is long (about 1100 words) noted, not blocking The source diff carries 2 added comment lines against 21 added code lines, so the context sits in the message rather than in the code
10 💡 #115958 adds to the same failpoint list and edits the same two files noted, no action Different defect (Keeper cleanup after a failed CREATE, not worker lifetime). Neither supersedes the other; the expected interaction is a textual conflict in APPLY_FOR_FAILPOINTS, which whichever merges second resolves

Not covered, and disclosed rather than claimed: the backup-restore waiter reaches
waitForReplicaToProcessAllEntries from a thread holding no DDL guard, so the shared_ptr covers
it, but parking that thread needs new scaffolding and it has no test of its own.

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

Session id: cron:clickhouse-review-slot-9:20260831-180800

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c46bb15]

Summary: ✅


AI Review

Summary

The PR serializes SYSTEM RESTORE DATABASE REPLICA against replicated DDL and database synchronization, and retains shared ownership of the DDL worker during client-thread calls. One major review finding remains: the regression test can pass without the database-level guard because its sync rendezvous depends on scheduling.

Findings

⚠️ Majors

  • 05442_restore_database_replica_waits_for_in_flight_ddl.sh:76: Process-list visibility does not establish that the sync has attempted its database guard. executeQueryImpl inserts the query into system.processes before constructing and executing the interpreter. With the restore's database-level getDDLGuard removed, the sync can register and then be descheduled. The test releases the parked DDL, the restore recreates the replica, and the sync subsequently reads the restored Keeper nodes and succeeds. All assertions can therefore pass despite the missing serialization. Use a server-side rendezvous that establishes the sync's lock attempt while the replica is still absent. This remains the existing unresolved inline finding; no duplicate comment was posted.
Tests
  • ⚠️ Verify the strengthened sync regression against a control with only the restore's database-level getDDLGuard removed, including a sync delayed after process-list registration. The control must fail reliably and the complete fix must pass.
Final Verdict

Status: ⚠️ Request changes. Strengthen the sync rendezvous and demonstrate that the guard-removed control reliably fails.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro pytest test_restore_db_replica/test.py::test_restore_db_replica_waits_for_in_flight_ddl and ::test_restore_db_replica_waits_for_database_sync. Both red on pristine master plus the failpoint hunks, and each red on the fix minus the one guard it measures; both green with the fix. Repeats are counted per test, on the text being shipped: 8/8 green for the database-sync test, and 1/1 for the in-flight-DDL test plus 8/8 on the revision immediately before it, which differed only by a teardown assertion that libfiu makes unable to fail. Three consecutive green runs of the whole module.
b Root cause explained SYSTEM RESTORE DATABASE REPLICA is the one database-lifecycle entrypoint taking no DDL guard, and ddl_worker is handed to client threads as a raw pointer whose owner another thread resets. processTask runs on the calling client thread and no DDLWorker::shutdown join covers it.
c Fix matches root cause Serialization where a catalog guard already exists, lifetime extension where none does. No widened bound, no no-random-* tag, no defensive check at the crash site.
d Test intent preserved / new test added Two new integration tests, one per guard; no pre-existing test weakened. Oracles were strengthened, not relaxed: Code: 159 is pinned alongside the message, and each test's load-bearing condition is a latched Keeper fact. One assertion I had added myself, on the order in which two independent clients return, was removed as racy and redundant, and both of its controls were then re-measured red to show no sensitivity was lost by removing it. For the same reason the sync test's ordering barrier is a latch on a fact the server itself logs, not a timing threshold: SYSTEM SYNC DATABASE REPLICA emits a <Trace> line after taking the database guard and immediately before it waits, so matching that line for the test's own query_id proves the guard is held. Two weaker forms were measured and discarded first. Process-list visibility precedes the guard, because the row is inserted before the interpreter is even constructed; adding elapsed > 2 does not repair that, since elapsed is measured from before the insert too and the pre-guard path takes the global context mutex, so no threshold makes it an ordering barrier. The latch line was measured 285 ms ahead of the restore's start, and the control stays red on the same Keeper condition afterwards. The full-suite repeats show the neighbouring tests still assert what they did.
e Both directions demonstrated Each test fails on pristine master plus the failpoint hunks, and fails on the fix with only the guard it measures removed, so each guard is attributed individually. Both pass with the fix, at the per-test repeat counts in row (a), on a green full module.
f General across code paths Both reset sites and all six dereference carriers enumerated. grep -rl ddl_worker src/Databases/ matches only DatabaseReplicated.{h,cpp}; the hasReplicationThread() sibling DatabaseMaterializedPostgreSQL keeps its own replication_handler under handler_mutex, so it is not a carrier.
g Generalizes across inputs No column types involved, so the wrapper matrix does not apply. Covered axes: ON CLUSTER and plain restore, restart and no-restart, healthy-database refusal, single-replica and two-replica databases, an entry enqueued locally and one enqueued from the other replica, and both SyncReplicaMode::DEFAULT and STRICT branches of waitForReplicaToProcessAllEntries.
h Backward compatible No setting, no serialization format, no on-disk change, no new error code, so no SettingsChangesHistory.cpp row. The only behaviour delta is the TIMEOUT_EXCEEDED described in the PR body, which matches what DROP DATABASE already does.
i Invariants and contracts preserved Error codes, messages and return values at both call sites are byte-identical; the is_probably_dropped test stays at both, and waitForReplicaToProcessAllEntries still returns false on both prior conditions. Lock order is the tree's existing one (database-level guard, then exclusive), and no catalog lock is taken under ddl_worker_mutex. chassert(!ddl_worker) still holds because it tests the member. The one assertion whose operands were reordered in commitAlterTable accepts and rejects exactly the same states: both operands are pure and `

Style: various_checks.sh, check_cpp.sh and ruff check all clean.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @evillique, could you review this? SYSTEM RESTORE DATABASE REPLICA is the one database-lifecycle entrypoint that takes no DDL guard, so reinitializeDDLWorker can destroy the database DDL worker while a client thread is still executing a replicated DDL entry through it (tryEnqueueAndExecuteEntry runs processTask on the calling thread, and no join covers it); this takes the two guards DROP DATABASE and CREATE DATABASE already take, in their order.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c46bb1586e4bea49c8312918322e869b581bda95 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8ebb92e972af08f1daa537e85d1c981565b5641b

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases InterpreterSelectQuery turns enable_parallel_replicas off for the settings combination the test sets, so on the old-analyzer lane no statistics are collected and the first two reference rows read 0 0 instead of 1 1; deterministic, 3 of 3 reruns #117364 (external, merged 2026-08-31T22:05:00Z)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) the shard's nested containers breach the /docker cgroup leaf, so the kernel kills processes inside it and the job errors with no test attributed #117411 / #117412 (external, open)
Bugfix validation (integration tests, amd64 / aarch64), Finish Workflow / Post Hooks both per-arch jobs abort on assert build_urls, "Could not find master builds in S3" (the functional pair is SKIPPED, this PR changes no functional test), so nothing could validate and new_tests_check.py then reds the post hook #117433 (ours, open)

03707_autopr_unsupported_cases is not specific to this PR: it fails the same way on 120 distinct pull requests and on 12 master runs since 2026-08-31 14:00Z, and 133 of its 146 recorded failures are on this one lane. #117364 forces the analyzer in the test itself. I measured it ABSENT from this tree: the symbol it adds has 0 occurrences at 8ebb92e972af against 1 at the fix's own merge commit c9ed88dbecbb, with a pre-fix negative control at 0.

The /docker breach is a job-level condition, not a test result: every test of that shard at this head is OK or SKIPPED and the module this PR changes ran in shard 1/6, not in 6/6, where all 14 of its rows are OK. It fires on 259 distinct pull requests and 25 master runs in 7 days. #117202 (merged 2026-08-31T11:05:36Z) serialized the shutdown gdb attach and is ABSENT from this tree, but it is not the owner of what remains: on two other heads of mine where I measured it PRESENT, the same breach still fired, so the residual belongs to the two open PRs above, which resize the /docker leaf itself.

I have not merged master to pick #117364 up yet. It would not change Mergeable Check, because the /docker row is gating too and its fix is still open, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks up both once the /docker fix lands.

Mergeable Check reports Failed: 3 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of result_pr.json, so it also covers the rows Mergeable Check does not gate.
CH Inc sync was success at this head, so nothing here is exempt.

Session id: cron:our-pr-ci-monitor:20260901-023000

@evillique evillique self-assigned this Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 13, 2026
…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]>
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear the conflict. The only conflict was 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 adds database_replicated_pause_before_initial_entry_execution; both entries are
kept. Nothing else needed resolution, and the change against master is still the same six files.

#118481 landed in the meantime and does not subsume this one: SYSTEM RESTORE DATABASE REPLICA
still takes no DDL guard, ddl_worker is still a unique_ptr, and tryEnqueueReplicatedDDL still
executes the entry through a raw pointer after releasing ddl_worker_mutex. What it did change is
where the worker is destroyed: the stop now runs at the top of restoreDatabaseInKeeper, before the
first Keeper write, so the digest znode that test_restore_db_replica_waits_for_database_sync
watched can no longer move inside the measured window. Measured on the merged tree with
getDDLGuard(db, "") removed, every in-window assertion passed and the test only failed after the
failpoint was released. So the test now watches that stop instead, which is what the guard has to
prevent: the line is logged 0.14 ms into an unguarded restore and never appears while the sync waits.

Re-measured on this head:

  • fix: test_restore_db_replica/ full module, 15 passed in 617 s
  • control without getDDLGuard(db, ""): red inside the window, on the new assertion
  • control without getExclusiveDDLGuardForDatabase: red on the in-flight-DDL test
  • ci/jobs/check_style.py: 14 of 15 legs pass, the exception being settings_changes_history,
    which cannot run locally (it needs the changed-file list recorded by the CI workflow hook)

I also corrected the description, which still described the digest oracle, attributed the
destruction to reinitializeDDLWorker alone, and reported 14 module cases.

Session id: cron:clickhouse-maint-slot-19:20260915-120900

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1b00221

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 176 checks, 151 pass, 22 skipped, 2 failed,
aggregator complete, and nothing left running except CH Inc sync. The last real check completed at
17:55:47Z, well past the 20 minute buffer the CI database needs.

Check / test Reason Owner / fixing PR
Build profile diff infra, nothing tested: has_pr_data raised RuntimeError: CI logs cluster query failed on the binary_sizes read and aborted the job before any comparison ran #120121 (mine, open), which turns a transient cluster read failure into a skipped comparison instead of a failed one
CH Inc sync still pending: the private mirror sync does not complete on a fork CH Inc sync (private, not actionable by me)

PR aggregate the rows above rather than adding a failure of their own.

Bugfix validation (integration tests, amd64) and (aarch64) both concluded SUCCESS, so neither is a ledger line. For the record, the CI database carries 13 FAIL rows per arch under them for test_restore_db_replica/test.py: bugfix validation publishes its own job verdict independently of the per-test rows it stores, which is why a green job can carry them.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117399&sha=1b002217a6c7ccdf74073b14fa784088f5ddfc78&name_0=PR

Session id: cron:our-pr-ci-monitor:20260915-190256

@groeneai

Copy link
Copy Markdown
Collaborator Author

The use-after-free Finding A predicted has now crashed a server in CI, so it is no longer only a
static reading.

BuzzHouse (amd_debug), STID: 2275-4f79, 2026-09-17 04:16:00 UTC, on an unrelated branch whose
diff is confined to src/Functions/array/arrayIndex.* and whose tree still carries
std::unique_ptr<DatabaseReplicatedDDLWorker> ddl_worker at DatabaseReplicated.h:286. It is the
only parseQueryFromEntry failure in 90 days of the CI database.

Address: NULL pointer. Access: read., thread 150:

unique_ptr.h:267                    std::unique_ptr<...>::operator*
DDLTask.cpp:303                     DDLTaskBase::parseQueryFromEntry
DatabaseReplicatedWorker.cpp:470    DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry
DatabaseReplicated.cpp:1529         DatabaseReplicated::tryEnqueueReplicatedDDL
InterpreterCreateQuery.cpp:2171     InterpreterCreateQuery::createTable
StorageMaterializedView.cpp:833     StorageMaterializedView::prepareRefresh
RefreshTask.cpp:1360                RefreshTask::executeRefreshUnlocked  (BackgroundSchedulePool)

The window is 14 ms wide in the server log:

04:12:08.502812 [150]  {48efaade-...} DatabaseReplicated (d0): Proposing query: CREATE OR REPLACE TABLE `.tmp.inner_id.a1cab059-...`
04:12:08.516353 [1582] {daa72325-...} SYSTEM RESTORE DATABASE REPLICA `d0`;
04:12:08.516411 [1582] DatabaseReplicated (d0): Stopping DDL worker before restoring database metadata in Keeper.

Thread 150 is a refreshable MV refresh creating its temporary target table. It then sat in Keeper for
3m41s while the embedded Keeper hung, so it reached DatabaseReplicatedWorker.cpp:470 long after
thread 1582 had destroyed the worker. Line 470 passes DDLWorker::context, which the worker solely
owns (Context::createCopy, DDLWorker.cpp:104); since libc++ ~unique_ptr stores nullptr before
running the deleter, a destroyed Context leaves exactly settings == nullptr, and
getSettingsRef()'s *settings then makes Settings::operator[] read impl from address 0. A live
Context never has a null settings (Context.cpp:1425, :1446).

That "Stopping DDL worker" line is the block #118481 added to restoreDatabaseInKeeper, so
SYSTEM RESTORE DATABASE REPLICA is now a reset site reachable on a live server, which is what the
exclusive database guard here closes. The shared_ptr copy taken under ddl_worker_mutex closes it
for the other reset sites too.

One more observation from the same fatal.log, which the CI database does not carry: thread 1582
itself segfaulted 2.1 s earlier at a non-null unmapped address, in the Coordination::Requests
destructor inside ZooKeeper::createAncestors under restoreDatabaseNodesInKeeper
(DatabaseReplicated.cpp:1118), just as the session expired. I cannot tell from the log alone
whether that is a separate defect or fallout of the same window, and the core dump is encrypted.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119090&sha=50848d129891a86d3c9ab449a367c6b0592c7976&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Dear @evillique, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The second segfault I could not explain in my earlier comment, in ZooKeeper::createAncestors under restoreDatabaseNodesInKeeper, is the same use-after-free. A new CI run uploaded a core, which settles it.

BuzzHouse (amd_debug), 2026-10-10, CI reports it as STID: 5029-4dec: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120908&sha=277309c4766ae6bb0fd4eadba58e3ece123a9893&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29

Same window: a refreshable MV refresh proposes CREATE OR REPLACE TABLE .tmp.inner_id... on d2, and 2 ms later SYSTEM RESTORE DATABASE REPLICA d2 logs Stopping DDL worker before restoring database metadata in Keeper. and destroys the worker. Two threads then fault together: the refresh thread in DDLTaskBase::parseQueryFromEntry (the known null Settings stack), and the restore thread while destroying the Coordination::Requests of createAncestors, which is the frame CI fingerprints.

From the core:

((DB::DDLWorker*)0x7f59106ed800)->context   = {__ptr_ = 0x7f58a721f000, __cntrl_ = 0x7f58a7230ac0}   # the freed worker the refresh thread runs on
create_ops (restore thread)                  = {__begin_ = 0x7f58a7230ac0, __end_ = 0x7f58a7230ae0}
x/4gx 0x7f58a7230ac0                         = 0x7f58a7100c58 0x7f58a7100c42 | 0x7f58a7101f98 0x7f58a7101f80

The worker's 32-byte Context control block was reused as the 2-element vector buffer, so its __shared_owners_ overlays create_ops[0].__cntrl_. That slot reads 0x7f58a7100c42, while the real block is at 0x7f58a7100c40 (vtable __shared_ptr_emplace<ZooKeeperCreateRequest>, path /clickhouse). The +2 is the two by-value ContextPtr copies the refresh thread makes (DatabaseReplicatedTask::parseQueryFromEntry, then DDLTaskBase::parseQueryFromEntry) right before it faults. So createAncestors is a victim, not a second defect, and this PR covers both stacks: the refresh thread holds a table DDLGuard at that point, which the exclusive guard waits for, and the strong reference keeps the worker alive regardless.

This is the fifth server crash from this window in BuzzHouse (amd_debug) since 2026-09-17, each on an unrelated PR. Master still has the raw unique_ptr dereference at DatabaseReplicated.cpp:1555.

`test_restore_db_replica_waits_for_in_flight_ddl` needs one server, Keeper,
a failpoint and concurrent clients, all of which stateless tests have, so
per the integration-test guidance in `.claude/CLAUDE.md` it moves to
`05442_restore_database_replica_waits_for_in_flight_ddl.sh`. The Keeper
surgery that makes the restore legal uses `$CLICKHOUSE_KEEPER_CLIENT`.

The old test watched a fixed 15-second window. The new one latches on the
condition itself: while the restore waits for the exclusive database lock,
`DDLGuard` refuses every other DDL on the database, so a no-op
`DROP TABLE IF EXISTS` probe failing with `Code: 159` proves the restore is
blocked behind the parked entry. Until the probe is refused, the test still
asserts that the restore neither finishes nor recreates the replica node,
and afterwards that the parked `CREATE` fails with `Code: 159` on the lock.
On a correct build the test now takes about 3.4 seconds.

Measured on this head:
- fix: 20/20 passed with randomized settings;
- fix minus `getExclusiveDDLGuardForDatabase`: 5/5 failed (the restore
  goes ahead, the probe is never refused, the parked `CREATE` succeeds);
- merge-base plus the two failpoint hunks only: 3/3 failed the same way;
- `test_restore_db_replica/` full module: 14 passed.

`no-parallel` is required because the failpoint pauses the first replicated
DDL entry that any query on the server executes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove `test_restore_db_replica_waits_for_database_sync` from the
integration module: it parked the DDL worker at a failpoint and watched
for the absence of a trace line during a fixed eight-second window, on
top of a five-second distributed DDL timeout.

`05442_restore_database_replica_waits_for_in_flight_ddl` now covers the
same guard causally. Once the no-op `DROP TABLE IF EXISTS` probe is
refused, the restore holds the database-wide `DDLGuard` and waits for
the exclusive database lock, so a `SYSTEM SYNC DATABASE REPLICA` started
then must wait for the restore and return after it. Without
`getDDLGuard(database_name, "")` in `restoreDatabaseReplica` the sync
runs at once and fails with `KEEPER_EXCEPTION` reading the `log_ptr` of
the replica that the restore has not recreated yet. The sync is released
only after it is seen in `system.processes`, and the restore cannot
finish earlier than one second after the failpoint is released, because
the parked entry first has to give up on the database lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(${CLICKHOUSE_CLIENT} --query_id="${SYNC_ID}" -q "SYSTEM SYNC DATABASE REPLICA ${DB}" > "${OUT}.sync" 2>&1; echo $? > "${OUT}.sync_rc") &
started=0
for _ in {1..300}; do
if [ -s "${OUT}.sync_rc" ] || [ "$(${CLICKHOUSE_CLIENT} -q "SELECT count() FROM system.processes WHERE query_id = '${SYNC_ID}'")" = "1" ]; then

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.

[P2] Establish the sync's lock attempt before releasing the DDL

Visibility in system.processes does not establish that syncReplicatedDatabase has attempted its database guard: executeQueryImpl inserts the query before constructing or executing the interpreter. With only the database-level getDDLGuard removed from the restore, the sync can register and then be descheduled, this loop releases the paused DDL, the restore recreates the replica, and the sync resumes against the restored Keeper nodes and succeeds. Every assertion then passes despite the missing guard, so this replacement for the independent sync regression remains dependent on scheduling.

Please use a server-side rendezvous that establishes the sync's guard attempt while the replica is still absent, and verify that the guard-removed control also fails when the sync is delayed after process-list registration.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3db3a0e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 3/6) / long_primary_key #1, long_primary_key #2 not from this PR (it changes only how SYSTEM RESTORE DATABASE REPLICA waits for in-flight replicated DDL): client time 0.31 s to 0.44-0.46 s, scored as a confirmed regression. The same queries were flagged slower on 15 of the 18 PRs that ran this shard between 06:03Z and 06:58Z today, while the master run in that window was not a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-083003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 3/6) long_primary_key red: #127365

This branch has not been deployed

No deployments
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-review-human PR origin: human review feedback on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants