Skip to content

Fix a data race on the active connection count of remote query connections - #131436

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-tsan-race-active-connection-count
Nov 16, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-tsan-race-active-connection-count

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131213

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

Stress test (amd_tsan) reported ThreadSanitizer: data race (STID: 4761-4859): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131213&sha=84f0cdd8256b3471d86053f28bac4788b2bbcfde&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

With async_socket_for_remote = 0, RemoteQueryExecutor::read releases was_cancelled_mutex before connections->receivePacket() (since #107888). When LIMIT closes the port, RemoteSource::onUpdatePorts calls finish() on another thread, and its drain loop reads hasActiveConnections() with no lock while the reader's receivePacket() decrements active_connection_count on EndOfStream under cancel_mutex. The comment on MultiplexedConnections::hasActiveConnections ("sendCancel() does not change the state of the replicas") no longer covers that. HedgedConnections has the same unlocked accessor.

The fix makes the top-level counter std::atomic<size_t> in both classes. No value changes: the counter only guards the drain loop, and receivePacket() re-checks it under cancel_mutex.

No released version shows a user-visible effect (the query result is the same either way), hence not a bug fix.

Validation: with temporary local instrumentation that forces the interleaving (reader waits before the EndOfStream receive until finish has sent the cancel), a TSan build reports the CI pair 10/10 without the fix (5 MultiplexedConnections, 5 HedgedConnections) and 0/10 with it. The 36 stateless tests that use async_socket_for_remote = 0 or use_hedged_requests give identical results with and without the fix over 5 randomized runs (3 that need CI-only setup fail on both). No test is added: a deterministic one would have to hold a pipeline thread inside RemoteSource::work, and the failpoint tests for this path were removed in #125005.


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

Version info

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

…tions

With `async_socket_for_remote = 0`, `RemoteQueryExecutor::read` releases
`was_cancelled_mutex` before `connections->receivePacket()` (since
58718f2 in ClickHouse#107888, which fixed a livelock on detach). When `LIMIT`
closes the port, `RemoteSource::onUpdatePorts` calls `finish()` on another
executor thread, and its drain loop reads `hasActiveConnections()` without a
lock while the reader's `receivePacket()` decrements `active_connection_count`
on `EndOfStream` under `cancel_mutex` only. TSan reports it as STID 4761-4859
(Stress test (amd_tsan)). The comment that justified the lock-free accessor
("sendCancel() does not change the state of the replicas") did not cover this
writer. `HedgedConnections` has the same accessor and the same writer
(`finishProcessReplica`).

Make the top-level counter `std::atomic<size_t>` in both classes. This only
makes the existing lock-free read defined: no value changes, because the
counter just guards the drain loop and the next `receivePacket()` re-checks it
under `cancel_mutex` and returns `EndOfStream` once the query is cancelled.
`HedgedConnections::OffsetState::active_connection_count` stays a plain
`size_t`: it is never read by `hasActiveConnections()`.

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; 1 finding) plus my own cold review (1 finding, the same one).

# Sev Finding Verdict Evidence / action
1 💡 The class doc of MultiplexedConnections (MultiplexedConnections.h:14-16) still says every method except sendCancel runs on one thread AGREE, not changed Pre-existing: inaccurate since #107888 let finish() call receivePacket() from the onUpdatePorts thread; the line is outside this diff. The real invariant is stated on the active_connection_count member.

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

Session id: cron:clickhouse-review-slot-8:20261113-205100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A TSan build with temporary local instrumentation (relaxed-atomic handshake: the reader waits before its EndOfStream receive until finish has sent the cancel) reports the CI pair on every run of a LIMIT 1 query over remote() with async_socket_for_remote = 0.
b Root cause explained? Sync read() releases was_cancelled_mutex before receivePacket() (since #107888), so onUpdatePorts -> finish() reads active_connection_count without a lock while the reader decrements it under cancel_mutex on EndOfStream.
c Fix matches root cause? Yes. The counter is the only connection state finish reads without cancel_mutex; making it atomic makes that read defined. No value, lock or control flow changes.
d Test intent preserved / new tests added? No test added: a deterministic test would have to hold a pipeline thread inside RemoteSource::work. Validated by the local TSan A/B.
e Both directions demonstrated? Yes. Without the fix 10/10 reports (5 MultiplexedConnections, 5 HedgedConnections), with it 0/10; each run confirmed to reach the interleaving.
f Fix is general across code paths? Yes. Both IConnections implementations are fixed; every other call finish makes on the connections takes cancel_mutex, and the async path is serialized by was_cancelled_mutex.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for data types; covered use_hedged_requests 0 and 1.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the classes were already non-copyable.
i Invariants and contracts preserved? Yes. Every existing access keeps its meaning through std::atomic operators; the locks guarding the counter and their order are unchanged.

Session id: cron:clickhouse-impl-slot-5:20261113-190300

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5ca9c7]

Summary: ✅


AI Review

Summary

Makes active_connection_count atomic in MultiplexedConnections and HedgedConnections, fixing the race between synchronous packet receipt and cancellation draining in RemoteQueryExecutor::finish. No actionable findings at commit c5ca9c765df939623dd01e857394a91c1cfa9ee7.

Validation includes the author's documented forced-interleaving TSan comparison: 10/10 race reports before the fix and 0/10 afterward across both implementations. No builds or tests were run during this review.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c5ca9c765 with master 6b2d25cb5 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.57, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.3 s 9.3 s +5.8 s (+162%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.5 s +5.5 s (+272%)
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

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Nov 13, 2026
@PedroTadim PedroTadim self-assigned this Nov 15, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 16, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@mstetsyuk this seems to have been introduced by #107888, I think this fix is right

Merged via the queue into ClickHouse:master with commit 7074838 Nov 16, 2026
606 of 608 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 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-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants