Skip to content

Do not pre-allocate huge buffers when deserializing SingleValueDataString - #110630

Closed
alexey-milovidov wants to merge 13 commits into
masterfrom
fix-single-value-string-huge-alloc
Closed

alexey-milovidov wants to merge 13 commits into
masterfrom
fix-single-value-string-huge-alloc

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

SingleValueDataString::read (the deserialization used by min, max, argMin, argMax over String) reads a 4-byte size prefix from possibly corrupted or truncated input and then pre-allocated the entire declared size (up to ~2 GiB) via allocateLargeDataIfNeeded before readStrict could verify that the buffer actually contains that many bytes.

For invalid input with a huge declared size but little actual data — e.g. CAST('AggregateFunction(...)...', 'AggregateFunction(min, String)'), whose leading bytes Aggr decode as a ~1.79 GiB size — this attempted a ~2 GiB allocation. Under memory pressure the allocation itself trips the overcommit tracker and the query fails with MEMORY_LIMIT_EXCEEDED instead of the expected CANNOT_READ_ALL_DATA. That made the tests 02481_i43247_ubsan_in_minmaxany and 02477_single_value_data_string_regression flaky (observed on master in Stateless tests (amd_asan_ubsan, distributed plan, parallel)).

This reads the payload incrementally instead: when the payload is already fully available in the buffer (the common case — contiguous on-disk parts, small states), the previous single-allocation direct read is kept; otherwise the bytes are accumulated in a memory-tracked scratch buffer as they actually arrive and committed to the arena in one allocation once complete. Incomplete input now fails with CANNOT_READ_ALL_DATA without a large allocation up front, and valid large strings read back correctly byte-for-byte. The on-disk/wire format is unchanged.

Known, accepted tradeoff: a valid large state that genuinely spans multiple ReadBuffer refills is staged in the scratch buffer and then copied into the arena, so both are briefly live — a transient peak of roughly twice the payload size. Near a tight max_memory_usage, such a read can now fail with MEMORY_LIMIT_EXCEEDED where the old single-allocation path would have succeeded. This is the irreducible cost of not trusting the declared size: the arena destination can neither grow incrementally nor free intermediate buffers, so unverified bytes must be staged outside the arena before the single arena allocation. The scratch buffer is heap-allocated and freed immediately after the copy (it does not leak into the arena).

Verified locally: the failing queries now return CANNOT_READ_ALL_DATA after allocating only a few hundred bytes; both tests pass repeatedly under randomized settings; and argMax(String) states of 5 MB / 17 MB (spanning many buffer refills) round-trip through disk byte-for-byte.

Note: #110632 fixes the same issue with a different approach; only one of the two should be merged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=81f8ef5172094f3a8abe5b01e3fe9fdc68307951&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29

Changelog category (leave one):

  • Improvement

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

Avoid huge up-front allocations when deserializing corrupted or truncated AggregateFunction(min|max|argMin|argMax, String) states; such inputs now fail with CANNOT_READ_ALL_DATA instead of MEMORY_LIMIT_EXCEEDED.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

…ring

`SingleValueDataString::read` (used by `min`/`max`/`argMin`/`argMax` over
`String`) reads a 4-byte size prefix from possibly corrupted or truncated
input and then pre-allocated the whole declared size (up to ~2 GiB) via
`allocateLargeDataIfNeeded` before `readStrict` had a chance to verify that
the buffer actually contains that many bytes.

For invalid input with a huge declared size but little actual data (e.g.
`CAST('AggregateFunction(...)...', 'AggregateFunction(min, String)')`, whose
first bytes `Aggr` decode as a ~1.79 GiB size) this attempted a ~2 GiB
allocation. Under memory pressure the allocation itself trips the overcommit
tracker and the query fails with `MEMORY_LIMIT_EXCEEDED` instead of the
expected `CANNOT_READ_ALL_DATA`, making the tests
`02481_i43247_ubsan_in_minmaxany` and
`02477_single_value_data_string_regression` flaky in CI (observed in
`Stateless tests (amd_asan_ubsan, distributed plan, parallel)` on master).

Read the payload incrementally instead, growing the buffer only as bytes
actually arrive (preserving already-read bytes on reallocation). Incomplete
input now fails with `CANNOT_READ_ALL_DATA` without a large allocation up
front, while valid large strings still read back correctly. The capacity
computation is unchanged, so the on-disk format and all existing behavior are
preserved.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=81f8ef5172094f3a8abe5b01e3fe9fdc68307951&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf2d02c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) FAIL
03758_fix_isssue_87414 FAIL cidb
Stress test (arm_debug) FAIL
Logical error: Inconsistent KeyCondition behavior (STID: 5182-2f27) FAIL cidb
Stress test (arm_msan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR changes SingleValueDataString::read so corrupted or truncated serialized String aggregate states stop preallocating their declared size up front, and the new tests cover both malformed-input and multi-refill reads. The main logic looks sound, but the legacy compatibility fixup still adds an avoidable extra full-size copy on one large-string path, so I’m requesting one follow-up change before merge.

Findings

⚠️ Majors

  • [src/AggregateFunctions/SingleValueData.cpp:1461] The legacy large-string fixup copies the already-read payload into StringWithMemoryTracking tmp before growing the arena buffer. Because Arena::alloc keeps older chunks alive, this path can copy directly from the previous large_data pointer instead. Keeping old arena buffer + tmp + new arena buffer live at once makes valid old-format states with capacity == bytes_to_read < size fail with avoidable MEMORY_LIMIT_EXCEEDED exceptions under tighter limits.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 16, 2026
…ng buffer

Growing the destination inside the Arena on every ReadBuffer refill via
allocateLargeDataIfNeeded left every intermediate allocation behind (Arena
never frees), so a valid large String state spanning several refills used to
allocate a single buffer of the final rounded-up size, but now accumulated
every smaller intermediate buffer as garbage (e.g. 4 + 8 + 16 + 32 = 60 MiB
for a 17 MiB payload instead of a single 32 MiB buffer), which could regress
valid min/max/argMin/argMax(String) state reads back to MEMORY_LIMIT_EXCEEDED
under external or distributed aggregation.

Grow the buffer with Arena::allocContinue instead: it extends the current
Arena chunk in place when there is room, and otherwise copies only the bytes
read so far rather than allocating an ever bigger buffer on every refill.
When the existing buffer is already large enough, read directly into it with
a single readStrict, matching the pre-fix behavior. Incomplete input with a
huge declared size still fails with CANNOT_READ_ALL_DATA without a large
allocation up front.

Verified locally: 02477_single_value_data_string_regression and
02481_i43247_ubsan_in_minmaxany still pass, and a 17 MiB argMax(String) state
spanning multiple refills round-trips byte-for-byte through a MergeTree part.
…p, not the Arena

The previous fix grew the destination buffer inside the `Arena` via
`Arena::allocContinue` on each `ReadBuffer` refill. Because the `Arena`
never frees (it is documented to waste memory across `allocContinue` chunk
boundaries), a valid large `String` state that spans several refills kept
every intermediate reallocation live -- e.g. a 17 MiB payload arriving in
4 MiB chunks could occupy `4 + 8 + 16 + 32 = 60` MiB in the `Arena` --
regressing valid `min`/`max`/`argMin`/`argMax(String)` reads back to
`MEMORY_LIMIT_EXCEEDED`.

Additionally, setting `capacity = bytes_to_read` exactly left no room for
the legacy-format fixup, which appends one byte at index `size - 1`,
turning the old non-zero-terminated compatibility path into a one-byte
out-of-bounds write for any large value.

Now the payload is staged in a temporary heap buffer (`String`), which
releases its intermediate buffers as it grows, and only once the whole
payload has arrived do we make a single `Arena` allocation via
`allocateLargeDataIfNeeded` (rounded up to a power of two, which also
leaves room for the legacy fixup byte). The reuse branch now requires
`capacity >= size` so the fixup stays in bounds there too. Truncated input
still fails with `CANNOT_READ_ALL_DATA` without a large up-front
allocation, and the `capacity` "power of two or zero" invariant is
restored.

Verified locally: `02481_i43247_ubsan_in_minmaxany` and
`02477_single_value_data_string_regression` (whose large case exercises the
large legacy-fixup path) pass; a 5 MB `argMax(String)` state spanning ~76
decompression refills and a 2^20-byte state round-trip byte-for-byte
through a `MergeTree` part.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Note: #110632 fixes the same issue (SingleValueDataString::read preallocating the untrusted declared size upfront) with a different approach (exact-size chunk accumulation with a single final arena allocation there vs. Arena::allocContinue here). Only one of the two should be merged.

Related: #110632

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master to refresh the branch.

On the AI-review blocker (the transient two-buffer peak for a first-time large state that spans several ReadBuffer refills): this is the irreducible cost of not trusting the untrusted declared size up front, which is the entire point of the fix. Worth noting that the sibling PR #110632 — which fixes the same issue via exact-size chunk accumulation instead of a heap String — received the identical blocker, so the transient peak is inherent to any "stage the unverified bytes, then commit to a single arena buffer" strategy rather than specific to this implementation.

The one alternative that avoids the second buffer — growing the destination in the Arena in place (Arena::allocContinue) — was rejected by an earlier review here because the Arena never frees: the intermediate power-of-two allocations leak permanently (a valid 17 MiB state read in 4 MiB refills would leave 4 + 8 + 16 + 32 = 60 MiB alive in the arena for its whole lifetime). Heap staging is strictly better than that: the scratch buffer is released immediately after the memcpy, leaving exactly one arena buffer, and the transient peak is bounded rather than permanently retained.

For the common repeated-read case the reuse branch (capacity >= size) still reads directly into large_data with no staging, matching the pre-fix single-buffer behavior. The only path with a transient 2× peak is a first-time large read that also spans multiple refills; and even there the pre-fix behavior on malformed input was a hard MEMORY_LIMIT_EXCEEDED on a bogus (up to ~2 GiB) up-front allocation.

Since this PR and #110632 fix the same problem with the same inherent tradeoff, only one should be merged — leaving the choice of approach, and whether that transient peak is acceptable, to the maintainer.

The only remaining CI failure is 04498_query_condition_cache_local_files, a known flaky test unrelated to this change (fix in flight: #110763).

…String::read

The staging buffer was a plain `String`, whose heap allocations go through
the global `operator new`: they are counted against the query memory limit
but not refused when it is exceeded. A corrupted state with a large actual
payload could therefore stage arbitrarily many bytes past `max_memory_usage`
before failing with `CANNOT_READ_ALL_DATA` at EOF, weakening the memory-limit
contract compared to the old single-`Arena`-allocation path.

Use `StringWithMemoryTracking` (backed by `AllocatorWithMemoryTracking`,
which calls the enforcing `CurrentMemoryTracker::alloc`), so the limit is
enforced as the staging buffer grows — the same fix that was applied to the
sibling PR #110632.

Verified: `02477_single_value_data_string_regression` and
`02481_i43247_ubsan_in_minmaxany` pass; a 10 MB `argMax(String)` state
written in 64 KiB compressed blocks (~150 read-buffer refills) round-trips
byte-for-byte, and the same read under `max_memory_usage = '8Mi'` is now
refused with `MEMORY_LIMIT_EXCEEDED` during staging.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 865d236: the staging buffer is now StringWithMemoryTracking instead of a plain String. Plain-String heap allocations go through the global operator new, which only counts memory against the query limit without refusing allocations that exceed it — so a corrupted state with a large actual payload could stage arbitrarily many bytes past max_memory_usage before failing at EOF. StringWithMemoryTracking is backed by AllocatorWithMemoryTracking (the enforcing CurrentMemoryTracker::alloc), so the limit is enforced as the buffer grows, matching the Arena path's behavior. This mirrors the equivalent fix already applied to the sibling #110632, keeping the two alternatives at parity.

Verified locally: 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany pass; a 10 MB argMax(String) state written in 64 KiB compressed blocks (~150 read-buffer refills) round-trips byte-for-byte; the same read under max_memory_usage = '8Mi' is refused with MEMORY_LIMIT_EXCEEDED during staging (previously it staged the whole payload uncounted); and the truncated-input cases still fail with CANNOT_READ_ALL_DATA after only a few hundred bytes.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jul 18, 2026
The test asserts `QueryConditionCacheHits` on the instance-wide query
condition cache. A parallel sibling test that drops or renames any
UUID-less (path-keyed) `MergeTree` table calls `Context::clearCaches`,
which wipes the query condition cache, so an expected cache hit turns
into a miss and the test output differs from the reference.

Confirmed from a failed CI run: `CurrentMetric_QueryConditionCacheEntries`
dropped from 331 to 1 exactly between the test's cache-populating query
and the query expected to hit the cache, with no
`SYSTEM DROP QUERY CONDITION CACHE` in the server log.

All other tests asserting query condition cache hits are already tagged
no-parallel for the same reason.

Failures:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110433&sha=62da4c8be297d0ee37833fc6d0af32868f4bbc9f&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29
ClickHouse#110433
ClickHouse#110630

Co-Authored-By: Claude Fable 5 <[email protected]>
…::read

The AI review (clickhouse-gh) noted that the existing regressions
(`02477_single_value_data_string_regression`,
`02481_i43247_ubsan_in_minmaxany`) deserialize contiguous string
literals or small states, so they never force repeated `ReadBuffer`
refills and never exercise the incremental staging path
(`while (bytes_read < bytes_to_read)`) or the `StringWithMemoryTracking`
`MEMORY_LIMIT_EXCEEDED` contract introduced in `865d236`.

Add `04607_single_value_data_string_multi_refill`: an 8 MB
`AggregateFunction(max, String)` state is written with small compressed
blocks so that reading it back spans many read-buffer refills. The test
asserts the state round-trips byte-for-byte through the incremental read
path, and that reading it under a `max_memory_usage` far below the
payload is refused with `MEMORY_LIMIT_EXCEEDED` while staging (the
staging buffer is `StringWithMemoryTracking`, which enforces the limit
as it grows rather than merely counting the bytes).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…f-two payloads

The reuse (direct-read) branch in `SingleValueDataString::read` required
`capacity >= size` (i.e. `>= bytes_to_read + 1`). Because
`allocateLargeDataIfNeeded` rounds capacities up to a power of two, a valid
payload whose content length is exactly a power of two (`1 MiB`, `8 MiB`, ...)
leaves `capacity == bytes_to_read`, so a subsequent read of that state took the
staging path, re-copying the whole value into a temporary `StringWithMemoryTracking`
and potentially failing with `MEMORY_LIMIT_EXCEEDED` where the old single-buffer
read succeeded.

Only the normal zero-terminated format needs `bytes_to_read` bytes in the buffer
(`getStringView` returns `size - 1` bytes); the extra byte is required solely by
the rare legacy (non-zero-terminated) fixup that appends one byte at index
`size - 1`. Take the direct-read reuse path whenever `capacity >= bytes_to_read`,
and grow the buffer once (preserving the bytes already read) inside the legacy
fixup only when `capacity == bytes_to_read` leaves no room for the trailing byte.

This is a no-op for the common fresh-place deserialization path, which always has
`capacity == 0 < bytes_to_read` and keeps taking the staging branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ueDataString payloads

The previous fix entered the incremental staging path whenever the
destination buffer was not already large enough (`capacity < bytes_to_read`).
On the common fresh-state deserialization path
(`SerializationAggregateFunction::deserializeBinary` /
`ColumnAggregateFunction::deserializeAndInsertFromArena`), `function->create`
yields a `SingleValueDataString` with `capacity == 0`, so every large
`min` / `max` / `argMin` / `argMax(String)` state was staged through
`StringWithMemoryTracking` even when the whole payload was already present
contiguously in the `ReadBuffer` -- regressing one arena allocation plus a
direct `readStrict` into a heap growth plus two full copies, and adding a
transient memory peak.

Stage incrementally only when it is really necessary: the destination buffer
is not already large enough AND the whole payload is not yet present in the
read buffer (`buf.available() < bytes_to_read`). In every other case the bytes
either already fit in the existing buffer or are proven to physically exist in
the read buffer, so we allocate exactly `bytes_to_read` (via the no-op-when-it-
fits `allocateLargeDataIfNeeded`) and read directly. The malformed-input
invariant is preserved: a truncated state with a bogus huge size prefix still
has `buf.available() < bytes_to_read`, so it stages and fails with
`CANNOT_READ_ALL_DATA` instead of attempting a huge allocation.
… 02477

The existing `2^31-1` / `2^30` malformed-input assertions in
`02477_single_value_data_string_regression` run without a memory limit, so on
roomy runners the pre-fix speculative-allocation path could still pass by
eventually reaching `CANNOT_READ_ALL_DATA` after the huge allocation succeeded.

Add a focused assertion that reads a malformed state with a bogus `2^30`
(~1 GiB) size prefix under `max_memory_usage = '100Mi'`. Before the fix the
whole declared size was allocated up front, tripping the memory tracker with
`MEMORY_LIMIT_EXCEEDED`; now the ~100 KB of actual data is staged incrementally
below the limit and the read reaches EOF, reporting `CANNOT_READ_ALL_DATA` --
exactly the regression this PR fixes.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

On the AI-review Tests ask (a focused repro with max_memory_usage in the window between the old single-buffer peak and the new scratch+arena peak, to prove whether valid multi-refill reads preserve the previous memory envelope):

I'm intentionally not adding that test.

  • It would assert that a valid large state fails with MEMORY_LIMIT_EXCEEDED inside that narrow window — i.e. it just codifies the transient two-buffer peak, which is exactly the design tradeoff already flagged (and dismissed) above. Whether that transient peak is acceptable is the maintainer's call, not something to pin as expected behavior.
  • The window (old_peak, new_peak) is narrow and build-dependent: arena chunk sizing, roundUpToPowerOfTwoOrZero rounding, memory-tracker granularity, and per-config overhead differ substantially across the debug / ASan / TSan / MSan / coverage builds. A test pinned to a single max_memory_usage value in that window would pass on some configs and fail on others — reintroducing the very flakiness (02477_single_value_data_string_regression / 02481_i43247_ubsan_in_minmaxany) this PR fixes.
  • The sibling Fix flaky 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany #110632 (same fix, same inherent tradeoff via exact-size chunk accumulation) declined the same test for the same reason and is approved.

The behavior that is deterministic and worth covering is already covered: truncated/bogus sizes fail with CANNOT_READ_ALL_DATA (02477/02481, incl. a tight-memory malformed case), a valid multi-refill state round-trips byte-for-byte, and a valid multi-refill read under a too-tight limit is refused during staging (04607_single_value_data_string_multi_refill).

As noted, only one of #110630 / #110632 should be merged — leaving the choice of approach, and whether the transient multi-refill peak is acceptable, to the maintainer.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-ci labels Jul 24, 2026
/// format; the staging branch above already reserves the extra byte.
if (capacity < size)
{
StringWithMemoryTracking tmp;

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.

Here the bytes are already resident in the old Arena allocation, so staging them through StringWithMemoryTracking tmp is unnecessary. Arena::alloc never invalidates earlier chunks, so this branch can save old_large_data, call allocateLargeDataIfNeeded(size, arena), and copy directly from the old arena buffer.

As written, a valid legacy non-zero-terminated state with capacity == bytes_to_read < size (for example a 2^k + 1 payload on the direct-read path) keeps three full copies live at once: the old arena buffer, tmp, and the new arena buffer. That still creates avoidable MEMORY_LIMIT_EXCEEDED failures on a compatibility path where only the old arena buffer plus the grown arena buffer are actually needed.

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 25/29 (86.21%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing in favour of the test-only fix in #110632.

Both approaches complicated the hot read path of SingleValueDataString::read only to make the error code deterministic for two tests, which is not worth it: staging the value outside the arena costs a transient peak of about twice the payload on the multi-refill path, and growing the allocation in place with Arena::allocContinue strands every superseded copy in the arena until the query ends.

The flakiness is fixed in the tests instead — 02477_single_value_data_string_regression and 02481_i43247_ubsan_in_minmaxany now accept MEMORY_LIMIT_EXCEEDED as well as CANNOT_READ_ALL_DATA, since the property under test is that a corrupted state is rejected, not which of the two errors is reported. The read path stays exactly as it is on master.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test asserts `QueryConditionCacheHits` on the instance-wide query
condition cache. A parallel sibling test that drops or renames any
UUID-less (path-keyed) `MergeTree` table calls `Context::clearCaches`,
which wipes the query condition cache, so an expected cache hit turns
into a miss and the test output differs from the reference.

Confirmed from a failed CI run: `CurrentMetric_QueryConditionCacheEntries`
dropped from 331 to 1 exactly between the test's cache-populating query
and the query expected to hit the cache, with no
`SYSTEM DROP QUERY CONDITION CACHE` in the server log.

All other tests asserting query condition cache hits are already tagged
no-parallel for the same reason.

Failures:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110433&sha=62da4c8be297d0ee37833fc6d0af32868f4bbc9f&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29
ClickHouse#110433
ClickHouse#110630

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant