Repository navigation
Bound element count in aggregate function state deserialization - #108465
alexey-milovidov merged 4 commits into
Conversation
Several aggregate functions read an element count from a serialized state and then resize/reserve before reading any data. A crafted state (reachable via CAST(... AS AggregateFunction(...)), -Merge functions, distributed merges and AggregateFunction columns) can declare a count near 2^32 and make the deserializer request tens of GiB of memory from a few bytes of input. Cap the count and throw TOO_LARGE_ARRAY_SIZE before allocating, mirroring the existing windowFunnel guard (100,000,000). Affected paths: - StatCommon.h read() (mannWhitneyUTest, rankCorr, largestTriangleThreeBuckets) - quantileGK - sequenceMatch / sequenceCount - groupArrayIntersect (numeric and generic paths) Legitimate states round-trip unchanged; only states declaring more than 100,000,000 elements are rejected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Note: this PR intentionally scopes to the four deserialization paths with fully reproduced, byte-minimal PoCs. Other hardening candidates in the same family (the stream-loop Session id: cron:clickhouse-worker-slot-15:20260625-113300 |
|
cc @rschu1ze @Algunenano — could you review this? It bounds the element count read from serialized aggregate states (mannWhitneyUTest/rankCorr/largestTriangleThreeBuckets, quantileGK, sequenceMatch, groupArrayIntersect) before resize/reserve, so a crafted state can no longer make the deserializer allocate tens of GiB from a few bytes. Same hardening pattern as #104141, mirrors the existing windowFunnel cap (100M). |
|
Workflow [PR], commit [d82b375] Summary: ✅
AI ReviewSummaryThis PR hardens several aggregate-function state deserializers by adding element-count caps before PR Metadata
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Minimum required actions: resolve the count-cap design so malformed short states cannot trigger GiB allocations at the accepted boundary, and provide a compatibility story for real serialized states that older versions could produce. |
The groupArrayIntersect bomb test only crafted an Array(UInt64) state, which exercises the numeric AggregateFunctionGroupArrayIntersect<T> deserialize path. The generic AggregateFunctionGroupArrayIntersectGeneric path (non-numeric array element types such as Array(String)) was left untested, so the test would keep passing if the generic guard were dropped. Add the same 00ffffffff0f blob cast as Array(String) and keep the numeric case so both guarded paths are covered. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Added the generic-path coverage in 6176a8c.
both asserting Validated both directions on a debug build:
Session id: cron:clickhouse-worker-slot-4:20260625-161700 |
…ontract The shared StatisticalSample::read() is used by largestTriangleThreeBuckets, whose existing contract caps the state at MAX_ARRAY_SIZE = 1ULL << 30. A flat 100,000,000 bound rejected legitimate pre-upgrade persisted/distributed states with 100M..1<<30 points before merge/finalization (backward-incompatible). Raise the shared cap to 1ULL << 30 so no previously-accepted state is rejected (for an oversized state the error simply moves from getResult to deserialize, same error code), while crafted multi-GiB bombs declaring ~4.29e9 elements still throw TOO_LARGE_ARRAY_SIZE before allocating. Add an explicit largestTriangleThreeBuckets bomb case and round-trip to the regression test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch on the backward-compat regression. Fixed in 4cf835f.
Change: raised the shared Validation (debug binary, Build ID
Test 04401 now adds an LTTB bomb case and an LTTB round-trip alongside the existing functions. |
| { | ||
| readVarUInt(size_x, buf); | ||
| readVarUInt(size_y, buf); | ||
| if (size_x > MAX_STATISTICS_STATE_SIZE || size_y > MAX_STATISTICS_STATE_SIZE) |
There was a problem hiding this comment.
This bound is still high enough to leave the allocation-bomb path open. A crafted state can encode size_x = 1ULL << 30 and size_y = 0; because the check is > it passes, then x.resize(size_x, arena) requests 8 GiB before readStrict verifies that the payload exists (16 GiB if both sizes are at the cap). That is still a few-byte aggregate state driving multi-GiB allocation instead of the promised TOO_LARGE_ARRAY_SIZE.
Please make the deserialize limit a practical allocation limit, or split the compatibility concern from the hardening path (for example per-function limits or a compatibility setting). At minimum this should not accept largestTriangleThreeBuckets states at MAX_ARRAY_SIZE, because its existing finalization contract rejects size >= MAX_ARRAY_SIZE.
|
Confirmed finding 1. The So findings 1 and 2 are the two ends of one axis: any element-count cap N still permits N*sizeof(element) bytes from a tiny state (finding 1), and lowering N rejects legitimate large states written by older shards (finding 2). A pure count cap cannot satisfy both. On the suggested bytes-remaining bound: it is reliable on the complete-buffer path ( Options, with the existing convention in mind ( A. Bounded pre-allocation, no count cap. Grow the target geometrically while reading (resize/reserve capped per round, B. Keep count caps, treat them as a deliberate on-read contract. Per-function values aligned to each function's existing limit (LTTB already rejects No human review yet and the bound is a real tradeoff (allocation safety vs backward compatibility vs convention). @rschu1ze @Algunenano which direction do you prefer before I push the next revision? I lean A, since it is the only option that closes finding 1 without any backward-incompatible rejection, but B is smaller and closer to the current convention. |
The legitimate round-trip used mannWhitneyUTestMerge()(s) with empty parameter parens. The old analyzer (enable_analyzer=0) rejects the empty () parameter form with BAD_ARGUMENTS "Parameters list to aggregate functions cannot be empty", so the test failed on the old-analyzer lane. mannWhitneyUTest is non-parametric; drop the empty parens. The merge call is now valid under both analyzers and the bomb cases are unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed d82b375 fixing an old-analyzer test failure (independent of the open Option A/B bound-design question above). The legitimate round-trip case used Validated against a running server: the test's full output matches .reference on BOTH analyzers; the 6 bomb cases still throw TOO_LARGE_ARRAY_SIZE; the original empty-parens form still fails under the old analyzer (confirming the fix is what resolves it). The bound-design tradeoff (bounded-resize vs per-function caps) remains open for your call. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 34/36 (94.44%) | Lost baseline coverage: none · Uncovered code |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRBound element count in aggregate function state deserialization ClickGap verified: reproduced it with the script below on ReproductionBisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: cc fix PR author: @groeneai ClickGap · Finding: Triage metadata
|
`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.
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.
`04401_aggregate_function_deserialize_allocation_bomb` and the element-count caps it asserts come from #108465, which is not on 26.3, so both are left out and only the payload-first reads land. `05055_aggregate_state_refill_staging` covers them.
`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.
…-deserialize-allocation-bombs Bound element count in aggregate function state deserialization
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed excessive memory allocation when deserializing crafted aggregate function states for
mannWhitneyUTest,rankCorr,largestTriangleThreeBuckets,quantileGK,sequenceMatch/sequenceCountandgroupArrayIntersect. A malformed state could declare a huge element count and make the server try to allocate tens of gigabytes from a few bytes of input; such states are now rejected withTOO_LARGE_ARRAY_SIZE.Description
These aggregate functions read an element count from the serialized state and then
resize/reservethat many elements before reading any actual data. The count is unbounded, so a crafted state, only a handful of bytes, can declare a size near 2^32 and make the deserializer request 32-96 GiB before reading the body.The states are reachable from a regular authenticated session via
CAST(unhex('...') AS AggregateFunction(...)),*Mergefunctions, distributed merges, andAggregateFunctioncolumns. With the default server memory configuration this is a low-severity denial-of-service (no crash, no persistent damage, but the server can be driven to allocate huge buffers).Fix: cap the declared count and throw
TOO_LARGE_ARRAY_SIZEbefore allocating, mirroring the existingwindowFunnelguard (100,000,000) andHashTable::read(1e11). Affected deserialization paths:StatCommon.hread()— shared bymannWhitneyUTest,rankCorr,largestTriangleThreeBucketsAggregateFunctionQuantileGK.cpp—sampled.resize_exact(sampled_len)AggregateFunctionSequenceMatch.cpp—events_list.reserve(size)AggregateFunctionGroupArrayIntersect.cpp—set.reserve(size)on both the numeric and the generic (string) pathsThe cap is on the element count, not on bytes remaining in the buffer, because aggregate states arrive in network-sized chunks during distributed
-Mergeand bytes-remaining is not a reliable bound there.100,000,000is far above any realistic serialized state and matches the siblingwindowFunnelguard. Legitimate states round-trip unchanged; only states declaring more than 100,000,000 elements are rejected.This follows the same hardening pattern as #104141 (the already-merged
quantileTimingdeserialization fix) for thedeserialize(ReadBuffer&)family not covered by #90031. Regression test added intests/queries/0_stateless/04401_aggregate_function_deserialize_allocation_bomb.sql(asserts each crafted blob throws and that legitimate states still merge correctly).Version info
26.7.1.138