Skip to content

Do not allocate from peer-declared sizes when reading settings from the Native protocol - #118612

Merged
nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/settings-wire-no-allocation-from-declared-size
Sep 18, 2026
Merged

nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/settings-wire-no-allocation-from-declared-size

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Reading settings from the Native protocol no longer sizes a string from the length a peer declares before the payload arrives, so a Query packet or a server hello can no longer turn a few bytes on the wire into a large memory allocation. This covers BaseSettings::read, BaseSettings::readBinary and readQueryParameters, on the server and in the client.

Description

Requested by @ rschu1ze.

BaseSettingsHelpers::readString is the single funnel for every string on the settings wire. It used readStringBinary, which resizes its destination to the declared size before any payload arrives, so five varint bytes committed up to 1 GiB. I measured +1024 MiB RSS for one connection, +3072 MiB for three. Nothing refuses it: the allocation is counted, but enforcement needs min_allocation_size_to_throw_on_memory_limit, which defaults to never.

Both callers reach the loop before the peer is trusted: TCPHandler::processQuery reads settings 98 lines before comparing the interserver secret hash, and the post-authentication path is open to any user. Connection::receiveHello decodes server-supplied settings in the client, which has no memory limit and where every other string read is already bounded by DBMS_MAX_HELLO_STRING_SIZE; no server-side fix reaches it.

This applies #117011's remedy for the same class, readStringBinaryGrowing, to the twelve carriers here. I did not add a bound: a setting value is open-ended user data, so a cap risks rejecting a working configuration. The wire format, setting names and defaults are unchanged. Two observable changes: a truncated payload now raises ATTEMPT_TO_READ_AFTER_EOF rather than CANNOT_READ_ALL_DATA, and a large fully backed value grows geometrically instead of being resized once, as in #117011. #117015 bounds the pair count; this bounds each string.

Two gtest cases cover six of the twelve, one per decoding shape; the other six repeat two of them. Each declares 64 MiB, sends no payload, fails before the change and passes after, on debug and asan_ubsan. A unit test, not a stateless one: the property is that the allocation never happens, which needs an in-process clamp; a socket probe sees only the error code.

Raised separately, not fixed here: SettingFieldNumber<T>::readBinary's signed-integral branch (src/Core/SettingsFields.cpp:263) assigns from its own member instead of the value just read, so a signed setting's wire value is discarded.


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

Version info

  • Merged into: 26.10.1.117 (included in 26.10 and later)

`readStringBinaryGrowing` was added in fb3a21b as a file-local helper for
the three handshake exception strings. The settings wire needs the same
primitive, so give it external linkage: drop `static`, declare it in
ReadHelpers.h next to `skipStringBinary`, and move its explanatory comment onto
the declaration. The default argument moves with the declaration, since a
default may appear only once per translation unit.

No behaviour change: its three existing callers in `readException` are
untouched.
`BaseSettingsHelpers::readString` is the single funnel for every string on the
settings section of the Native protocol: the setting name at the head of the
loop, all three value branches, the discarded value of an unknown setting, and
both strings of `readQueryParameters`. It used `readStringBinary` at the default
1 GiB bound, and that primitive resizes its destination to the declared size
before reading any payload, so a length prefix alone was the allocation. About
five bytes of varint on the wire committed up to 1 GiB of resident memory with
nothing backing it, and each connection could do it again: I measured 1024 MiB
of RSS growth for one connection and 3072 MiB for three concurrent connections,
persisting for as long as the sockets stayed open.

Nothing refuses that on a default-configured server. The allocation is counted,
because ClickHouse intercepts the global operator new, but enforcement on that
path requires `min_allocation_size_to_throw_on_memory_limit`, which defaults to
0, meaning never enforce. Counted but not enforced is the state
src/Common/VectorWithMemoryTracking.h describes as the precondition for an OOM
kill, not a mitigation.

Both callers reach the loop before the peer is trusted.
`TCPHandler::processQuery` reads the settings section 98 lines before it
compares the interserver secret hash, so on that path the loop consumes
unverified peer input, and the ordinary post-authentication path is open to any
user including `readonly`. `Connection::receiveHello` decodes server-supplied
settings in the client, which has no memory limit at all; every other read in
that function is already bounded by DBMS_MAX_HELLO_STRING_SIZE, so this was the
one unguarded read left there, and no server-side change reaches it.

Use `readStringBinaryGrowing` at all twelve string carriers instead: the shared
helper, the seven leaf readers that the legacy `SettingsWriteFormat::BINARY`
branch reaches through `accessor.readBinary`, and the four string carriers of
the generic binary `Field` decoder that a `Map` setting reaches through
`SettingFieldMap::readBinary`. That decoder accepts any recursive tag before it
validates shape, so fixing only its bare `String` case would leave the
invariant false.

I did not add a bound instead. A setting value is open-ended user data, for
instance a long `log_comment`, a SQL fragment in `additional_result_filter`, or
an arbitrary custom payload, so any cap risks rejecting a configuration that
works today. The wire format, the setting names and the defaults are unchanged,
as is the `TOO_LARGE_STRING_SIZE` refusal at the same 1 GiB bound. One error
code does change: a truncated payload now raises `ATTEMPT_TO_READ_AFTER_EOF`
from the growing loop, where `readStrict` raised `CANNOT_READ_ALL_DATA`
(`src/IO/ReadBuffer.cpp:62-68`). No test or documented contract depends on
either code. The cost is that a genuinely large, fully backed value now grows
geometrically rather than being resized once; both that tradeoff and the
error-code substitution are ones this project already accepted for the
handshake strings in `fb3a21b5c2a7`.

The regression test drives six of the twelve carriers, one per distinct decoder
this commit changes, with a declared length of 64 MiB and no payload; the other
six are the identical one-line swap in sibling `SettingField*::readBinary` leaf
readers and in the line following `Field.cpp:472`. Each entry fails before the
change and passes after, on the debug and the `asan_ubsan` build alike.
Afterwards every entry raises `ATTEMPT_TO_READ_AFTER_EOF`. Before, the debug
build refuses the 64 MiB allocation under a clamped global limit
(`MEMORY_LIMIT_EXCEEDED`), while `asan_ubsan` has no `operator new`
interception, so there the resize succeeds and the short read surfaces as
`CANNOT_READ_ALL_DATA`. A second case reads a well-formed settings block under
the same clamp, so the clamp itself is not what produces the first outcome, and
the empty string end marker still terminates the loop.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Three independent passes over this diff (my own cold read each round, plus a second model), adjudicated against the recorded validation evidence.

❌ Fixed before publishing: two inaccurate claims about my own change. A truncated payload now raises ATTEMPT_TO_READ_AFTER_EOF where readStrict raised CANNOT_READ_ALL_DATA, which an earlier draft asserted was unchanged; and the unit test drives six of the twelve changed carriers, not all twelve, which the commit message, the description and an in-diff test comment each stated otherwise. The second one took two passes: my first correction still left the test's leading comment claiming one entry per string-decoding path on this wire, which a six-entry table over twelve call sites does not satisfy, so that line is now deleted rather than reworded. Each entry's own label already names what it drives, and the exact accounting is in the commit message.

⚠️ Raised and not done: adding a normative "consume the declared length incrementally" note to docs/reference/interfaces/specs/NativeProtocol.mdx. The encoding is byte-identical and the accepted-input set is unchanged, including the same TOO_LARGE_STRING_SIZE refusal at the same 1 GiB default, so nothing that file documents changes; every normative statement in it concerns wire alignment or rejection rather than a receiver's allocation strategy; and #117011, which introduced this exact remedy, changed no documentation. The receiver-side limits table there is being added by #117015, and its catch-all 1 GiB row stays true after this change.

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @vitlibar, could you review this? BaseSettingsHelpers::readString is the single funnel for every string on the settings section of the Native protocol, and it used readStringBinary, which resizes its destination to the peer-declared length before any payload arrives, so about five varint bytes committed up to 1 GiB of resident memory per connection. This switches the twelve string carriers on that wire to readStringBinaryGrowing, the primitive #117011 already introduced for the same class.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad1e8c1]

