Skip to content

Await the consumer channel close before deleting RabbitMQ queues on DROP TABLE - #116050

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:rabbitmq-drop-await-consumer-channel-close
Sep 20, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:rabbitmq-drop-await-consumer-channel-close

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #114269

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

Fixed a broker-side queue leak when dropping a RabbitMQ table. DROP TABLE asked the broker to delete the table's queues without waiting for its own consumer channels to close, so the broker could still see a registered consumer and refuse the deletion with PRECONDITION_FAILED. The queues are declared durable and are never auto-deleted, so they survived permanently together with any unconsumed messages.

Description

StorageRabbitMQ::shutdown() sent channel.close on every consumer channel and then immediately issued queue.delete with AMQP::ifunused on a separate, freshly created channel. AMQP orders method completion per channel only, so the broker could evaluate the deletion while the consumer was still registered on the other channel. A classic queue then answers exactly what the flag asks for, PRECONDITION_FAILED - queue '...' in use, which was logged before giving up. Losing that race depends on broker scheduling, so it is rare.

shutdown() now waits, on a dropped table only, for the broker to answer those closes before asking for the deletion. rabbit_channel deregisters a channel's consumers while handling its channel.close, before answering it, so that answer is the ordering the deletion needs. The deletion is unchanged: still a single ifunused attempt, so a queue shared through rabbitmq_queue_base still survives.

The cleanup now also requires shutdown()'s own drop argument, so a failed TRUNCATE latching the internal drop flag no longer costs a later DETACH its queues.

The bound is small rather than the 30s used elsewhere: a channel awaiting a reply that never arrives queues its own close, so such a table would otherwise pay the full timeout on every DROP TABLE. Expiring restores the previous behaviour.

startBlockingLoopWithTimeout also refreshes the loop's cached time before arming its timer: uv_timer_start derives the deadline from that value, which libuv only updates while the loop runs, so between two waits the timer can already be overdue and the wait returns at once. The four pre-existing 30s waits could end early the same way.

Two limitations are out of scope. Quorum and stream queues still leak, because the broker does not implement if-unused for them at all, so no client-side barrier helps. A table that has already nacked also still leaks, tracked separately as an AMQP-CPP defect.

Validation (deterministic forcing, base vs fixed binary)

The losing interleaving was forced deterministically by suspending the consumer channel's broker-side process until its channel.close arrived, then releasing it after 300ms.

Arm Base Fixed
queue deleted, forced losing interleaving 6/6 leaked 6/6 deleted
same fixture with no forcing (control) 3/3 deleted -
ordinary drop, mean wall time over 10 0.1015s 0.0980s
queue shared through rabbitmq_queue_base survives survives
shared queue, other table reconnecting during the drop survives survives
table that has nacked, drop wall time 0.18s 1.08s
DETACH TABLE, added waits 0s, 0 0s, 0
rabbitmq_num_consumers = 2 leaked deleted

test_storage_rabbitmq/ was run on both binaries: 58 passed on the fixed one, and the two
failures (test_rabbitmq_select[1], test_rabbitmq_broker_log_is_collected) fail identically on
the base binary and are unrelated to this change. The new test fails on the base binary and passes
on the fixed one; it plus test_rabbitmq_drop_table_properly ran 50 times each, 100/100 passed.


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

Version info

  • Merged into: 26.10.1.258-master (included in 26.10 and later)

groeneai and others added 3 commits August 23, 2026 18:36
…ROP TABLE

StorageRabbitMQ::shutdown() sent channel.close on every consumer channel and then
immediately issued queue.delete with AMQP::ifunused on a separate, freshly created
channel. AMQP orders method completion per channel only, and RabbitMQ dispatches each
channel to its own process, so the broker could evaluate the deletion while the consumer
was still registered on the other channel. A classic queue then answers what the flag
asks for, PRECONDITION_FAILED - queue '...' in use, which was logged before giving up.
The queues are declared durable and deliberately not autodelete, so they leaked
permanently together with any unconsumed messages. Losing the race depends on broker
scheduling, so it showed up rarely and mostly on slow configurations.

RabbitMQProducer::finish already awaited its own channel close while the consumer
discarded the Deferred that close() returns, and that asymmetry was the bug. The
consumer now observes its close, and shutdown() waits for those answers on a dropped
table before asking for the deletion. rabbit_channel deregisters a channel's consumers
while handling its channel.close and before answering it, through a synchronous
notify_down_all, so that answer is the ordering the deletion needs.

The deletion itself is unchanged, still a single ifunused attempt, so a queue shared with
another table through rabbitmq_queue_base is still refused and still survives. The bound
is small rather than the 30s used elsewhere in this file, because a channel whose last
method awaits a reply that never arrives queues its own close, and such a table would
otherwise pay the full timeout on every DROP TABLE; expiring restores the previous
behaviour of not waiting.

startBlockingLoopWithTimeout also refreshes the event loop's cached time before arming
its timer. uv_timer_start derives the deadline from that cached value, which libuv only
updates while the loop runs, so between two blocking waits it could be far enough in the
past that the timer was already overdue and the wait returned at once. That silently
shortened every bounded wait here; it went unnoticed with a 30s bound and made a 1s one
useless.

Two limitations are out of scope. Quorum and stream queues still leak, because the broker
does not implement if-unused for them at all, so no client-side barrier can help. A table
that has already nacked a message also still leaks, which is an AMQP-CPP defect tracked
separately.
The regression test asserted that the consumer channel close is logged before
the queue deletion, but that ordering can also arise from the order two replies
happen to be drained in, so it did not pin the wait that establishes it. It now
also requires the wait's own bounded loop to have started before the deletion,
matched on a four-digit bound so the unrelated 30000ms waits cannot satisfy it.
Removing only the wait's use of the timed loop, while leaving the wait itself in
place so every other assertion still passes, trips the new assertion on 5 of 5
runs; the test is green on 10 of 10.

Refreshing the event loop's cached time before arming the timer had no arm at
all, yet dropping that line makes every bounded wait expire on its first
iteration. Both existing tests in gtest_rabbitmq_handler.cpp arm the timer on a
freshly created loop, so neither can observe a stale cache. The new one idles
the loop for two seconds first and asserts a lower bound on how long a 500ms
wait actually took: 400ms with the refresh, 0ms without it, on 5 of 5 runs.

The wait is measured rather than stopped by a second timer, because such a timer
is armed against the same stale clock and is therefore overdue as well: the
correct build then returns immediately and the assertion fails on it. Only a
lower bound is asserted, so a loaded runner overshooting the timeout cannot make
the test fail.

Co-Authored-By: Claude Opus 5 <[email protected]>
StorageRabbitMQ::shutdown() discarded its is_drop argument and gated the
queue deletion only on the drop_table flag. checkTableCanBeDropped() sets
that flag before the statement it guards can fail, and nothing ever clears
it, so a table left fully alive by a failed TRUNCATE stayed marked: a later
DETACH TABLE, or a server shutdown, then deleted its durable queues along
with every unconsumed message in them.

TRUNCATE reaches this state with no settings and no race. RabbitMQ does not
implement truncate, so InterpreterDropQuery calls checkTableCanBeDropped()
and only then hits the IStorage default, which throws NOT_IMPLEMENTED. A
failing dependency check on DROP latches the flag the same way.

Conjoining the two conditions is a strict narrowing. Replacing drop_table
with is_drop would not be: TemporaryTableHolder's destructor and
DatabaseReplicated's recovery drop both pass is_drop = true without ever
latching the flag, so that form would add deletions on two paths that do
not have them today.

Before this change the deletion on that path raced the still-registered
consumer and was usually refused, which is the defect the surrounding
commit fixes, so the two have to land together.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 24, 2026
@groeneai

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

Reviewed cold against the resulting tree over four rounds, then adjudicated against the recorded
validation evidence. 3 findings agreed and fixed, 9 disagreed with evidence, 2 resolved while
reviewing. Final two rounds: 0 findings.

