Skip to content

Bound zero-sized nested aggregate states in one place for all combinators - #130120

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/generic-nested-states-bound
Nov 8, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/generic-nested-states-bound

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121082
Related: #121083

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

Aggregate function combinators no longer run for minutes ignoring max_execution_time when nested states that occupy no memory multiply: creating one aggregate state, or growing a -ForEach state, now throws ARGUMENT_OUT_OF_BOUND if it would create more than 1048576 such states, e.g. -ForEach over a zero-sized -Resample, or a forged sumForEach state.

Description

Generic re-implementation of #121083, as asked there.

On 26.10.2.103, SELECT unhex('0000000010000000')::AggregateFunction(sumForEach, Array(Nullable(Nothing))) pins a core 159 s despite max_execution_time = 2.

Root cause: -Resample and -ForEach create arrays of nested states in a loop. The memory limit bounds this only when a state occupies memory; for a zero-sized state nothing does, and nesting multiplies the loops. #121083's tree walk in the -Resample constructor misses -ForEach and rejects the type at parse time.

Change: IAggregateFunction::createNestedStates, used by -Resample and by -ForEach when it grows, counts zero-sized states in a thread-local scope and throws before creating more than 1048576. The scope spans everything one create makes, through any wrapper and across -Tuple elements; -Tuple also counts its own zero-sized elements. Memory-backed states are not counted, so countResampleIfResample(0, 2048, 1, 0, 2048, 1) keeps working; the tree walk and forEachNestedFunction are removed, so every type parses again. The Protobuf reader no longer destroys a state whose create threw. No per-row work is added. Price: release GROUP BYs creating 1M such states (one thread) show no slowdown beyond A/A noise.

Bound: separately created states (GROUP BY keys, -Map keys, array elements) get 1048576 each, as one -Resample level does today. Behaviour change, only for nothing and NULL-only arguments: over-limit creations now throw, e.g. nothingForEach(range(1048577)), also when reading such a state written by an older version.

Validation: 05247_nested_resample_combinators_bound hangs on master and passes with the fix; 05247_nested_resample_combinators_bound_protobuf aborts under ASan without the reader change.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/130120]

Version info

  • Merged into: 26.11.1.1697-master (included in 26.11 and later)

groeneai and others added 6 commits November 8, 2026 02:10
Combinators that hold an array of nested states (-Resample, -ForEach) create them in a loop,
and every later operation walks them again. The work is normally bounded by memory, because
the array is allocated before its states are created. When the nested state occupies zero
bytes (`nothing`, and what -Null substitutes for only-NULL arguments), the allocation is
empty and nothing bounds the loop, which runs inside one `create`/`add`/`deserialize` call
where the query is not checked for cancellation.

Replace the -Resample-specific constructor walk over the function tree with one helper,
`IAggregateFunction::createNestedStates`, used by -Resample and -ForEach. It keeps a
thread-local count of the zero-sized states created by the outermost call and everything
below it, through any wrapper, and throws ARGUMENT_OUT_OF_BOUND before creating anything once
the count would exceed 1048576 (the per-level limit of -Resample). States that occupy memory
are not counted, so memory-backed chains such as
`countResampleIfResample(0, 2048, 1, 0, 2048, 1)` keep working, and since the type is no longer
rejected at parse time, stored AggregateFunction columns of any such type still attach.

This also covers -ForEach, which the walk could not see:
- `SELECT unhex('0000000010000000')::AggregateFunction(sumForEach, Array(Nullable(Nothing)))`
  created 2^36 states for an 8-byte element count before reading them;
- `SELECT nothingResampleForEach(0, 1048576, 1)(range(1048576), range(1048576))`
  created 2^40 states in one `add`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`createNestedStates` counted the zero-sized states of one call. Combinators that reach several
nested creations in one call make separate calls, so each key, element or child started from
zero: `-Map::add` creates one state per new key of the row, `-ForEach` and `-Array` add every
element of the row to the nested function, and `-Tuple::create` creates one state per child.
One row of `nothingResampleMap(0, 1048576, 1)` with 2^20 keys, or `-ForEach` over 2^20 one-key
maps, still created 2^40 states in one `add`.

Add `IAggregateFunction::NestedStatesScope`, which keeps one count for every `createNestedStates`
call on the thread while it is alive, and open one in `-Tuple::create`, `-Map::add`, `-Array::add`,
`-ForEach::add` and the per-row body of the `-ForEach` batch paths. Merges and reads of a stored
state are not scoped: they rebuild states that earlier rows already paid for. A top-level `-Array`
is unwrapped by the Aggregator, so `-Array::add` is reached only when it is nested in another
combinator.

`ProtobufSerializerAggregateFunction::stringToData` called `create` inside the `try` whose `catch`
destroys the state, so a `create` that throws (now: a chain over the limit) had its states
destroyed again and the never-created ones destroyed once (UBSan: shift exponent 190 in the
`HashTable` of a `-Distinct` state). Create before the `try`, as
`SerializationAggregateFunction::deserializeBinary` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`NestedStatesScope` is opened for every row of `-ForEach`, `-Map` and a nested `-Array`, and its
constructor and destructor were out-of-line calls that read and wrote thread-locals defined in
`IAggregateFunction.cpp`. Define them in the header over constant-initialized inline thread-local
members (as `QueryProfiler.h` does for its timer), so the hot path is two inlined TLS accesses and
no call or TLS wrapper. Semantics are unchanged.

Add `05247_nested_resample_combinators_bound_protobuf`: it reads one Protobuf row whose aggregate
state type creates too many zero-sized states, so `create` throws inside
`ProtobufSerializerAggregateFunction::stringToData`. With `create` back inside the `try`, ASan+UBSan
aborts in the catch's `destroy` (shift exponent 190 in a `-Distinct` `HashTable`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the `NestedStatesScope` from the per-row paths of `-Map`, `-Array` and
`-ForEach` (`add`, `addRowToPlace`). The scope there costs about 0.8-0.9 ns
per row even when inlined (avgMap +5-9%, sumForEach([number, 1]) +12% on a
release build at max_threads = 1), and it does not close the class it was
meant to close: a top-level `-Array` or `arrayReduce` element is a separate
row for the nested function anyway.

The limit now applies to everything one `create` (or one `-ForEach` growth)
creates, through any wrapper and across the elements of a `-Tuple`;
separately created states (GROUP BY keys, `-Map` keys, array elements) get
the limit each, as one `-Resample` level does on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`-Tuple` of zero-sized elements has a zero-sized state, and its `create`
calls each element's plain `create`, so the outer `-Resample` counted one
state per tuple while K elements created K of them: for example
`nothingTupleResample(0, 524289, 1)(tuple(number, number), number)` created
1048578 zero-sized states in one `create` without hitting the limit.
`-Tuple` now counts its zero-sized elements in its own scope.

The counting moves into `NestedStatesScope::addZeroSizedStates`, and
`createNestedStates` goes back to the try/catch rollback master used at both
call sites. The `SCOPE_EXIT` closure captured the loop index by reference,
which kept it in memory and enabled the stack protector, about 40 extra
instructions per `sumResample(0, 4, 1)` state created.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the createNestedStates and NestedStatesScope docs, drop two comments that restate the member name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @rschu1ze, could you review this and add the can be tested label so CI runs? It replaces the -Resample-specific bound of #121083 with a generic one: IAggregateFunction::createNestedStates (used by -Resample and -ForEach) and -Tuple::create count the states that occupy no memory created by one create, through any wrapper, and throw above 1048576, so no parse-time tree walk is needed.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT unhex('0000000010000000')::AggregateFunction(sumForEach, Array(Nullable(Nothing))) and SELECT nothingResampleForEach(0, 1048576, 1)(range(1048576), range(1048576)) with max_execution_time = 2 are still running after 30 s on master (with #121083) every run; on 26.10.2.103 the first one ends after 159 s.
b Root cause explained? -Resample and -ForEach create an array of nested states in a loop, and -Tuple creates one state per element. The memory limit bounds this only when a state occupies memory; a zero-sized state (nothing*, or what -Null substitutes for only-NULL arguments) makes the allocation empty, nesting multiplies the loop, and cancellation is not checked inside create/add/deserialize.
c Fix matches root cause? Yes. The bound sits where nested states are created: IAggregateFunction::createNestedStates counts zero-sized arrays of states and -Tuple::create counts its zero-sized elements, so everything one create (or one -ForEach growth) creates, through any wrapper and across -Tuple elements, shares one count. It replaces the per-wrapper tree walk of #121083.
d Test intent preserved / new tests added? 05247_nested_resample_combinators_bound is extended append-only: the two queries above, the 1048576 boundary, and lines for -Tuple (children of one created state; zero-sized vs memory-backed elements). Removing the -Tuple count makes its line pass; counting every element rejects the memory-backed line; raising the limit makes the zero-sized lines fail. New 05247_nested_resample_combinators_bound_protobuf reads one Protobuf row of such a type.
e Both directions demonstrated? Extended 05247: hangs on master (rc 124), passes with the fix; the -Tuple lines return a value on master and throw with the fix. 50/50 randomized runs pass. The Protobuf test aborts under ASan+UBSan with only that create moved back into the try (a never-created -Distinct state is destroyed) and passes with the fix; 50/50.
f Fix is general across code paths? Every place that creates an array of nested states goes through createNestedStates (-Resample::create, -ForEach growth and deserialization), and -Tuple, the only function with several nested functions, counts its zero-sized elements in the same scope. States created separately (GROUP BY keys, -Map keys, array elements, arrayReduce) get the limit each, like one -Resample level on master; merges and reads of a stored state are not counted together.
g Fix generalizes across inputs (params/datatypes/wrappers)? Signed and unsigned keys; -If, -Distinct, -Tuple, -Map, -OrNull, -Array, -State, -ArgMin between -Resample levels; serialized-state and Protobuf paths; memory-backed controls (countResampleIfResample(0, 2048, 1, 0, 2048, 1), sumForEach(range(3000000)), sumTupleResample(0, 524289, 1)) unchanged; 1048576 accepted, 1048577 rejected.
h Backward compatible? (maintainer-approved exception only) No setting or format change, and the type of every combinator chain parses again, so stored AggregateFunction(...) columns attach. Only states that occupy no memory are limited, per created state (e.g. a -Tuple of 64 zero-sized -Resample(0, 1048576, 1) children now throws).
i Invariants and contracts preserved? The check runs before any state is created; already created states are destroyed on exception (try/catch, as master did at both call sites); the scope is RAII, so the thread-local flag is restored on every exit and the counter reset at each outermost scope (several failing queries in one session: no carry-over); the Protobuf reader now creates before its try, like SerializationAggregateFunction::deserializeBinary; state layout and serialization unchanged.

Session id: cron:clickhouse-impl-slot-40:20261108-084100

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5676b4]

Summary: ✅


AI Review

Summary

The PR centralizes limits on zero-sized nested aggregate states across -Resample, -ForEach, and -Tuple, and fixes Protobuf cleanup when state creation throws. Blocked by an upgrade compatibility regression: valid existing aggregate states become unreadable without a way to restore access.

Findings

❌ Blockers

  • IAggregateFunction.cpp:108: The unconditional cap rejects valid persisted states. AggregateFunctionForEach::deserialize calls ensureAggregateData, which now enforces this limit. The previous implementation writes sumForEachState(arrayResize(CAST([], 'Array(Nullable(Nothing))'), 1048577, NULL)) as a valid 1,048,585-byte RowBinary state. Reading the same file returns length 1048577 on baseline 30a51e18f, but throws ARGUMENT_OUT_OF_BOUND on PR head c5676b4c2; both reads take approximately 0.114 seconds. Existing AggregateFunction(sumForEach, Array(Nullable(Nothing))) data therefore becomes unreadable after upgrade despite its type attaching successfully. Provide a configurable or versioned compatibility path that restores access to existing states.
Tests
  • ⚠️ Add an old-writer/new-reader round trip for a valid state above the new default limit, exercising the compatibility path. The current tests cover rejection of a forged count but do not protect existing data.
Final Verdict

Status: ❌ Block. Preserve access to valid pre-upgrade states and cover that behavior with a focused regression.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Nov 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c5676b4c2 with master 057d9a76e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7a92b973c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

148 object files changed (-1.26 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.65 MiB 13.56 MiB -83.12 KiB (-0.59%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.94 MiB 6.88 MiB -64.79 KiB (-0.91%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 7.13 MiB 7.07 MiB -64.49 KiB (-0.88%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.95 MiB 5.89 MiB -55.98 KiB (-0.92%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 5.83 MiB 5.79 MiB -42.03 KiB (-0.70%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.85 MiB 3.81 MiB -38.56 KiB (-0.98%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… 3.14 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.15 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.15 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.14 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.15 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.15 MiB 3.12 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.14 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.15 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.14 MiB 3.11 MiB -32.57 KiB (-1.01%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 3.01 MiB 2.98 MiB -27.05 KiB (-0.88%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.66 MiB 13.64 MiB -22.30 KiB (-0.16%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.45 MiB 2.43 MiB -21.96 KiB (-0.88%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.43 MiB 2.41 MiB -21.79 KiB (-0.87%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 16.07 MiB 16.05 MiB -18.68 KiB (-0.11%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

334 translation units recompiled, 2608 s compile time in total, 334 of them have a recent master baseline.

Job report

`Build (wasm64)` compiles with `-fvisibility=hidden`, where the
`static inline thread_local` members in `IAggregateFunction.h` trip
`-Werror,-Wunique-object-duplication`: a mutable header-defined object with
hidden visibility gets one copy per shared object. Declare them in the header
and define them once in the `.cpp`, as master's `b633746f17c` did for the
other sites. `constinit` lets `AggregateFunctionTuple.cpp` access them
directly instead of through a TLS wrapper call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Nov 8, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
Merged via the queue into ClickHouse:master with commit 545d3ca Nov 8, 2026
187 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
Resolve the five conflicts of the 26.8 cherry-pick of ClickHouse#131595. They are
all regions where master has code that 26.8 does not have: the deferral
of large merges (ClickHouse#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (ClickHouse#130678), the
bound of zero-sized nested states (ClickHouse#130120), and the partition-by-partition merge of
the adaptive aggregator (ClickHouse#129565). None of them is labelled for 26.8, and
the resolution takes none of them.

26.8 has no catch around the per-function loop of the batch merge (master
got it in ClickHouse#117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.8 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of ClickHouse#131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.8 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.9 cherry-pick of #131595. They are
all regions where master has code that 26.9 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.9, and
the resolution takes none of them.

26.9 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.9 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.9 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.10 cherry-pick of #131595. They are
all regions where master has code that 26.10 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.10, and
the resolution takes none of them.

26.10 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.10 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.10 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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.

3 participants