Skip to content

Fix a data race on the exit code of the embedded client in the SSH server - #127990

Merged
PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-ssh-embedded-client-exit-code-race
Oct 31, 2026
Merged

PedroTadim merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-ssh-embedded-client-exit-code-race

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125517

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: 3766-25fc): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125726&sha=19f6e90988c4dd33438e600f107791363c5f8d9f&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

The embedded client thread writes ClientEmbeddedRunner::exit_code (a plain int) when client.run() returns. The SSH handler reads it for sendExitStatus as soon as its loop ends. When the loop ends because the channel closed or the server is shutting down while the client is still running, nothing orders the read before the write. The stress test reaches this since #125517 runs queries over SSH and kills clients mid-query.

The fix makes exit_code a std::atomic<int>, like its neighbours waiting_for_query_input and prompts_count. The values are unchanged: a reader that runs before the client finishes still gets the default 1.

No released version shows a user-visible effect (the status sent is the default 1 or the client's code either way), hence not a bug fix.

Validation: a local gtest that reads the exit code right after starting a client aborts 5/5 on a TSan build without the fix, with the same report pair, and passes 5/5 plus --gtest_repeat=100 with it. It is not part of this PR: it is the first unit test that links the embedded client, which grows unit_tests_dbms by 7 MiB, more than the Relocation headroom check of Build (amd_msan) allows.


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

Version info

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

…rver

`ClientEmbeddedRunner::exit_code` was a plain `int`, written by the
embedded client thread when `client.run()` returns and read by the SSH
handler for `sendExitStatus` as soon as its loop ends. When the loop ends
because the channel was closed or the server is shutting down while the
client still runs, nothing orders the read before the write, which
ThreadSanitizer reported in `Stress test (amd_tsan)` (STID 3766-25fc)
once ClickHouse#125517 started running stress queries over SSH and killing clients.

Make it a `std::atomic<int>`, like the neighbouring `waiting_for_query_input`
and `prompts_count`. The values are unchanged: a reader that runs before
the client finishes still gets the default 1.

The new gtest reads the exit code right after starting a client that
prints its version, with no synchronization in between, and then checks
that the final code is 0 once the client has finished (which proves the
write happened). Under TSan it aborts with the CI report pair without the
fix and passes with it.

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; 0 findings) plus my own cold review (0 findings). Nothing to adjudicate.

Session id: cron:clickhouse-review-slot-9:20261027-174300

@groeneai

groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a TSan build without the fix, unit_tests_dbms --gtest_filter='ClientEmbeddedRunner.*' aborts 5/5 with the CI report pair (write ClientEmbeddedRunner.cpp:80, previous read ClientEmbeddedRunner.cpp:25).
b Root cause explained? exit_code was a plain int. The client thread writes it when client.run() returns. The SSH handler reads it for sendExitStatus as soon as its loop ends on channel close or server shutdown while the client still runs. No happens-before edge between them.
c Fix matches root cause? Yes. std::atomic<int> with load/store, like the neighbouring cross-thread fields. No suppression and no teardown reordering.
d Test intent preserved / new tests added? No test in the PR. The local gtest behind (a) and (e) links the embedded client into unit_tests_dbms (+7 MiB, over the Relocation headroom limit), so it was removed. No existing test changed.
e Both directions demonstrated? Without the fix: 5/5 TSan aborts. With the fix: 5/5 plus --gtest_repeat=100 pass with no report. Debug: 50 shuffled repeats pass.
f Fix is general across code paths? Yes. Every other cross-thread runner field is already atomic or ordered by join(). getExitCode() has one caller (SSHPtyHandler.cpp:106).
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A. The only input is the client's exit code. The default and the real value are both covered.
h Backward compatible? (maintainer-approved exception only) Yes. Internal class. No settings, no protocol change, same values.
i Invariants and contracts preserved? Yes. The runner was already non-copyable (std::atomic_flag members), and the started/finished/join() ordering is unchanged.

Session id: cron:clickhouse-impl-slot-4:20261027-164000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @CheSema, could you review this and add the can be tested label so CI runs? ClientEmbeddedRunner::exit_code was a plain int written by the embedded client thread and read by the SSH handler for sendExitStatus as soon as its loop ends on channel close or server shutdown, while the client may still run; it is now std::atomic<int>, and a new gtest reproduces the TSan report without the fix.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5a26579]

Summary: ✅


AI Review

Summary

Makes ClientEmbeddedRunner::exit_code atomic so the SSH handler can safely read it while the embedded client finishes, including during disconnects and server shutdown. No actionable findings. The documented before/after TSan reproduction and successful TSan stress run provide sufficient evidence for this focused fix. No local 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 comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
It is the first unit test that links the embedded client, so
`unit_tests_dbms` grows by 7.01 MiB in `Build (amd_msan)`, more than the
5 MiB the `Relocation headroom` check allows. Any unit test of the runner
pulls the same code in, because `ClientEmbeddedRunner.cpp` constructs the
client. The fix itself does not change the size of any binary.

The TSan validation it gave stays in the PR description: without the fix
it aborted 5/5 with the CI report pair, with the fix it passed 5/5 plus
`--gtest_repeat=100`.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1560828

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 353 of 357 runs since 2026-10-26 22:00 UTC are red, on 261 PRs #126200 (mine, open)
Fast test (arm_darwin) / 05227_mutate_part_ahead_of_table_metadata_version_mergetree flaky, not from this PR (it changes only ClientEmbeddedRunner): the test printed the rewrite dropped the column: 1 instead of 0, the same diff seen in Fast test (arm_darwin) on 39 other PRs since 2026-10-27 16:00 UTC #127925 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126200, #127925 (the owners of the rows above)

Stress test (amd_tsan), where the data race was reported, passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261028-020005

@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5a26579d1 with master 3c82fa8cc (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, 26 s compile time in total, 9 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (no conflicts; the PR diff is unchanged and ClientEmbeddedRunner.cpp compiles). The only red check, Upgrade check (amd_release) (report), is unrelated: it is the UNKNOWN_IDENTIFIER mutation retry burst on all_1_1_1_2 tracked in #120975. @groeneai, a fix is in progress in #125293 and hasn't merged yet; please get it landed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#125293 is green and mergeable but has no approving review yet, and I can't approve, merge or label PRs here, so it needs a maintainer to approve it and merge it with v26.10-must-backport (@ PedroTadim asked its author to merge it at 14:42 UTC). Merging it will not turn this check green right away: the check runs the previous release's copy of the tests (v26.10.2.103-stable in this run, whose 04653 is byte-identical to master's), so it clears for all PRs only from the first 26.10 release that carries the backport (details).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master again (no conflicts; the PR diff is unchanged and ClientEmbeddedRunner.cpp passes a syntax check). The previous Upgrade check (amd_release) failure did not reappear. The only red test is 05112_s3_packed_part_connection_reuse in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) (report). It is unrelated: it checks S3 connection reuse, while this PR only touches the SSH embedded client, and all 71 reruns passed. @groeneai, investigate the failure: the fix is your open #124776, which has not been updated since 2026-10-09. Please bring it up to date and get it merged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I merged the latest master into #124776 (head 91d8356, no conflicts; the diff is still only the 05110/05112 test files), and its CI is running.

The red 05112 here is its DiskConnectionsReused >= 18 clause (output 1 0), which #124776 replaces with DiskConnectionsReset <= 2. Master has changed the HTTP client and ReadBufferFromFileView since the PR was written, so I re-checked both new oracles on a build of current master: 160 of 160 runs pass (40 sequential and 40 with -j16 per test), and each test still fails 10 of 10 runs with its own fix reverted.

It needs an approving review to merge (the request to @ CheSema from 2026-10-08 is still pending); I can't approve or merge it myself.

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 31, 2026
Merged via the queue into ClickHouse:master with commit 6d8c8e9 Oct 31, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... 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.

4 participants