Repository navigation
Do not allocate from sizes declared in aggregate function states - #117536
nikitamikhaylov merged 16 commits into
Conversation
`deserialize` read a size out of an untrusted aggregate state and then reserved, resized or allocated that much before reading the payload meant to back it. `readVarUInt` has no maximum, and the bounds that exist are element counts, which cannot bound an allocation: a count cap N still admits N * sizeof(element) bytes. ClickHouse#108465 capped the counts at four of these sites and left exactly that residual. Six bytes of state (`unhex('808080800400')`, which is exactly MAX_STATISTICS_STATE_SIZE and so passes its strict `>`) requested 8.00 GiB through StatisticalSample::read. Tracked peak for that state is now 31.70 KiB, and for a legitimate state it is byte-identical before and after. The sites read payload-first instead, choosing a mechanism per destination: clamp a reserve that is only an optimization to what the buffer already holds; grow a PODArray in place, the way addX/addY already fill those same arrays; grow a String destination directly; or, for an Arena, allocate once after staging the payload outside it, since an Arena cannot reuse a superseded block. Every count * width product is checked with common::mulOverflow using serialized widths rather than sizeof(Element), which differ for timeSeriesGroupArray because Element is padded. A -Map state that repeats a key is now rejected, since serialize() walks a map and cannot emit one, while each repetition used to allocate a nested state that emplace then dropped. No cap, error code, constant or allocation policy moves, and the fully-buffered path is unchanged, so there is no format change, no setting and no compatibility shim. groupBitmap keeps a plain String rather than a tracking container precisely to preserve its counted-but-not-refused allocation policy, because 8d044e8 raised its bound to 100 GiB for real user states. This is deliberately not a universal claim: SingleValueDataString::read still allocates from its declared size, by 6594a77, and is untouched here. The mechanism follows the arc of PR ClickHouse#110632, whose last commit reverted it for test determinism rather than on a fault in the design; here it is the only remedy that closes the finding without rejecting states the current writer can produce. Comments left over-budget by ClickHouse#108465 in StatCommon.h, GroupArrayIntersect.cpp and SequenceMatch.cpp are trimmed to the invariant they state.
Review round 1 on the previous commit. windowFunnel carried the same reserve-behind-a-count-cap residual in both of its state layouts, and this change cites windowFunnel three times as the precedent for its own caps, so a reader following the citation landed on unfixed code. Each divisor is taken from that layout's own serialize, which is why the strict_once variant carries the extra sizeof(UInt64) for unique_id. The *ToGrid family reserved its bucket map before a single bucket index arrived, bounded only by a grid size the same caller chooses through the aggregate's parameters: an 18-byte state reached 2.50 GiB. The divisor at that shared site is sizeof(size_t), the bucket index, because the bucket payload varies by derived function. readStringBinaryGrowing duplicated a helper of the same name that landed two days earlier in ReadHelpers.cpp, in this exact doctrine and with a different error code. It built only because that file does not include ReadHelpersArena.h. Its single caller now spells the four lines out, so the name belongs to its author again and readStringGrowing stays the shared primitive. timeSeriesGroupArray staged both wire runs, holding them across the final allocation. Staging the timestamps run alone makes the element count payload-backed, so the values run reads straight into place as the fast path already does, and one temporary disappears. quantileGK reserved where the call it replaced allocated exactly; reserve_exact keeps the allocation policy the description claims is unmoved. Tests: a fixture per newly bounded site, both windowFunnel layouts and both grid sizes, plus positive controls. A groupBitmap state and a -Map String key allocate through operator new, which the memory tracker counts but never refuses at the default min_allocation_size_to_throw_on_memory_limit, so no in-suite assertion can separate the arms there; those two fixtures pin the path and the error, and the allocation change is carried by measurement. The compressed block sizes are pinned on the round-trip table so its block structure stops depending on the randomizer.
Review round 2 on the previous commit. readStringBinaryInto stages a value that spans compressed blocks before committing it to the Arena, because an Arena cannot reuse a superseded block. Staging it as one tracked object per buffer refill made the cost a function of the block size rather than of the value: at 4-byte blocks a 1 MB value needs 250001 objects of 24 bytes each. Small blocks are supported and reachable, and 02124_uncompressed_cache pins 12 bytes, while the test harness randomizes both compress-block settings down to 1. Since the staging containers are memory-tracked and throwing, that overhead converted a state that used to load into MEMORY_LIMIT_EXCEEDED, so this is a compatibility fix as well as a simplification. Measured on a wide part with both block sizes pinned to 4, reading one legitimate 1 MB value back needs over 10 MB with per-refill staging and at most 1.5 MB with one growing container. The three TimeSeries/ deserializers are dropped from this change. ClickHouse#117404 covers all four sites they touched, so nothing is lost by leaving them to it. The two fixtures whose destination is operator new pin their path and error only, and their comment now says so. The tracker counts that destination but never refuses it: enforce_memory_limit is size >= min_allocation_size_to_ throw_on_memory_limit, a ServerSettings entry defaulting to UInt64::max, so no stateless test can make either side refuse. Arena and PODArray destinations do refuse, because Allocator.cpp allocates through CurrentMemoryTracker::alloc with the limit enforced, which is why the other sites here redden. Peak RSS for the -Map key improves from 1444 to 423 MiB. The refill fixture pins min_bytes_for_wide_part = 0 beside its two block sizes. Part type is randomized per run, and a compact part resolves its own 1 MiB bound: at a 64 KiB pin it wrote 2 blocks where the wide writer writes 31. Without the pin the block structure that arm depends on was not deterministic.
This change rewrote `quantileGK`'s deserialize loop from `resize_exact` plus indexed assignment to a clamped `reserve_exact` plus `push_back`, and nothing in the repository executed it. `AggregateFunction(quantileGK(...))` is declared by exactly one test file, 04401 itself, and both of its fixtures throw before the first append, so deleting `sampled.push_back(stats)` left the suite green while every state read from storage or through a distributed merge would silently lose its samples. Two assertions now cover it and that mutation reddens BOTH of them: a captured valid state, which is fully buffered so the clamp equals the count, and a table round-trip through 4-byte compressed blocks, where the clamp is 0 and all 212 appends grow the array. Under the same mutation the pre-existing in-memory line stays at 497, which is the control: `-Merge` merges the in-arena state and never deserializes. The `-Map` duplicate-key rejection now does one lookup rather than `contains` followed by `emplace`, so a legitimate key is hashed once. Literal names in added comments are backticked per `.claude/CLAUDE.md`. The three inherited `(matches/mirrors windowFunnel)` lines are deliberately left alone: that text comes verbatim from merged ClickHouse#108465, so re-marking it would be churn on prose already in master. The two table fixtures move to `05055_aggregate_state_refill_staging`, keeping 04401 at its 0.3 s runtime. `add-test` proposed 05054, but master has since merged `05054_storage_alias_materialize_ttl`, so the new test is 05055.
The -Map combinator allocates and `create`s a nested state before `merged_maps` takes ownership of it, so every path that leaves the map without the place has to run the destructor itself. Two such paths exist: the duplicate-key rejection added earlier in this branch, and an `emplace` that throws, which is reachable because `merged_maps` is an `UnorderedMapWithMemoryTracking` and can raise MEMORY_LIMIT_EXCEEDED on rehash. `destroyImpl` walks `merged_maps`, so a place that was never inserted is never destroyed. The cost is not the arena, which is discarded with the outer state, but heap owned by the nested state. It is wrong to assume a freshly created state owns none: the -Map combinator wraps an arbitrary nested function, and `groupArrayIntersect`'s data holds a plain `HashSet`, whose default constructor allocates its bucket array unconditionally. Measured over 20000 duplicate-key rejections of `groupArrayIntersectMap(Map(String, Array(UInt64)))`, the server's tracked memory grows 2052.9 bytes per rejection before this change and 4.6 bytes after, so the leak is per-rejection and attacker-repeatable. An earlier round of this branch argued it cost nothing; that was wrong. The `try`/`catch` is cleanup and rethrow, not a fallback to a slower path. It stops before `deserialize`, because from that point the map owns the place and `destroyImpl` reaches it. `SerializationAggregateFunction::deserializeBinary` pairs `create` with destroy-on-throw the same way. Also add a `05055` fixture that reads a `mannWhitneyUTest` state back from a table pinned to 4-byte compressed blocks. `StatisticalSample::readSample` grows the sample by what the buffer already holds, and every existing test of a StatCommon consumer feeds it a fully buffered `CAST(unhex(...))` blob, so the loop ran exactly one batch and the `done > 0` arithmetic was untested. At 4-byte blocks each element spans a refill; mutating `sample.data() + done` to `sample.data()` now reddens that assertion and leaves the buffered ones green. Finally, backtick `windowFunnel` in the three comment lines this branch adds, per `.claude/CLAUDE.md`. An earlier round left them alone on the grounds that the text is inherited from a merged PR; the lines themselves are new here, and the rule predates this branch's base, so it applies.
`.claude/CLAUDE.md` asks for names from the SQL language, classes and functions inside inline code blocks, and for function names written without parentheses. An earlier round applied that to the source comments and missed the test files. Comment text only; no comment is added or removed, and both references are unchanged.
The guard added earlier in this branch compared the declared `string_size` against `in.available()`, but the allocation it exists to prevent is `string_size - serialize_string_with_zero_byte` bytes; the remaining byte is consumed by a separate `in.ignore`. The extra byte made the guard fire on a strictly larger set than master's own failure condition: with the zero-byte terminator enabled and `string_size == in.available() + 1`, master read the payload successfully and threw ATTEMPT_TO_READ_AFTER_EOF from `ignore`, while the guard answered CANNOT_READ_ALL_DATA. That is a live path rather than a theoretical one, because `createForAggregationState` sets the flag and every aggregation-state caller uses it. Subtracting the terminator makes the guard fire exactly when `readStrict` itself would, with the same error code and, once the format argument is reduced too, the same message text, so the change moves no cap and no error code. The subtraction cannot underflow: a size below the terminator width is already rejected as INCORRECT_DATA two lines above. The new `04401` line pins the boundary from all three sides. It raises ATTEMPT_TO_READ_AFTER_EOF on pristine master and on this build, and CANNOT_READ_ALL_DATA on the build before this commit, where it is the only line of the file that fails. `03716_topk_bad_data`, which pins both codes on this exact path, stays green.
`04401` already runs the duplicate-key rejection, but it only asserts the error code, and the code is identical with and without the cleanup: deleting the whole `try`/`catch` leaves the entire suite green while every crafted state leaks 2048 bytes. The leak has no in-suite oracle because a server accumulates it silently, so this test drives the same blob through `clickhouse local`, whose at-exit leak check runs while the process is short enough for the state to be the only thing outstanding. `04834_aggregation_in_order_partial_key_state_leak` is the in-tree precedent and supplies the shape: the ASan probe that makes the test results-only elsewhere, the unique `--path` that keeps it parallel-safe with no tag, and a verdict line stable across both builds. One difference is forced: there the query succeeds, so a non-zero return code is itself the leak signal, while here the rejection makes an error code expected. The signal is therefore an abort, plus the report text for a runner that does not redirect it. One rejection is enough, measured rather than assumed. Removing the `try`/`catch` and rebuilding turns this test into a failure reporting `2048 byte(s) leaked in 1 allocation(s)`, whose stack is the `HashSet` bucket array that `groupArrayIntersect`'s data allocates in `create`. Under the same mutation `04834` and `04401` both stay green, so this detects the leak rather than an unrelated noise floor, and `04401` is confirmed not to cover it.
…y carries My open PR ClickHouse#113926 ("Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators") gained commit `be0cdb16e128` earlier today, fixing this same leak in this same loop: the duplicate-key `INCORRECT_DATA` rejection, the `destroy` of the nested state it abandons, and a stateless test for it. That PR is the elder and dedicated owner of the leak, so carrying a second copy here would only ask a reviewer to referee a duplicate of my own making. What stays is the allocation half, which is what this PR is about and which ClickHouse#113926 does not contain: `AggregateFunctionMapCombinatorData<String>::readKey` still reads its declared size, refuses it above `DEFAULT_MAX_STRING_SIZE`, and grows the key from the bytes actually read instead of reserving the declaration. ClickHouse#113926 does not touch `readKey`, so the two changes do not overlap. The two 04401 assertions that exercised the rejection go with it, as does `05056_aggregate_map_duplicate_key_state_leak`, whose oracle now has no fix to observe here. That test is kept in `.scratch/handoff-05056-for-113926/`: it is stronger coverage than ClickHouse#113926's `.sql`, because an at-exit leak is invisible to a test that only asserts an error code, and it is available to whoever finishes that PR. The bounded `readKey` read keeps its own 04401 coverage.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). 7 rounds, 59 findings: 50 AGREE,
Nits, agreed and fixed: literal class and function names wrapped in inline code per the repository Reported and not fixed. Two comment blocks run to about 190 characters across two lines each, Reviewed and deliberately not changed. Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260901-135800 |
|
Workflow [PR], commit [f34c2c7] Summary: ❌
AI ReviewSummaryThis PR hardens several aggregate-state deserializers so truncated states no longer allocate from attacker-declared sizes before any payload is read, and it adds focused stateless coverage for both malformed and refill-spanning states. Most of that work checks out on the current head, but Findings
Final VerdictChanges requested. The remaining LLVM Coverage ReportMeasured on commit f34c2c7.
Changed lines: Changed C/C++ lines covered: 101/108 (93.52%) · Uncovered code |
Pre-PR validation gate (click to expand)
Randomized runs: 100 of 100 on the two changed tests with settings randomization, and 100 of 100 with Session id: cron:clickhouse-impl-slot-4:20260901-132500 |
|
cc @Algunenano @azat, could you review this? Several aggregate function deserializers sized an allocation from a count declared in the serialized state, so a six-byte state could request 8 GiB before any payload was read; they now extend their destination only by bytes the buffer already holds, moving no cap, constant or error code. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units38 translation units recompiled, 310 s compile time in total, 38 of them have a recent master baseline. |
`05055_aggregate_state_refill_staging` pins `max_compress_block_size = 4`, so its 1 MB value arrives in 250001 compressed blocks. With full part storage a stream's on-disk buffer is the compress block size (`MergeTreeWriterStream.cpp:312`), so each block became its own `write()`: 1875016 syscalls, 2.4 s of a 2.7 s test. Under the flaky checks' `--jobs 8` that is 218-243 s on amd_binary, 228-287 s on amd_debug and the 600 s cap on amd_asan_ubsan, against a 180 s per-test ceiling. The amd_asan_ubsan iterations that drew packed storage from `min_bytes_for_full_part_storage` randomization finished in 26-33 s and passed. The part holds one row, so `min_rows_for_full_part_storage = 2` selects packed storage whatever the payload size is. The reader sees the same input either way: `CompressedReadBufferBlocks` 250002, `CompressedReadBufferBytes` 1000052, peak `memory_usage` 1231304 bytes, and `max_memory_usage = 8000000` unchanged, so the assertion still discriminates a per-piece staging cost. Storing the same value in one 2 MB block reports 2 blocks, so that counter does separate the shapes. 50 randomized plus 50 non-randomized runs at `--jobs 8`, all green: 05055 max 2.84 s -> 0.88 s and 2.79 s -> 0.83 s.
Four `///` blocks were over the limit asked for on this work: 153, 194, 181 and 189 characters. Each states a property that is not visible at the call site, so the wording is shortened rather than the content dropped.
|
The The fixture pins Nothing the reader sees changes, so the assertion is not weakened: Also shortened four |
`Stateless tests (amd_binary, flaky check)` fails it 5 of 5 at 236.8-251.4 s against the 180 s per-test ceiling, while at the same commit it runs in 6.0-9.5 s on amd_debug, 8.1-12.6 s on amd_asan_ubsan, 25.1-31.9 s on amd_msan, 77.4-103.6 s on amd_tsan and 2.2-3.7 s in the non-flaky `arm_binary, parallel` lane. Sibling 04401 passes in the same amd_binary job in 8.8-18.3 s, so the cost is this fixture under the flaky check's thread fuzzer and 8-way self-concurrency, not the runner. The cost is the 250001 four-byte compressed blocks of the second arm, and that count is what the arm measures: `max_memory_usage = 8000000` separates a staging implementation costing the number of pieces from one costing the value. Measured against the per-refill-object build this PR started from, peak `memory_usage` at 250002 blocks is 1232632 vs 9762882 bytes; at 50002 blocks 429672 vs 1375560; at 25002 blocks both report 331000, because the per-piece overhead no longer clears `max_untracked_memory`, 4 MiB by default. A smaller fixture would have to pin that threshold too, so shrinking it trades the assertion for a smaller number. `long` skips the too-long verdict (`tests/clickhouse-test:3630-3634`) and repeats the test at `--long-test-runs-ratio 0.1`, 5 runs of 50; every other lane runs it unchanged. The tag is parsed rather than silently ignored: at `--test-runs 10 --flaky-check --jobs 8` the runner expands to 11 tests with it and to 20 with the prefix corrupted to `Tagz:`, 11/11 and 20/20 green.
|
I tagged the test
Unrelated to this diff: both |
…its byte count The generic path clamped an element count with `buf.available()`, which is a byte count. One long element makes the two diverge, and `HashTable::reserve` sizes the table from that count at a 0.5 load factor with a 16 byte slot, so the reserve was up to 64 times the bytes that had arrived. The ceiling from this line was 4.00 GiB, reached with about 100 MB of payload. Every other clamp on this branch divides `buf.available()` by the per element wire size, which for those functions also equals the per element cost of the container, so their reserve is already bounded by the payload. Elements here are variable length and have no such size, so the divisor is the slot size instead. The reserved table then stays within about four times the arrived bytes, the same bound the numeric path gets from `sizeof(T)`. Reserving is only an optimization, so a state that now under reserves grows in the loop as it did before. Measured on release builds, one element in a state declaring 99999999: payload before after 5 MB 256.01 MiB 16.01 MiB 20 MB 1.00 GiB 64.01 MiB 100 MB 4.00 GiB completes under a 858 MiB limit Legitimate states are unaffected: 100000 short elements, 50000 empty elements, 500 long elements, a state read back from a table in 4 byte blocks, and both `is_plain_column` instantiations return identical results on the previous head, on this commit and on master. The new 04401 line pins it. Its 200000000 limit sits between the two arms: the previous head asks for a single 256.01 MiB chunk that exceeds the limit on its own, and this commit needs 44.73 MiB in total on both debug and release.
The reserve on this branch is derived from `buf.available()`, so a state whose payload spans compressed block boundaries under reserves and the append loop then falls back to `PaddedPODArray` geometric growth, which doubles past the declared length. A valid state kept more `Stats` capacity than it serialized, so a state that fit under a given `max_memory_usage` could start failing only because of where its blocks happened to end. Measured on debug builds, a well formed state of 1000000 elements read back from a table at 4096 byte blocks, whose exact array is 23.02 MiB: arm final array passes at max_memory_usage master 23.02 MiB 28.61 MiB previous head 33.00 MiB 66.76 MiB this commit 22.89 MiB 47.68 MiB The retained cost is what multiplies across live states, so the same fixture at 64 states of 100000 elements in one block is the sharper measurement: master and this commit both pass at 162.12 MiB, the previous head needs 247.96 MiB. Clamping the ladder costs nothing when the payload arrived in full, because the initial reserve already covers the whole array and the branch never fires. The residual gap in the single state column is the old buffer still being live while the larger one is allocated, which is inherent to reading payload first and is bounded by what arrived. The `chassert` is what pins the clamp. 04401 already reads a `quantileGK` state at 4 byte blocks, where `available` is below one element and the branch fires on every append, so with the clamp deleted that test dies on the assertion rather than passing quietly: `Logical error: 'sampled.capacity() <= sampled_len'`. A memory threshold was measured as the alternative and rejected: the widest separation I could build is 12 percent either side of the limit, and dropping the `preferred_block_size_bytes` pin makes both arms pass, so the oracle would fail silently rather than loudly. `quantileGK` held the only `reserve_exact` on this branch. Legitimate states round trip byte identically on master, on the previous head and here for 1, 2, 169, 170, 171, 341, 342, 683, 5000 and 100000 elements read across 4096 byte blocks, and the cap boundary has not moved: at the cap the read reports `CANNOT_READ_ALL_DATA`, one past it `TOO_LARGE_ARRAY_SIZE`.
CI finish ledger - f34c2c7Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260904-020000 |
47bc5bf
Backport #117536 to 26.8: Do not allocate from sizes declared in aggregate function states
…egate function states
Backport #117536 to 26.7: Do not allocate from sizes declared in aggregate function states
Cherry pick #117536 to 26.3: Do not allocate from sizes declared in aggregate function states
…egate function states
Cherry pick #117536 to 26.6: Do not allocate from sizes declared in aggregate function states
…egate function states
Backport #117536 to 26.6: Do not allocate from sizes declared in aggregate function states
Backport #117536 to 26.3: Do not allocate from sizes declared in aggregate function states
…ed in aggregate function states
AGG: aggregate-function states that declare huge sizes -> the deserializers allocate for the declared size before reading any data (1-32 GiB requests from a few bytes: OOM/DoS). Effect in the production build a394e92: 15 of the 18 crafted states that ClickHouse#117536 added to upstream test 04401 fail with MEMORY_LIMIT_EXCEEDED under a 100 MB limit, while official 26.8.8.8 reports the missing payload (evidence/fix_ci_20260925/upstream_repro/corrected3/aggbomb_matrix_PROD263_UP2688.tsv). Upstream test 04401 itself cannot pass on 26.3: it also expects the size caps of ClickHouse#108465, which was never backported to 26.3. Upstream patch unchanged, with the backport's test 05055_aggregate_state_refill_staging (it passes on the production build as well); the old-fail/new-pass test is the fork test 10319_aggregate_state_declared_size_no_allocation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lared size (ClickHouse#117536) The 18 crafted states that upstream ClickHouse#117536 added to its test 04401 declare a huge element count or string length and carry no payload. Under a 100 MB memory limit the result must be a read error or a size bound, never MEMORY_LIMIT_EXCEEDED; the legitimate controls keep the upstream results. Upstream 04401 itself also expects the per-function caps of ClickHouse#108465, which 26.3 never got, so it cannot be the fork's test. Production build a394e92: fails (15 of 18 states hit MEMORY_LIMIT_EXCEEDED); official 26.8.8.8: passes (isolated servers and clickhouse local: evidence/fix_ci_20260925/upstream_repro/corrected3/). Co-Authored-By: Claude Opus 5.5 <[email protected]>
… topology check for the open GROUP BY defect - stateless_tests.txt: +77 tests of the third batch and 10319 (13 pyarrow tests run outside the gate). - known_defects.json: +64 KD-UP entries (fixed, each naming its commit), now 145 entries, 1 open. Three entries use the tests their 26.3 backports carry instead of the upstream tests the triage had used: ClickHouse#108728 (26.3 has no CREATE OR REPLACE MATERIALIZED VIEW; 04492_create_or_replace_table_as_select_keeps_merges), ClickHouse#110590 (05059 aborts the production server; 04307/04350 with the separately backported guards; 03057 is external), ClickHouse#117536 (05055 and the fork test 10319; upstream 04401 also needs ClickHouse#108465). - KD-D512-MIXED-GROUPBY-NULLABLE stays open; its decision records the isolated validation of the replica-group upgrade topology and the rules it needs. It is not a rollout approval. - tools/replication/upgrade_topology_check.sh: that validation, vendored from the skill draft. - tools/upstream/triage_server_tests.py: a row whose test came from the upstream PR (the backport does not carry it) is classed `...-upstream-test` (a lead to review, not evidence); https URLs and web disks count as external. - VENDORED.sha256 and README (selection count, the mandatory mixed-version GROUP BY release check - the text still said it was not part of the gate - and the two tools). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…its bytes arrive `ThetaSketchData::read` read the sketch bytes with `readVectorBinary` at its default 1 GiB bound, which resizes the vector to the declared size before the payload is read. A 5-byte state (`varint(1 << 30)` and no payload) therefore allocated and zeroed 1 GiB before failing with `CANNOT_READ_ALL_DATA`, and `max_memory_usage` did not stop it: the vector is allocated through `operator new`, which the memory tracker counts but only refuses above `min_allocation_size_to_throw_on_memory_limit` (0 by default, i.e. never). On master the constant `CAST` of that state is evaluated four times during analysis, so each query allocated 4 GiB. Read the length, keep the 1 GiB bound and `TOO_LARGE_ARRAY_SIZE`, and append only the bytes the buffer already holds, throwing `CANNOT_READ_ALL_DATA` with the `readStrict` message when it ends early. Every valid state reads the same bytes (a fully buffered state is still a single exact-size allocation), and every malformed one fails with the same code and message as before. This is the approach of ClickHouse#117536 for 14 other aggregate states. A cap was rejected: the DataSketches parser bounds the entry count only by the buffer, so a cap tight enough to matter rejects sketches that read today. The bytes stay in `vector_bytes` (heap storage, aligned) because the parser reads the preamble through `uint16_t` / `uint64_t` pointer casts, which a short `String` would misalign. The test checks the peak `memory_usage` of three crafted states in `system.query_log` (1.00 GiB on master, about 35 KiB with the fix), the 1 GiB bound, and a MergeTree state read through 4-byte compressed blocks, which goes through the append loop thousands of times (a mutation that throws on the second iteration fails it). Closes ClickHouse#121410 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #108465
Related: #117370
Related: #117404
Related: #113926
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Several aggregate function deserializers allocated memory from a size declared in the serialized state before reading the payload, so a state of a few bytes could request gigabytes. They now read only what the buffer already holds.
Description
deserializereads a size out of an untrusted state, then reserves or allocates that much before reading the payload.readVarUInthas no maximum, and existing bounds are element counts, which cannot bound an allocation: a capNstill permitsN * sizeof(element)bytes. My #108465 capped the counts and left that residual;fb3a21b5c2a7bfaand #117370 landed the same doctrine forNativeand for a block of states.On master, 6 bytes:
That blob is exactly
MAX_STATISTICS_STATE_SIZE, which the strict>admits.The change reads payload-first, moving no cap and no error code. Peak tracked memory for that state goes from 8.00 GiB to 31.70 KiB, and a legitimate state costs what it did before. A value crossing compressed-block boundaries is staged once and copied into the arena, so it costs the value, not the block count.
Sites:
StatisticalSample::read(four consumers, both limbs),windowFunnel(both layouts), the-MapStringkey,readStringBinaryInto(-Distinct,groupUniqArray, genericgroupArrayIntersect),ColumnString::deserializeAndInsertFromArena,groupBitmap, and #108465's four reserves. The audit'stimeSeries*deserializers are covered by #117404. Not universal: othersrc/AggregateFunctionsdeserializers still allocate from a declared size,SingleValueDataString::readdeliberately so.6594a777e9c0067reverted this mechanism on 2026-07-25, where it only gave two tests a deterministic error code. Here it is the only remedy that does not reject states the current writer can produce:8d044e8880a588a7raisedgroupBitmap's bound to 100 GiB andaddX/addYare unbounded.Validation, and findings reported rather than fixed
Every fixture ran on both binaries at
max_memory_usage = 100000000; after the fix each costs ~30 KiB and raisesCANNOT_READ_ALL_DATA.StatCommon::read, four consumers,size_yaloneColumnString::deserializeAndInsertFromArenawindowFunnel,windowFunnel(strict_once)readStringBinaryInto, #108465's four reservesOne past the cap still gives
TOO_LARGE_ARRAY_SIZEon both, so the boundary has not moved. Legitimate states round-trip identically on both, including through a table, whose staged path is confirmed by mutation rather than assumed. 04401 fails on pristine master and passes here; 04401 and 05055 pass 100 of 100 runs with all randomization on and 100 of 100 with it pinned off. A 419-test sweep over the touched symbols produced no failure attributable to this change.A
-MapStringkey andgroupBitmapallocate throughoperator new, which the tracker counts but never refuses at the defaultmin_allocation_size_to_throw_on_memory_limit, so both sides raise the same error and only the tracked peak differs (1.00 GiB and 953.75 MiB). Those two rest on measurement, not an assertion.Reported, not fixed:
-ForEachstill builds every nested state before reading any payload, and withnested_size_of_data == 0a byte budget cannot see it; its remedy goes throughensureAggregateData, which #113926 rewrites. #113926 also owns the-Mapduplicate-key leak this audit found, so that half is not here.Roaring64Map::readSafecan underflowmaxbytes(roaring64map.hh:1222-1226) and upstream'sa24a8f97a451bis not in the pin025ae3f7add169bc, but I could not observe it under ASan. Severity is Low (auth required).Workflow [PR]
Sync PR [sync-upstream/pr/117536]
Version info
26.8.3.40,26.7.7.28,26.6.5.64,26.3.33.6