Repository navigation
Bound zero-sized nested aggregate states in one place for all combinators - #130120
alexey-milovidov merged 7 commits into
Conversation
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]>
|
cc @azat @rschu1ze, could you review this and add the |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261108-084100 |
|
Workflow [PR], commit [c5676b4] Summary: ✅
AI ReviewSummaryThe PR centralizes limits on zero-sized nested aggregate states across Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. Preserve access to valid pre-upgrade states and cover that behavior with a focused regression. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes148 object files changed (-1.26 MiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units334 translation units recompiled, 2608 s compile time in total, 334 of them have a recent master baseline. |
`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]>
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]>
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]>
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]>
Related: #121082
Related: #121083
Changelog category (leave one):
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_timewhen nested states that occupy no memory multiply: creating one aggregate state, or growing a-ForEachstate, now throwsARGUMENT_OUT_OF_BOUNDif it would create more than 1048576 such states, e.g.-ForEachover a zero-sized-Resample, or a forgedsumForEachstate.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 despitemax_execution_time = 2.Root cause:
-Resampleand-ForEachcreate 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-Resampleconstructor misses-ForEachand rejects the type at parse time.Change:
IAggregateFunction::createNestedStates, used by-Resampleand by-ForEachwhen it grows, counts zero-sized states in a thread-local scope and throws before creating more than 1048576. The scope spans everything onecreatemakes, through any wrapper and across-Tupleelements;-Tuplealso counts its own zero-sized elements. Memory-backed states are not counted, socountResampleIfResample(0, 2048, 1, 0, 2048, 1)keeps working; the tree walk andforEachNestedFunctionare removed, so every type parses again. The Protobuf reader no longer destroys a state whosecreatethrew. 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,
-Mapkeys, array elements) get 1048576 each, as one-Resamplelevel does today. Behaviour change, only fornothingand 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_boundhangs on master and passes with the fix;05247_nested_resample_combinators_bound_protobufaborts under ASan without the reader change.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/130120]
Version info
26.11.1.1697-master(included in26.11and later)