Skip to content

Let an in-flight replicated DDL entry finish before DETACH DATABASE detaches its tables - #117235

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:drain-in-flight-ddl-before-detach-database
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:drain-in-flight-ddl-before-detach-database

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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 DATABASE on a Replicated database detaches tables one by one. There,
shouldReplicateQuery sees a database-level AST with a null drop->table, so each detach reaches
DatabaseAtomic::detachTable, which DatabaseReplicated does not override and which leaves
tables_metadata_digest untouched. An already-executing replicated DDL entry still holds its
ZooKeeperMetadataTransaction, so checkDigestValid's "database is probably being dropped" exemption
does not cover it, and its digest assertion compares the full counter against the half-emptied map:
LOGICAL_ERROR Digest does not match, which aborts the server in debug and sanitizer builds.
checkQueryValid already refuses DETACH TABLE here, but only on the enqueue path this fan-out never
takes. DROP DATABASE fans out drops, which do reach the overriding DatabaseReplicated::dropTable, so
it 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 DDL
guard 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 in
120 days: ci/jobs/scripts/stress/stress.py:865 detaches 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_database 46/46; test_postgresql_replica_database_engine 86/86 (the only other engine
with a replication thread). DETACH DATABASE is unchanged when idle, +0.11s with 6 concurrent DDL
streams. It needs one new PAUSEABLE_ONCE failpoint; no existing pause point parks an entry between
its transaction and the digest commit.

Also noticed, not fixed here: assertCanBeDetached runs after the fan-out, so a concurrent reader can
make DETACH DATABASE throw DATABASE_NOT_EMPTY with its table map already empty.

The interleaving, from the failing run's own server log
08:03:02.765701  [27764] {94b7b544}  DETACH DATABASE test_2                  <- stress.py teardown
08:03:02.992034  [36842] {c4328688}  test_2.t_dv: Loading data parts
                                     ^ replicated entry #890, in flight, holds its transaction
08:03:03.125867  [ 3252] DDLWorker(test_2): Unexpected error ... Code: 341 Replication was stopped.
08:03:03.180690  [33523] {94b7b544}  test_2.`03164_multi_key__fuzz_4`: Start preparing for shutdown
   ... dozens more {94b7b544} per-table detaches ...
08:03:03.396327  [36842] {c4328688}  Current in-memory metadata digest: 175636054655643525
08:03:03.507749  [36842] {c4328688}  Digest of local metadata (10323468412571698593)
                                     is not equal to in-memory digest (175636054655643525)
08:03:03.508884  [36842] {c4328688}  Logical error: 'Digest does not match'.

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 reported
frame 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]

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold review plus a second model reviewed this change before it was pushed. Findings and
what I did with each.

# Finding Verdict Action
❌ 1 The title, the description, the commit message and rows (b) and (f) of the validation gate below all claimed DROP DATABASE also detaches the tables one by one and so reached DatabaseAtomic::detachTable. That is wrong: executeToDatabaseImpl copies the query kind into the per-table query, so DROP DATABASE fans out drops, which reach the overriding DatabaseReplicated::dropTable and do maintain the counter. Only DETACH DATABASE, or DROP DATABASE on a read-only disk where the per-table kind is forced to DETACH, reaches the un-overridden base detach. AGREE All four corrected. The drain still covers both kinds, which is why it sits in the shared branch.
❌ 2 The description did not say that the drain is not a new unbounded wait, even though the same function already acquires that mutex exclusively and unconditionally about 300 lines further down. That is the first question a new exclusive lock on this path invites. AGREE Stated in the description and in the commit message.
⚠️ 3 On a fixed server the regression test always spends the full 30 s failpoint wait, because the DETACH is blocked at the drain and never reaches the post-fan-out pause point. AGREE, no change The window has to be long enough to tell "blocked" from "merely slow". Recorded, not blocking.
⚠️ 4 If the primary assertion fires, the test skips its ATTACH/DROP, leaving the database detached and its Keeper path registered. AGREE, no change Bounded: it is the last test in the module, each CI module run gets a fresh Keeper, and this matches the cleanup shape already used in the file. Recorded, not blocking.
💡 5 The 50/50 repeat ran on the build made before the pre-push comment trim; the final tree is a different build id. AGREE, no change The delta is comments only, and the final build was re-verified on the shell reproducer and the integration test. Recorded so the difference is not read as a validation gap.

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 CI Fix or Improvement, not Bug Fix. assertDigestWithProbability is wrapped
in #if defined(DEBUG_OR_SANITIZER_BUILD), so the LOGICAL_ERROR cannot fire in an official stable
release, and the skew leaves no persisted trace: the value commitCreateTable writes to the Keeper
/digest node is derived from a counter the fan-out never touches, and re-attaching re-seeds the counter
from the map. The measured consequence is therefore CI signal loss, 19 aborted stress runs in 60 days
across 19 unrelated pull requests. Calling it user-visible misbehavior in a stable release would be an
over-claim. If you prefer Bug Fix, note that Bugfix validation would pass: the test's primary oracle
is the emptied table map, which reddens on a release build too.