Summary: ✅


AI Review

Summary

This PR switches settings and parameter string decoding away from sizing destinations from the peer-declared length before payload bytes arrive, which is the right direction for the memory-amplification bug it targets. I did not find a C++ correctness regression in the implementation itself, but the PR still leaves the native protocol spec stale for third-party implementations.

Findings

⚠️ Majors

  • [src/Core/BaseSettings.cpp:31] The PR changes how native Query / ServerHello settings are safely decoded, but docs/reference/interfaces/specs/NativeProtocol.mdx still documents only the wire shape of Setting / Parameter. A client or proxy implemented from that spec can still preallocate from the declared string length and retain the same amplification bug on truncated payloads.
    Suggested fix: add a short receiver-side note under Setting / Parameter (and, if helpful, the server_settings note in ServerHello) stating that decoders must not size destination strings from the declared length before the corresponding bytes arrive.
Final Verdict

Request changes until the native protocol spec is updated to describe the new resource-safe decoding rule for settings and parameters.

LLVM Coverage Report

Measured on commit ad1e8c1.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 115/128 (89.84%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-settings Settings & configuration infrastructure (server/user/query settings, profiles). labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6ac97a5

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
Stress test (arm_asan_ubsan, s3) / Logical error: Column identifier A is already registered (STID: 4697-4326) pre-existing analyzer defect in a different dimension from this diff (settings deserialization): 4 distinct carrier PRs over 30 days, 0 rows on the master branch. The merged fix #112219 is an ancestor of this head (compare reports behind_by=0), so the error fired with that fix present and it does not cover this arm a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Build profile diff RuntimeError: CI logs cluster query failed - the job's has_pr_data probe on default.binary_sizes is refused with ACCESS_DENIED. Red repo-wide since 2026-09-07 16:06Z across ~20 PRs per hour by many authors a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)

Bugfix validation (unit tests) is red but reported inconclusive, so it owes no owner: the base branch moved contrib/jemalloc after this branch split, so the before-worktree cannot be populated at the merge-base submodule revisions. That is neither a reproduction nor a refutation.

Session id: cron:our-pr-ci-monitor:20260907-233055

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Build profile diff row in the CI finish ledger above: #118685 fixes the repo-side defect that failure exposed, namely that a failing first cluster read left an earlier commit's comparison pinned to the pull request, presenting an older revision as the current one.

The logs-cluster user switch that addresses the ACCESS_DENIED trigger itself is linked from that PR's description. CIDB still shows Build profile diff as error on all 7 runs started after that switch merged, with no success rows in the window, so this row's check may stay red until the cluster side is provisioned.

Comment thread src/Core/BaseSettings.cpp
{
String str;
readStringBinary(str, in);
readStringBinaryGrowing(str, in);

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.

The protocol hardening is in the C++ decoder now, but the corresponding contract is still missing from docs/reference/interfaces/specs/NativeProtocol.mdx. The Setting / Parameter sections currently describe only the wire bytes, so a third-party native client implementing from the spec can still preallocate from the declared string length and keep the same amplification bug on truncated Query / ServerHello payloads. That spec already includes receiver-side resource-safety requirements for password_complexity_rules, so this settings/parameters decode rule should be documented in the same PR.

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.

Verified the premise before acting on it, and it holds: the spec does carry one receiver-side resource note, on password_complexity_rules under ServerHello ("cap the decoded count at 256 entries and each pattern and message String at 4096 bytes"). I am still not adding a Setting/Parameter decode rule here.

  1. That text is already being written, in Bound the collections read from the Native protocol #117015, whose new "Receiver-side size limits" section documents this exact surface, including a row for the number of Setting and Parameter entries in a Query. It also already edits two of the files this PR changes (src/Core/BaseSettings.cpp, src/IO/ReadHelpers.h), so a second version of that section here would only add a docs collision.

  2. Nothing the spec states today stops being true. TOO_LARGE_STRING_SIZE, 1 GiB, allocate and preallocat have 0 hits in NativeProtocol.mdx on master, and this PR leaves the encoding and the accepted-input set byte for byte identical: readStringBinaryGrowing keeps the same DEFAULT_MAX_STRING_SIZE = 1_GiB default and the same TOO_LARGE_STRING_SIZE rejection as readStringBinary (src/IO/ReadHelpers.h:39, :154, :176). The password_complexity_rules note bounds what a client should reject, and this PR moves no limit.

  3. The in-tree rule that would compel the edit (.claude/CLAUDE.md:15) triggers on the Native format and names NativeFormat.mdx; this change is in the protocol's settings decoder. Its own "if unsure whether the spec needs updating, flag it" tie-breaker is what this reply is.

Worth flagging for whoever merges second: #117015's new section opens with "a receiver allocates for the declared size before the data behind it arrives", which stops being true of the settings strings once this lands.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad1e8c107 with master 55c256363 (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

1902 translation units recompiled, 11200 s compile time in total, 1902 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR link-back for the Logical error: Column identifier A is already registered (STID: 4697-4326) row in the CI finish ledger above: #118734.

It splits the two column censuses in QueryAnalyzer::resolveJoin by purpose, so a JOIN USING key that resolves to a table function's ALIAS column no longer registers the same identifier twice.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ad1e8c1

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
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, public master regression with a hard onset on 2026-09-06: the injected reenqueue fault handled line never appears, so the result differs from the reference #118417 (external, open), confirmed by @ alexey-milovidov as covering both tests; the failpoint-reset fix #105942 (external, open) applies to this one too
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation same onset: the recorded CANNOT_SCHEDULE_TASK (439) is lost on the way out and the client is given POCO_EXCEPTION (1000) #118390 (mine, open), plus #118417 (external, open)

PR is the workflow aggregator of the two rows above and carries no failure of its own. Neither test is reachable from this diff, which is confined to settings deserialization in BaseSettings::read(): the pair is a repo-wide regression tracked in issue #118626, and both reproduced 0 out of 3 reruns here.

Session id: cron:our-pr-ci-monitor:20260908-113133

@nickitat nickitat self-assigned this Sep 18, 2026
@nickitat
nickitat added this pull request to the merge queue Sep 18, 2026
@nickitat
nickitat removed this pull request from the merge queue due to a manual request Sep 18, 2026
@nickitat
nickitat added this pull request to the merge queue Sep 18, 2026
Merged via the queue into ClickHouse:master with commit b18ca9e Sep 18, 2026
344 of 345 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 Sep 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

It broke clang-tidy. Resubmitted.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for catching it, and sorry for the breakage.

The duplicate was not in this PR's diff: #118610 and this PR each added #include <IO/VarInt.h> to src/Core/tests/gtest_settings.cpp at a different position in the same include block (after WriteBufferFromString.h in #118610, after ReadBufferFromString.h here), and both were written against the same base revision of that file, so git merged the two insertions with no textual conflict. This PR's own Build (arm_tidy) was green at ad1e8c10773e, which ran on 2026-09-08, before #118610 merged, so no run on either PR could see the collision.

#120931's tree carries exactly one copy of the include, so the duplicate cannot come back. I had a one-line deletion ready and dropped it once your revert landed; I am not opening a competing fix.

clickhouse-gh Bot pushed a commit that referenced this pull request Sep 19, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 120763 120477 Revert "Remove stale entries from `parallel_replicas_blacklist.txt`"
Changelog-revert: 120801 120767 Revert "CI: give revert pull requests a green light at once"
Changelog-revert: 120930 118612 Revert "Do not allocate from peer-declared sizes when reading settings from the Native protocol"
Changelog-deleted-entry: 118612 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Reading settings from the Native protocol no longer sizes a string from the length a peer declares before the payload arrives, so a Query packet or a server hello can no longer turn a few bytes on the wire into a large memory allocation. This covers `BaseSettings::read`, `BaseSettings::readBinary` and `readQueryParameters`, on the server and in the client. [#118612](#118612) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 120767 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * CI: give revert pull requests a green light at once. [#120767](#120767) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-settings Settings & configuration infrastructure (server/user/query settings, profiles). groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default 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