Repository navigation
Conversation
…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]>
Internal second-model review: adjudication log (click to expand)Reviewed cold against the resulting code before reading the implementation's own evidence, then
Not covered, and disclosed rather than claimed: the backup-restore waiter reaches Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260831-180800 |
|
Workflow [PR], commit [c46bb15] Summary: ✅
AI ReviewSummaryThe PR serializes Findings
Tests
Final VerdictStatus: |
Pre-PR validation gate
Style: |
|
cc @tuanpach @evillique, could you review this? |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger -
|
| 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
…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.
|
Merged master to clear the conflict. The only conflict was #118481 landed in the meantime and does not subsume this one: Re-measured on this head:
I also corrected the description, which still described the digest oracle, attributed the Session id: cron:clickhouse-maint-slot-19:20260915-120900 |
CI finish ledger - 1b00221Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 176 checks, 151 pass, 22 skipped, 2 failed,
Session id: cron:our-pr-ci-monitor:20260915-190256 |
|
The use-after-free Finding A predicted has now crashed a server in CI, so it is no longer only a
The window is 14 ms wide in the server log: Thread 150 is a refreshable MV refresh creating its temporary target table. It then sat in Keeper for That "Stopping DDL worker" line is the block #118481 added to One more observation from the same |
|
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. |
|
The second segfault I could not explain in my earlier comment, in
Same window: a refreshable MV refresh proposes From the core: The worker's 32-byte This is the fifth server crash from this window in |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e-replica-inflight-ddl
`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 |
There was a problem hiding this comment.
[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.
CI finish ledger - 3db3a0eEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261022-083003 |
|
Fixing PR for the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a use-after-free when
SYSTEM RESTORE DATABASE REPLICAreplaces the DDL worker of aReplicateddatabase while another session is still executing a replicated DDL query through it. In debug and sanitizer builds the same window also produces aDigest does not matchlogical error.Description
Related: #114819
Related: #117235 (comment)
Reported there by @ zlareb1.
Root cause.
tryEnqueueReplicatedDDLreadsddl_workerunderddl_worker_mutex, releases the lock, then executes the entry through the raw pointer.tryEnqueueAndExecuteEntryrunsprocessTaskon the calling client thread, andDDLWorker::shutdownjoins only the worker's own threads.SYSTEM RESTORE DATABASE REPLICAis 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 ofrestoreDatabaseInKeeper, before its first Keeper write, and again inreinitializeDDLWorker.Fix. Take the two guards
DROP DATABASEandCREATE DATABASEalready take, in their order, across the restore. A table-levelDDLGuardholds the same database mutex shared for its whole lifetime, and everytryEnqueueReplicatedDDLcall site runs on a thread that holds one, so the restore cannot overlap an executing entry.ddl_workeralso becomes ashared_ptr, with a local strong reference at both client-thread call sites, becausecreateTableRestoredFromBackupwaits on the worker from aRestorerFromBackupthread holding no DDL guard.SYSTEM SYNC DATABASE REPLICAand 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_EXCEEDEDon the database lock instead of racing;DROP DATABASEalready does this on master (measured). It also serializes againstSYSTEM SYNC DATABASE REPLICA, which takes the same guard.Two reported items I deliberately do not change, reasoning in the thread: the
DatabaseReplicated::shutdownhalf is not reachable (every live-server caller already holds that exclusive guard, and shutdown force-exits viasafeExitwhile any connection remains), and the three digest assertions missing the!ddl_worker ||guard need none (not evaluated outsideDEBUG_OR_SANITIZER_BUILD, no remaining unsynchronized read can observe a reset after this fix, and locking them deadlocks againststopReplication).Validation and notes
One new stateless test,
05442_restore_database_replica_waits_for_in_flight_ddl. It parks a replicatedCREATE TABLEat a new failpoint and deletes the replica's Keeper node. Until the restore is seen waiting for the exclusive database lock (a no-opDROP TABLE IF EXISTSon the database is refused withCode: 159), it must neither complete nor recreate the node, and once released the entry must fail withCode: 159. ASYSTEM SYNC DATABASE REPLICAstarted while the restore waits isolates the database-level guard: it must wait for the restore and succeed.getExclusiveDDLGuardForDatabasegetDDLGuard(db, "")KEEPER_EXCEPTIONon the missinglog_ptrDDLWorker::processTasktest_replicated_database/full: identical to unmodified master.initializeReplicationcallscheckDigestValidunconditionally, so one unsynchronizedddl_workerread is not debug-only; it runs on the worker's own main thread, which both reset sites join before assigningnullptr. The other five arechassertonly.Every strong reference is taken through a
DatabasePtrits caller holds, so it never outlives the database;~DDLWorkerjoins 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]