Related: rather than Closes: on the issue. It was closed once as fixed and reopened for this
recurrence, so I would rather leave the close to you after the stress signal actually stops than claim
it a second time.

Also checked and left alone. SYSTEM RESTART REPLICA is the only other caller that detaches through
the un-overridden detachTable, and it is already covered by its own guard, which is why overriding
DatabaseReplicated::detachTable is the wrong layer for this. The existing debug dump
(AST differs for table ...) is structurally blind to this failure shape, since it compares the tables
that ARE in the map while here the tables are missing from it, so the absence of that dump in the
original report is expected and is not what hid the cause.

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A single node with an embedded Keeper, a Replicated database with 5 tables, database_replicated_force_metadata_digest_check on: park a replicated CREATE TABLE inside commitCreateTable, run DETACH DATABASE, release. 100% reproduction on the unfixed build, 0% (50/50) on the fixed one. Not "~1%".
b Root cause explained? The DETACH DATABASE fan-out reaches the un-overridden DatabaseAtomic::detachTable, which empties the in-memory tables map without touching tables_metadata_digest, while a replicated DDL entry that is already executing still holds its ZooKeeperMetadataTransaction and so is not covered by checkDigestValid's drop-time exemption. Its digest assertion then compares the full counter against the half-emptied map. DROP DATABASE fans out drops, which reach the overriding DatabaseReplicated::dropTable and do maintain the counter, so it is affected only on a read-only disk, where the per-table kind is forced to DETACH.
c Fix matches root cause? Yes. It closes the window (drain the in-flight entry before the map is emptied) rather than suppressing the report. Widening the exemption by dropping its !txn conjunct was rejected: it suppresses instead of preventing, and isCurrentlyActive() is also false during a transient reinitializeDDLWorker, so the exemption would be wider than the case. The assertion's probability, its build gating and its diagnostic are untouched.
d Test intent preserved / new tests added? New integration test test_replicated_database/test.py::test_detach_database_drains_in_flight_ddl. Integration form because the scenario needs a Replicated database plus server-global failpoints and the test waits on a failpoint. No existing test weakened or removed.
e Both directions demonstrated? Yes, same tree, one-line source difference. Without the fix: assert 0 == 5 (the table map was emptied while the CREATE was parked) plus Digest of local metadata (...) is not equal to in-memory digest (...) and Logical error: 'Digest does not match'. With the fix: 5 of 5 tables still attached, both statements succeed, 0 digest errors. The forced digest check executed on both arms, so the fixed arm's zero is not a vacuous zero.
f Fix is general across code paths? The drain sits inside the existing if (!truncate && database->hasReplicationThread()) branch, so it covers both kinds that reach the fan-out: DETACH DATABASE, and DROP DATABASE on a read-only disk, where the per-table kind is forced to DETACH. TRUNCATE DATABASE is excluded by !truncate and separately rejected for Replicated. Only two engines override hasReplicationThread() to true, DatabaseReplicated and DatabaseMaterializedPostgreSQL, and both are covered by the run matrix. Nothing is guarded at the assertion site.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change consumes no user input: no types, no settings values, no boundary values. The only input dimension is which database engine and which drop kind, both enumerated in (f). The digest arithmetic, where type/wrapper generality would matter, is untouched.
h Backward compatible? Yes. No setting, default, persisted format or protocol change, so no SettingsChangesHistory.cpp entry. The digest published to Keeper is unchanged: commitCreateTable derives it from the counter, which the fan-out never modified, so both comparisons in checkDigestValid behave exactly as before. Old and new servers can share a Replicated database.
i Invariants and contracts preserved? Lock ordering: the drain's scope closes before getLockForDropDatabase is taken, so no database_ddl_mutex -> restart_replica_mutex edge is created; the enclosing database-level DDLGuard does not take database_ddl_mutex at all, so this is not a re-entrant exclusive acquisition. Error paths: the drain is a std::unique_lock, released by its destructor on any throw. Scope: it must be released before the fan-out, because a table-level DDLGuard only try-locks the same mutex; the comment states that so a later edit cannot widen it silently. DETACH DATABASE latency is unchanged on an idle database and +0.11s with 6 concurrent DDL streams.

Session id: cron:clickhouse-impl-slot-40:20260830-232100

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2d49cf0]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot check whether the mutation submitted before the upgrade was finished (see mutation_across_upgrade_error.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
and_compare_chain_derived #2 FAIL dashboard

AI Review

Summary

This PR correctly drains client-thread replicated DDL before the DETACH DATABASE fan-out and the new integration test covers that interleaving. The remaining problem is that the same worker-lifetime invariant is still broken on the restore/reinitialize path, so the patch does not yet make replicated DDL teardown safe on a live server.

Findings

❌ Blockers

  • [src/Databases/DatabaseReplicated.cpp:1171-1191, 1523-1543, 2427-2479] tryEnqueueReplicatedDDL still drops ddl_worker_mutex before calling ddl_worker->tryEnqueueAndExecuteEntry, while both restoreDatabaseInKeeper and reinitializeDDLWorker can concurrently run ddl_worker->shutdown() and assign ddl_worker = nullptr. That means SYSTEM RESTORE DATABASE REPLICA can still tear down the worker out from under an initial-query replicated DDL, leaving the client thread to continue through commitCreateTable / commitAlterTable / dropTable with a dangling ddl_worker pointer. This is a release-build use-after-free on a live-server entrypoint, not just a debug-only digest assertion gap. Suggested fix: add the same kind of drain/barrier on the restore/reset path (or otherwise join client-thread replicated DDL before ddl_worker = nullptr), and then keep ddl_worker accesses behind that lifetime guarantee.
Final Verdict

Do not merge as-is: the DETACH DATABASE race is closed, but the restore/reinitialize path still has a live ddl_worker teardown race.

LLVM Coverage Report

Measured on commit 2d49cf0.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @alesapin, could you review this? DETACH DATABASE on a Replicated database fans out per-table detaches that reach the un-overridden DatabaseAtomic::detachTable, so the in-memory table map empties without any tables_metadata_digest arithmetic, and a replicated DDL entry that still holds its ZooKeeperMetadataTransaction then asserts the digest against the half-emptied map. The fix drains that entry with the database-wide exclusive DDL guard, after stopReplication and before the fan-out.

@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The drain closes the DETACH DATABASE path, and I could not find a deadlock or TOCTOU in it: worker-side executions are joined by DDLWorker::shutdown, initiator-side executions already hold the shared database DDLGuard before enqueueing (so any entry that can still commit holds the lock the drain waits on), and a late initiator throws at the stop_flag predicate before a ZooKeeperMetadataTransaction exists.

One sibling of the same shape stays uncovered: server shutdown. DatabaseReplicated::shutdown runs stopReplication, resets ddl_worker, then DatabaseAtomic::shutdown reaches DatabaseWithOwnTablesBase::shutdown, which does tables.clear() with tables_metadata_digest untouched and no drain. An initial-query replicated entry executes on the client's own thread, which no join covers, so an entry that commits after the clear hits the same Digest does not match assertion in a debug or sanitizer build (the exemption in checkDigestValid does not apply while the transaction is alive). The window is narrowed by the shutdown query grace but not closed.

A related detail on the same path: the chassert(!ddl_worker->isCurrentlyActive() || txn) in commitCreateTable, detachTablePermanently and removeDetachedPermanentlyFlag dereferences ddl_worker without the !ddl_worker || guard their siblings in dropTable and renameTable carry, so once shutdown has reset the pointer these three become a null dereference in debug builds instead of a clean assertion.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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. tryEnqueueReplicatedDDL holds ddl_worker_mutex only long enough to read getCommonHostID (DatabaseReplicated.cpp:1469-1474) and releases it before ddl_worker->tryEnqueueAndExecuteEntry at :1489, which runs processTask on the client thread. shutdown then destroys the worker at :2490-2494 while that call can still be inside it, and the grace period is bounded: Server.cpp:3953-3965 cancels queries without joining them, waits shutdown_wait_unfinished, logs "Closed connections. But N remain.", and continues. So the same window is also a use-after-free on the worker object in every build type, not only the digest assertion where chassert is armed. reinitializeDDLWorker (:1119-1133) is a second reset site, reached from restoreDatabaseInKeeper on a live server, so a fix has to cover both.

I kept it out of this pull request because the drain here only relocates an existing wait: InterpreterDropQuery.cpp:814 already takes the same mutex exclusively and unconditionally. Nothing on the shutdown path does, so a drain there is a new wait during shutdown and needs its own design and its own regression test.

Finding B is confirmed for exactly those three sites. One correction: the siblings that carry !ddl_worker || are dropTable and commitAlterTable; renameTable asserts txn instead and has no isCurrentlyActive assertion.

I wrote that guard and then dropped it rather than pushing it. DatabaseReplicated.cpp:585-587 states that every ddl_worker access must hold ddl_worker_mutex, and !ddl_worker || !ddl_worker->isCurrentlyActive() reads the unsynchronized pointer twice, so a reset between the two operands still gives a use-after-free: it narrows the window instead of closing it, and the two existing siblings have the same gap. It is also not testable on its own, since the pause in commitCreateTable is reached after the assertion. Once the drain is in place a reset can no longer overlap an executing entry, and the right form for all five assertions can be settled on evidence then. Both changes go in the follow-up.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2d49cf06b with master f369f7694 (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 75296248ed899f725c9e1e228a649d9a65955baf

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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-3989 calls safeExit when current_connections is non-zero after the bounded wait, and safeExit ends in _exit (base/base/safeExit.cpp:37), which skips static destructors. A client thread inside tryEnqueueAndExecuteEntry still holds its connection open, so that branch is taken, and it is an inner scope exit that runs before the outer one holding global_context->shutdown() at :1843. DatabaseCatalog is never reached.
  • DETACH DATABASE and DROP DATABASE already take the exclusive database guard unconditionally at InterpreterDropQuery.cpp:814, before detachDatabase at :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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@zlareb1 the follow-up is #117399, and it does not ship what I told you it would. Two corrections.

The shutdown half is not reachable, and my evidence for it was wrong. I claimed Server.cpp logs Closed connections. But N remain. and then continues into DatabaseCatalog::shutdownImpl. It does not: when current_connections is still non-zero after waitServersToFinish, Server.cpp:3977-3989 calls safeExit(0, LeakCheck::SkipAndReport), and a client thread inside tryEnqueueAndExecuteEntry necessarily still holds its connection. Every path that resets ddl_worker on a live server goes through DatabaseCatalog::detachDatabase, which InterpreterDropQuery.cpp:807 already reaches holding the exclusive database guard. So there is nothing left to drain there and I added no shutdown drain.

The three digest assertions are declined. There are six unsynchronized ddl_worker reads, not five. Five are inside chassert and are not evaluated outside DEBUG_OR_SANITIZER_BUILD. The sixth, the live if in checkDigestValid, is reached from DatabaseReplicatedDDLWorker::initializeReplication with no #if and throws in every build, but it runs on the worker's own main thread, which ddl_worker->shutdown() joins before either reset site assigns nullptr. Guarding those reads only means something under the mutex, and taking it there deadlocks against stopReplication, which holds ddl_worker_mutex while joining the very threads that reach them.

The one read on your list that a caller can reach holding no catalog guard is commitAlterTable, on the background ALTER_METADATA path. #117399 reorders that assertion's operands so txn short-circuits first, which closes it without a lock.

What #117399 does fix is the second reset site, reinitializeDDLWorker, reached from SYSTEM RESTORE DATABASE REPLICA: it takes the two guards DROP DATABASE and CREATE DATABASE already take. One behaviour change to flag: a replicated DDL query concurrent with a restore now fails with TIMEOUT_EXCEEDED on the database lock instead of racing, which is what DROP DATABASE already does on unmodified master.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3290a67

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases result differs from the reference on the old analyzer lane, and it is trunk-wide rather than specific to this branch: 84 rows over 72 distinct pull requests and 12 true-master commits on 08-31 alone #117364 (external, merged 2026-08-31 22:05Z), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) job-level container-memory abort with no failing test assertion, on a tree that already contains the gdb-attach serialisation; 277 rows over 269 distinct trees and 25 true-master commits on 08-31 #117202 (external, merged 2026-08-31) is already on this tree and the shard fired anyway, so it is not the owner of this row. A fix task holds the residual, blocked on the integration-test capacity decision I put to the maintainers at #115963 (comment)

None of the rows above is caused by this pull request.

On the 03707_autopr_unsupported_cases row: the test collects parallel-replicas statistics from the
query plan, which only the analyzer builds, so on the old analyzer lane every shape it checks
reported no statistics. #117364 forces the analyzer in the test itself. It merged at 22:05:00Z, and
compare reports this head diverged from its merge commit c9ed88dbecbb, so the run predates the
fix. On true master, the 7 runs after that merge are clean against 2 to 4 failures per hour before
it. I am not merging master here purely to re-run CI, to keep the review load down.

On the /docker row: the /docker cgroup that bounds the nested test containers is capped at
40.78 GiB, and docker compose stop signals every node of a cluster at once, so each node that
outlives the 60 s deadline attaches gdb at the same moment, holding about 3.4 GiB of anonymous
memory each on an ASan build. #117202 serialises those attaches. This head already carries #117202, picked up by an
earlier master merge, and the shard fired anyway. That matches what master shows: on trees that do
contain it, shards 2/6 and 5/6 are clean but 6/6 still fires. So that PR is deliberately not
linked as this row's owner.

Session id: cron:our-pr-ci-monitor:20260831-233000

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Still firing after publication: three more occurrences, measured

I traced the three Digest does not match occurrences that post-date this pull request. All three are
this defect.

date (UTC) carrier lane assertion site in-flight DDL detached under it
2026-09-02 #116365 arm_msan commitCreateTable:2648, inline CREATE TABLE, stalled 9.6 s in object-storage work 12 tables in 52.7 ms
2026-09-04 #113963 arm_asan_ubsan txn finalizer, :1345 DETACH TABLE ... PERMANENTLY SYNC, blocked 23.8 s 55 tables in 12.6 ms
2026-09-11 #119495 arm_asan_ubsan dropTable:2535, inline DROP TABLE <TimeSeries> SYNC, blocked 5.5 min in dropInnerTableIfAny ~20 tables in 2 ms

In each one the fan-out is a DETACH DATABASE test_2 running on a different query id and thread from
the aborting one, preceded within ~20 ms by Replication was stopped. (UNFINISHED) /
Marking reinitializing / Cleaned DDLWorker state.

On 2026-09-02 the counter is accounted for to the bit, which I think is worth having explicitly. The
last passing check read 5572673194698203588; the fan-out then removed all 12 tables and the CREATE
added its own hash:

5572673194698203588 + 4585224049691586466 = 10157897244389790054

10157897244389790054 is the reported in-memory digest, and 4585224049691586466 is both the reported
local digest and the hash of the single table left in the map. On 2026-09-04 the map was emptied
outright, so the local digest is literally 0.

The blocking durations in the table are also the measured answer to how long this drain can hold
DETACH DATABASE: 9.6 s, 23.8 s and 5.5 min of genuinely in-flight DDL, observed in CI.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e433c95

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff (job level) infra: the CI logs cluster answered the resolve_run read with Code: 241 ... memory limit exceeded: would use 212.52 GiB ... (MEMORY_LIMIT_EXCEEDED), and Db.query treats a failed read as fatal, printing its own SQL instead of the cluster's error (72 distinct PRs carry an error head for this check today) #118708 (ours, open), which replaces that exact raise site
Sync - CH Inc sync (private, not actionable by me)

It is the only red on this head: Finish Workflow and Mergeable Check are green and all 172
checks are terminal at their newest attempt (147 success, 24 skipped).

Session id: cron:our-pr-ci-monitor:20260915-173213

@groeneai

Copy link
Copy Markdown
Collaborator Author

Second independent confirmation of this window, from Stress test (arm_msan) on #118242 (head 98981483a2d9, 2026-09-20), so the theory now rests on two sightings rather than one:

DETACH DATABASE test_5 at 03:33:32.480708 erased 9 tables from the in-memory map (detachTableUnlocked, 03:33:33.288610 to 03:33:34.061346) while entry query-0000000479 was still executing inline on the initiating thread since 03:33:32.170241, which then aborted at 03:33:34.295517 with a local-only skew (0 is not equal to digest in Keeper lines). Timeline: #118242 (comment)

…-before-detach-database

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2d49cf0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Cannot check whether the mutation submitted before the upgrade was finished, Error message in clickhouse-server.log not from this PR (it changes only the DETACH DATABASE drain in DatabaseReplicated): the upgraded server cannot attach test_1.t_pfl_05079 (AggregateFunction(quantile('0.5'), Float64), Code 70 Cannot convert String to double) that the previous 26.9 release wrote. Same failure on 77 other PRs from 2026-09-21 to 2026-09-26 13:10Z, none after the first 26.9 release carrying the fix (v26.9.3.38-stable, 2026-09-26 16:08Z) #121590 (external, merged; its first release shipped after this 09:35Z run)
Performance Comparison (arm_release, master_head, 2/6) / and_compare_chain_derived #2 noisy perf query, not from this PR: client time 14 ms to 20 ms, scored as a confirmed regression. The same query was flagged slower or unstable on 260 PRs and in 142 master rows from 2026-09-11 to 2026-09-26. The polymorphic_parts_m "too long" note of this job also appears on passing master runs #122458 (external, merged 2026-09-26 23:16Z, after this run)
Mergeable Check, PR praktika rollups of the rows above #121590, #122458 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-050037

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Not for CI any more, as far as I can measure. The stress failure it targets (Digest does not match, #114819) had 10 hits in Stress test (*) between 2026-08-20 and 2026-09-20 (last one, arm_msan) and none since, while the same jobs kept running thousands of times. I did not find the change that made it stop.

The race is still on master: DETACH DATABASE stops replication and detaches the tables one by one before it takes the exclusive DDL guard (InterpreterDropQuery.cpp:546, :753, :875 at 0c5db0a9f0c5), and #128824 added the wait for admitted initial queries only to SYSTEM RESTORE DATABASE REPLICA. But its only symptom is that assertion, which exists only in debug and sanitizer builds, and the PR now conflicts with master. So I am fine with closing it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants