Skip to content

Cherry pick #111287 to 26.3: Fix double free when finalizing -State aggregates under looping combinators - #121970

Merged
PedroTadim merged 18 commits into
backport/26.3/111287from
cherrypick/26.3/111287
Sep 25, 2026
Merged

PedroTadim merged 18 commits into
backport/26.3/111287from
cherrypick/26.3/111287

Conversation

@robot-ch-test-poll4

Copy link
Copy Markdown
Contributor

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-pick locally.
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:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 17 commits July 21, 2026 20:20
…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]>
…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
@groeneai

Copy link
Copy Markdown
Collaborator

Resolved, on my fork, as a subset: 26.3 has no -Tuple combinator

src/AggregateFunctions/Combinators/AggregateFunctionTuple.{h,cpp} do not exist on this branch, they were added to master after the 26.3 cut, and registerAggregateFunctions.cpp here has no registerAggregateFunctionCombinatorTuple call. Git reports them as "deleted in backport/26.3/111287, modified in cherrypick/26.3/111287" and leaves master's version in the tree, which would backport the combinator itself rather than this fix, so I dropped them. The port is the part of #111287 that applies to the combinators 26.3 does have.

Omitted on purpose:

  • AggregateFunctionTuple.{h,cpp}, per the above.
  • REGULAR(aggregate_function_state_transfer_throw_after_child) in src/Common/FailPoint.cpp: its only consumer is AggregateFunctionTuple.h, so on 26.3 it would register a failpoint nothing can fire. aggregate_function_state_transfer_throw is registered as on master.
  • The nine scenarios that name a -Tuple combinator, and their reference rows. Four of the thirteen remain, unchanged from master: plain -State, -Resample over -ForEach, -ForEach alone, and the single-bucket -Resample. The reference is master's rows 1-4 and 7, which are exactly the rows those four produce.

Conflicts resolved:

  • src/Common/FailPoint.cpp: the registration goes at the end of APPLY_FOR_FAILPOINTS, whose last entry here is ONCE(zk_send_thread_request_window_throw) rather than master's REGULAR(marks_loader_hold_task_until_canceled). I kept this branch's list and appended after its own last entry.
  • src/AggregateFunctions/Combinators/AggregateFunctionMerge.h: 26.3 has no insertMergeResultInto override, which on master is the code the new rollbackInsertResult override was added after. Only the new override is added; the absent one is a different PR's content and stays absent.

Coverage this costs 26.3, to be explicit: the rollbackInsertResult overrides for -Map, -Null, -OrFill, -If and -Distinct are still ported in src/, but nothing exercises them here, because every master statement that reached them went through a -Tuple wrapper. What the four surviving statements do cover is -State, -ForEach (its own loop and its undo by a parent) and -Resample. I did not invent replacement statements, since I cannot run the branch to establish their expected output.

I do not have push access here, so the merge is on my fork:

git fetch https://github.com/groeneai/ClickHouse groeneai/resolve-26.3-cherrypick-111287
git push origin FETCH_HEAD:cherrypick/26.3/111287

9186d0a50fbe714ec7ac652e3d5e425a916274ac, tree d2614217433c6feb9af790fdfc396859220ce1d9. It is the plain git merge --no-ff --no-edit backport/26.3/111287 on this branch: first parent 6c2fec3f (this PR's head), second parent 0da95294 (its base). git merge-base --is-ancestor 6c2fec3f 9186d0a5 and git merge-base --is-ancestor 0da95294 9186d0a5 both return 0, so the push is a fast-forward.

git diff --name-only backport/26.3/111287 9186d0a5 is 18 paths: the 20 of #111287 minus the two AggregateFunctionTuple files. git diff 0da95294..9186d0a5 differs from git diff 47217a23..6c2fec3f only in the items listed above, and in two context lines: this branch's AggregateFunctionMerge.h and AggregateFunctionResample.h (no #include <Common/memory.h>). The hunks in the other 16 files are byte-for-byte master's.

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: IColumn::getCheckpoint, IColumn::rollback, IColumn::capacity, IColumn::reserve, abortOnFailedAssertion(const String &), MEMORY_LIMIT_EXCEEDED, Common/VectorWithMemoryTracking.h and the -Map combinator. ci/jobs/check_style.py passes on the reduced test, 16 of 17 legs, the one failure being the settings_changes_history leg refusing to run outside CI.

#121973 (26.9), #121972 (26.8) and #121971 (26.7) all have -Tuple, so those three carry the full change with only the one-line FailPoint.cpp conflict.

Conflicts resolved for 26.3:

- `AggregateFunctionTuple.{h,cpp}`: the `-Tuple` combinator does not exist on
  this branch, so both files are dropped.
- `FailPoint.cpp`: only `aggregate_function_state_transfer_throw` is added;
  `aggregate_function_state_transfer_throw_after_child` is injected solely from
  `AggregateFunctionTuple.h` and would be dead here.
- `AggregateFunctionMerge.h`: takes only this PR's `rollbackInsertResult`. The
  adjacent `insertMergeResultInto` override in the incoming side is an unrelated
  master-only change that git pulled into the same hunk.
- `04614_group_array_state_resample_finalize_no_crash`: 9 of 13 blocks go
  through `-Tuple` and are removed, leaving plain `-State`, `-ForEachResample`,
  `-ForEach` and single-bucket `-Resample`; the reference is trimmed to match.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@PedroTadim
PedroTadim merged commit 46f121e into backport/26.3/111287 Sep 25, 2026
1 check passed
@PedroTadim
PedroTadim deleted the cherrypick/26.3/111287 branch September 25, 2026 13:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants