Repository navigation
Fix clickhouse-client segfault in Connection::poll after sendQuery failure - #105386
Conversation
…ilure
clickhouse-client < big_insert.sql crashed with SIGSEGV at Address 0x108
inside ReadBufferFromPocoSocketChunked::poll when the INSERT query was
large enough that sendQuery failed mid-stream (e.g. server closed the
connection or the pipe broke). Reproduced deterministically by routing
the client through a TCP proxy that drops the connection after 200 KB.
Root cause: Connection::sendQuery registers a SCOPE_EXIT that calls
Connection::disconnect if the query did not complete. On a NetException
from a buffered write, the SCOPE_EXIT fires and resets `in` to nullptr.
The catch (NetException) block in ClientBase::processOrdinaryQuery then
calls receiveResult to drain the socket receive buffer, which calls
Connection::poll, which dereferences the now-null `in`.
The fix has two parts:
1. Make Connection::poll, hasReadPendingData, checkPacket and
receivePacketType null-safe (matching the existing guard in
Connection::receivePacket): throw a NetException when `in` is null
rather than crashing.
2. In ClientBase::processOrdinaryQuery's NetException catch, only
attempt the receive-buffer drain when connection->isConnected().
This preserves the original NetException (e.g. "Broken pipe")
instead of replacing it with "Connection terminated".
Closes ClickHouse#105292.
Pre-PR validation gatea) Deterministic repro? YES. A 50-line Python TCP proxy that closes the client→server stream after 200 KB reproduces SIGSEGV 100% of the time before the fix and 0% after. The same proxy is used as the regression test ( b) Root cause explained? YES. c) Fix matches root cause? YES. Two complementary changes:
d) Test intent preserved? / New test added? YES. No existing tests were weakened. Added e) Demonstrated in both directions?
f) Fix is general, not a narrow patch? YES. The fix covers ALL four sibling methods on
The "fix the symptom or the cause?" check: the root cause is the SCOPE_EXIT in Session: |
|
cc @azat @alexey-milovidov — could you review this? It addresses a SIGSEGV in clickhouse-client (Connection::poll dereferencing null in after SCOPE_EXIT-triggered disconnect in sendQuery). The receive-side methods now match the existing null guard in Connection::receivePacket, and processOrdinaryQuery skips the drain attempt when the connection is already gone so the original NetException is preserved. |
|
Workflow [PR], commit [07b70ac] Summary: ✅ AI ReviewSummaryThis PR adds a focused stateless regression test for the Final VerdictStatus: ✅ Approve |
CI feedback on PR ClickHouse#105386: 1. Style check failed: test file name contains the substring "fail" (ci/jobs/check_style.py:181 rejects any name with "fail" in it). 2. Bugfix validation passed on master HEAD without the fix, meaning the reproducer was not aggressive enough to trigger the crash in the CI environment. 3. Test number 04258 collides with PR ClickHouse#105387. Changes: - Rename `04258_client_segfault_insert_send_failure_105292.sh` to `04259_client_segfault_send_error_105292.sh` (drops the "failure" substring and avoids the 04258 collision). - Strengthen the TCP-proxy reproducer: * Increase INSERT VALUES payload from 20k to 200k rows (~40 MB) so the client write loop overflows any realistic loopback send buffer. * Set SO_LINGER with timeout 0 on the proxy sockets after the cutoff, forcing a TCP RST so the client's next write observes ECONNRESET immediately instead of waiting for the kernel to push out the auto-tuned send buffer. * Stop the server->client relay once the cutoff fires. Verified locally: * 10/10 OK against the fixed binary (~1.8s per run). * Deterministic SIGSEGV at Address 0x108 in ReadBufferFromPocoSocketChunked::poll when run against the pre-fix binary (matches the original crash signature).
|
Pushed fix-up commit ba7c137 addressing the CI feedback from the previous run:
Verified locally against the rebuilt binary:
PR description, root cause, and fix unchanged. Awaiting CI. |
| /// `in` can be null when `Connection::disconnect` was called from `sendQuery`'s | ||
| /// `SCOPE_EXIT` after a send failure. Surface as a network error rather than | ||
| /// dereferencing a null pointer. | ||
| if (!in) | ||
| throw NetException(ErrorCodes::NETWORK_ERROR, "Connection to {} is terminated", getDescription()); |
There was a problem hiding this comment.
The modification in the ClientBase::processOrdinaryQuery should be enough
Per @azat: drop the null-safety guards in Connection::poll, hasReadPendingData, checkPacket, receivePacketType. The only path that could reach them on a disconnected connection is ClientBase::receiveResult, called from processOrdinaryQuery's NetException catch block. The isConnected() guard there is sufficient. Defense-in-depth in Connection.cpp would silently mask any future misuse rather than failing loud. Per clickhouse-gh[bot]: assert the send-error path was actually exercised. Without this, a test that completed cleanly (proxy cutoff missed, buffer absorbed the INSERT) would pass and stop catching the bug. Now require CLIENT_EXIT != 0 and a NETWORK_ERROR / Broken pipe / Connection reset by peer marker in the client log. Also pass --send_logs_level=none to the proxied client so the connection close does not race with server-side log packets, which would otherwise land in the client's fatal-log file and unrelatedly fail the test under asan_ubsan / tsan. Local verification: 5/5 OK on debug build; deterministic SIGSEGV (Address 0x108, ReadBufferFromPocoSocketChunked::poll, ClientBase::receiveResult) when the ClientBase guard is reverted.
|
Reverted the null-safety guards in
So the Commit: c601560 |
|
Tightened the assertions in if [ "${CLIENT_EXIT}" = "0" ]; then
echo "BAD: proxy did not trigger the send-error path (CLIENT_EXIT=0)"
head -50 "${CLIENT_LOG}"
exit 1
fi
if ! grep -qE "NETWORK_ERROR|Broken pipe|Connection reset by peer" "${CLIENT_LOG}"; then
echo "BAD: no network-error marker in client output (CLIENT_EXIT=${CLIENT_EXIT})"
head -50 "${CLIENT_LOG}"
exit 1
fiNow the test fails unless the client both exits non-zero AND the log contains a network-error marker. A clean INSERT (proxy cutoff missed, send buffer absorbed the payload) will no longer pass. Also added |
| cutoff = int(sys.argv[3]) | ||
| port_file = sys.argv[4] | ||
|
|
||
| # Force an RST (TCP reset) on close so the client gets ECONNRESET on its |
There was a problem hiding this comment.
Can't we just use clickhouse-client with long list of Values and maybe some throttling?
This custom script bundled into .sh is hacky, at least it should be in a separate file, or better implement the first suggestion
Remember, this will be read by humans
|
at the server I see It looks like there are 2 separate issues:
|
|
@groeneai check CI failures. |
@azat: the inline Python proxy in the .sh was hacky. Moved it to `tests/queries/0_stateless/helpers/04260_client_segfault_proxy.py` and compacted the .sh comments. Made the proxy single-shot (one connection, then exits) so no external `kill -9` is needed, which also removes the "Killed" bash job-control notification that the runner reported as test stderr noise on `amd_tsan, s3` and `amd_tsan` (this is what was actually breaking the test in CI). The C++ fix in `ClientBase::processOrdinaryQuery` is unchanged. Renumbered to 04260 to avoid the collision with ClickHouse#105439's new `04259_count_distinct_optimization_nullable.sql` that just landed on master. Verified locally: pre-fix master binary deterministically SIGSEGVs at Address 0x108 in `ReadBufferFromPocoSocketChunked::poll`; the rebuilt binary with the fix passes 10/10 with empty stderr. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105386
|
Pre-PR validation gate (after fix-up df186d4):
|
|
@PedroTadim master merged into the branch as commit CI failure classification on the previous commit
Fix-up
Verified locally: 10/10 OK with empty stderr. |
|
@azat moved the Python proxy out of the On the "long Values + throttling" alternative: I traced the path the original den-crane reproducer uses. The server-side trigger is Also made the proxy single-shot so the test no longer needs |
|
@groeneai the |
Concurrent SELECT * FROM system.functions calls invoke FunctionNaiveBayesClassifier::create(context) for every function, which called NBModelRegistry::instance(context). When nb_models is absent from the config (the common case in CI), load() throws inside the Meyer's-singleton initialization. The C++ runtime then re-enters initialization on the next caller. TSan flags the second attempt's default-construction of models against the first attempt's exception-unwind destruction because __cxa_guard_abort is not consistently treated as a synchronization edge for the guarded object's memory. Replace the magic-static with std::mutex + std::optional<NBModelRegistry>. All access to the registry now goes through the mutex, so construction and exception-unwind destruction are happens-before ordered for any subsequent caller. Behavior is otherwise unchanged: failed load rethrows and leaves the optional empty so the next caller can retry, and once populated, the returned const reference is stable. Surfaced by BuzzHouse (amd_tsan) on PR #105386 as STID 0250-34ba. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105386&sha=ba7c1374c550b32153b098c286f7a49d30a45e67&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29 Co-authored-by: Claude <[email protected]>
@den-crane probably due to async INSERTs, do you have a stacktrace? |
|
@groeneai bug fix validation failed |
azat
left a comment
There was a problem hiding this comment.
In general looks good, but need to fix the test
| /// `Connection::sendQuery` resets `in` via its `SCOPE_EXIT` on send failure, so calling | ||
| /// `receiveResult` after that would dereference a null read buffer (issue #105292). | ||
| if (connection->isConnected()) | ||
| receiveResult(parsed_query, signals_before_stop, settings[Setting::partial_result_on_first_cancel]); |
There was a problem hiding this comment.
Will be superseeded by #105996
Let's wait until it will be merged and leave only test here
…92-client-segfault-connection-poll
…eded the fix Per @azat's directive (ClickHouse#105386 (comment)), PR ClickHouse#105996 ("Fix possible OOM due to a too-large string literal sent within the query", merged 2026-06-04T15:07:46Z) supersedes the source-code fix in this PR by adding a `Connection::ensureConnected()` helper and an early-return guard at the top of `ClientBase::receiveResult` for the disconnected case. Both halves together prevent the same segfault this PR was originally addressing. Drop the remaining `ClientBase.cpp` change (the `connection->isConnected()` guard inside the `processOrdinaryQuery` `NetException` catch block) — it is strictly subsumed by the new check in `receiveResult`. Keep the regression test as forward-looking coverage for issue ClickHouse#105292: - tests/queries/0_stateless/04319_client_segfault_send_error_105292.sh - tests/queries/0_stateless/04319_client_segfault_send_error_105292.reference - tests/queries/0_stateless/helpers/04319_client_segfault_proxy.py Renumbered 04260 -> 04319 (next free slot on master; 04260 already taken by several merged tests). Verified locally against post-ClickHouse#105996 master: 5/5 iterations of the test report `CLIENT_EXIT=210` with `Code: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR)` instead of the original SIGSEGV at Address 0x108 in `ReadBufferFromPocoSocketChunked::poll`. The PR's `Bug Fix` changelog category will be updated in a follow-up to `CI Fix or Improvement (changelog entry is not required)` because the source fix lives in ClickHouse#105996; this PR's scope is now regression test coverage only. Closes: ClickHouse#105292 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260606-062300 |
|
@azat #105996 merged at 2026-06-04T15:07:46Z. This PR is now trimmed to test-only as you asked: the I verified locally against post-#105996 master that the test PASSes 5/5 iterations: Side effects of the trim:
The "bug fix validation failed" comment from earlier (and PedroTadim's |
…rcised the regression path The previous version of the test could pass without ever hitting the mid-write cutoff path that triggered issue ClickHouse#105292: 1. The proxy returned normally (no exit-code signal) on every early-exit path (target-connect failure, accept timeout, client EOF before cutoff). The shell wrapper accepted any non-zero clickhouse-client exit that mentioned NETWORK_ERROR / Broken pipe / Connection reset by peer, so a failure that occurred BEFORE Connection::sendQuery (e.g. during the native handshake) would still produce one of those markers and falsely "pass" the test. 2. The proxy invocation used `${CLICKHOUSE_CLIENT} ... --host=127.0.0.1 --port=${PROXY_PORT}`. In CI ${CLICKHOUSE_CLIENT} already carries the runner-injected `--host=` and `--port=` of the real server, and Boost program_options keeps the FIRST occurrence of `--port`. The appended proxy port was silently dropped, the client connected directly to the server, the INSERT succeeded, CLIENT_EXIT=0, and the wrapper would have hit its `CLIENT_EXIT=0` BAD branch — so the test could only pass on a different early-error path, not on the regression path. Both issues are fixed: - The proxy now exits 0 ONLY after forwarding more than `cutoff` bytes AND injecting the RST. Every other path (target-connect failure, accept timeout, EOF / recv error / send error before cutoff) prints a labelled marker and exits 1. - The shell wrapper waits for the proxy, captures PROXY_EXIT, and refuses to declare OK unless the proxy emitted CUTOFF_EXCEEDED and exited 0. - The proxy-bound clickhouse-client invocation now uses ${CLICKHOUSE_CLIENT_BINARY} directly instead of ${CLICKHOUSE_CLIENT}, so the proxy `--host=` / `--port=` are the only host/port flags and are honoured. Verified on a debug build, post-ClickHouse#105996 master: 20/20 PASS with the new assertions; 1/1 deterministic FAIL when cutoff is set above the INSERT size (CLIENT_EOF_BEFORE_CUTOFF surfaces and the wrapper rejects it). Related: ClickHouse#105386 Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI Ledger — covered SHA:
|
| Failure | Classification | Disposition |
|---|---|---|
Stateless tests (amd_debug, parallel) — Logical error: Virtual row boundary violated in MergingSortedAlgorithm for input 0 on sort column '__table1.timestamp' DESC (STID 2651-3359) → server died → cascade ERROR on 01280_min_map_max_map |
Trunk regression — NOT PR-caused | Tracked in chronic-trunk task 2026-06-06-p0-stid-2651-3359--virtual-row-boundary. 30-day cross-PR shows 4 distinct unrelated PRs hit it (this one + #93462, #49966, #106412). Stack lands in src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp:45 checkVirtualRowBoundary. This PR is test-only (only tests/queries/0_stateless/04319_client_segfault_send_error_105292.{sh,reference} and helpers/04319_client_segfault_proxy.py after the @ azat-requested trim — fix delivered in #105996, merged 2026-06-04). The crash path has zero overlap with this diff. |
PR-caused gate: zero PR-caused failures. Diff is tests/queries/0_stateless/... only; no src/, no Fast test, no Bugfix, no Style failures.
Status: waiting_ci → on_review. Reviewer: @ azat (asked for the trim and is the assignee).
|
@groeneai, we've fixed this |
|
Merged current `master` into this branch (`69d1e33d266..07b70ac`, fast-forward; only the three test files differ from `master`). The branch base was ~18 days / 6542 commits behind `master`. The prior CI red — `Server died` and `Logical error: Virtual row boundary violated in MergingSortedAlgorithm ... (STID: 2651-3359)` in the The regression test now runs against a |
LLVM Coverage Report
Changed lines: No C/C++ source files changed — skipping uncovered code analysis. Newly covered by added/modified tests: 260 line(s), 19 function(s) across 94 file(s) · Details Top files
|
CI finish ledger — 07b70acCI fully finished and is green on this head: 167 checks all terminal (163 completed + 4 success), 0 queued/in_progress/pending, Finish Workflow + Mergeable Check SUCCESS. Zero test FAIL/ERROR in CIDB on this commit.
The earlier This PR is the test-only regression for #105292 (the user-visible fix shipped in #105996). Ready for review/merge. Session id: cron:our-pr-ci-monitor:20260624-123000 |
CI feedback on PR ClickHouse#105386: 1. Style check failed: test file name contains the substring "fail" (ci/jobs/check_style.py:181 rejects any name with "fail" in it). 2. Bugfix validation passed on master HEAD without the fix, meaning the reproducer was not aggressive enough to trigger the crash in the CI environment. 3. Test number 04258 collides with PR ClickHouse#105387. Changes: - Rename `04258_client_segfault_insert_send_failure_105292.sh` to `04259_client_segfault_send_error_105292.sh` (drops the "failure" substring and avoids the 04258 collision). - Strengthen the TCP-proxy reproducer: * Increase INSERT VALUES payload from 20k to 200k rows (~40 MB) so the client write loop overflows any realistic loopback send buffer. * Set SO_LINGER with timeout 0 on the proxy sockets after the cutoff, forcing a TCP RST so the client's next write observes ECONNRESET immediately instead of waiting for the kernel to push out the auto-tuned send buffer. * Stop the server->client relay once the cutoff fires. Verified locally: * 10/10 OK against the fixed binary (~1.8s per run). * Deterministic SIGSEGV at Address 0x108 in ReadBufferFromPocoSocketChunked::poll when run against the pre-fix binary (matches the original crash signature).
…eded the fix Per @azat's directive (ClickHouse#105386 (comment)), PR ClickHouse#105996 ("Fix possible OOM due to a too-large string literal sent within the query", merged 2026-06-04T15:07:46Z) supersedes the source-code fix in this PR by adding a `Connection::ensureConnected()` helper and an early-return guard at the top of `ClientBase::receiveResult` for the disconnected case. Both halves together prevent the same segfault this PR was originally addressing. Drop the remaining `ClientBase.cpp` change (the `connection->isConnected()` guard inside the `processOrdinaryQuery` `NetException` catch block) — it is strictly subsumed by the new check in `receiveResult`. Keep the regression test as forward-looking coverage for issue ClickHouse#105292: - tests/queries/0_stateless/04319_client_segfault_send_error_105292.sh - tests/queries/0_stateless/04319_client_segfault_send_error_105292.reference - tests/queries/0_stateless/helpers/04319_client_segfault_proxy.py Renumbered 04260 -> 04319 (next free slot on master; 04260 already taken by several merged tests). Verified locally against post-ClickHouse#105996 master: 5/5 iterations of the test report `CLIENT_EXIT=210` with `Code: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR)` instead of the original SIGSEGV at Address 0x108 in `ReadBufferFromPocoSocketChunked::poll`. The PR's `Bug Fix` changelog category will be updated in a follow-up to `CI Fix or Improvement (changelog entry is not required)` because the source fix lives in ClickHouse#105996; this PR's scope is now regression test coverage only. Closes: ClickHouse#105292 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rcised the regression path The previous version of the test could pass without ever hitting the mid-write cutoff path that triggered issue ClickHouse#105292: 1. The proxy returned normally (no exit-code signal) on every early-exit path (target-connect failure, accept timeout, client EOF before cutoff). The shell wrapper accepted any non-zero clickhouse-client exit that mentioned NETWORK_ERROR / Broken pipe / Connection reset by peer, so a failure that occurred BEFORE Connection::sendQuery (e.g. during the native handshake) would still produce one of those markers and falsely "pass" the test. 2. The proxy invocation used `${CLICKHOUSE_CLIENT} ... --host=127.0.0.1 --port=${PROXY_PORT}`. In CI ${CLICKHOUSE_CLIENT} already carries the runner-injected `--host=` and `--port=` of the real server, and Boost program_options keeps the FIRST occurrence of `--port`. The appended proxy port was silently dropped, the client connected directly to the server, the INSERT succeeded, CLIENT_EXIT=0, and the wrapper would have hit its `CLIENT_EXIT=0` BAD branch — so the test could only pass on a different early-error path, not on the regression path. Both issues are fixed: - The proxy now exits 0 ONLY after forwarding more than `cutoff` bytes AND injecting the RST. Every other path (target-connect failure, accept timeout, EOF / recv error / send error before cutoff) prints a labelled marker and exits 1. - The shell wrapper waits for the proxy, captures PROXY_EXIT, and refuses to declare OK unless the proxy emitted CUTOFF_EXCEEDED and exited 0. - The proxy-bound clickhouse-client invocation now uses ${CLICKHOUSE_CLIENT_BINARY} directly instead of ${CLICKHOUSE_CLIENT}, so the proxy `--host=` / `--port=` are the only host/port flags and are honoured. Verified on a debug build, post-ClickHouse#105996 master: 20/20 PASS with the new assertions; 1/1 deterministic FAIL when cutoff is set above the INSERT size (CLIENT_EOF_BEFORE_CUTOFF surfaces and the wrapper rejects it). Related: ClickHouse#105386 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…2-client-segfault-connection-poll Fix clickhouse-client segfault in Connection::poll after sendQuery failure
Adds a regression test for #105292.
The original
clickhouse-clientSIGSEGV atAddress 0x108inReadBufferFromPocoSocketChunked::poll(when an INSERT was interrupted by a broken pipe /ECONNRESETmid-write andConnection::sendQuery'sSCOPE_EXITresetinto nullptr beforeClientBase::processOrdinaryQuery'sNetExceptioncatch calledreceiveResult) is fixed in #105996, which centralizes the disconnected-connection guard inConnection::ensureConnectedand adds an early-return at the top ofClientBase::receiveResult.Per @azat's directive (#105386 (comment)), this PR is now trimmed to test-only: it adds a stateless regression test that drives the exact failure path through a single-shot Python TCP proxy that emits a
RSTafter a configurable byte cutoff, so any future regression that re-introduces the null deref on the disconnected receive path is caught by04319_client_segfault_send_error_105292.Verified locally against post-#105996 master: 5/5 iterations of the test report
CLIENT_EXIT=210withCode: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR)and noAddress: 0x108/Segmentation faultmarkers.Closes: #105292
Related: #105996
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Not required (CI Fix or Improvement).
Documentation entry for user-facing changes
Version info
26.7.1.36