Repository navigation
Cherry pick #117536 to 26.6: Do not allocate from sizes declared in aggregate function states - #118143
Merged
robot-clickhouse-ci-2 merged 18 commits intoSep 7, 2026
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. #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 #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 #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. #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 #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.
My open PR #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 #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. #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 #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.
`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.
`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.
…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`.
The two legitimate-state rows for `sumMap` and `groupBitmap` finalized or merged an in-memory state, so neither entered a deserializer at all. Measured with an instrumented `readStringGrowing`: both ran it 0 times, while a table round-trip at a 4-byte compress block size ran it 76 and 8 times. At the default block size those same reads complete in a single iteration, and these two files are the only tests that pair a tiny compress block size with an `AggregateFunction` column, so nothing exercised the growing loop for `AggregateFunctionMapCombinatorData` `readKey` or for `RoaringBitmapWithSmallSet` `read`. The first two `05055` assertions were `sum(length(x))`, which cannot see wrong bytes: with the loop storing filler past the first chunk, the whole file reproduced its reference byte for byte. Both now also compare content, and under that mutation the length columns stay unchanged while the new columns go to 0.
…ocate-from-declared-size Do not allocate from sizes declared in aggregate function states
`04401_aggregate_function_deserialize_allocation_bomb` and the element-count caps it asserts come from #108465, which is not on 26.6, so both are left out and only the payload-first reads land. `05055_aggregate_state_refill_staging` covers them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #117536
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job