Skip to content

Do not fail DROP DATABASE of a Replicated database on a transient Keeper error - #112829

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-drop-database-replicated-keeper-shutdown
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-drop-database-replicated-keeper-shutdown

Conversation

@groeneai

@groeneai groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112045

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes DROP DATABASE of a Replicated database failing with KEEPER_EXCEPTION when a transient Keeper error hits the best-effort removal of the replica's active ephemeral node. The database was left attached with its replication already stopped.

Description

DatabaseReplicatedDDLWorker::shutdown eagerly removes the replica's active ephemeral node. That removal only exists so SYSTEM DROP DATABASE REPLICA does not spuriously report the replica as active; the node is released by session expiry regardless. But ZooKeeper::tryRemove throws on a hardware Keeper error, and nothing on the DROP path caught it, so a transient Connection loss failed the user's whole DROP DATABASE ... SYNC. The throw happens before any table is touched, so the database stayed attached with its replication worker already stopped.

DatabaseReplicated::shutdown already wraps stopReplication in a first-error-and-continue path for this exact hazard, but InterpreterDropQuery called it bare. Two changes:

First, DatabaseReplicatedDDLWorker::shutdown releases its node holders on the throwing path as well, so a repeated shutdown does not retry the same failing removal. The exception still propagates, so the DatabaseReplicated::shutdown contract and its database_replicated_throw_on_stop_replication failpoint keep working. setAlreadyRemoved stays on the success path only, so that after a failed eager removal ~EphemeralNodeHolder still retries it.

Second, InterpreterDropQuery treats the pre-drop stopReplication as best effort for a DROP, rethrowing anything that is not a hardware Keeper error. DETACH keeps the database on disk to be reattached, so there the error still surfaces.

Both are required: with only the interpreter catch, DatabaseCatalog::detachDatabase calls shutdown a second time during the same DROP, the removal throws again and is rethrown, so the DROP still fails.

Validation: a new failpoint makes the failure deterministic. A new stateless test fails on the unfixed build (the DROP fails with the injected Coordination::Exception on the active path) and passes with the fix; mutations show each change is separately required. test_drop_database_replica still passes.

Found by Integration tests (amd_tsan, 4/6), which failed the same way on four unrelated pull requests on the same day: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29


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

groeneai and others added 5 commits July 31, 2026 03:50
…per error

DatabaseReplicatedDDLWorker::shutdown() eagerly removes the replica's "active"
ephemeral node. That removal only exists so SYSTEM DROP DATABASE REPLICA does not
spuriously report the replica as active; the node is released by session expiry
regardless. But ZooKeeper::tryRemove throws on a hardware Keeper error and nothing
on the DROP path caught it, so a transient Connection loss failed the user's whole
DROP DATABASE ... SYNC with KEEPER_EXCEPTION and left the database attached with
its tables half torn down.

DatabaseReplicated::shutdown() already wraps stopReplication() in a
first-error-and-continue path for exactly this hazard. The DROP path called
stopReplication() bare, so it never got that handling. Two changes:

- DatabaseReplicatedDDLWorker::shutdown() releases its node holders on the throwing
  path as well, so a repeated shutdown() does not retry the same failing removal.
  The exception still propagates, so the DatabaseReplicated::shutdown() contract
  and its database_replicated_throw_on_stop_replication failpoint keep working.
  setAlreadyRemoved() stays on the success path only, so that after a failed eager
  removal ~EphemeralNodeHolder still retries it.
- InterpreterDropQuery treats the pre-drop stopReplication() as best effort for a
  DROP, rethrowing anything that is not a hardware Keeper error. DETACH keeps the
  database on disk to be reattached, so there the error still surfaces.

Both changes are required: with only the interpreter catch, DatabaseCatalog::
detachDatabase calls db->shutdown() a second time during the same DROP, the removal
is retried, throws again and is rethrown, so the DROP still fails.

Found by Integration tests (amd_tsan, 4/6), which failed the same way on four
unrelated pull requests on the same day.

Co-Authored-By: Claude Fable 5 <[email protected]>
The healthy-session test added in the previous commit could not fail. It
asserted that the replica path is gone after a DROP, but DatabaseReplicated::drop
removes that subtree recursively anyway, so deleting the eager removal in
DatabaseReplicatedDDLWorker::shutdown left every assertion passing.

DETACH is the state that makes the removal observable:
DatabaseCatalog::detachDatabase calls db->drop() only when dropping, so a DETACH
stops replication and detaches the database while leaving the Keeper subtree
intact. The new test asserts the active node is gone AND that the replica path
still exists; the second half is what attributes the absence to the shutdown
path rather than to a recursive cleanup.

Deleting the eager tryRemove while keeping setAlreadyRemoved() now fails the new
test on the active node assertion, while the pre-existing DROP test still passes.
That pair is the evidence. The DROP test is kept: it is the only one asserting
that a healthy DROP takes neither the injected error nor the best-effort branch.

Also correcting the previous commit message: it said the failure left the tables
half torn down. It does not. stopReplication() is called before table
enumeration begins, so the database was left attached with its replication
worker already stopped and no table touched.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Related: ClickHouse#112045

Co-Authored-By: Claude Fable 5 <[email protected]>
The DROP path treats a failure to stop replication as best effort only for a
hardware Keeper error:

    if (!drop || !Coordination::isHardwareError(e.code))
        throw;

The test module pinned only the !drop term. Its single failpoint hardcodes
ZCONNECTIONLOSS, so no test injected a user-class error and neutralizing the
isHardwareError term left every test green while a DROP silently swallowed
ZNONODE, ZBADVERSION, ZNODEEXISTS, ZNOTEMPTY and ZNOCHILDRENFOREPHEMERALS.

Add a second REGULAR failpoint at the same site that throws ZBADVERSION, a code
that is in isUserError and that tryRemove itself can surface, and a test that
asserts the DROP still reports it and leaves the database attached.

Two mutations bracket the new test. Neutralizing only the isHardwareError term
fails exactly this test and leaves the other six passing. Reverting
InterpreterDropQuery.cpp to master entirely leaves this test passing, because the
error surfacing is also master's behaviour, while the best-effort DROP test
fails, so the two tests are complementary rather than redundant.

Module: 7 passed, and 70 passed with --count 10 --repeat-scope=function.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Reported on ClickHouse#112045
The restore test disarmed the failpoint before its second SYSTEM RESTORE
DATABASE REPLICA, so that restore only showed the database was usable again.
Keep the failpoint armed across both restores instead: reinitializeDDLWorker
throws out of ddl_worker->shutdown() before it can reset ddl_worker, so the
second restore shuts the same stale worker down again, and it can only succeed
if the failed shutdown released its holders. The INJECTED log count must then
stay unchanged, asserted with exact equality, because count_in_log counts log
lines and an unhandled throw on this path emits two of them, so any offset
would be scale dependent.

Deleting the SCOPE_EXIT block now fails this test on the second restore itself,
alongside the best-effort DROP test that pins the same release through the
other carrier.

This also corrects the previous commit message, which described the injected
ZBADVERSION as a code that tryRemove can itself surface. That is wrong:
ZooKeeper::tryRemove returns ZOK, ZNONODE, ZBADVERSION and ZNOTEMPTY rather
than throwing them, so the injection is synthetic. ZBADVERSION is still the
right choice, because the test only needs a code that isUserError accepts and
isHardwareError therefore rejects. The user-class codes tryRemove does throw,
and that the guard rethrows, are ZNOCHILDRENFOREPHEMERALS and ZNODEEXISTS, so
the branch is reachable in production even though the injected code is not.

Module: 7 passed, and 70 passed with --count 10 --repeat-scope=function.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Reported on ClickHouse#112045
The restore test sampled the INJECTED count as soon as query_and_get_error
returned. The client returns once the server has sent the exception, while the
remaining record for that same throw is written afterwards by TCPHandler::run,
so a record could land between the two reads and fail the equality for a reason
that has nothing to do with the removal being re-entered. Both reads now poll
until the count stops growing, which keeps the assertion independent of how
many records one throw emits, and raise if it never settles. The exact equality
is unchanged: an unchanged count is what shows the removal was skipped rather
than attempted and happening to succeed.

This also corrects a false claim in my previous commit message, which named
ZNOCHILDRENFOREPHEMERALS and ZNODEEXISTS as user-class codes this tryRemove can
throw, and concluded from that the branch is reachable in production. That is
wrong in both parts. Neither code can arrive from a remove request: in
KeeperStorageImpl.cpp they occur only inside the ZooKeeperCreateRequest and
ZooKeeperCheckRequest preprocess overloads, while the remove overload can return
only ZBADARGUMENTS, ZNOAUTH, ZOK, ZNONODE, ZBADVERSION and ZNOTEMPTY.
Of those, isUserError accepts ZNONODE, ZBADVERSION and ZNOTEMPTY, and tryRemove
returns exactly those three rather than throwing them, so there is no
user-class code this call site can throw. ZBADVERSION remains the right thing
to inject, because the test only needs a code that isUserError accepts and
isHardwareError therefore rejects, and the injection is synthetic either way.

The guard's non-hardware branch is a conservative default rather than a branch
some known production code reaches. The catch is keyed on the exception type,
so it covers everything stopReplication can throw and not just this one
tryRemove: DDLWorker::shutdown runs first and clears its own active node
holders, and DatabaseReplicatedDDLWorker makes further Keeper calls on other
paths. Narrowing to hardware errors keeps a genuine user-class or programming
error visible instead of letting a DROP swallow it.

Module: 7 passed, and 70 passed with --count 10 --repeat-scope=function.
Deleting the SCOPE_EXIT block still fails the restore test on its second
restore.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112045&sha=6c7ac2f6fa2f42fad0b432647d063876394a67c5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
Reported on ClickHouse#112045
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (5 rounds): all findings resolved, no open items

Independent review of this branch by a second model, plus my own cold review of the
resulting code. Each round reviews the delta that closed the previous round's findings.

Round 5

Finding Verdict
The independent pass reported no findings on this round's delta. Nothing to resolve. It re-read all six changed files in full and re-traced the shutdown, DROP, DETACH and RESTORE paths, the other engine that has a replication thread, the Keeper error semantics, the existing tests and the supplied CI report.
💡 The provenance link to #112045 sat inside the leading HTML comment, which GitHub does not render, so it would not have been visible on this page. AGREE, fixed in the description above before this round was reviewed. Of the last 60 merged pull requests, 16 carry a visible relationship line and only 3 keep it comment-only, so the visible form is the house style.
💡 The new bounded log-count poll reads only the current server log file, so a log rotation between its two reads could make the counts differ. DISAGREE on failure direction. A differing count fails the assertion with its explanatory message; it can never make a broken build pass, which is the same reasoning that graded the ordering item in round 4 a robustness note. Making the read rotation-aware would additionally count records from earlier tests in the same module and weaken the exact-equality oracle that round 3 established as the mechanism witness. Measured over ten repeats of the module: the poll never hit its ceiling.
💡 black reformats the new test file. DISAGREE, not this change's dirt and not a check that runs. No continuous integration job invokes black; the style job runs mypy, pylint and ruff, and ruff passes on the file with the file confirmed inside its scan set. Five of eight randomly sampled existing integration tests on master fail the same local black, and the set of lines black proposes here is byte-identical before and after this round, with the new helper appearing only as context.

Round 4

Finding Verdict
⚠️ zbadversion-reachability-claim (consistency): the commit message that corrects the round-3 ZBADVERSION claim replaces it with another false one, namely that ZNOCHILDRENFOREPHEMERALS and ZNODEEXISTS are user-class codes this removal can throw, making the non-hardware branch reachable in production. AGREE, being corrected in a new commit. Neither code can arrive from a remove request: a remove can only produce ZBADARGUMENTS, ZNOAUTH, ZOK, ZNONODE, ZBADVERSION or ZNOTEMPTY, while those two are produced only by create and check requests. Intersecting the user-class set with what a remove can produce leaves ZNONODE, ZBADVERSION and ZNOTEMPTY, and tryRemove returns all three rather than throwing them, so the set of user-class codes this call can throw is empty. The wording was again mine, from my round-3 instruction, so this is my error for the second round running rather than a deviation. Nothing about the guard, the failpoint, the test or the mutation evidence changes: the test only needs a code that is user-class and therefore not hardware. The corrected message states what is demonstrable, that the guard is keyed on the exception type and covers everything stopping replication can throw, so narrowing to hardware errors is the conservative default, without asserting a specific reachable code.
💡 The reworked restore test samples the injected-error log count as soon as the failed query returns, while a second matching record is written by the connection handler afterwards, so the equality could fail spuriously. AGREE, hardened alongside the item above. Measured stable over four independent runs plus a tenfold repeat, and the failure direction is loud rather than silently passing, so this is robustness rather than a correctness gap. The count comparison itself is kept: a successful second restore shows the restore worked, while the unchanged count is what shows the removal was skipped rather than attempted and happening to succeed.

Round 3

Finding Verdict
⚠️ restore-unarmed-retry (test-liveness, raised in two consecutive rounds): test_restore_database_replica_after_failed_shutdown disables the failpoint before its second restore, so the retry takes the healthy path and proves nothing about holder release. AGREE - real, and still open. My round-2 remedy for it was wrong and measurement refuted it: I asked for the injected-error log count to grow by one, but that counter counts log lines and one unhandled throw emits two, and on the fixed build the second restore does not reach the removal at all, because a failed restore keeps the stale worker whose holders the new scope guard has already released, so the guard short-circuits and the restore succeeds. The corrected oracle keeps the failpoint armed across both restores and asserts the second one succeeds with the count unchanged, which is only possible if the holders were released. Measured on both arms: with the fix the armed second restore succeeds and the count is unchanged, stable over four runs; with the scope guard deleted it throws and the count grows.
⚠️ zbadversion-mechanism-claim (consistency): the newest commit message claims ZBADVERSION is a code tryRemove itself can surface. AGREE, corrected in a later commit. ZooKeeper::tryRemove returns ZBADVERSION rather than throwing it, so the failpoint's injection is synthetic. This does not affect the guard, the test or the mutation evidence: the only property the test needs is that the code is a user-class error and therefore not a hardware one. The wrong sentence came from my own round-2 instruction, so this is my error rather than a deviation. See round 4: my round-3 replacement wording was wrong too.
💡 Test comment presents the synthetic ZBADVERSION injection as a realistic inconsistency at this site. AGREE, one clause clarified alongside the item above.

Round 2 (closed)

Finding Verdict
❌ nonhardware-drop-oracle (test-liveness): the tests did not pin the isHardwareError half of the DROP guard. The failpoint injected only ZCONNECTIONLOSS, so narrowing the guard to if (!drop) throw; kept every test green while DROP would swallow user-class Keeper errors. AGREE, fixed. This is the change's own published contract, so it must be pinned. A second failpoint injects a user-class code at the same site, and a new test asserts the DROP still reports it and leaves the database attached. Two mutations bracket it: neutralising only the hardware-error term fails exactly that test and leaves the other six passing, while reverting the interpreter catch entirely leaves it passing and fails the best-effort test instead, so the two tests are complementary rather than redundant.

Round 1 (all closed and verified closed)

Finding Verdict
❌ healthy-active-oracle (test-liveness): the healthy-session test could not fail. It asserted the replica path is gone after a DROP, but DatabaseReplicated::drop wipes that subtree recursively anyway, so deleting the eager removal left every assertion passing. AGREE, fixed. Replaced by a DETACH oracle: DatabaseCatalog::detachDatabase calls drop() only when dropping, so a DETACH leaves the Keeper subtree intact and the removal becomes observable. It asserts the active node is gone AND that the replica path still exists, which is what attributes the absence to the shutdown path. Deleting the eager tryRemove now fails the new test while the old DROP test still passes.
💡 changelog-teardown-state: the changelog said the failure left tables partially torn down. AGREE, fixed. It does not: stopReplication runs before table enumeration begins, so the database was left attached with its replication worker stopped and no table touched. The correction is in the description and, since amending is not used here, stated in the following commit message.
💡 commit-ci-links: the commit message omitted the supplied CI report URL and the corresponding pull-request link. AGREE, fixed in a new commit.
💡 Comment style: prefer f over f() and backtick literal names. DISAGREE, with an offer. The f() form appears 13 times in InterpreterDropQuery.cpp and 14 times in DatabaseReplicated.cpp in pre-existing comments, including the adjacent DatabaseReplicated::shutdown comment this change is paired with and references, so reformatting only the new lines would break that pair. Happy to reformat both together if preferred.

Verified independently this round (no change requested)

The fix logic itself is correct. I re-derived it from source rather than accepting
the recorded evidence:

  • isHardwareError includes ZCONNECTIONLOSS, and ZooKeeper::tryRemove throws
    on exactly the codes it does not swallow, so the reported failure path is real.
  • The new SCOPE_EXIT cannot throw during unwinding: ~EphemeralNodeHolder has
    its own catch (...), shared_ptr::reset and condition_variable::notify_all
    are noexcept, and ~ZooKeeper only deactivates a reconnect task. So plain
    SCOPE_EXIT is right here rather than the exception-swallowing variant.
  • Declaration order is right: the Keeper component guard outlives the scope-guard
    body, so the holder destructor's own guarded retry still runs with the component
    set.
  • No new race: both markReplicasActive call sites run on the DDL worker main
    thread, which DDLWorker::shutdown joins before this code touches the holders.
  • setAlreadyRemoved correctly stays on the success path, so a failed eager
    removal still gets the destructor's guarded retry.
  • Both hunks are separately required, and the interpreter catch alone is not
    enough because DatabaseCatalog::detachDatabase calls shutdown a second time
    during the same DROP.

Disclosure: overlap with #110886

The new catch keys on the exception type rather than the engine. It is unreachable
today for the only other engine with a replication thread, whose
stopReplication touches no ZooKeeper. #110886 makes that function coordinated,
after which this catch would also cover it. That is benign by that change's own
design, since its veto lives in beforeDropDatabase, which runs above this line.
Merge-tested against its head with an explicit merge base: no conflict, and the
merged file carries both changes correctly nested.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A new REGULAR failpoint, database_replicated_fail_active_node_removal_on_shutdown, throws Coordination::Exception(ZCONNECTIONLOSS) at the reported site, so the failure needs no race with a real Keeper. Repro: enable the failpoint, then DROP DATABASE <replicated db> SYNC. A second REGULAR failpoint, database_replicated_fail_active_node_removal_nonretryable, throws ZBADVERSION at the same site so the user-class half of the guard is exercised deterministically too. The plan's suggested lever database_replicated_throw_on_stop_replication is unusable here: it sits inside the DatabaseReplicated::shutdown wrapper, which the DROP path never enters.
b Root cause explained? ZooKeeper::tryRemove swallows only ZOK/ZNONODE/ZBADVERSION/ZNOTEMPTY and throws otherwise, and ZCONNECTIONLOSS is in the throwing set. DatabaseReplicatedDDLWorker::shutdown called it unguarded for the replica's active ephemeral node, a removal its own comment declares a best-effort optimization for SYSTEM DROP DATABASE REPLICA promptness. DatabaseReplicated::shutdown already wraps stopReplication in a first-error-and-continue path for that hazard, but InterpreterDropQuery called it bare, so a transient Keeper error failed the whole DROP DATABASE ... SYNC and left the database attached.
c Fix matches root cause? Yes. The DROP path adopts the handling its sibling consumer already had, and the throw keeps propagating out of the worker so that sibling's contract is not weakened. No widened bound, no no-random-* tag, no data reduction, no defensive check masking an upstream bug. Notably the obvious shape, re-adding a swallowing try/catch at the removal, was rejected: it would revert the deliberate propagation decision and would also suppress the destructor's own retry.
d Test intent preserved / new tests added? 7 new integration tests in test_drop_replicated_database_keeper_error (7 passed; the whole module also passed 70 out of 70 with --count 10 --repeat-scope=function, 0 assertion failures and 0 Code: 209/210 host-contention noise). No existing test weakened; the restore test was strengthened rather than relaxed, by keeping the failpoint armed across both restores so that the second restore succeeding is itself the evidence that the failed shutdown released its holders, with the unchanged INJECTED log count as the mechanism witness. That count is read on both sides only after it has settled, under a bounded poll, because the client returns once the server has sent the exception while the remaining record for the same throw is written afterwards; the comparison stays an exact equality rather than being relaxed to a tolerance, and the wait deliberately does not hard-code how many records one throw emits. Guard modules test_drop_database_replica and test_database_catalog_shutdown_system_logs still pass (8 passed). One of the seven asserts the must-not-regress behaviour through a DETACH rather than a DROP, because DatabaseReplicated::drop removes the replica subtree recursively and would mask the eager removal.
e Both directions demonstrated? Yes. Pre-fix arm (this tree with the failpoint kept and both hunks reverted, Build ID 8a172b08e21a9): 2 failed, 3 passed, and the DROP failure reproduces the reported stack frame for frame through DatabaseReplicatedWorker.cpp -> stopReplication -> InterpreterDropQuery. Fixed arm: all tests pass. Each hunk is separately load-bearing: part 1 alone and part 2 alone both fail the DROP test, part 2 alone failing through the second shutdown call that DatabaseCatalog::detachDatabase makes during the same DROP. A further mutation deleting only the eager tryRemove fails the healthy-session DETACH test on its Keeper-state assertion while the healthy-session DROP test still passes, which is why the DETACH oracle exists. Two further mutations pin the isHardwareError term of the guard: neutralizing only that term (Build ID 9fda2b5076910) fails exactly the new non-hardware test and leaves the other six passing, and reverting InterpreterDropQuery.cpp to master entirely (Build ID 63513f252b720) leaves that new test passing while the best-effort DROP test fails, so the two tests are complementary rather than redundant. A final mutation deleting only the SCOPE_EXIT holder-release block (Build ID a6c2813dce1bb) fails both carriers of that release: the restore test fails on its second, still-armed SYSTEM RESTORE DATABASE REPLICA with the injected Code: 999 raised from DatabaseReplicatedWorker.cpp:161 through reinitializeDDLWorker, and the best-effort DROP test fails on its count_in_log(INJECTED) == 1 assertion, so the two pin the same release through different carriers. Restoring the source leaves git diff HEAD -- src/ empty with each file md5-identical to git show HEAD:<file>. That SCOPE_EXIT mutation was re-run after the log-count read was made settle-based (Build ID 2f808af6) and still reddens the restore test on the second restore itself, at node.query("SYSTEM RESTORE DATABASE REPLICA ..."), so the bounded wait does not mask it.
f Fix is general across code paths? Yes. All 4 stopReplication call sites and both ddl_worker->shutdown callers were enumerated: the server-shutdown site is already guarded and untouched, the interpreter site is fixed, DatabaseCatalog::detachDatabase is covered by the holder release, and DatabaseMaterializedPostgreSQL has no ZooKeeper. SYSTEM RESTORE DATABASE REPLICA reaches the changed function through reinitializeDDLWorker and has its own test, which asserts the release on that path directly: reinitializeDDLWorker throws out of ddl_worker->shutdown() at DatabaseReplicated.cpp:1128 before it can reset ddl_worker at :1131, so a failed restore creates no fresh worker and a second restore re-enters the same stale one. A sweep for other unguarded teardown-context tryRemove calls found none: the EphemeralNodeHolder destructor and DDLWorker::shutdown are both guarded.
g Fix generalizes across inputs (params/datatypes/wrappers)? No type or wrapper axis applies: this is a DDL statement, not an expression. The relevant axes were enumerated instead. Statement kind: DROP is fixed, DETACH is deliberately unchanged and still reports the error, TRUNCATE is excluded by the pre-existing gate. Error class: only a hardware Keeper error is treated as best effort, everything else is rethrown, and both sides of that split are now asserted (ZCONNECTIONLOSS handled best effort, ZBADVERSION still failing the DROP). Engine: hasReplicationThread is true for exactly two engines and both were checked.
h Backward compatible? Yes. No settings, formats, metadata or ABI change, so no SettingsChangesHistory.cpp entry is needed. The only user-visible change is that a DROP DATABASE which previously failed now succeeds.
i Invariants and contracts preserved? Yes. The holder reset order is unchanged, which matters because the holder keeps a ZooKeeper & that its destructor dereferences. setAlreadyRemoved stays on the success path only, so a failed eager removal still leaves the destructor's guarded retry armed; that property is asserted directly against Keeper state and it reddens when either hunk is reverted. The propagation contract of DatabaseReplicated::shutdown is preserved and covered by an existing module. The cleanup runs on every exit path, including the branch that skips the removal entirely.

