Skip to content

Fix use-after-free of the Replicated database DDL worker - #128824

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-replicated-ddl-worker-race
Nov 6, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-replicated-ddl-worker-race

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

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. La Casa Del Dolor hit this with a refreshable materialized view in a Replicated database (the refresh creates its temporary table through tryEnqueueReplicatedDDL) while the fuzzer ran SYSTEM RESTORE DATABASE REPLICA on the same database: segmentation fault in DDLTaskBase::parseQueryFromEntry, STID 2923-5201. waitForReplicaToProcessAllEntries (SYSTEM SYNC DATABASE REPLICA) had the same problem.

ddl_worker is now a shared_ptr, and query threads take their own reference under the lock (tryGetDDLWorker). A worker stopped while a query waits in it makes the query throw DATABASE_REPLICATION_FAILED ("replication stopped, try again"), as before for a stopped worker. Also, DatabaseReplicatedDDLWorker::shutdown takes the worker's mutex before notifying waiters, so that a waiter that has just checked stop_flag cannot miss the notification and wait for the whole database_replicated_initial_query_timeout_sec.

SYSTEM RESTORE DATABASE REPLICA is 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. Test 05484_replicated_database_restore_replica_waits_for_initial_query holds an initial CREATE TABLE with the new database_replicated_pause_before_initial_query_execution failpoint to check this.

The new test runs DDL and SYSTEM SYNC DATABASE REPLICA concurrently with SYSTEM RESTORE DATABASE REPLICA for 10 seconds. Without the fix the server crashes in DDLTaskBase::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):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix a crash of DDL queries in a Replicated database (including refreshes of refreshable materialized views) that run concurrently with SYSTEM RESTORE DATABASE REPLICA or DROP DATABASE.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1515-master (included in 26.11 and later)

alexey-milovidov and others added 2 commits November 2, 2026 22:44
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [90fa0dc]

Summary: ✅


AI Review

Summary

The change retains the Replicated database DDL worker while queries use it, interrupts sync waits on shutdown, and drains admitted initial queries before restoring replication state. Commit 90fa0dc102c addresses the remaining ALTER deadlock by keeping the worker active during the drain, with a focused regression test. All four earlier findings are addressed in the current code; no new findings remain.

Missing context / blind spots
  • ⚠️ Current-head sanitizer/flaky CI checks are pending. No local ClickHouse binary was available for an independent test run; the author reports five successful local runs of the new ALTER regression. Completed CI for 90fa0dc102c would provide independent runtime validation.
Final Verdict

Status: ✅ Approve. No further code changes requested; current-head CI remains pending.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Nov 3, 2026
Comment thread src/Databases/DatabaseReplicated.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Nov 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 90fa0dc10 with master c8c741126 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

8 object files changed (+30.16 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseReplicatedWorker.cpp.o 418.44 KiB 438.38 KiB +19.95 KiB (+4.77%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 2 commits November 4, 2026 00:24
… 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]>
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
…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]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Nov 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 5, 2026
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]>
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
…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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
Merged via the queue into master with commit 1d7799a Nov 6, 2026
186 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-replicated-ddl-worker-race branch November 6, 2026 12:57
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 6, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 6, 2026
Backport #128824 to 26.10: Fix use-after-free of the Replicated database DDL worker
robot-clickhouse added a commit that referenced this pull request Nov 7, 2026
Cherry pick #128824 to 26.9: Fix use-after-free of the Replicated database DDL worker
robot-clickhouse added a commit that referenced this pull request Nov 7, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Nov 7, 2026
Cherry pick #128824 to 26.3: Fix use-after-free of the Replicated database DDL worker
robot-clickhouse added a commit that referenced this pull request Nov 7, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Nov 7, 2026
Cherry pick #128824 to 26.8: Fix use-after-free of the Replicated database DDL worker
alexey-milovidov added a commit that referenced this pull request Nov 7, 2026
Resolve conflicts in `src/Databases/DatabaseReplicated.cpp`:
- `tryEnqueueReplicatedDDL`: use the worker reference from `tryGetDDLWorker`
  with the 26.8 signature of `tryEnqueueAndExecuteEntry` (`flags.internal`).
- `restoreDatabaseInKeeper`: 26.8 does not have
  #118481 (stop the DDL worker
  before `SYSTEM RESTORE DATABASE REPLICA` re-initialises the replica), on top
  of which #128824 waits for admitted initial queries. Keep the master version of
  this block, which brings in that small prerequisite: stop the worker before
  the restore, reinitialize it in `SCOPE_EXIT_SAFE` on failure, and set
  `need_reinitialize_ddl_worker = false` before the final `reinitializeDDLWorker`.
  Add the `Common/scope_guard_safe.h` include it needs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse added a commit that referenced this pull request Nov 7, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #128824 to 26.9: Fix use-after-free of the Replicated database DDL worker
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #128824 to 26.8: Fix use-after-free of the Replicated database DDL worker
alexey-milovidov added a commit that referenced this pull request Nov 7, 2026
Backport #128824 to 26.3: Fix use-after-free of the Replicated database DDL worker
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 8, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 8, 2026
…-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]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants