Repository navigation
Conversation
…etaches its tables `DETACH DATABASE` on a `Replicated` database detaches the tables one by one. In that fan-out `shouldReplicateQuery` is consulted with the still database-level AST, whose `drop->table` is null, so it returns false and the per-table detach takes the non-replicated branch into `DatabaseAtomic::detachTable`. `DatabaseReplicated` does not override that, and the base implementation erases the table from the in-memory map without any `tables_metadata_digest` arithmetic. `DROP DATABASE` fans out drops instead, and those reach the overriding `DatabaseReplicated::dropTable`, which does maintain the counter. So `DROP DATABASE` is affected only on a read-only disk, where the per-table kind is forced to `DETACH`. A replicated DDL entry that is already executing on the initiator thread still holds its `ZooKeeperMetadataTransaction`, so the "database is probably being dropped" exemption in `DatabaseReplicated::checkDigestValid` does not cover it: that exemption requires `!txn` as well as an inactive DDL worker. The entry then reaches `commitCreateTable`, assigns the new counter and asserts, recomputing the digest over a map several tables short. The result is `LOGICAL_ERROR: Digest does not match`, which aborts the server in debug and sanitizer builds. `DatabaseReplicated::checkQueryValid` already refuses `DETACH TABLE` on a `Replicated` database for exactly this reason, but it only runs on the replicated-DDL enqueue path that this fan-out never takes. The fix takes and releases the database-wide exclusive DDL guard as a drain, after `stopReplication()` and before the fan-out. Every table-level `DDLGuard` holds the same mutex shared for the duration of its DDL, so acquiring it exclusively waits for the in-flight entry to finish. It sits in the branch both kinds reach, so it covers the read-only-disk `DROP DATABASE` case as well. Both edges of that placement are load-bearing: - Acquiring it before `stopReplication()` can stall for up to `database_replicated_initial_query_timeout_sec` (default 300). A queued enqueuer calls `guard->releaseTableLock()`, which keeps the database read lock, and then waits in `DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry`; that wait is broken early only by the stop flag `stopReplication()` sets. So the exclusive acquisition would block behind the very waiter that `stopReplication()` releases. - Holding it across the fan-out breaks the operation outright. A table-level `DDLGuard` does not block on that mutex, it `try_lock_shared`s it ten times at 100 ms and then throws `TIMEOUT_EXCEEDED`, so every per-table detach would fail after a second. The drain is not a new unbounded wait. This function already acquires the same mutex exclusively, unconditionally, about 300 lines below, so the drain relocates a wait that was always there. It can only slow a `DETACH` that previously threw or aborted the server before reaching that point, never one that previously succeeded. Overriding `DatabaseReplicated::detachTable` to maintain the counter, which looks like the fix at the owning layer, is wrong. `SYSTEM RESTART REPLICA` detaches through `detachTable` and relies on the digest not changing: it raises `tables_being_restarted` so the check early-returns, re-attaches on success through the equally un-overridden `attachTable`, and compensates only on the failure path via `adjustDigestOnTableLostFromRestart`. A decrement in `detachTable` would leave the counter permanently low on success and double-decrement on failure, and three more callers in `DatabaseOnDisk` already account for the base detach inside operations whose overrides do the arithmetic themselves. All 19 occurrences of this signature in the CI database over 60 days are on `Stress test (*)`, spread over 7 detecting call sites and 19 unrelated pull requests, with none on master in 120 days. `ci/jobs/scripts/stress/stress.py` detaches every database in parallel at teardown without waiting for in-flight DDL, and no other job does that. The regression test needs one new `PAUSEABLE_ONCE` failpoint. No existing pause point can park an entry between the moment it holds its transaction and the digest commit: `database_replicated_stop_entry_execution` lives in the background worker's `initAndCheckTask`, which notifies the initiator before it pauses and which `stopReplication()` would then join and deadlock on; `atomic_populate_pause_before_source_guard` is unreachable once a metadata transaction is set, by an explicit check in `shouldPopulateMaterializedViewAtomically`; and `create_or_replace_before_rename` sits after the temporary table's own commit, where the resumed rename cannot reach the digest arithmetic. Related: ClickHouse#114819 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (click to expand)An independent cold review plus a second model reviewed this change before it was pushed. Findings and
The second model raised no findings on the change itself. Two PR-facing calls, and why, so they are cheap to overrule. Changelog category is
Also checked and left alone. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260830-232100 |
|
Workflow [PR], commit [2d49cf0] Summary: ❌
AI ReviewSummaryThis PR correctly drains client-thread replicated DDL before the Findings❌ Blockers
Final VerdictDo not merge as-is: the LLVM Coverage ReportMeasured on commit 2d49cf0.
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
|
cc @tavplubix @alesapin, could you review this? |
|
The drain closes the One sibling of the same shape stays uncovered: server shutdown. A related detail on the same path: the Both are debug/sanitizer-only manifestations with no data at stake, so they may be fine to leave for a follow-up, but they fall under the same #114819 signature this PR addresses. |
|
Thanks for checking the drain itself; I agree with all three of your reasons. Both findings are confirmed. I am fixing both in a follow-up pull request and will link it here. Finding A is real, and it reaches further than debug builds. I kept it out of this pull request because the drain here only relocates an existing wait: Finding B is confirmed for exactly those three sites. One correction: the siblings that carry I wrote that guard and then dropped it rather than pushing it. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 26 s compile time in total, 9 of them have a recent master baseline. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) |
the job's containers breach the /docker cgroup budget and the kernel kills processes inside it, so the shard errors at job level |
#117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 3290a679261ad82c86e64cb3bfdf6759ad3b0b76 |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
same signature | #117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 3290a679261ad82c86e64cb3bfdf6759ad3b0b76 |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / Container memory budget exceeded (/docker) |
same signature; it fired in one of the two concurrent PR runs at this head, and a real CI row owes an owner whichever run produced it |
#117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 3290a679261ad82c86e64cb3bfdf6759ad3b0b76 |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_s3_plain_rewritable/test.py::test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] |
Code: 210. DB::NetException: Connection refused at OPTIMIZE TABLE test FINAL (test.py:138): a server in the module was the kernel's chosen victim of the same cgroup breach, so the node died mid-test |
#117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 3290a679261ad82c86e64cb3bfdf6759ad3b0b76 |
All four failures are one condition, and none of them can be caused by this PR: its diff is
src/Common/FailPoint.cpp, src/Databases/DatabaseReplicated.cpp,
src/Interpreters/InterpreterDropQuery.cpp and tests/integration/test_replicated_database/test.py,
which cannot change how much memory an unrelated integration module's containers use.
The two signatures share one owner rather than two. Container memory budget exceeded (/docker) is
the breach itself, and the test_s3_plain_rewritable node death is what that breach looks like when
the kernel happens to pick a live server instead of a gdb process, which is why the budget row is
the higher-sensitivity signal of the pair. #117202 serializes the shutdown gdb attach that produced
the fan-out, so it addresses both.
This head predates that fix: 7fc3004ed25a2dc8aa66428f4f010244dea3046a is not an ancestor of
75296248ed89, so I merged master in at 3bfee6a80b1078391ca7e18d51eed444d1e5c996 to pick it up and
CI is re-running. The merge is a pure master merge: it adds no commit of my own, the resulting tree is
byte-identical to the tree I merged locally, its first parent is the pre-merge head, and no
contrib/ submodule pin moved.
CH Inc sync was success at this head, so nothing here is exempt.
Session id: cron:our-pr-ci-monitor:20260831-153000
| /// An executing replicated DDL entry holds a ZooKeeperMetadataTransaction, so its digest assertion is | ||
| /// not covered by the drop-time exemption in DatabaseReplicated::checkDigestValid. Let it finish before | ||
| /// the detach below empties the table map. The detach only try-locks this mutex, so do not hold it there. | ||
| auto in_flight_ddl_drain = DatabaseCatalog::instance().getExclusiveDDLGuardForDatabase(database_name); |
There was a problem hiding this comment.
This only drains in-flight DDL before the DETACH DATABASE fan-out. The same invariant is still open in DatabaseReplicated::shutdown() and reinitializeDDLWorker(): both reset ddl_worker without an equivalent drain, while tryEnqueueReplicatedDDL() releases ddl_worker_mutex before calling ddl_worker->tryEnqueueAndExecuteEntry().
That means an initial-query replicated DDL already executing on the client thread can still outlive the worker object (release-build use-after-free), and shutdown() then reaches DatabaseWithOwnTablesBase::shutdown() and clears tables with a live ZooKeeperMetadataTransaction, reproducing the same digest-mismatch assertion on the shutdown path. This patch fixes the DETACH DATABASE interleaving, but it still leaves the shutdown / restoreDatabaseInKeeper interleavings open. Those reset paths need the same kind of barrier before ddl_worker = nullptr / table-map clear, or another explicit join of client-thread replicated DDL executions.
There was a problem hiding this comment.
Half of this is confirmed and half does not hold. Line numbers are at the current head.
reinitializeDDLWorker is real. It destroys the worker at DatabaseReplicated.cpp:1117-1133, reached from restoreDatabaseInKeeper at :2399 on a live server, while tryEnqueueReplicatedDDL holds ddl_worker_mutex only long enough to read getCommonHostID (:1470-1473) and then calls ddl_worker->tryEnqueueAndExecuteEntry at :1489 without it. So a client-thread execution can outlive the worker object, in any build type. That path does not clear the table map, so the consequence there is the use-after-free alone, not the digest assertion. It is being fixed in a separate pull request and I will link that pull request here.
shutdown() is not reachable with an entry in flight, which also corrects my earlier comment on this pull request:
- Server shutdown exits before it gets there.
Server.cpp:3977-3989callssafeExitwhencurrent_connectionsis non-zero after the bounded wait, andsafeExitends in_exit(base/base/safeExit.cpp:37), which skips static destructors. A client thread insidetryEnqueueAndExecuteEntrystill holds its connection open, so that branch is taken, and it is an inner scope exit that runs before the outer one holdingglobal_context->shutdown()at:1843.DatabaseCatalogis never reached. DETACH DATABASEandDROP DATABASEalready take the exclusive database guard unconditionally atInterpreterDropQuery.cpp:814, beforedetachDatabaseat:821. That is the same guard this patch takes at:500.
I kept the remaining reset site out of this pull request because the drain here only relocates a wait that path already takes, while a barrier on a reset path is a new wait during a reset and needs its own design and its own regression test.
|
@zlareb1 the follow-up is #117399, and it does not ship what I told you it would. Two corrections. The The three digest assertions are declined. There are six unsynchronized The one read on your list that a caller can reach holding no catalog guard is What #117399 does fix is the second reset site, |
CI finish ledger - 3290a67Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
None of the rows above is caused by this pull request. On the On the Session id: |
Still firing after publication: three more occurrences, measuredI traced the three
In each one the fan-out is a On 2026-09-02 the counter is accounted for to the bit, which I think is worth having explicitly. The 10157897244389790054 is the reported in-memory digest, and 4585224049691586466 is both the reported The blocking durations in the table are also the measured answer to how long this drain can hold |
Conflict in src/Common/FailPoint.cpp: master appended intersect_or_except_transform_pause and intersect_or_except_transform_counts_pause to the end of APPLY_FOR_FAILPOINTS while this branch appended database_replicated_pause_before_commit_create_table there. Kept all three, with this branch's entry last and master's two carrying the line-continuation backslash they need in the middle of the list.
CI finish ledger - e433c95Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
It is the only red on this head: Session id: cron:our-pr-ci-monitor:20260915-173213 |
|
Second independent confirmation of this window, from
|
…-before-detach-database Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
CI finish ledger - 2d49cf0Every 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-050037 |
|
@groeneai is this PR still needed? |
|
Not for CI any more, as far as I can measure. The stress failure it targets ( The race is still on master: |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Related: #114819
Found on
Stress test (arm_msan)for #101273: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101273&sha=87554fdfaf4167d4d5449321eca60e3e24c8eaa5&name_0=PR&name_1=Stress%20test%20(arm_msan)DETACH DATABASEon aReplicateddatabase detaches tables one by one. There,shouldReplicateQuerysees a database-level AST with a nulldrop->table, so each detach reachesDatabaseAtomic::detachTable, whichDatabaseReplicateddoes not override and which leavestables_metadata_digestuntouched. An already-executing replicated DDL entry still holds itsZooKeeperMetadataTransaction, socheckDigestValid's "database is probably being dropped" exemptiondoes not cover it, and its digest assertion compares the full counter against the half-emptied map:
LOGICAL_ERRORDigest does not match, which aborts the server in debug and sanitizer builds.checkQueryValidalready refusesDETACH TABLEhere, but only on the enqueue path this fan-out nevertakes.
DROP DATABASEfans out drops, which do reach the overridingDatabaseReplicated::dropTable, soit is affected only on a read-only disk, which forces the per-table kind to
DETACH.Fix: after
stopReplication()and before the fan-out, take and release the database-wide exclusive DDLguard as a drain, covering both kinds. Both edges of that placement are load-bearing. It is no new
unbounded wait: this function already acquires that mutex exclusively 300 lines below.
All 19 CIDB occurrences in 60 days are on
Stress test (*), from 7 assertion sites, 0 on master in120 days:
ci/jobs/scripts/stress/stress.py:865detaches every database in parallel at teardown,without waiting for in-flight DDL.
Validation: a new integration test, red without the fix, 50/50 green with it;
test_replicated_database46/46;test_postgresql_replica_database_engine86/86 (the only other enginewith a replication thread).
DETACH DATABASEis unchanged when idle, +0.11s with 6 concurrent DDLstreams. It needs one new
PAUSEABLE_ONCEfailpoint; no existing pause point parks an entry betweenits transaction and the digest commit.
Also noticed, not fixed here:
assertCanBeDetachedruns after the fan-out, so a concurrent reader canmake
DETACH DATABASEthrowDATABASE_NOT_EMPTYwith its table map already empty.The interleaving, from the failing run's own server log
Two threads, two query ids, 0.63 s. The aborting query, from
fatal.log, is/* ddl_entry=query-0000000890 */ CREATE TABLE test_2.t_dv UUID '842f90c7-...' (...), and the reportedframe is
DatabaseReplicated.cpp:1303 assertDigestWithProbability <- :2648 commitCreateTable.The counter is high by the sum of the hashes of the tables the fan-out had already removed, which is why
the delta is not any single table's hash.
Workflow [PR]
Sync PR [sync-upstream/pr/117235]