Session id: cron:clickhouse-review-slot-9:20260731-211900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @vdimir, could you review this? DatabaseReplicatedDDLWorker::shutdown removes the replica's active ephemeral node as a best-effort optimization, but ZooKeeper::tryRemove throws on a hardware Keeper error and nothing on the DROP path caught it, so a transient connection loss failed the whole DROP DATABASE ... SYNC; the worker now releases its holders on the throwing path too and InterpreterDropQuery treats that pre-drop stopReplication as best effort for a DROP only.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d0efed]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
05019_cascades_replicated_total_rows FAIL cidb

AI Review

Summary

Reviewed #112829 at 5d0efedf398bfe229555a0a2e0ad54c7d7109980, including all prior discussion. The change lets DROP DATABASE continue after hardware Keeper errors during replication shutdown and releases active-node holders on exceptional exits, while preserving error reporting for DETACH DATABASE and non-hardware errors. No actionable findings remain; the author's explanation of the holder destructor's retry addresses the previous inline concern.

Missing context / blind spots
  • ⚠️ Current-head functional and bugfix-validation results are pending, and no local ClickHouse binary was available to execute the replacement stateless test. Earlier-head regression and mutation results are recorded in the PR discussion; current-head CI must validate the test migration and merged shutdown changes.
Final Verdict

Status: ✅ Approve. No new inline findings or thread changes are needed. Runtime verification remains subject to the pending CI results.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 33/38 (86.84%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ea2fe0

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.

174 check runs, 0 queued or in progress, Finish Workflow green. One real job failure.

Check / test Reason Owner / fixing PR
Stress test (arm_msan) / Hung check failed, possible deadlock found hung check, not caused by this diff a fix task is investigating this at full effort, and I will post the fixing-PR link here when it opens
Bugfix validation (integration tests, amd64 and aarch64) not a failure: the check conclusion is success. The two rows recorded against this PR's own new integration test have empty context, which is the expected bookkeeping for a bugfix PR whose test does reproduce the bug on master no owner needed
Sync - CH Inc sync (private, not actionable by me)

On the hung check: I grepped the ingested 32 KiB of hung-check context for every path this diff touches and found zero occurrences of DatabaseReplicated, DROP DATABASE, Keeper, ZooKeeper, InterpreterDropQuery, stopReplication and dropDatabase. The visible payload is an unrelated stress workload exception (Code: 36 ... widthBucket count cannot be 0, from 02581_width_bucket.sql). This diff is test-only, one file, +33/-3, with no change under src/.

I am deliberately not linking the merged fix for one sub-cause of this hung-check family: it is already an ancestor of this head, so this run failed with that fix present and it does not resolve this signature.

Session id: cron:our-pr-ci-monitor:20260801-153000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Only conflict was the failpoint registry in src/Common/FailPoint.cpp, where master
added REGULAR(database_catalog_shutdown_sleep_per_table) at the same anchor as the
two entries this branch adds. Kept all three. The merged list holds every failpoint
master registers plus those two, with no kind change and no duplicate.

The two other files this branch touches merged without conflict: master's edits to
DatabaseReplicatedWorker.cpp (saturatedDuration, a settings type) and to
InterpreterDropQuery.cpp (drop dependency ordering, QueryFlags, has_like) are all
outside the shutdown() and stopReplication() call sites this branch changes.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d0efedf3 with master 4eada96ac (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c70065887; 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, 24 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 - 159aae5

CI is fully finished and green on this head: 147 OK, 23 skipped, 0 failures, nothing to own. The only check without a result is the private CH Inc sync, which is not actionable here.

For the record, Bugfix validation (integration tests, amd64/aarch64) reports OK: the three arms that pin the fix fail against the merge base as intended, and the two ..._on_healthy_session control arms pass there, which is what those arms are for.

Session id: cron:our-pr-ci-monitor:20260828-180000

@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 and others added 2 commits November 8, 2026 13:13
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]>
The scenario needs one server, Keeper and failpoints, all of which the
stateless tests have, so it does not need a dedicated integration cluster
(see the integration test guidelines in .claude/CLAUDE.md). The test keeps
the four cases: DROP survives a hardware Keeper error, DETACH still reports
it and the active node is still removed, a non-hardware error still fails
the DROP, and a second SYSTEM RESTORE DATABASE REPLICA does not repeat the
removal. It is no-parallel because the failpoints fire on the shutdown of
every Replicated database's DDL worker.

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

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5d0efed

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
Stateless tests (arm_binary, parallel) / 05019_cascades_replicated_total_rows flaky, not from this PR (no join or query-plan file in the diff): with a non-zero query_plan_optimize_join_order_randomize seed and a small index_granularity the self-JOIN over the bucketed distributed read counts 800000 rows instead of 200000; it reproduces on master #129420 (mine, open)
Mergeable Check / PR praktika rollup of the row above #129420 (the owner above)

Session id: cron:our-pr-ci-monitor:20261108-180009

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants