Repository navigation
Fix use-after-free of the Replicated database DDL worker - #128824
Conversation
`DatabaseReplicated::tryEnqueueReplicatedDDL` checked `ddl_worker` under `ddl_worker_mutex`, but then called `ddl_worker->tryEnqueueAndExecuteEntry` without the lock. A concurrent `SYSTEM RESTORE DATABASE REPLICA`, `DROP DATABASE` or `reinitializeDDLWorker` could stop and destroy the worker while the query was waiting in it, and the query then read the destroyed worker's context (segmentation fault in `DDLTaskBase::parseQueryFromEntry`). `waitForReplicaToProcessAllEntries` had the same problem. Make `ddl_worker` a `shared_ptr`, and let query threads take their own reference under the lock. A stopped worker makes the waiting query throw `DATABASE_REPLICATION_FAILED`. Also take the worker's `mutex` before notifying waiters in `DatabaseReplicatedDDLWorker::shutdown`, so that a waiter cannot miss the stop. Found by `La Casa Del Dolor (amd_debug)`, STID 2923-5201: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7f4d0d6a57530682fa5ad1f105191c04529c1239&name_0=MasterCI&name_1=La%20Casa%20Del%20Dolor%20%28amd_debug%29 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [90fa0dc] Summary: ✅
AI ReviewSummaryThe change retains the Missing context / blind spots
Final VerdictStatus: ✅ Approve. No further code changes requested; current-head CI remains pending. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (+30.16 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units31 translation units recompiled, 247 s compile time in total, 31 of them have a recent master baseline. |
… sync wait on shutdown The callbacks of DDL queries (`commitCreateTable`, `dropTable`, `commitAlterTable`, `detachTablePermanently`, `removeDetachedPermanentlyFlag`, `checkDigestValid`) read the `ddl_worker` member directly. An initial query executes them on its own thread after `tryEnqueueAndExecuteEntry`, so a concurrent `SYSTEM RESTORE DATABASE REPLICA` could reset the member to `nullptr` in the meantime (UBSan: member call on null pointer in `removeDetachedPermanentlyFlag`). They cannot take `ddl_worker_mutex`, because it is held while the worker's threads, which also run these callbacks, are joined. Add a separate `ddl_worker_ptr_mutex` that guards only the pointer assignment and is never held during shutdown, and read the pointer under it in `isDDLWorkerCurrentlyActive`. `DatabaseReplicatedDDLWorker::waitForReplicaToProcessAllEntries` now returns false when the worker is stopped, and `shutdown` sets the events of waiters in the second phase (waiting for `log_ptr` in Keeper), so `SYSTEM SYNC DATABASE REPLICA` does not wait for the whole timeout on a stopped worker. The `STRICT` loop stops on a stopped worker instead of spinning. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128824&sha=c5805fd790df36d7fea61bd0c6653a6f0c312560&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 PR: #128824 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tabase Two concurrent restores both run `initDatabaseReplica`, which writes `max_log_ptr_at_creation` (TSan data race in the flaky check of the new test, which runs two restore threads), and they stop and re-create the DDL worker under each other. Take a dedicated mutex in `restoreDatabaseInKeeper`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128824&sha=c5805fd790df36d7fea61bd0c6653a6f0c312560&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29 PR: #128824 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the replica An initial DDL query that `DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry` has admitted executes and commits on the submitting thread, and `shutdown` joins only the worker's own threads. `SYSTEM RESTORE DATABASE REPLICA` now waits for such queries of the old worker (`waitForForegroundTasks`) before it rewrites the replication state and starts the new worker. Otherwise the query could commit its metadata while the recovery of the new worker compares the Keeper snapshot with the local tables, and the recovery would move the just created table to `<db>_broken_replicated_tables`. Add the `database_replicated_pause_before_initial_query_execution` failpoint and a test that holds an initial `CREATE TABLE` while the restore runs. Addresses the review comment in #128824 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test creates `d1_<db>` and `d2_<db>` `Replicated` databases outside of the test database and never dropped them. In the targeted stateless tests of the merge queue, the leftovers made `05061_system_drop_database_replica_access` fail: `SYSTEM DROP DATABASE REPLICA` was denied because the user had no privilege on these unrelated `Replicated` databases. Wait for the `ASYNC` backups of the test to finish and drop the databases. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=gh-readonly-queue/master/pr-128824-6a59c73762ac8f364be1f5d1af3220bef0c37df1&sha=7934b5112596e4462ce6df045d58d9c59a0a68db&name_0=MergeQueueCI&name_1=Stateless%20tests%20%28amd_binary%2C%20targeted%29 PR: #128824 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s still active `SYSTEM RESTORE DATABASE REPLICA` stopped the DDL worker and then waited for the initial queries that the worker had admitted. But an admitted `ALTER` of a `ReplicatedMergeTree` table with `alter_sync` waits until the table executes its `ALTER_METADATA` entry, and the table postpones the entry while `canExecuteReplicatedMetadataAlter` is false, which is the case once the worker is stopped. The restore and the `ALTER` waited for each other. Now the restore first makes the worker reject new initial queries (`stopInitialQueries`), waits for the admitted ones while the worker keeps running, and only then stops it. Test `05546_replicated_database_restore_replica_waits_for_initial_alter` holds an initial `ALTER` with the `database_replicated_pause_before_initial_query_execution` failpoint while the restore starts. Addresses the review comment: #128824 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #128824 to 26.10: Fix use-after-free of the Replicated database DDL worker
Cherry pick #128824 to 26.9: Fix use-after-free of the Replicated database DDL worker
Cherry pick #128824 to 26.3: Fix use-after-free of the Replicated database DDL worker
Cherry pick #128824 to 26.8: Fix use-after-free of the Replicated database DDL worker
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]>
Backport #128824 to 26.9: Fix use-after-free of the Replicated database DDL worker
Backport #128824 to 26.8: Fix use-after-free of the Replicated database DDL worker
Backport #128824 to 26.3: Fix use-after-free of the Replicated database DDL worker
Resolve the conflict with ClickHouse#128824 in DatabaseReplicatedDDLWorker::shutdown: its wake-up of the log_ptr waiters moves into the SCOPE_EXIT together with the holder release, so it also runs when the active node removal throws. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-replicated Conflicts: - src/Databases/DatabaseReplicated.cpp: tryEnqueueReplicatedDDL now calls tryEnqueueAndExecuteEntry through the local `worker` reference that ClickHouse#128824 introduced, after the idempotency key failpoint. - src/Databases/DatabaseReplicatedWorker.cpp: FailPoints extern list. Co-Authored-By: Claude Opus 5.5 <[email protected]>
DatabaseReplicated::tryEnqueueReplicatedDDLcheckedddl_workerunderddl_worker_mutex, but then calledddl_worker->tryEnqueueAndExecuteEntrywithout the lock. A concurrentSYSTEM RESTORE DATABASE REPLICA,DROP DATABASEorreinitializeDDLWorkercould stop and destroy the worker while the query was waiting in it, and the query then read the destroyed worker's context.La Casa Del Dolorhit this with a refreshable materialized view in aReplicateddatabase (the refresh creates its temporary table throughtryEnqueueReplicatedDDL) while the fuzzer ranSYSTEM RESTORE DATABASE REPLICAon the same database: segmentation fault inDDLTaskBase::parseQueryFromEntry, STID 2923-5201.waitForReplicaToProcessAllEntries(SYSTEM SYNC DATABASE REPLICA) had the same problem.ddl_workeris now ashared_ptr, and query threads take their own reference under the lock (tryGetDDLWorker). A worker stopped while a query waits in it makes the query throwDATABASE_REPLICATION_FAILED("replication stopped, try again"), as before for a stopped worker. Also,DatabaseReplicatedDDLWorker::shutdowntakes the worker'smutexbefore notifying waiters, so that a waiter that has just checkedstop_flagcannot miss the notification and wait for the wholedatabase_replicated_initial_query_timeout_sec.SYSTEM RESTORE DATABASE REPLICAis serialized per database and, after stopping the old worker, waits for the initial queries that the old worker had already admitted (they execute and commit on the submitting threads). Otherwise such a query could commit while the recovery of the new worker compares the Keeper snapshot with the local tables, and the just created table would be moved to<db>_broken_replicated_tables. Test05484_replicated_database_restore_replica_waits_for_initial_queryholds an initialCREATE TABLEwith the newdatabase_replicated_pause_before_initial_query_executionfailpoint to check this.The new test runs DDL and
SYSTEM SYNC DATABASE REPLICAconcurrently withSYSTEM RESTORE DATABASE REPLICAfor 10 seconds. Without the fix the server crashes inDDLTaskBase::parseQueryFromEntry(checked locally); with the fix it passes, and 178 DDL queries got "replication stopped, try again" instead.CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7f4d0d6a57530682fa5ad1f105191c04529c1239&name_0=MasterCI&name_1=La%20Casa%20Del%20Dolor%20%28amd_debug%29
Related: #128774
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a crash of DDL queries in a
Replicateddatabase (including refreshes of refreshable materialized views) that run concurrently withSYSTEM RESTORE DATABASE REPLICAorDROP DATABASE.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/128824]
Version info
26.11.1.1515-master(included in26.11and later)