Skip to content

Fix RabbitMQ tables inserting received messages twice after a reconnect - #125105

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
comino:rabbitmq-clear-stale-deliveries
Oct 19, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
comino:rabbitmq-clear-stale-deliveries

Conversation

@comino

@comino comino commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #124655

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 RabbitMQ tables inserting most of the already received but unprocessed messages twice after a lost connection or channel, sometimes followed by unknown delivery tag channel errors.

Description

Impact: one lost connection to the broker makes a RabbitMQ table insert the messages its consumers had already received a second time: 9000 of 10000 rows in the test below, on master and on 26.9. Broker restarts, network blips and missed heartbeats are routine in production, and each of them can silently duplicate up to the whole received backlog in the target tables.

Fix: clear the consumer's queue of received messages when its channel is replaced. Nothing is acked or rejected, so nothing is lost: the broker redelivers the messages of the closed channel once. Channel callbacks capture a channel generation, check it under a mutex that updateChannel also holds while it clears the queue, and do nothing once their channel is replaced. A late delivery from the old channel, including one already running in the background loop, therefore cannot refill the queue, and a block can no longer mix two channels. Small enough to backport.

Proof: test_rabbitmq_reconnect_drops_stale_deliveries queues 10000 messages, closes the connections with rabbitmqctl close_all_connections while most of them are still in the consumer's queue, and waits until the broker holds nothing and no rows are added. It fails on master (9000 and 9100 duplicates in two runs) and on every other build without this change, also with #124655; it passes 10 of 10 runs with it. The rest of test_storage_rabbitmq passes on a minimal local build, except two tests that need Arrow or the JSON type and fail on master too. One-minute repro on the official 26.9 image: ./stale-deliveries.sh in https://gist.github.com/comino/9f0f008a24d0cbf9606b36a5426c4a6c (26.9: about 9000 duplicates; a build of this branch: 100, the block that was in flight, which comes back as before).

Mechanism and scope

After a lost connection, streamToViews gives every consumer a new channel (after a channel error, only the failed one), but deliveries already received on the old channel stay in the consumer's queue. They are inserted, cannot be acked (delivery tags are per channel), and the broker redelivers them, so they are inserted twice. A block that holds old and new deliveries also commits the largest tag (old channel) with the channel id of its last message (new channel); the ack check passes, and if the new channel has not delivered that many messages yet, the broker answers PRECONDITION_FAILED - unknown delivery tag, closes the new channel and redelivers its whole window, and the cycle can repeat.

Not changed here: a block that is being read when the connection drops still takes deliveries of the dead channel until it is full or its flush interval ends, and those come back too; with a large block size that can be many. A direct SELECT reconnects without replacing channels.

How it was found, server log

Found while benchmarking #124655 (2M-message backlog, 4 consumers × 4 queues, builds that include #124655, which master needs to drain a backlog that large): about 1 in 6 runs lost the connection once (cause not known yet) and then had 10–90k duplicates and unknown delivery tag channel errors. With this change such runs had 3–25k duplicates (4 runs), the blocks that were inserted but not yet acked.

Server log of one such run: connection lost → Connection restored, updating channels → one second later Consumer committed messages with deliveryTags up to 134253 on channel 4_1_… → broker: operation basic.ack caused a channel exception precondition_failed: unknown delivery tag 134253.

If the new channel has already delivered as many messages as the stale tag, the broker accepts the bad ack instead, and it acks deliveries that are not inserted yet; they are lost if the server stops before inserting them.

cc @kssenii


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

Version info

  • Merged into: 26.11.1.159-master (included in 26.11 and later)

After a channel or connection error the consumer gets a new channel, but
messages already received on the old one stayed in the queue. They can no
longer be acked (delivery tags are per channel) and the broker redelivers
them, so they were inserted twice, and a block could mix tags of both
channels in one commit. Clear them when the channel is replaced.
@clickhouse-gh clickhouse-gh Bot added comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). external Author is not a member of the ClickHouse organization labels Oct 10, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 11, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4d28d9b]

Summary: ✅


AI Review

Summary

The PR prevents queued RabbitMQ deliveries from being inserted again after channel replacement by clearing stale deliveries and serializing generation checks with enqueueing. The previous findings are addressed in the current code, and no new actionable findings remain.

Final Verdict

Status: ✅ Approve.

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

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4d28d9b81 with master 0a3052562 (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, 23 s compile time in total, 9 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits October 12, 2026 19:19
…ale_deliveries` by two blocks

With one consumer, only the block in flight when the connection dropped is
replayed legitimately; a second block is possible only if the connection drops
while that block is being acked. Allowing up to 10% of the backlog would let a
regression that replays several stale blocks pass.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failures below and provide fixes in separate PRs. If a fix is already in progress, link it here. Neither is related to this RabbitMQ change.

test_database_disk::test_copy_of_temporary_table_under_unrelated_name was fixed by #125292, and this branch now includes it after a master merge.

@groeneai

Copy link
Copy Markdown
Collaborator

05210_lightweight_update_materialized_cte_in_ignore: the fix is already in progress, #123121 (mine, open). This run has the same signature as the other ParallelReplicas failures: Code: 60 ... Unknown table expression identifier '_materialized_cte_c_9427038037214177124' (query 26), and 1 of 114 reruns failed. It is the #112642 race: with a local plan, the query sent to the replicas can start before the initiator has materialized the CTE.

clickbench_parquet_short query 5 (the UserID = 435090932899640449 point lookup) is not a regression in this PR. The reference here is the merge base ae0dac42, so the two binaries differ only by the RabbitMQ change. Two Parquet changes on master made this query 2.4-2.9x faster: #123579 (Oct 3) and #120907 (Oct 7) moved its reference time from ~9.1 ms to ~3.8 ms on arm (~12.3 ms to ~4.2 ms on amd). At ~4 ms, 1-2 ms of jitter is 25-50% and crosses its threshold (here 0.004 s -> 0.005 s, +0.325 vs 0.29). Since Oct 11 it has been flagged 4 times in ~650 arm runs, on four unrelated changes (master #124868, #110886, #119976, this PR), and never in the 3 weeks before.

I'll send a separate PR that makes this query robust to that jitter and link it here.

AMQP-CPP can dispatch callbacks of the old channel after `updateChannel`.
A late `onReceived` could refill `received` after it was cleared and tag
the stale delivery with the new `channel_id`. Capture a per-channel
generation by value in every channel callback and return early when the
channel was replaced.

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

Copy link
Copy Markdown
Collaborator

clickbench_parquet_short query 5: #125513. The cause turned out not to be jitter: each perf server generates its own copy of the fixture, and a bloom filter false positive in one copy makes that server decode one UserID dictionary page on every run. The PR makes both copies identical.

…annel`

`streamToViews` only asks the background loop to stop before replacing the
channels and does not wait for it, so an `onReceived` callback of the old
channel that had already passed the generation check could push a stale
delivery after `updateChannel` cleared `received`.

The channel callbacks now check the generation and touch the consumer state
under `channel_mutex`, and `updateChannel` bumps the generation and clears
`received` under the same mutex. A callback of the old channel either
completes before the queue is cleared or sees the new generation and does
nothing. `onReceived` waits for space in the queue on a condition variable
with the mutex released, so a full queue cannot block `updateChannel`; the
wait ends when the channel is replaced or the consumer is stopped. The mutex
is recursive because AMQP-CPP calls the error callback of a failed `consume`
right away, from `subscribe` inside `onReady`.

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

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. 05210_lightweight_update_materialized_cte_in_ignore is tracked by #123121, and the clickbench_parquet_short query 5 fixture is fixed in #125513. Neither failure is related to this PR. I also pushed 6c0ff68, which closes the remaining reconnect race the AI review raised: onReceived now checks the channel generation and pushes under the same mutex that updateChannel holds while it clears the queue.

alexey-milovidov and others added 2 commits October 14, 2026 04:21
# Conflicts:
#	tests/integration/test_storage_rabbitmq/test.py
…sumer

A callback woken up by `stop` could still push a delivery if the queue had space. Such a delivery is never read
and is redelivered by the broker anyway.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125105&sha=c60fb087b8648d5380c3abcb74bae14cc55d2421&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 (Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan, STID 2467-34d3) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is not related to this RabbitMQ change: CIDB shows the same error in about 20 unrelated PRs today alone. The other red jobs are unstable queries in Performance Comparison (iceberg_suite_s3_rw_features, set_index), which this PR does not touch.

@groeneai

Copy link
Copy Markdown
Collaborator

STID 2467-34d3: the fix is already in progress, #125043 (mine, open). I ran the exact fatal query, DELETE FROM t_lwu_cte_in_ignore WHERE ignore(id IN (WITH c AS MATERIALIZED (...) SELECT a.x FROM c AS a, c AS b GROUP BY ALL WINDOW w_fuzz_1015 AS () LIMIT -9223372036854775808)), on the 05210 table. It aborts 3/3 with the CI build of c60fb08 and with master d245b786, and passes 3/3 with the CI build of #125043. The trigger is the negative LIMIT: its transform starts reading before any output asks for data. The WINDOW clause is incidental (LIMIT -2 without it aborts too, LIMIT 2 does not). #125043's CI is green and it is waiting for review.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. The AST fuzzer failure (STID 2467-34d3) is tracked by #125043. I merged the latest master (e46d3cf) to refresh CI; the merge was clean, and the RabbitMQ objects compile. The red Performance Comparison shards (arm 2/6 and 6/6) only show unstable or too-long queries, and their CIDB upload failed. They are unrelated to this change.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The only red checks on e46d3cf were the Performance Comparison (arm_release, master_head, */6) shards, which hit the 7200 s job timeout (the CI logs host also returned TOO_MANY_SIMULTANEOUS_QUERIES). On 2026-10-16 the same shards ended in error for 46 PRs, so this is a CI infrastructure problem and has nothing to do with this RabbitMQ change. I merged the latest master (4d28d9b) to rerun CI. The merge was clean, the PR diff is unchanged, and RabbitMQConsumer.cpp compiles.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 18, 2026
Merged via the queue into ClickHouse:master with commit c22dc6a Oct 19, 2026
177 of 178 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 Oct 19, 2026
comino added a commit to comino/ClickHouse that referenced this pull request Oct 19, 2026
The prefetch window bounds the deliveries of a channel to num_queues * prefetch_count <= queue_size, so the queue never fills and ClickHouse#125105's wait for space never blocks the loop.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 28, 2026
…es without rabbitmqctl

`rabbitmqctl close_all_connections test` timed out after 300 s in 3 runs of
`Integration tests (arm_binary, 2/4)` (master 524a0c2, ClickHouse#127389, ClickHouse#126642). The
close never reached the broker: no `Closing connection ... because "test"` line
in its log, and ClickHouse's AMQP connection stayed open for 5 minutes until the
test dropped the database. The broker passed its `rabbitmq-diagnostics ping`
healthcheck 29/29 times in each window, so a new CLI process again never got to
its RPC, like the `list_queues` call before.

Bounding the call and asking again does not fit here: the drop must happen while
most of the backlog is still queued (`view_rows() < messages_num // 2`), which
leaves about 9 s after the 500-row trigger at ~490 rows/s, and a timed-out
`docker exec` leaves the CLI running in the container, where a late close would
force a second reconnect.

Close through the management API instead:
`DELETE /api/connections/username/root` with `X-Reason: test` reaches the same
`rabbit_networking:close_connection(Pid, "test")` for every connection of the
broker's only user, synchronously before the 204 reply, and starts no CLI process.

Validated: an injected never-returning close fails the unfixed test after 300 s
with the CI error; without the DELETE the test fails waiting for the reconnect;
the pre-ClickHouse#125105 binary still fails on the duplicates bound (9500, 9400); 50/50
runs pass with `204` (p50 0.1 s) and ClickHouse logs `CONNECTION_FORCED - test`
then `Connection restored`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 31, 2026
…_drops_stale_deliveries

The drain loop started a new `rabbitmqctl list_queues` (an Erlang CLI VM via
`docker exec`) on every iteration, 15-22 times per run on arm, and waited up to
the harness default of 300 s for each without a retry. In 3 runs of
`Integration tests (arm_binary, 2/4)` on 2026-10-19 one call never returned and
printed nothing, while ClickHouse had inserted all 10100 rows and the broker
passed its `rabbitmq-diagnostics ping` healthcheck 29/29 times in that window,
so the loop's own 180 s deadline was never checked.

Ask the broker only once the row count has been stable for 3 s (same exit
condition, about one call per run), and abandon a call after 30 s and ask again
under the existing deadline. Only a timeout is treated as "not drained yet".
`close_all_connections` is unchanged: a retry could force a second reconnect.

Validated with an injected never-returning call (unfixed: fails after 300 s with
the CI error; fixed: passes 2/2 with one abandoned call), 50/50 normal runs, and
the pre-ClickHouse#125105 binary, which still fails on the duplicates bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@comino
comino deleted the rabbitmq-clear-stale-deliveries branch November 13, 2026 16:15
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). external Author is not a member of the ClickHouse organization 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.

4 participants