Skip to content

Fix possible OOM due to a too-large string literal sent within the query - #105996

Merged
nickitat merged 5 commits into
masterfrom
tcp_query_unbounded_alloc_repro
Jun 4, 2026
Merged

nickitat merged 5 commits into
masterfrom
tcp_query_unbounded_alloc_repro

Conversation

@nickitat

@nickitat nickitat commented May 27, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed a possible crash due to a too-large string literal sent within the query.

Version info

  • Merged into: 26.6.1.391
  • Backported to: 26.5.2.35, 26.4.4.33, 26.3.13.31

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [84e7efd]

Summary: ✅


AI Review

Summary

This PR moves the normal native TCP query-body receive path to StringWithMemoryTracking, caps query_id, and adds an integration regression for oversized query bodies. The main receive path is improved, but two full-query materialization paths still bypass the throwing allocator, so the PR does not yet fully satisfy the promised MEMORY_LIMIT_EXCEEDED behavior for oversized query text.

Findings

❌ Blockers

  • [src/Interpreters/executeQuery.cpp:1365] executeQueryImpl still materializes query.assign(begin, query_end) into a plain String after state->query was safely read. When max_query_size = 0, or for a non-secret SECONDARY_QUERY where executeQueryImpl forces max_query_size = 0, a native client can send an oversized query that passes the StringWithMemoryTracking receive and then duplicates the full text through the non-refusing allocation path for logging/processlist. This violates the PR contract that oversized query text is rejected with MEMORY_LIMIT_EXCEEDED instead of driving RSS past max_server_memory_usage. Suggested fix: avoid the full plain String copy for logging/processlist, for example by using a bounded view/slice or tracked storage, and add a regression for max_query_size = 0 or SECONDARY_QUERY.
  • [src/Server/TCPHandler.cpp:2577] processUnexpectedQuery still reads the unexpected Query packet body into plain String skip_string before throwing UNEXPECTED_PACKET_FROM_CLIENT. A client can first enter receivePacketsExpectData, then send another Query packet with a large query body; this malformed path bypasses the new QueryState::query storage and can still push RSS over max_server_memory_usage. Suggested fix: skip the encoded query strings without materializing them, or read them into StringWithMemoryTracking or bounded storage, and cover the malformed-packet path.
Tests
  • ⚠️ The new integration test covers only the normal Query receive path with max_query_size = 1000. It would not fail for either remaining OOM path above. Add focused regressions for max_query_size = 0 or SECONDARY_QUERY, and for an unexpected Query packet sent while the server is expecting data.
Final Verdict

Status: ❌ Block

Minimum required actions: eliminate the remaining full-query plain String materializations on the logging/processlist path and unexpected-packet path, then add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels May 27, 2026
Comment thread src/Client/Connection.cpp Outdated

bool Connection::poll(size_t timeout_microseconds)
{
/// `disconnect()` resets `in`, so reaching here from an outer loop after

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

First it crashed right after OOM with the following stack:

(version 26.6.1.1, build id: 43EFBE2551DD08C486BD9577020C1D769CD96B4F, git hash: ce552bdb05e1113e84d1b570f849fda27551a6d7) (from thread 262524) (no query) Received signal Segmentation fault (11)
Address: 0x108. Access: read. Address not mapped to object.
Stack trace: 0x000062a39d13e305 0x000062a39d0f2b73 0x000062a39d0f1717 0x000062a39d0eef20 0x000062a39d0fb65c 0x000062a39d0fc9f7 0x000062a39d108e0e 0x000062a393647e6b 0x000062a3a20758b4 0x000062a393656e8e 0x000062a38c9fb21e 0x00007f1f3602a1ca 0x00007f1f3602a28b 0x000062a38c9dc66e
3. src/IO/ReadBufferFromPocoSocketChunked.cpp:47:9: DB::ReadBufferFromPocoSocketChunked::poll(unsigned long) const @ 0x000000001988a305
4. src/Client/ClientBase.cpp:1485:29: DB::ClientBase::receiveResult(boost::intrusive_ptr<DB::IAST>, int, bool) @ 0x000000001983eb73
5. src/Client/ClientBase.cpp:1385:17: DB::ClientBase::processOrdinaryQuery(String, boost::intrusive_ptr<DB::IAST>) @ 0x000000001983d717
6. src/Client/ClientBase.cpp:2479:13: DB::ClientBase::processParsedSingleQuery(std::basic_string_view<char, std::char_traits<char>>, boost::intrusive_ptr<DB::IAST>, bool&, unsigned long) @ 0x000000001983af20
7. src/Client/ClientBase.cpp:2859:21: DB::ClientBase::executeMultiQuery(String const&) @ 0x000000001984765c
8. src/Client/ClientBase.cpp:3121:12: DB::ClientBase::processQueryText(String const&) @ 0x00000000198489f7
9. src/Client/ClientBase.cpp:3950:13: DB::ClientBase::runNonInteractive() @ 0x0000000019854e0e
10. programs/client/Client.cpp:439:9: DB::Client::main(std::vector<String, std::allocator<String>> const&) @ 0x000000000fd93e6b
11. base/poco/Util/src/Application.cpp:315:8: Poco::Util::Application::run() @ 0x000000001e7c18b4
12. programs/client/Client.cpp:1372:23: mainEntryClickHouseClient(int, char**) @ 0x000000000fda2e8e
13. programs/main.cpp:475:21: main @ 0x000000000914721e

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.

I guess this should be fixed by #105386 ?

@nickitat nickitat May 27, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Pls merge it, and I will rebase on top of it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@azat, we might as well merge this PR in its current state since 105386 isn't moving anywhere. I don't really like the idea of leaving green PRs hanging for weeks.

@azat azat Jun 2, 2026 •

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.

Ok, but let's make it LOGICAL_ERROR, since it is responsibility of the caller not to use connection after disconnect, and it happens usually in some try/catch blocks.

There is already such check in receivePacket (added in #95466) but it is not enough

Let's add some helper and verify the state of "in" there

P.S. and also don't forget to adjust "receivePacketType"

Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Server/TCPHandler.h Resolved
@azat azat self-assigned this May 27, 2026
@nickitat
nickitat marked this pull request as ready for review May 28, 2026 12:45

std::pair<ASTPtr, BlockIO> executeQuery(
const String & query,
std::string_view query,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This avoids the function-boundary String copy, but the query can still be duplicated outside a throwing allocator a bit later. For a native client that sends a large query with max_query_size = 0, or for a non-secret SECONDARY_QUERY where executeQueryImpl forces max_query_size = 0, state->query is read with StringWithMemoryTracking and then executeQueryImpl can reach query.assign(begin, query_end) for logging/processlist. That allocates a full plain String; with the default min_allocation_size_to_throw_on_memory_limit = 0, this path is accounted but not refused by the memory tracker, so it can still push RSS past max_server_memory_usage after the tracked receive succeeds.

Can we avoid materializing the full query into plain String here, for example by deriving query_for_logging from a bounded slice/view or by using tracked storage for this copy, and add a regression with max_query_size = 0 or a secondary query?

Comment thread src/Server/TCPHandler.h
/// cleanly, rather than driving the server's RSS past
/// `max_server_memory_usage` via `allocNoThrow` and getting
/// cgroup-OOM-killed.
StringWithMemoryTracking query;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This tracks the normal Query packet body, but the same native-protocol string is still read into a plain String on the unexpected-packet path. A client can send a query that makes the server enter receivePacketsExpectData, then send another Query packet; processUnexpectedQuery reads both the query id and the query body into String skip_string before throwing UNEXPECTED_PACKET_FROM_CLIENT. The query-body read at src/Server/TCPHandler.cpp:2577 still resizes a plain String, so an oversized malformed packet can take the non-refusing allocation path and push RSS past max_server_memory_usage before the handler rejects it.

Can we skip these encoded strings without materializing them, or at least use StringWithMemoryTracking on this path too?

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 24/29 (82.76%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@nickitat

nickitat commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

I've considered the two auto-suggestions above, and I think we shouldn't try to solve every possible problem here; instead, we're better off continuing to apply more WMT containers, including the Client/Server code, to close the remaining gaps.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The flaky check was done locally:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ok [Integration tests (arm_binary, distributed plan, 3/4)]
  | Failures: 0/50
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@nickitat
nickitat added this pull request to the merge queue Jun 4, 2026
Merged via the queue into master with commit 81a8bce Jun 4, 2026
326 of 329 checks passed
@nickitat
nickitat deleted the tcp_query_unbounded_alloc_repro branch June 4, 2026 15:07
nickitat added a commit that referenced this pull request Jun 4, 2026
Cherry pick #105996 to 26.3: Fix possible OOM due to a too-large string literal sent within the query
nickitat added a commit that referenced this pull request Jun 4, 2026
Cherry pick #105996 to 26.4: Fix possible OOM due to a too-large string literal sent within the query
nickitat added a commit that referenced this pull request Jun 4, 2026
Cherry pick #105996 to 26.5: Fix possible OOM due to a too-large string literal sent within the query
nickitat added a commit that referenced this pull request Jun 4, 2026
Cherry pick #105996 to 25.8: Fix possible OOM due to a too-large string literal sent within the query
@robot-ch-test-poll1 robot-ch-test-poll1 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo labels Jun 4, 2026
robot-clickhouse added a commit that referenced this pull request Jun 4, 2026
robot-clickhouse added a commit that referenced this pull request Jun 4, 2026
robot-clickhouse added a commit that referenced this pull request Jun 4, 2026
robot-clickhouse added a commit that referenced this pull request Jun 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 4, 2026
@clickgapai

clickgapai commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix possible OOM due to a too-large string literal sent within the query

ClickGap verified: reproduced it with the script below on 26.5; tested 5 version(s) — 4 affected, 1 clean (see Affects); confirmed it predates the oldest available release (pre-existing).

Reproduction

pytest -s tests/integration/test_tcp_query_body_oversized_read/test.py

Bisect

  • Bisect skipped — bug predates available CI binaries. Maintainer-side bisect needed.

Affects

  • Tested on master @ commit 0af404d2dbbb
  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 25.8
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 25.8

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-protocols
Severity: P2

cc fix PR author:
cc fix PR reviewer: @azat


ClickGap · Finding: phase_d_pr105996

nickitat added a commit that referenced this pull request Jun 5, 2026
Backport #105996 to 26.5: Fix possible OOM due to a too-large string literal sent within the query
nickitat added a commit that referenced this pull request Jun 5, 2026
Backport #105996 to 26.4: Fix possible OOM due to a too-large string literal sent within the query
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 6, 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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 6, 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]>
alexey-milovidov added a commit that referenced this pull request Jun 6, 2026
Backport #105996 to 26.3: Fix possible OOM due to a too-large string literal sent within the query
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…5996

Backport ClickHouse#105996 to 26.4: Fix possible OOM due to a too-large string literal sent within the query
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

6 participants