Repository navigation
Cherry pick #111287 to 26.9: Fix double free when finalizing -State aggregates under looping combinators - #121973
Conversation
…nators
A server crash (double free) happens when an aggregate function with the
-State combinator is nested under a looping combinator (-Resample, -ForEach,
-Map) and finalization hits a memory limit part-way through.
The -State combinator inserts its result by aliasing the raw aggregate state
pointer into a ColumnAggregateFunction (AggregateFunctionState::insertResultInto
-> ColumnAggregateFunction::getData().push_back(place)). Ownership of that state
is transferred to the column, and Aggregator::insertAggregatesIntoColumns relies
on this transfer being atomic per place: on an exception it destroys the whole
place exactly once.
A looping combinator breaks that atomicity. It aliases many sub-states into the
column one at a time inside a loop. The push_back into the column's pointer array
can reallocate and, being memory-tracked, throw MEMORY_LIMIT_EXCEEDED mid-loop.
At that point the sub-states inserted so far are already owned by the column, but
the aggregator's cleanup runs the combinator's full destroy() over every
sub-state, so the transferred ones are freed once by the aggregator and again by
~ColumnAggregateFunction. The reported crash was:
SELECT arrayMap(x -> finalizeAggregation(x), state)
FROM (SELECT groupArrayStateResample(0, 1048576, 1)(number, number % 20) AS state
FROM numbers(...))
crashing in ~GroupArrayNumericData -> PODArray::dealloc from
~ColumnAggregateFunction, reached via Aggregator::prepareChunkAndFillWithoutKey.
Fix: reserve the destination columns before the transfer loop so the aliasing
push_backs cannot reallocate (and therefore cannot throw) once a transfer has
started. ColumnAggregateFunction previously used the no-op IColumn::reserve, so a
real reserve() (and matching capacity()) is added for its state-pointer array.
For -Map, the (possibly variable-width) key inserts are moved into their own loop
before the value transfer, keeping all throwing work out of the aliasing loop.
Reserving happens before any aliasing, so a throw there is harmless.
The transfer loop is now non-throwing at the point of aliasing, restoring the
atomic-per-place contract; results are unchanged. All three looping combinators
share the same aliasing path (AggregateFunctionState::insertResultInto ->
insertResultIntoImpl -> Aggregator::insertAggregatesIntoColumns), so the fix is
applied to all three. The added stateless test reproduces the crash deterministically
via -Resample (empty buckets keep memory low until the finalization transfer, so a
memory limit reliably lands the throw mid-transfer); -ForEach and -Map build their
sub-states eagerly during aggregation and are not deterministically reproducible
under a memory limit, but are fixed as the same class.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nstate-combinator-double-free
…t wrappers
The -Tuple combinator transfers each element's result into its own subcolumn one
element at a time. When an element is a -State aggregate (directly, or under a
looping or transparent combinator), that transfer aliases the state pointer into a
ColumnAggregateFunction. If a later element's transfer then throws (for example a
memory limit hit while a nested -Resample element reserves its buckets),
Aggregator::insertAggregatesIntoColumns runs the -Tuple function's full destroy()
over every element, so the already-aliased earlier element is freed by the
aggregator and again by ~ColumnAggregateFunction: a double free.
Add a reserveForInsertResult() hook so all destination capacity is reserved before
any element is transferred:
- State reserves its ColumnAggregateFunction slot;
- the looping combinators (-Resample/-ForEach/-Map) reserve their nested columns;
- -Tuple calls it on every element before transferring any of them;
- the transparent combinators that delegate insertResultInto to a nested function
(-If/-Array/-Distinct/-Merge/-OrFill/-Null/-ArgMin/-ArgMax) forward the hook, so
a -State element reachable through them is reserved too.
Once the reservations are done, transferring the first element cannot be followed by
a throwing reservation while transferring a later element.
Reproducers (crashed before, clean MEMORY_LIMIT_EXCEEDED after), with
max_threads = 1, max_memory_usage = 285000000:
SELECT groupArrayStateResampleTuple(0, 1048576, 1)((number, number + 1), (number % 20, number % 20)) FROM numbers(100000)
SELECT groupArrayStateResampleIfTuple(0, 1048576, 1)((number, number + 1), (number % 20, number % 20), (number > 0, number > 0)) FROM numbers(100000)
Co-Authored-By: Claude Opus 4.8 <[email protected]>
The regression test asserted a fixed absolute memory limit (150MB/285MB) tripping MEMORY_LIMIT_EXCEEDED via 'seen_limit' echoes. Whether a query crosses a fixed byte limit is not portable across sanitizers (ASan/MSan/TSan shift memory accounting), so the flaky check failed deterministically on all three sanitizers with 'result differs with reference'. Drop the threshold-dependent assertions; keep the crash-driving finalization loops (which crash an unfixed server) but discard their output and assert only the deterministic tail (server survived, correct results), like 01302_aggregate_state_exception_memory_leak. The loops now sweep a small range of memory limits per combinator family so the throw still lands mid-transfer on an unfixed server regardless of sanitizer. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e-free Master added getArgumentsThatCanBeOnlyNull overrides to the ArgMin/ArgMax and Resample wrappers at the same anchor this branch uses for its reserveForInsertResult overrides, so both files conflicted textually. The two methods are independent, and both sides are kept. The Resample pre-reservation call still runs before the per-bucket aliasing transfer loop, which is the property the fix depends on. The merged tree differs from master by exactly the 17 files of this pull request, with no submodule pointer drift.
Earlier review rounds answered each challenge by writing the justification into the source, and nothing removed those lines again, so the comments had ratcheted up to nine consecutive lines in one block. Each comment now states only the local invariant a reader needs at that spot. The mechanism, the reachability evidence for each combinator, and the alternatives that were ruled out live in the earlier commit messages and in the pull request discussion instead. No functional change.
`AggregateFunctionOrFill::reserveForInsertResult` forwarded the reserve only when `insertResultInto` transfers into `to` itself. In the complementary branch (`result_is_nullable && !inner_nullable`) it was a complete no-op, although `insertResultIntoImpl` does transfer there too, into `col.getNestedColumn()`. `DataTypeAggregateFunction::canBeInsideNullable()` is false, so a bare `-State` result is never wrapped in `Nullable` and that branch is unreachable for it. But `DataTypeTuple::canBeInsideNullable()` is true, so `createResultType` does wrap a Tuple-of-States: `sumStateTupleOrNull((1,2))` is `Nullable(Tuple(AggregateFunction(sum, UInt8), ...))`. A single `-OrNull` frame is still safe, because it appends the null-map entry before the nested transfer. The window opens one level up. `-Resample`, `-ForEach` and `-Map` pre-reserve their destination with the generic `IColumn::reserve`, which recurses through `ColumnNullable` (nested column plus null map) and `ColumnTuple` (every element), so a nullable wrapper under them is covered. `AggregateFunctionTuple::insertResultIntoImpl` instead pre-reserves by asking each element function, so for an `-OrNull` element nothing was reserved: the second element's transfer could reallocate the destination after the first had already aliased a `-State` pointer into it, and the aggregator's cleanup then destroyed states the result column destroys again. Measured on a debug build with `groupArrayStateResampleTupleOrNullTuple(0, 1048576, 1)(...)` over `numbers(100000)` at `max_threads=1`: `max_memory_usage=360000000` segfaulted 3/3 in `ColumnAggregateFunction::~ColumnAggregateFunction` before this change and reports `MEMORY_LIMIT_EXCEEDED` 3/3 after it, with 340000000/380000000/400000000 unchanged in both directions. `-OrDefault`, the same class with `result_is_nullable` false, is clean 8/8 on both binaries, which attributes the crash to the skipped branch rather than to the query shape. `-ForEach` over a `Null`-adapted Tuple-of-State is also clean before the change, as the generic-reserve reading predicts. `AggregateFunctionNull::reserveForInsertResult` has the same shape, but for an element of an outer `-Tuple` the `-State` redirect in the `Null` combinator moves the nullability into the argument type rather than the result, so no `ColumnAggregateFunction` sits under a nullable `to` there. It is left unchanged.
`AggregateFunctionNullBase::reserveForInsertResult` had the same shape as the `-OrNull` hook fixed in the previous commit: it forwarded the reserve only in the non-nullable instantiation, although `insertResultIntoImpl` also transfers in the nullable one, into `to_concrete.getNestedColumn()`, and appends the null-map entry after that transfer rather than before it. The previous commit's reasoning for leaving this alone was wrong. It only covered the `-State` redirect in the `Null` combinator, which moves the nullability into the argument type for an element of an outer `-Tuple`. A `Nullable(Tuple(...))` argument reaches the adapter directly, and then the result really is `Nullable(Tuple(AggregateFunction(...)))`: `sumStateTupleDistinctTuple(CAST(..., 'Tuple(Nullable(Tuple(UInt8, UInt8)), ...)'))` under `enable_nullable_tuple_type`. Measured with `groupArrayStateResampleTupleDistinctTuple(0, 1048576, 1)` over `numbers(100000)` at `max_threads=1` and `max_memory_usage=360000000`: segfault 3/3 in `ColumnAggregateFunction::~ColumnAggregateFunction` without this change, `MEMORY_LIMIT_EXCEEDED` 3/3 with it. Reverting either hook in isolation reddens only its own query and leaves the other passing, so the two are independently needed. `-ForEach` over the same adapter is clean before either change, because the looping combinators pre-reserve their destination with the generic `IColumn::reserve`, which recurses through `ColumnNullable` and `ColumnTuple`. Only `AggregateFunctionTuple::insertResultIntoImpl`, which pre-reserves by asking each element function, could observe a wrapper that reserved nothing.
Master's only churn on this branch's files since the previous merge is 037ef93 "Revert \"Add aggregate function gini\"", which removes the getArgumentsThatCanBeOnlyNull() overrides that the previous merge had kept alongside this branch's reserveForInsertResult() hooks. Seven of this branch's seventeen files drifted; five auto-merged and two conflicted (AggregateFunctionResample.h, AggregateFunctionCombinatorsArgMinArgMax.cpp), in both cases because master deleted the override at the same anchor where this branch adds the reserve hook. Resolution keeps the reserve hook and takes master's deletion, matching what the five auto-merged files did. The two hunks are orthogonal: they override different base virtuals declared independently in IAggregateFunction.h, which master did not touch. Verified: no conflict markers; the merged tree differs from master in exactly the seventeen files of this branch and in zero submodule gitlinks; and for all seventeen the md5 of this branch's added-plus-removed lines is unchanged before and after the merge. The Resample pre-reservation remains ahead of the aliasing loop in insertResultIntoImpl.
AggregateFunctionState::insertResultInto transfers ownership by aliasing the state pointer into a ColumnAggregateFunction, so for a moment the pointer has two owners. Both aggregator entry points, Aggregator::insertAggregatesIntoColumns and IAggregateFunctionHelper::insertResultIntoBatch, disambiguate positionally and therefore rely on insertResultInto being atomic: on an exception they run a full destroy for the place that threw. A combinator that transfers several sub-states in one call (-Resample, -ForEach, -Map, -Tuple) aliases child 0 and then throws while transferring child 1, so child 0 is destroyed by the aggregator and freed a second time by ~ColumnAggregateFunction. Reserving the destination columns before the loop, which is what this branch did until now, only narrows that window. ColumnArray::reserve cascades with the same n, so a nested -ForEach destination is sized for the outer bucket count instead of one slot per element and its own reservation is itself the throwing reallocation; ColumnString cannot pre-size its chars at all, which leaves a -Map with String keys unreachable by any reservation; and -Map reserved its offsets after the value loop, inside the window the change was meant to close. All of that scaffolding is removed. Atomicity is restored by undoing a partial transfer instead. IAggregateFunction::rollbackInsertResult(place, to) removes exactly the rows a matching insertResultInto appended, in the reverse of the order it appended them, allocating nothing and throwing nothing; the default pops the single top-level row that every insertResultInto appends. -State pops its aliased row through the new ColumnAggregateFunction::popBackWithoutDestroy, so the state that place still owns stays alive. The four multi-transfer combinators wrap their transfer loop AND their own offsets append in a scope guard that undoes the children whose transfer returned and rethrows; -Null and -OrFill guard their own null-map entry the same way, wrapping only that entry so a nested call that threw, and has therefore already restored the nested column, is not undone twice; the seven pass-through combinators forward the undo. The transaction is entered only on the aliasing instantiation and only when the nested function is a state. A merge chain creates states the column owns, so popping one without destroying it would leak. And a leaf is not required to be atomic: AggregateFunctionGroupUniqArray appends its array offset before a throwing resize, so rolling back a completed sibling of such a child could over-pop, and a throw inside a noexcept undo would abort the server instead of failing the query. -Map recovers its sorted append order by reading the keys back out of the destination column, because merged_maps is unordered while the values were appended in sorted key order, and a value row's undo depends on which place produced it: the null adapter aliases a state for a key that has values and inserts a default the column owns for a key that has none. A key that cannot be found aborts rather than skipping a row, since skipping would leave an aliased row for the aggregator to destroy a second time. Its interrupted key insert is undone with a column checkpoint rather than a row count, because ColumnString::insert grows chars before it appends the offset. The stateless test is rewritten as a .sql that drives a partial transfer deterministically through a new failpoint, aggregate_function_state_transfer_throw, and asserts both the error code and the finalized values over 11 aggregate chains, including the five shapes the previous .sh covered. That file drove a memory-limit sweep and discarded all output by design, which is what the review objected to. This implements the redesign requested in review 5244310605 on #111287. Co-Authored-By: Claude Opus 5 <[email protected]>
fiu_do_on is evaluated once per aliased sub-state: per output row from both aggregator insertion paths, and per bucket/element/key inside -Resample, -ForEach, -Map and -Tuple, which is 32768 evaluations for one output row in 02427_msan_group_array_resample. Testing !column.empty() first keeps the first alias into every destination column off libfiu entirely. Semantics are unchanged: the injected throw still fires exactly when the destination already holds an aliased row, and the 11 failpoint arms of 04614_group_array_state_resample_finalize_no_crash were re-run in both directions to confirm it (arms 2-11 still abort with a double-free on the pre-fix binary, all 11 still return MEMORY_LIMIT_EXCEEDED with the fix). The residual cost either way is small, and smaller than the reasoning in ColumnAggregateFunction.cpp's "avoid checking failpoint in a loop" comment suggests: ClickHouse's libfiu fork guards fiu_do_on with a relaxed atomic load of has_any_failpoint_been_registered (contrib/libfiu/libfiu/fiu.h), so fiu_fail's process-global rwlock and hash lookup are never reached until some failpoint has actually been enabled in the process. Measured on this tree: 0.18 ns per evaluation single-threaded with nothing enabled, versus 37 ns (1 thread) and 429 ns (32 threads) once the flag is set. Co-Authored-By: Claude Opus 5 <[email protected]>
The first failpoint can only throw inside the innermost -State transfer or at -Resample's own offset append, so a -Resample(-State) never returns successfully while it is armed: it is never a completed child whose undo a parent requests, and AggregateFunctionResample::rollbackInsertResult was reached by no arm. -OrFill::rollbackInsertResult was unreached for the same reason, its only arm wrapping that internally-throwing -Resample. aggregate_function_state_transfer_throw_after_child throws at the top of a -Tuple element whose predecessor transferred in full, which makes the child being undone a completed one. It is a second, separately named failpoint, so the two existing injection sites and the eleven existing arms are unchanged; it fires only on the non-merge path, where a transfer can alias. Two arms use it, both reusing the -Tuple(-Resample(-State)) chain the changelog names first. With -Resample::rollbackInsertResult replaced by the base to.popBack(1) both arms now abort with an ASan double-free, and with -OrFill::rollbackInsertResult so replaced the -OrNull arm alone aborts, so each undo is measured by the arm that reaches it rather than argued from the code. Co-Authored-By: Claude Opus 5 <[email protected]>
…e-free The only conflict was the tail of APPLY_FOR_FAILPOINTS in src/Common/FailPoint.cpp: master appended intersect_or_except_transform_pause and intersect_or_except_transform_counts_pause while this branch appended aggregate_function_state_transfer_throw and aggregate_function_state_transfer_throw_after_child. Resolved by keeping every master entry with master's spelling and appending both of ours at the end of the list.
…mbinator-double-free Fix double free when finalizing -State aggregates under looping combinators
Resolved, on my forkOne conflict, in I do not have push access here, so the merge is on my fork:
I did not build the branch, since its submodule pins differ from master's, so the verification is that byte equality plus a check that every declaration the new code needs already exists here: The same one-line conflict and the same resolution apply to #121972 (26.8) and #121971 (26.7). #121970 (26.3) has no |
Conflict resolved for 26.9: - `FailPoint.cpp`: keep this branch's failpoint list and append the two this PR adds, `aggregate_function_state_transfer_throw` and `aggregate_function_state_transfer_throw_after_child`. Everything else, including the `-Tuple` combinator and the full `04614_group_array_state_resample_finalize_no_crash` test, applies unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Original pull-request #111287
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.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
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