# Finding Verdict
❌ checkTableCanBeDropped() sets a sticky internal flag before the statement it guards can fail, and nothing ever clears it, while shutdown() discarded the one argument that says whether this really is a drop. So a still-alive table could delete its durable queues and their unconsumed messages on a later DETACH or a server restart. AGREE - fixed by also requiring shutdown()'s own drop argument, which is a strict subset of the previous condition (the other two callers that pass a true drop argument never set the flag, so using it alone would have added deletions). Reachable with no settings and no race: TRUNCATE TABLE sets the flag and then fails NOT_IMPLEMENTED, leaving the table fully alive. A new test fails 5/5 without the fix, on the assertion carrying messages contained 1, and passes 10/10 with it.
❌ The first regression test did not discriminate the new barrier: with the wait made a no-op, the already-sent channel.close reply is drained by the cleanup's own loop turns, so the reply-ordering assertion could still hold. AGREE - fixed. The test now also asserts the bounded wait itself ran before the deletion. It discriminates three separate mutants, each tripping a different assertion, and the isolating one (barrier works, only the wait's own line absent) fails 5/5 on exactly the new assertion with no pre-existing assertion hit. The finding's own predicted mechanism was wrong: that mutant fails earlier, because the drained reply stops the deletion wait.
❌ Nothing deterministically covered the uv_update_time addition, although removing it re-breaks the fix, and both existing handler unit tests arm the timer on a freshly created loop. AGREE - fixed. A unit test idles the loop past the bound before waiting. Removing the line again makes it fail 5/5 with an elapsed time of 0 against a required 400 ms, while both pre-existing tests stay green, so the arm discriminates the line rather than the suite. It asserts a lower bound only, so load can overshoot but cannot redden it.
⚠️ closeConnections() installs channel-close callbacks capturing this, and on a non-drop shutdown they are never abandoned before the consumer is destroyed. DISAGREE - no reachable dispatch. ~ConnectionImpl closes an already-closing channel through the branch that invokes nothing and then only detaches; ~TcpConnection clears its handler before its members destruct; reaching the error-reporting path needs the loop driven or a reconnect between consumer destruction and connection destruction, and the shutdown path does neither. RabbitMQProducer::finish has had the identical shape for as long as it has existed.
⚠️ A channel already in the closed state receives neither callback, so the barrier burns the whole bound and then warns about a refusal that cannot happen. DISAGREE - the already-closed path returns a deferred object that is not in a failed state, so no immediate error callback fires; the cost is bounded at 1 s, on the drop path only, measured at 0.0980 s against 0.1015 s for an ordinary drop.
⚠️ A connection that is nominally connected but actually dead pays the new bound before the cleanup re-probes liveness. DISAGREE - bounded at 1 s by construction, on the drop path only, and strictly less than the 30 s the same connection already pays in the cleanup wait itself.
⚠️ The new detach test ends by dropping the same table, which emits the line its own earlier negative assertion forbids, and the log scan has no time window. DISAGREE, and settled by measurement rather than by argument. Both patterns embed the per-test database name, which carries the repeat index, so a 50-times repetition against one container is a direct test of the claim: 50 distinct database names each carry that line exactly once, and the refusal line the test also forbids appears zero times. Sensitivity control over the same log: the unscoped pattern an unscoped assertion would use matches 50 and would have failed from the second repetition on, while the committed one matches 1.
💡 The same sticky-flag construct exists in StorageNATS. DISAGREE - no consequence there: that engine sets the flag and never reads it, and its shutdown discards the argument with nothing destructive downstream. A latent trap for a future change, not a defect, so it is disclosed rather than folded into this change.
💡 Two headers relied on transitive includes for std::atomic and std::shared_ptr. DISAGREE - the header already relied on the identical transitive includes before this change; adding them is style-only churn.
💡 The uv_update_time change was not in the written plan. DISAGREE - disclosed in the description and the commit message, correct at the source rather than compensated in the caller, and it also protects the four pre-existing 30 s waits in the same file.
💡 The only provenance link sat inside the leading HTML comment, so it did not render. Resolved during review: the upstream template block is restored verbatim and a rendered Related: line added.
💡 The description named the loop-clock mechanism but not its consequence for the pre-existing waits. Resolved during review: the description now states it.

Also verified independently, from the pinned broker's own sources rather than from the plan: the
ordering claim (notify_queues runs a synchronous notify_down_all while handling channel.close,
and close_ok is written later, from ready_for_close) and that the classic-only scoping is real
(the consumer-pid helper filters by queue type, so it says nothing about quorum or stream). Also:
the test's four-digit bound pattern matches 1000 ms and 999 ms and rejects 30000 ms, including under
a substring match, and every other wait in the engine uses 30000 ms; log timestamps are fixed-width
to the microsecond, so the lexicographic comparison is chronological; the barrier covers every
consumer rather than the first, and its remaining-time arithmetic cannot underflow; uv_timer_start
appears nowhere else in src/; AMQP::ifunused and test_rabbitmq_drop_table_properly are
untouched, the latter byte-identical to master; contrib/ is untouched; and no setting or default
changes, so no SettingsChangesHistory.cpp entry is required.

Stability, superseding the count in the description's validation block: all three tests, the two
added here and the reported one, were run 50 times each against one broker, 150 of 150 passed, and
every repetition emitted the bounded wait.

Session id: cron:clickhouse-review-slot-8:20260824-045600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The losing interleaving is forced by suspending the consumer channel's broker-side process until its channel.close arrives, then releasing it 300ms later: 6/6 leaked on the base binary, 6/6 deleted with the fix. With no forcing the same fixture is 3/3 deleted on base, so the forcing and not the fixture causes the leak. The DETACH-after-failed-TRUNCATE deletion needs no forcing at all: 5/5 destroyed without the gate fix, 10/10 kept with it.
b Root cause explained? Yes. shutdown() sent channel.close on the consumer channel and immediately issued queue.delete(ifunused) on a different channel. AMQP orders method completion per channel only, so the broker could evaluate the deletion while the consumer was still registered, and a classic queue answers PRECONDITION_FAILED - queue '...' in use (rabbit_amqqueue_process.erl:1484). The queues are durable and not autodelete, so the leak was permanent. Separately, shutdown() ignored its is_drop argument and gated the cleanup only on a sticky flag that checkTableCanBeDropped sets before the statement it guards can fail, so a table left alive by a failed TRUNCATE lost its queues on a later DETACH.
c Fix matches root cause? Yes. It installs the missing ordering edge: the broker deregisters a channel's consumers while handling its channel.close and before answering it (rabbit_channel.erl:1144-1157, via a synchronous notify_down_all), so awaiting that answer is exactly the guarantee the deletion needs. No timeout was raised, no test weakened, and the deletion is still a single ifunused attempt. The gate now reads both facts that decide the question, is_drop && drop_table, rather than guarding the deletion site.
d Test intent preserved / new tests added? Yes. test_rabbitmq_drop_table_properly and its 404-only bounded poll from #114269 are untouched. One new parallel-safe integration test asserts the ordering and still ends on the 404 passive declare, so "reported deleted" cannot pass for "really gone". A second new integration test asserts that a DETACH after a failed TRUNCATE keeps the queue, checking both that no deletion was logged and that a passive declare on a fresh channel still succeeds. One new gtest covers the loop-clock refresh that the bounded wait depends on.
e Both directions demonstrated? Yes. The new test fails on the base binary with DROP TABLE deleted the queue without awaiting the consumer channel close and passes with the fix. Arm B is 6/6 leaked vs 6/6 deleted. On the fix the log shows the close answered at +304ms and the deletion succeeding 6ms later. Each part of the change also has its own arm: removing the ordering wait leaves the deletion unconfirmed and the queue present (5/5), removing only the bounded wait's use of the timed loop trips the new ordering assertion (5/5), removing the clock refresh makes the new gtest measure a 0ms wait against a 400ms floor (5/5), and reverting the is_drop gate destroys the queue together with its unconsumed message on a table nobody dropped (5/5, Successfully deleted queue ..., messages contained 1). The full suite is 10/10 and 15/15 green.
f Fix is general across code paths? Yes. The wait covers every consumer, not the first; it is skipped when the user owns the queues (rabbitmq_queue_consume) and when there is no connection, since nothing will be deleted or awaited; it is not gated on subscription state, because a subscription in flight is still a subscription. RabbitMQProducer::finish already awaited its own close, and that asymmetry was the bug. Kafka and NATS do not use AMQP-CPP. The other is_drop = true callers were enumerated: neither TemporaryTableHolder's destructor nor DatabaseReplicated's recovery drop latches the flag, which is why the fix conjoins the two conditions instead of replacing one with the other, making it a strict subset of the previous behaviour.
g Fix generalizes across inputs (params/datatypes/wrappers)? No data path is touched, so type wrappers do not apply. The parameters that matter were exercised: rabbitmq_num_consumers 1/2/4/8/16, rabbitmq_num_queues 1/2/4, shared and unshared rabbitmq_queue_base, nacking and not, DROP and DETACH, healthy and wedged channels. Boundaries: no channel at all, zero consumers, and a callback arriving after the bound has expired. For the cleanup gate the axis is the shutdown path rather than a datatype: real DROP, DETACH, server shutdown, and DETACH after either a failed TRUNCATE or a failed dependency check.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is added and no default changes, so no SettingsChangesHistory.cpp entry is needed. The only observable changes are that a dropped table's queues are now actually deleted, that a table whose channel cannot be closed adds at most the small bound to its DROP TABLE, and that a non-drop shutdown no longer deletes queues. The gate change only ever removes deletions, so it cannot break an existing setup.
i Invariants and contracts preserved? Yes. The wait runs on the shutdown path inside the existing try/catch and cannot throw, so DROP TABLE still succeeds when the bound expires. The close state is a shared_ptr captured by value into both callbacks and guarded by an abandoned flag, so a callback dispatched after the wait was abandoned cannot touch a destroyed consumer. Total elapsed time is bounded across loop re-entries, which are needed because each completing close stops the loop. shutdown() stays idempotent: the shutdown_called exchange precedes the gate and is untouched, and the connection teardown after the gate is unchanged, so no path loses its cleanup.

Session id: cron:clickhouse-impl-slot-6:20260824-022400

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [43c1503]

Summary: ✅


AI Review

Summary

This PR fixes the RabbitMQ shutdown ordering around DROP TABLE: it waits for the consumer channels' channel.close replies before issuing queue.delete, and it narrows queue cleanup to real drop paths so a failed TRUNCATE no longer makes a later DETACH delete durable queues. The current diff and the focused regression coverage match that contract, and I did not find an unresolved correctness, lifecycle, test-evidence, or PR-metadata issue in the current revision.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 53/62 (85.48%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @antaljanosbenjamin, could you review this? DROP TABLE sent channel.close on the consumer channels and immediately issued queue.delete with ifunused on a separate channel, and AMQP orders method completion per channel only, so the broker could still see a registered consumer and refuse the deletion, leaking the durable queue; this waits for the broker to answer those closes first, on a dropped table only, and also requires shutdown its own drop argument so a failed TRUNCATE latching the internal drop flag no longer costs a later DETACH its queues.

@PedroTadim

Copy link
Copy Markdown
Member

cc @pamarcos nice for you when you return!

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 43c1503aa with master 4faa0468e (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
Binary Master PR Δ
programs/clickhouse-stripped 706.02 MiB 703.01 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -1.6 s (-5%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 353b58c2-8021-4713-a3b2-711146d2caf7
  • MIRAI run: da6c349e-28bb-4d9b-96ff-be4188835311
  • PR check IDs:
    • clickbench_110208_1787880066
    • clickbench_110369_1787880092
    • clickbench_110471_1787880117
    • tpch_adapted_1_official_110485_1787880118
    • tpch_adapted_1_official_110686_1787880139
    • tpch_adapted_1_official_110788_1787880146

@antaljanosbenjamin antaljanosbenjamin self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Sep 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 720a9a0 Sep 20, 2026
187 of 188 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
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-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants