Skip to content

Fix a data race between the RabbitMQ streaming task's reconnect and the looping task - #133632

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-rabbitmq-reconnect-vs-looping-task
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-rabbitmq-reconnect-vs-looping-task

Conversation

@groeneai

@groeneai groeneai commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131355

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

La Casa Del Dolor (amd_tsan) reported ThreadSanitizer: data race (STID: 3628-42d9): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122537&sha=092a5cded0a8ede0c5ab2a798a094f10ceaccc45&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29

The AMQP connection and its libuv loop are single-threaded, and a direct SELECT leaves the looping task running that loop. At the start of every streaming cycle StorageRabbitMQ::threadFunc called connection->isConnected() || connection->reconnect() without stopping the looping task, unlike read() and streamToViews(). When the broker dropped the connection during a direct SELECT (La Casa does it at random since #131994), the streaming task closed and replaced the AMQP::TcpConnection while the looping task was still processing the loss on it. Since #131355 the loop sleeps in the poller, so on master that reconnect also cannot complete until the SELECT ends.

The fix adds restoreConnection(): stop the loop, wait for the looping task to finish, reconnect, as unbindExchange() already does. threadFunc() and read() call it under loop_mutex, so neither can restart the loop in between, and both check the handler's atomic connectionRunning() instead of reading AMQP state while the loop may run.

Not changed: with rabbitmq_commit_on_select = 1 a direct SELECT still sends its ack from the query thread while the loop may run, a separate pre-existing path.

No stable release shows a user-visible effect: the delayed reconnect needs #131355, which is in the 26.11 branch but in no stable release yet, hence not a bug fix.

Validation: the new integration test test_rabbitmq_reconnect_during_direct_select drops the connection through the management API during a 20 s direct SELECT and requires a reconnect within 10 s. Without the fix it fails 4/4 on a debug build, and the CI TSan binary reports the same race pair. With the fix it passes 11/11 on debug and 3/3 on TSan without reports; test_system_stop.py and the other reconnect and direct-select tests pass on both builds.


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

…he looping task

A direct SELECT leaves the looping task running the event loop of the
table's connection. StorageRabbitMQ::threadFunc checked isConnected() and
called reconnect() at the start of every streaming cycle without stopping
that task, unlike read() and streamToViews(). After the broker dropped the
connection, the streaming task closed and replaced the AMQP::TcpConnection
while the looping task was still processing the loss on it (TSan STID
3628-42d9, La Casa Del Dolor). Since ClickHouse#131355 the loop blocks in the
poller, so that reconnect also could not complete until the SELECT ended.

restoreConnection() stops the loop, waits for the looping task and then
reconnects, as unbindExchange() already does. threadFunc() and read() call
it under loop_mutex, so the other one cannot restart the loop in between,
and both test the handler's atomic connectionRunning() instead of reading
AMQP state while the loop may run.

The new integration test drops the connection during a long direct SELECT
and requires a reconnect within 10 s.

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

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

Pre-publication review by an independent model (engine: codex; 3 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ After a reconnect during a direct SELECT the looping task stays deactivated until the query ends, so the new connection gets no deliveries or heartbeats (StorageRabbitMQ.cpp:457-462, :1345-1396) DISAGREE No consumer is subscribed on the new connection: RabbitMQConsumer::updateChannel, the only subscribe path, runs only in initRabbitMQ (:567) and streamToViews (:1546, :1567), so the running query's consumers stay on channels of the replaced connection whether the loop runs or not. An unserviced idle connection is also the normal state of a table without views or readers (threadFunc stops the loop at :1415-1416), and the next read() restarts the loop (:987).
2 ❌ streamToViews starts the loop and reconnects without loop_mutex, so if the last materialized view is dropped during a streaming cycle, a direct SELECT's restoreConnection can interleave with it (wait hangs, or the race comes back) DISAGREE (out of scope) No hang: a loop re-armed by streamToViews is stopped by streamToViews itself after its pipeline (:1530), which ends the wait. The remaining window needs the last view dropped during a cycle, a direct SELECT in that cycle and a broker disconnect at the same time; this PR does not change it (the old read() ran the same stop and reconnect sequence, streamToViews is untouched), and CI has not reported it. Not addressed here.
3 ⚠️ The test does not check that the loop resumes after the reconnect; asks for TSan evidence that removing only the deactivate() wait fails it DISAGREE Resuming the loop is not required (row 1). The test fails without the fix (4/4 on a master debug build, and the CI TSan binary reports the race) and passes with it (11/11 debug, 3/3 TSan, no reports). Without deactivate() only timing windows remain (the loop thread leaving uv_run, a queued looping task starting during the reconnect), which no deterministic test isolates; the join is the existing unbindExchange() idiom (:882-883).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261123-005000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_storage_rabbitmq/test.py::test_rabbitmq_reconnect_during_direct_select fails 4/4 on a master debug build (the reconnect cannot finish while the looping task sleeps in the poller), and the CI TSan binary of the report prints the race 1/1.
b Root cause explained? StorageRabbitMQ::threadFunc reconnected at cycle start without stopping the looping task that a direct SELECT keeps running, so RabbitMQConnection::reconnect closed and replaced the AMQP::TcpConnection while uv_run on the looping task processed the connection loss on it.
c Fix matches root cause? Yes. Both reconnect sites stop and join the looping task under loop_mutex before reconnecting (the unbindExchange() idiom), and decide by the handler's atomic connectionRunning(). No timeout, retry or guard.
d Test intent preserved / new tests added? New integration test test_rabbitmq_reconnect_during_direct_select; no existing test changed.
e Both directions demonstrated? Without the fix: 4/4 FAIL on debug, TSan report on the CI binary. With the fix: 11/11 PASS on debug, 3/3 PASS on TSan with 0 reports.
f Fix is general across code paths? threadFunc() and read() share the one helper; read()'s loop start decision reads atomics only. streamToViews(), shutdown() and unbindExchange() already stop the loop first; connectionFunc() runs before any loop exists; publishers own a separate connection without a looping task.
g Fix generalizes across inputs (params/datatypes/wrappers)? No type or format dimension. background_message_broker_schedule_pool_size = 1 covered by the single-worker tests of test_system_stop.py; several consumers share the same connection and loop, so the same path.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change; read() throws the same exception as before.
i Invariants and contracts preserved? Only the looping task drives the loop while it runs; the connection is replaced only after it finished. Lock order loop_mutex -> looping task -> connection mutex, the nesting read() already had; the looping task takes none of them, and shutdown's task_mutex is not taken. TSan shows no race and no lock-order inversion on the new test and test_system_stop.py.

Session id: cron:clickhouse-impl-slot-41:20261122-233301

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7cdc04c]

Summary: ✅


AI Review

Summary

Reviewed #133632 at 7cdc04cda2c7fdf597920a61a7a01eff2b2fd1ed, including all prior discussion. The change stops and waits for the RabbitMQ looping task before reconnecting, serializes the affected reconnect paths with loop_mutex, and adds regression coverage for a broker disconnect during a direct SELECT. No actionable findings remain for this change.

Missing context / blind spots
  • ⚠️ Integration tests were not rerun locally, and targeted integration CI is pending. The author reports that the regression fails without the fix and passes repeatedly on debug and TSan builds; completed targeted CI would independently confirm those results.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). can be tested Allows running workflows for external contributors labels Nov 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7cdc04cda with master 19f5e0ac8 (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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @pamarcos @alexey-milovidov

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-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants