Skip to content

Fix clickhouse-client segfault in Connection::poll after sendQuery failure - #105386

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105292-client-segfault-connection-poll
Jun 24, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105292-client-segfault-connection-poll

Conversation

@groeneai

@groeneai groeneai commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Adds a regression test for #105292.

The original clickhouse-client SIGSEGV at Address 0x108 in ReadBufferFromPocoSocketChunked::poll (when an INSERT was interrupted by a broken pipe / ECONNRESET mid-write and Connection::sendQuery's SCOPE_EXIT reset in to nullptr before ClientBase::processOrdinaryQuery's NetException catch called receiveResult) is fixed in #105996, which centralizes the disconnected-connection guard in Connection::ensureConnected and adds an early-return at the top of ClientBase::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 RST after a configurable byte cutoff, so any future regression that re-introduces the null deref on the disconnected receive path is caught by 04319_client_segfault_send_error_105292.

Verified locally against post-#105996 master: 5/5 iterations of the test report CLIENT_EXIT=210 with Code: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR) and no Address: 0x108 / Segmentation fault markers.

Closes: #105292
Related: #105996

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

  • Merged into: 26.7.1.36

…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a) 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 (04258_client_segfault_insert_send_failure_105292.sh).

b) Root cause explained? YES. Connection::sendQuery (src/Client/Connection.cpp:909) registers SCOPE_EXIT { if (!completed) disconnect(); }. When a buffered write to *out throws NetException, that SCOPE_EXIT fires first and resets in (src/Client/Connection.cpp:421-428). The catch (NetException) block in ClientBase::processOrdinaryQuery (src/Client/ClientBase.cpp:1356-1364) then calls receiveResult to drain residual data, which calls Connection::poll, which dereferences the now-null in. Address 0x108 matches the offset of the chunked member accessed at line 47 of ReadBufferFromPocoSocketChunked::poll through a null this.

c) Fix matches root cause? YES. Two complementary changes:

  • Connection::poll, hasReadPendingData, checkPacket, receivePacketType — handle null in the way Connection::receivePacket already does (existing guard at line 1359 in the same file).
  • ClientBase::processOrdinaryQuery — skip the receive-buffer drain when connection->isConnected() returns false, so the original NetException propagates with its actual cause (Broken pipe, Connection refused, etc.).

d) Test intent preserved? / New test added? YES. No existing tests were weakened. Added 04258_client_segfault_insert_send_failure_105292.sh which drives the exact bug scenario.

e) Demonstrated in both directions?

  • WITHOUT fix: exit 139, Address: 0x108, Stack: ReadBufferFromPocoSocketChunked::poll → Connection::poll → ClientBase::receiveResult — full crash stack matches user report.
  • WITH fix: exit 210, Code: 210. DB::NetException: I/O error: Broken pipe, while writing to socket (...) — clean error to the user.

f) Fix is general, not a narrow patch? YES. The fix covers ALL four sibling methods on Connection that can be called by ClientBase after a disconnect, not only the one in the user's stack:

  • poll — fixed (the crash site).
  • hasReadPendingData — fixed (called from Connection::checkPacket and MultiplexedConnections::tryGetReadyReplica).
  • checkPacket — fixed (called from ClientBase::sendDataFromPipe:2181 and receiveLogsAndProfileEvents:2223,2230).
  • receivePacketType — fixed (matches the existing guard in receivePacket).

The "fix the symptom or the cause?" check: the root cause is the SCOPE_EXIT in sendQuery. We do not change that (the disconnect is intentional — half-sent queries must not be reused). Instead we make the receive API contract null-safe and update the one caller that wrongly assumed the connection was still alive.

Session: cron:clickhouse-ci-task-worker:20260519-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [07b70ac]

Summary: ✅


AI Review

Summary

This PR adds a focused stateless regression test for the clickhouse-client send-error path fixed by #105996: a single-shot TCP proxy forces a mid-write RST, the shell test asserts the proxy actually crossed the cutoff, and the client must fail with a network error rather than the old Address: 0x108 / segmentation-fault signature. I did not find any current correctness, safety, or test-quality findings that need inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 20, 2026
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).
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed fix-up commit ba7c137 addressing the CI feedback from the previous run:

  1. Style check failed because the test file name contained the substring fail (rejected by ci/jobs/check_style.py:181). Renamed the test from 04258_client_segfault_insert_send_failure_105292.sh to 04259_client_segfault_send_error_105292.sh (also drops the 04258 number collision with Fix LOGICAL_ERROR in DistanceTransposedPartialReadsPass with Nullable arguments #105387).
  2. Bugfix validation (functional tests) ran the test against the pre-fix master binary and the test passed (0.9s), meaning the reproducer was not aggressive enough to trigger the crash in CI. Strengthened it:
    • INSERT VALUES payload increased from 20k to 200k rows (~40 MB) so the client write loop overflows any realistic loopback send buffer.
    • Proxy now sets SO_LINGER with timeout 0 after the cutoff, forcing a TCP RST so the client's next write observes ECONNRESET immediately instead of waiting for the kernel to drain the auto-tuned send buffer.
    • Stop the server-to-client relay once the cutoff fires.

Verified locally against the rebuilt binary:

PR description, root cause, and fix unchanged. Awaiting CI.

@azat azat self-assigned this May 20, 2026
Comment thread src/Client/Connection.cpp Outdated
Comment on lines +1313 to +1317
/// `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());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reverted the null-safety guards in Connection::poll, hasReadPendingData, checkPacket, receivePacketType per your note. Audited the callers:

  • Connection::poll: only ClientBase::receiveResult (line 1466).
  • Connection::checkPacket: ClientBase::receiveLogsAndProfileEvents, ClientBase::sendDataFrom, RemoteInserter::write. None of these can reach a disconnected Connection (none of them run after sendQuery's SCOPE_EXIT disconnect path).
  • Connection::hasReadPendingData: PacketReceiver, HedgedConnections, MultiplexedConnections. Same: their lifecycles do not cross a sendQuery-failure disconnect.
  • Connection::receivePacketType: only MultiplexedConnections::receivePacketTypeUnlocked, with current_connection != nullptr.

So the isConnected() guard in ClientBase::processOrdinaryQuery is sufficient.

Commit: c601560

@groeneai

Copy link
Copy Markdown
Collaborator Author

Tightened the assertions in 04259_client_segfault_send_error_105292.sh (commit c601560):

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
fi

Now 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 --allow_repeated_settings --send_logs_level=none to the proxied client invocation. Server-side log packets sent during the abrupt close were landing in the runner's fatal-log file and unrelatedly failing the test on asan_ubsan and tsan. Disabling log forwarding for this one call keeps the fatal-log file clean without changing what is being tested.

cutoff = int(sys.argv[3])
port_file = sys.argv[4]

# Force an RST (TCP reset) on close so the client gets ECONNRESET on its

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@den-crane

den-crane commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

at the server I see

2026.05.20 13:32:49.654453 [ 96976 ] {} <Error> TCPHandler: Code: 131. DB::Exception: Too large string size. (TOO_LARGE_STRING_SIZE), Stack trace (when copying this message, always include the lines below):

0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x000000001334b110
1. DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000dd4d158
2. DB::Exception::Exception(PreformattedMessage&&, int) @ 0x000000000dd4c9cc
3. DB::Exception::Exception<>(int, FormatStringHelperImpl<>) @ 0x0000000013349954
4. DB::readStringBinary(String&, DB::ReadBuffer&, unsigned long) @ 0x00000000134ac910
5. DB::TCPHandler::processQuery(std::shared_ptr<DB::QueryState>&) @ 0x0000000018d65e80
6. DB::TCPHandler::runImpl() @ 0x0000000018d505bc
7. DB::TCPHandler::run() @ 0x0000000018d70e88
8. Poco::Net::TCPServerConnection::start() @ 0x000000001db94858
9. Poco::Net::TCPServerDispatcher::run() @ 0x000000001db94e64
10. Poco::PooledThread::run() @ 0x000000001db53ef4
11. Poco::ThreadImpl::runnableEntry(void*) @ 0x000000001db520f0
12. httplib::detail::random_string(unsigned long)::engine @ 0x0000000000007624
13. ? @ 0x00000000000d166c

It looks like there are 2 separate issues:

  1. issue with super long insert into r values ..., though it should be streamable, and the length should not be matter. It's suspicious that clickhouse-client -q 'insert into r values' < values.txt and clickhouse-client < insert_and_values.txt behave differently. And server trows Too large string size..

  2. client segfault if the server threw Too large string size..

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check CI failures. 04259_client_segfault_send_error_105292 test failed, plus merge with master.

groeneai added 2 commits May 21, 2026 12:12
@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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (after fix-up df186d4):

  • (a) Deterministic repro? YES. Pre-fix master binary SIGSEGVs at Address 0x108 in ReadBufferFromPocoSocketChunked::poll:47 on every run of the regression test.
  • (b) Root cause? YES. Connection::sendQuery's SCOPE_EXIT calls disconnect() on send failure, which sets in to nullptr. The catch (NetException) in processOrdinaryQuery then called receiveResult which dereferenced the null read buffer.
  • (c) Fix matches root cause? YES. Guard receiveResult on connection->isConnected() in processOrdinaryQuery. Single upstream guard; no other callers reach the disconnected state (caller audit in commit c601560).
  • (d) Test intent preserved? YES. The test asserts both non-zero exit AND a NETWORK_ERROR / Broken pipe / Connection reset by peer marker in client output, so a clean INSERT cannot silently pass.
  • (e) Both directions demonstrated? YES. Local master binary SIGSEGVs deterministically; rebuilt binary with the fix passes 10/10 with empty stderr.
  • (f) Fix general? YES. Same isConnected() pattern already exists at ClientBase::cancelQuery (line 1546+); we are extending it to the symmetric receive path.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim master merged into the branch as commit 403bede0ab89. The 04259_* test number collided with #105439 (which just landed 04259_count_distinct_optimization_nullable.sql on master), so renumbered to 04260.

CI failure classification on the previous commit c6015601043b:

  • Stateless tests (amd_tsan, s3 storage, sequential, 1/2) and Stateless tests (amd_tsan, sequential, 1/2) on 04259_client_segfault_send_error_105292: the test stdout was OK (the bug WAS caught: client exits non-zero with NETWORK_ERROR, no 0x108 signature). The failure was stderr containing the line Killed python3 "${PROXY_SCRIPT}" ... from bash job-control when the background proxy was reaped with kill -9. The runner reads stderr and reports any content as a test failure.
  • Bugfix validation (functional tests): same cause (the regression test's stderr contained the Killed line).

Fix-up df186d477e4e resolves this by:

  • Moving the proxy to tests/queries/0_stateless/helpers/04260_client_segfault_proxy.py.
  • Making the proxy single-shot (listens, accepts one connection, RSTs after cutoff, exits). No external kill is needed, so bash never emits the Killed notification.

Verified locally: 10/10 OK with empty stderr.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@azat moved the Python proxy out of the .sh and into a separate helper file: tests/queries/0_stateless/helpers/04260_client_segfault_proxy.py. The proxy now has its own docstring and a clear single-purpose contract (relays one connection, RSTs the client after cutoff bytes, exits). The .sh is 100 lines of orchestration with compact comments.

On the "long Values + throttling" alternative: I traced the path the original den-crane reproducer uses. The server-side trigger is readStringBinary(state->query, *in) at TCPHandler.cpp:2312, which uses DEFAULT_MAX_STRING_SIZE = 1_GiB. Triggering TOO_LARGE_STRING_SIZE deterministically without a proxy requires sending a query packet whose size prefix is greater than 1 GiB, which is not viable for a CI regression test (data volume, runtime). max_network_bandwidth_* settings only apply after authentication, so they cannot starve the protocol read before the server has accepted the connection. The single-shot proxy is the minimum-data way to deterministically reach the Connection::sendQuery SCOPE_EXIT path.

Also made the proxy single-shot so the test no longer needs kill -9 for cleanup. The bash Killed job-control notification was what the CI runner was reporting as stderr noise on the amd_tsan and amd_tsan, s3 storage jobs.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai the 04260_client_segfault_send_error_105292 test failed

alexey-milovidov pushed a commit that referenced this pull request May 30, 2026
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]>
@azat

azat commented Jun 2, 2026

Copy link
Copy Markdown
Member

issue with super long insert into r values ..., though it should be streamable, and the length should not be matter. It's suspicious that clickhouse-client -q 'insert into r values' < values.txt and clickhouse-client < insert_and_values.txt behave differently. And server trows Too large string size..

@den-crane probably due to async INSERTs, do you have a stacktrace?

@azat

azat commented Jun 2, 2026

Copy link
Copy Markdown
Member

@groeneai bug fix validation failed

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general looks good, but need to fix the test

Comment thread src/Client/ClientBase.cpp Outdated
/// `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]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will be superseeded by #105996

Let's wait until it will be merged and leave only test here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@azat acknowledged. I'll wait for #105996 to merge, then trim this PR to keep only the regression test (tests/queries/0_stateless/04259_client_segfault_send_error_105292.{sh,reference}) and drop the ClientBase.cpp / Connection.cpp changes.

groeneai and others added 2 commits June 6, 2026 06:26
…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]>
@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 6, 2026
@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? YES. The Python helper 04319_client_segfault_proxy.py reproduces the original bug 100% of the time on a pre-#105996 binary (server returned the full INSERT chunk, proxy emits RST at the configured byte cutoff, clickhouse-client SIGSEGVs at Address 0x108 in ReadBufferFromPocoSocketChunked::poll). On post-#105996 master, 5/5 iterations exit 210 with Code: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR).
b Root cause explained? YES (lives in #105996). Connection::sendQuery registers a SCOPE_EXIT that calls disconnect() if the query did not complete; on a NetException from a buffered write, SCOPE_EXIT fires and resets in to nullptr. The catch (NetException) in ClientBase::processOrdinaryQuery then calls receiveResult which calls Connection::poll and dereferences the now-null in. The 0x108 offset corresponds to the chunked field of ReadBufferFromPocoSocketChunked reached through a null this.
c Fix matches root cause? N/A for this PR (test-only after the trim). The source-level fix in #105996 directly addresses the mechanism: Connection::ensureConnected throws a clean exception on !in, and ClientBase::receiveResult early-returns when connection->isConnected() is false so the catch-block drain attempt is skipped on an already-disconnected connection.
d Test intent preserved / new tests added? New test added: 04319_client_segfault_send_error_105292 plus the supporting helpers/04319_client_segfault_proxy.py. The test asserts (1) exit code is not 139 (SIGSEGV), (2) no Address: 0x108 / Segmentation fault marker in the client output, (3) exit code is non-zero (the cutoff actually triggered the send-error path), and (4) the output contains NETWORK_ERROR / Broken pipe / Connection reset by peer. Renumbered 04260 → 04319 (next free slot on master; 04260_* had collisions with already-merged tests).
e Both directions demonstrated? YES. Pre-#105996 master: SIGSEGV every time (the original symptom and the reason this PR was opened). Post-#105996 master: 5/5 iterations PASS reporting CLIENT_EXIT=210 and NETWORK_ERROR.
f Fix is general, not a narrow patch? N/A for this PR (test-only). #105996's source fix is general — ensureConnected is now called from Connection::poll, Connection::receivePacketType, and Connection::receivePacket, and the early-return in ClientBase::receiveResult covers every receive-side path that used to reach connection->poll() after a teardown.

Session id: cron:clickhouse-ci-task-worker:20260606-062300

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

@azat #105996 merged at 2026-06-04T15:07:46Z. This PR is now trimmed to test-only as you asked: the ClientBase.cpp change is dropped (commit 10e2a88) and only the 04319_client_segfault_send_error_105292 regression test plus its helper proxy remain.

I verified locally against post-#105996 master that the test PASSes 5/5 iterations: CLIENT_EXIT=210 with Code: 210. DB::NetException: Connection reset by peer ... (NETWORK_ERROR) instead of the original SIGSEGV at Address 0x108. So the test catches the bug shape that #105996 fixed, but no longer fails on master itself.

Side effects of the trim:

  • The PR no longer modifies any source code, so the Bug Fix changelog category cannot be honored — the bug fix validation check would (correctly) fail because the test now passes on master without our PR. I changed the changelog category to CI Fix or Improvement (changelog entry is not required) in the PR description; let me know if you'd prefer a different category or no entry.

  • I had to renumber the test from 04260 → 04319 because four tests with 04260_* prefixes have landed on master since this PR was opened. 04319 is the next free slot.

The "bug fix validation failed" comment from earlier (and PedroTadim's 04260_client_segfault_send_error_105292 test failed notes) should be resolved by this trim — the bug-fix-validation check no longer applies, and the test itself is now stable on master.

…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]>
@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: 69d1e33d26623e54554f5bf2e5d5ddf99cefdbf9

CI fully finished (Finish Workflow ✅, every check completed, ≥20min CIDB ingestion buffer met).

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).

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, we've fixed this Logical error: Virtual row boundary violated in MergingSortedAlgorithm in master. Please update the branch, so it has a chance to be merged.

@alexey-milovidov alexey-milovidov self-assigned this Jun 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

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 Stateless tests (amd_debug, parallel) job — was a stale-base artifact, not caused by this test-only PR: that debug assertion was added in #106565 (merged 2026-06-05) and the bug it caught was fixed in #106664 (merged 2026-06-07), which the 2026-06-06 base predated. Current master contains the fix, so the merge should clear it.

The regression test now runs against a master that already contains the user-visible fix (the ClientBase::receiveResult early-return guard for a disconnected connection, introduced in #105996), so 04319_client_segfault_send_error_105292 exercises the real fixed path.

@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.30% -0.10%
Functions 92.50% 92.50% +0.00%
Branches 77.60% 77.50% -0.10%

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
  • src/AggregateFunctions/AggregateFunctionQuantileGK.cpp: 15 line(s)
  • src/Functions/FunctionsBitmap.h: 12 line(s)
  • src/Parsers/parseFieldFromCastedLiteral.cpp: 10 line(s), 11 function(s)
  • src/Client/ClientBase.cpp: 10 line(s)
  • src/AggregateFunctions/AggregateFunctionQuantileExact.cpp: 8 line(s)

Full report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 07b70ac

CI 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.

Check / test Reason Fixing PR
(none) all checks passed n/a
Sync private CH Inc sync (not actionable)

The earlier Server died / Virtual row boundary violated in MergingSortedAlgorithm red (STID 2651-3359) was a stale-base artifact on the old base (~6542 commits behind; the #106565 debug assertion caught a bug fixed in #106664, both postdating the old base). Merging current master (69d1e33..07b70ac, only the three 04319 test files differ from master) picked up that fix, and the run is now clean.

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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 24, 2026
Merged via the queue into ClickHouse:master with commit c6647cb Jun 24, 2026
167 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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).
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…2-client-segfault-connection-poll

Fix clickhouse-client segfault in Connection::poll after sendQuery failure
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 pr-ci 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.

Clickhouse-client Segfault when executing sql

6 participants