Skip to content

Cherry pick #128824 to 26.3: Fix use-after-free of the Replicated database DDL worker - #129722

Merged
robot-ch-test-poll4 merged 9 commits into
backport/26.3/128824from
cherrypick/26.3/128824
Nov 7, 2026
Merged

robot-ch-test-poll4 merged 9 commits into
backport/26.3/128824from
cherrypick/26.3/128824

Conversation

@robot-ch-test-poll3

Copy link
Copy Markdown
Contributor

Original pull-request #128824

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 8 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]>
… 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]>
…race

Fix use-after-free of the Replicated database DDL worker
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-critical-bugfix labels Nov 6, 2026
Resolve conflicts against 26.3:
- `FailPoint.cpp`: add only `database_replicated_pause_before_initial_query_execution`; the other
  failpoints from master's context are not used in 26.3.
- `DatabaseReplicated.cpp`: keep the 26.3 structure of `waitForReplicaToProcessAllEntries` (STRICT mode)
  and `tryEnqueueAndExecuteEntry(entry, context, flags.internal)`, but use the local `worker` reference,
  and return early when the worker is stopped. Keep `assert` (26.3) with the new `isDDLWorkerCurrentlyActive`.
- `restoreDatabaseInKeeper`: 26.3 lacks #118481
  (stop the DDL worker before `SYSTEM RESTORE DATABASE REPLICA` re-initialises the replica), which
  this fix builds on. Include it inline (stop the worker before restore, `SCOPE_EXIT_SAFE` reinitialize
  on failure, `need_reinitialize_ddl_worker = false` on success).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Resolved the conflicts by merging backport/26.3/128824. 26.3 does not have #118481, which stops the DDL worker before SYSTEM RESTORE DATABASE REPLICA and which this fix builds on, so that small change is included inline in restoreDatabaseInKeeper. STRICT-mode waitForReplicaToProcessAllEntries keeps its 26.3 structure: it now uses the held worker reference and returns when the worker is stopped. tryEnqueueAndExecuteEntry keeps its 26.3 signature. A syntax-only compile of the affected files on the merged tree passes.

@robot-ch-test-poll4
robot-ch-test-poll4 merged commit 4a49f29 into backport/26.3/128824 Nov 7, 2026
2 checks passed
@robot-ch-test-poll4
robot-ch-test-poll4 deleted the cherrypick/26.3/128824 branch November 7, 2026 21:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! pr-critical-bugfix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants