Skip to content

Bound element count in aggregate function state deserialization - #108465

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregate-deserialize-allocation-bombs
Jun 27, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregate-deserialize-allocation-bombs

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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/sequenceCount and groupArrayIntersect. 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 with TOO_LARGE_ARRAY_SIZE.

Description

These aggregate functions read an element count from the serialized state and then resize/reserve that 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(...)), *Merge functions, distributed merges, and AggregateFunction columns. 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_SIZE before allocating, mirroring the existing windowFunnel guard (100,000,000) and HashTable::read (1e11). Affected deserialization paths:

  • StatCommon.h read() — shared by mannWhitneyUTest, rankCorr, largestTriangleThreeBuckets
  • AggregateFunctionQuantileGK.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) paths

The cap is on the element count, not on bytes remaining in the buffer, because aggregate states arrive in network-sized chunks during distributed -Merge and bytes-remaining is not a reliable bound there. 100,000,000 is far above any realistic serialized state and matches the sibling windowFunnel guard. 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 quantileTiming deserialization fix) for the deserialize(ReadBuffer&) family not covered by #90031. Regression test added in tests/queries/0_stateless/04401_aggregate_function_deserialize_allocation_bomb.sql (asserts each crafted blob throws and that legitimate states still merge correctly).

Version info

  • Merged into: 26.7.1.138

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Each crafted CAST(unhex('...') AS AggregateFunction(...)) blob deterministically triggers a fixed-size allocation (32/96/64/64 GiB) on unfixed master; reproduced with the server capped at 1 GiB (MEMORY_LIMIT_EXCEEDED showing the attempted size).
b Root cause explained? The deserializer reads an element count from the state, then resize/reserves that many elements before reading any data. The count is unbounded, so a count near 2^32 (0xffffffff) makes a few input bytes request tens of GiB.
c Fix matches root cause? Yes. The fix caps the count and throws TOO_LARGE_ARRAY_SIZE before the resize/reserve, directly at the unbounded read. No symptom masking.
d Test intent preserved / new tests added? New test 04401_aggregate_function_deserialize_allocation_bomb: asserts every crafted blob throws TOO_LARGE_ARRAY_SIZE AND that legitimate State→Merge round-trips still produce correct results.
e Both directions demonstrated? Yes. Unfixed binary (Build ID 9078b494…): all 4 blobs attempt GiB allocations. Fixed binary (8a87c6a3…): all 4 throw TOO_LARGE_ARRAY_SIZE; the 5 legitimate queries match the reference.
f Fix is general across code paths? Yes. StatCommon.h covers all 3 statistical functions that share read(). groupArrayIntersect is fixed on BOTH its numeric and generic (string) deserialize paths, not just the reproduced one.
g Fix generalizes across inputs? The guard is on the size field itself (independent of element type/wrapper), so it applies uniformly to every AggregateFunction(...) instantiation of these functions. Boundary: a state with exactly the cap or fewer deserializes normally; only > 100,000,000 is rejected.
h Backward compatible? Yes. No setting, on-disk, or wire-format change. Only rejects states declaring > 100,000,000 elements, which no real serialized state produces, so genuine states (incl. those written by older versions) round-trip unchanged.
i Invariants and contracts preserved? Yes. The cap is checked before resize/reserve, so the subsequent read loop and its bounds are unchanged. Serialization is untouched, so the serialize/deserialize symmetry is preserved for all valid states.

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 -Map/-Distinct/groupUniqArray/sparkbar paths, ColumnString/ColumnArray arena deserialize, the combinator-nesting depth limit, and tightening the 100_GiB byte budgets in -ForEach/groupBitmap) will follow as separate PRs.

Session id: cron:clickhouse-worker-slot-15:20260625-113300

@groeneai

Copy link
Copy Markdown
Collaborator Author

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).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d82b375]

Summary: ✅


AI Review

Summary

This PR hardens several aggregate-function state deserializers by adding element-count caps before resize, reserve, or resize_exact. The current approach still leaves accepted boundary values that allocate GiB from tiny states, and the new hard read caps change the accepted serialized-state contract for real pre-upgrade states. I do not think this is ready to merge as a bug fix until the allocation-safety and compatibility tradeoff is resolved.

PR Metadata
  • 💡 Bug Fix is the right category, and a changelog entry is required and present.
  • 💡 The changelog entry is incomplete for the actual shared code paths: the StatisticalSample change also affects kolmogorovSmirnovTest, QuantileGK is also used by quantilesGK, and AggregateFunctionSequenceMatchData is also used by sequenceMatchEvents. Suggested replacement:
    Fixed excessive memory allocation when deserializing crafted aggregate function states for mannWhitneyUTest, rankCorr, kolmogorovSmirnovTest, largestTriangleThreeBuckets, quantileGK/quantilesGK, sequenceMatch/sequenceCount/sequenceMatchEvents, and groupArrayIntersect. Malformed states that declare an unsafe element count are now rejected with TOO_LARGE_ARRAY_SIZE before large allocations.
Findings

❌ Blockers

  • [src/AggregateFunctions/StatCommon.h:128], [src/AggregateFunctions/AggregateFunctionQuantileGK.cpp:278], [src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp:124], [src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp:160] The fix still trusts an untrusted count up to the cap and allocates for it before verifying that the payload exists. For example, size_x = 1ULL << 30 passes the StatCommon check and then x.resize requests about 8 GiB from a few-byte state; similarly sampled_len = 100000000 in quantileGK passes and then sampled.resize_exact requests GiB-scale memory. This violates the PR contract that crafted short states are rejected before excessive allocation. Suggested fix: avoid preallocating directly from the serialized count, for example by growing in bounded chunks while reading, or make each deserialize limit a practical byte/allocation limit that cannot itself be used as the bomb.
  • [src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp:124], [src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp:160], [src/AggregateFunctions/AggregateFunctionQuantileGK.cpp:278] The new read caps introduce an on-read serialized-state contract that older versions did not have. sequenceMatch/sequenceCount/sequenceMatchEvents serialize the actual events_list.size, groupArrayIntersect serializes the actual set size, and quantileGK has no upper bound on its accuracy parameter that proves sampled_len <= 100000000. Persisted AggregateFunction columns or distributed partial states above the arbitrary cap can now fail with TOO_LARGE_ARRAY_SIZE, despite being genuine states written before this PR. Suggested fix: prefer bounded deserialization that preserves old states, or add an explicit compatibility/versioning story and document the backward-incompatible cutoff.
Tests
  • ⚠️ The regression test only exercises very large rejected values such as 0xffffffff; it does not prove that the accepted boundary cannot allocate GiB before payload validation. Add a focused boundary/regression test for whichever bounded-read or practical-cap design replaces the current count caps.
  • ⚠️ If the final design keeps any new hard cap, add compatibility evidence for legitimate states at and above the cutoff, or update the changelog/documentation to state the backward-incompatible behavior.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added the generic-path coverage in 6176a8c.

04401_aggregate_function_deserialize_allocation_bomb.sql now crafts the 00ffffffff0f blob (version 0, size 0xffffffff) as both:

  • AggregateFunction(groupArrayIntersect, Array(UInt64)) — numeric path (AggregateFunctionGroupArrayIntersect<T>::deserialize)
  • AggregateFunction(groupArrayIntersect, Array(String)) — generic path (AggregateFunctionGroupArrayIntersectGeneric::deserialize)

both asserting serverError TOO_LARGE_ARRAY_SIZE.

Validated both directions on a debug build:

  • With the fix: both cases throw TOO_LARGE_ARRAY_SIZE (Code 128).
  • With only the generic guard removed: the Array(String) case attempts a 128 GiB allocation -> MEMORY_LIMIT_EXCEEDED (Code 241), so the test fails; the numeric Array(UInt64) case still throws, confirming the two guards are independent and the generic guard is now covered.

Session id: cron:clickhouse-worker-slot-4:20260625-161700

Comment thread src/AggregateFunctions/StatCommon.h Resolved
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch on the backward-compat regression. Fixed in 4cf835f.

StatisticalSample::read() is shared by largestTriangleThreeBuckets (whose existing contract is MAX_ARRAY_SIZE = 1ULL << 30), rankCorr, mannWhitneyUTest and the t-test/z-test family. The flat 100'000'000 cap was below LTTB's contract, so a legitimate pre-upgrade LTTB state with 100M..1<<30 points would have thrown at deserialize/merge.

Change: raised the shared MAX_STATISTICS_STATE_SIZE to 1ULL << 30 to match LTTB's contract. No compatibility setting or BIC marking is needed because nothing previously accepted is now rejected: for an oversized LTTB state the error just moves from getResult to deserialize with the same TOO_LARGE_ARRAY_SIZE code; the other consumers were unbounded before. The bombs declare ~4.29e9 elements (0xffffffff), still well above 1<<30, so they continue to throw before allocating.

Validation (debug binary, Build ID d2af06e9d44, clickhouse local engine):

  • All 6 bomb cases (now incl. an explicit largestTriangleThreeBuckets(3) blob) -> Code 128 TOO_LARGE_ARRAY_SIZE, message maximum: 1073741824.
  • Backward-compat proof: a crafted LTTB state declaring 200,000,000 points (in the old-cap..new-cap gap) now passes the size check and fails downstream with CANNOT_READ_ALL_DATA (Bytes expected: 1600000000) instead of TOO_LARGE_ARRAY_SIZE -> it is accepted again. Under the old 100M cap it was rejected.
  • 6 legitimate State -> Merge round-trips (incl. LTTB) match the reference.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed finding 1. The 1ULL << 30 cap on StatisticalSample::read does not bound the allocation: a 6-byte state with size_x = 1<<30, size_y = 0 passes the > check, then x.resize(1<<30) requests 8 GiB before readStrict runs (16 GiB with both sizes at the cap):

SELECT mannWhitneyUTestMerge()(x)
FROM (SELECT CAST(unhex('808080800400'), 'AggregateFunction(mannWhitneyUTest, Float64, UInt8)') AS x)
-> Code 241 MEMORY_LIMIT_EXCEEDED: would use 8.00 GiB (attempt to allocate chunk of 8.00 GiB)

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 (CAST / deserializeFromString over ReadBufferFromString, which is the attack vector here), but not on the partial-state paths. The same deserialize() is reached from ColumnAggregateFunction::deserializeAndInsertFromArena (one ReadBuffer holding several concatenated states) and the Native / distributed -Merge path over a chunked CompressedReadBuffer, where buf.available() is the current decompressed block, not the state size. A bytes-remaining check there would falsely reject a legitimate state that spans multiple blocks, so it is not safe as a uniform rule.

Options, with the existing convention in mind (windowFunnel uses a flat 100M count cap; groupArray uses checkArraySize against its parameter):

A. Bounded pre-allocation, no count cap. Grow the target geometrically while reading (resize/reserve capped per round, readStrict drives the refill), so a bomb throws CANNOT_READ_ALL_DATA after a small allocation while a legitimate large state still deserializes on every buffer type. Closes both findings and is fully backward compatible, but it is a new pattern in these four deserialize loops and interacts with arena-allocator growth.

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 size >= 1<<30 at finalize, so deserialize can reject >= 1<<30 too), and for sequenceMatch / groupArrayIntersect either gate the stricter cap behind a compatibility setting or document it as a Backward Incompatible Change with migration guidance.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 mannWhitneyUTestMerge()(s) with empty parameter parens. enable_analyzer=0 rejects the empty () form with BAD_ARGUMENTS ("Parameters list to aggregate functions cannot be empty"), so 04401 failed on the old analyzer lane. mannWhitneyUTest is non-parametric, so the parens are dropped (mannWhitneyUTestMerge(s)).

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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 34/36 (94.44%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jun 27, 2026
@alexey-milovidov
alexey-milovidov merged commit 52eaf34 into ClickHouse:master Jun 27, 2026
166 of 167 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 27, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Bound element count in aggregate function state deserialization

ClickGap verified: reproduced it with the script below on 26.5; tested 6 version(s) — 5 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

Reproduction

-- Pre-fix: a crafted aggregate-function state declares a huge element count
-- (0xffffffff ~= 4.29e9) and the deserializer resize/reserve's it BEFORE reading
-- the body, allocating tens of GiB from a few input bytes.
SELECT finalizeAggregation(CAST(unhex('10270000000000007b14ae47e17a843f0000000000000000ffffffff00000000'), 'AggregateFunction(quantileGK(100), Float64)'));
-- Other affected paths: mannWhitneyUTest / rankCorr / largestTriangleThreeBuckets
-- (StatCommon read), sequenceMatch/sequenceCount, groupArrayIntersect.
-- Observed pre-fix: Code 241 MEMORY_LIMIT_EXCEEDED (attempt to allocate ~96 GiB).
-- Post-fix (correct): Code 128 TOO_LARGE_ARRAY_SIZE, rejected before allocating.

▶ Run on ClickHouse Fiddle

Bisect

  • Reproduces on every release line tested down to v24.7.6.8 (the oldest with a downloadable binary for this repro). The introducing change predates v24.7.6.8, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-aggregate-functions
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @alexey-milovidov


ClickGap · Finding: phase_d_pr108465

Triage metadata

  • Primary component: comp-aggregate-functions
  • Secondary components: comp-testing
  • Component owners (comp-aggregate-functions): @alexey-milovidov @nihalzp

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 4, 2026
`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.
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 4, 2026
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.
Algunenano added a commit that referenced this pull request Sep 7, 2026
`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.
Algunenano added a commit that referenced this pull request Sep 7, 2026
`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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-deserialize-allocation-bombs

Bound element count in aggregate function state deserialization
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
…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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants