Repository navigation
Do not pre-allocate huge buffers when deserializing SingleValueDataString - #110630
alexey-milovidov wants to merge 13 commits into
Conversation
…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]>
|
Workflow [PR], commit [cf2d02c] Summary: ❌
AI ReviewSummaryThis PR changes Findings
Final Verdict
|
…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]>
|
Note: #110632 fixes the same issue ( Related: #110632 |
|
Merged On the AI-review blocker (the transient two-buffer peak for a first-time large state that spans several The one alternative that avoids the second buffer — growing the destination in the For the common repeated-read case the reuse branch ( 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 |
…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]>
|
Pushed 865d236: the staging buffer is now Verified locally: |
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.
|
On the AI-review Tests ask (a focused repro with I'm intentionally not adding that test.
The behavior that is deterministic and worth covering is already covered: truncated/bogus sizes fail with 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. |
| /// format; the staging branch above already reserves the extra byte. | ||
| if (capacity < size) | ||
| { | ||
| StringWithMemoryTracking tmp; |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 25/29 (86.21%) · Uncovered code |
|
Closing in favour of the test-only fix in #110632. Both approaches complicated the hot read path of The flakiness is fixed in the tests instead — |
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]>
SingleValueDataString::read(the deserialization used bymin,max,argMin,argMaxoverString) reads a 4-byte size prefix from possibly corrupted or truncated input and then pre-allocated the entire declared size (up to~2 GiB) viaallocateLargeDataIfNeededbeforereadStrictcould 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 bytesAggrdecode as a~1.79 GiBsize — this attempted a~2 GiBallocation. Under memory pressure the allocation itself trips the overcommit tracker and the query fails withMEMORY_LIMIT_EXCEEDEDinstead of the expectedCANNOT_READ_ALL_DATA. That made the tests02481_i43247_ubsan_in_minmaxanyand02477_single_value_data_string_regressionflaky (observed on master inStateless 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_DATAwithout 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
ReadBufferrefills 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 tightmax_memory_usage, such a read can now fail withMEMORY_LIMIT_EXCEEDEDwhere 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_DATAafter allocating only a few hundred bytes; both tests pass repeatedly under randomized settings; andargMax(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):
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 withCANNOT_READ_ALL_DATAinstead ofMEMORY_LIMIT_EXCEEDED.Documentation entry for user-facing changes
🤖 Generated with Claude Code