Repository navigation
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
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260721-190200 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings across 1 full pass + 1 delta recheck; bounded).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-1:20260721-190200 |
|
cc @nihalzp — could you review this? It fixes a double free during aggregate finalization: a (@alexey-milovidov is already tracking this from #110975, where the crash was reported.) |
|
Workflow [PR], commit [cb562bc] Summary: ✅
AI ReviewSummaryThis PR replaces the earlier reservation-based fix with an explicit rollback contract for state-producing aggregate finalization. The current implementation now restores partial transfers in the looping combinators, forwards rollback through the transparent wrappers, and gives Final Verdict
LLVM Coverage ReportMeasured on commit cb562bc.
Changed lines: Changed C/C++ lines covered: 204/231 (88.31%) · Uncovered code |
…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]>
Internal second-model review trail (click to expand)Independent code review (2 rounds) of the -Tuple extension. Adjudication:
Verification: both named reproducers 50/50 clean |
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]>
|
Fixed the flaky-check failure on the new regression test Root cause: the test asserted a fixed absolute memory limit (150MB/285MB) tripping Fix (test only, source unchanged): drop the threshold-dependent assertions; keep the crash-driving finalization loops (they still crash an unfixed server) but discard their output and assert only the deterministic tail (server survived, correct results), the same shape as |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 60/82 (73.17%) · Uncovered code |
CI finish ledger — 64790d9Every failure below has an owner. None are PR-caused: the PR's own test
Session id: cron:our-pr-ci-monitor:20260722-113000 |
|
Fixing PR for the The failure is the plain-rewritable |
…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.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsNumericIndexedVector.cpp.o |
33.39 MiB | 33.70 MiB | +314.93 KiB (+0.92%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o |
10.93 MiB | 10.99 MiB | +65.04 KiB (+0.58%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o |
6.40 MiB | 6.45 MiB | +49.15 KiB (+0.75%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o |
6.58 MiB | 6.63 MiB | +48.86 KiB (+0.73%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… |
5.73 MiB | 5.77 MiB | +43.20 KiB (+0.74%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… |
7.19 MiB | 7.23 MiB | +43.05 KiB (+0.58%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/Combinators/AggregateFunctionM… |
1.56 MiB | 1.59 MiB | +37.71 KiB (+2.37%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o |
3.48 MiB | 3.50 MiB | +30.05 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… |
2.89 MiB | 2.91 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.92 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.82 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.81 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.81 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… |
2.89 MiB | 2.91 MiB | +24.81 KiB (+0.84%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/Combinators/AggregateFunctionD… |
1.49 MiB | 1.51 MiB | +22.44 KiB (+1.47%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… |
12.79 MiB | 12.81 MiB | +21.89 KiB (+0.17%) |
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… |
2.92 MiB | 2.94 MiB | +20.85 KiB (+0.70%) |
716 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
319 translation units recompiled, 2381 s compile time in total, 319 of them have a recent master baseline.
CI finish ledger - 62ffd58Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task of mine
157 of 175 checks succeeded, 17 skipped, 1 failed. The failing test is not part of this branch: it was added to master earlier today and reaches CI Session id: cron:our-pr-ci-monitor:20260807-233000 |
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.
CI finish ledger - 203ce57Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither failure is in this PR's diff, which is confined to Session id: cron:our-pr-ci-monitor:20260813-183000 |
|
The failure was on the previous head This PR touches 20 files ( It came from master, as a merge artifact of my own #118612: both parents of its merge commit I merged that revert into this PR at 04:51Z. On the current head |
Cherry pick #111287 to 26.3: Fix double free when finalizing -State aggregates under looping combinators
Cherry pick #111287 to 26.7: Fix double free when finalizing -State aggregates under looping combinators
Cherry pick #111287 to 26.8: Fix double free when finalizing -State aggregates under looping combinators
Cherry pick #111287 to 26.9: Fix double free when finalizing -State aggregates under looping combinators
…egates under looping combinators
…egates under looping combinators
…egates under looping combinators
…egates under looping combinators
Backport #111287 to 26.9: Fix double free when finalizing -State aggregates under looping combinators
Backport #111287 to 26.8: Fix double free when finalizing -State aggregates under looping combinators
Backport #111287 to 26.7: Fix double free when finalizing -State aggregates under looping combinators
Backport #111287 to 26.3: Fix double free when finalizing -State aggregates under looping combinators
Related: #110975
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a server crash (double free) when finalizing an aggregate function with the
-Statecombinator nested under a combinator that transfers several sub-states in one call (-Resample,-ForEach,-Map,-Tuple), for examplegroupArrayStateResample, if an exception such as a memory limit is thrown part-way through the transfer.Description
Found by CI on the PR linked above (unrelated to it): a segfault in
Aggregator::prepareChunkAndFillWithoutKey, later the same defect as ause-after-dtorinStress test (arm_msan).Root cause:
AggregateFunctionState::insertResultIntotransfers ownership by aliasing the state pointer into aColumnAggregateFunction, so the pointer briefly has two owners. Both aggregator entry points disambiguate positionally and so assume the transfer is atomic: on an exception they run a fulldestroyfor the place that threw. A combinator transferring several sub-states in one call aliases child 0, then throws while transferring child 1, so child 0 is freed by the aggregator and again by~ColumnAggregateFunction.Change: atomicity is restored by undoing a partial transfer. A new
IAggregateFunction::rollbackInsertResult(place, to) noexceptremoves exactly the rows a matchinginsertResultIntoappended, in reverse;-Statepops its aliased row without destroying the state (newColumnAggregateFunction::popBackWithoutDestroy);-Resample,-ForEach,-Mapand-Tuplewrap their transfer loop and their own offsets append in atrythat undoes the children whose transfer returned, restores their own bookkeeping and rethrows; the pass-through combinators forward. The undo path is entered only where a state is aliased, so nothing else changes behaviour. This replaces the previousreserveForInsertResultapproach, which cannot close the window in general (ColumnString::charscannot be pre-sized); that scaffolding is removed.Validation: the stateless test drives the failure deterministically through two failpoints, one inside a partially transferred
-Statechild and one at a-Tupleboundary whose predecessor transferred in full, and asserts the error code and finalized values over 13 chains. Twelve of them abort with an ASan double-free before the change and pass after it; the thirteenth is a control, a plain-Statetransfer being atomic already. Each of the seven undo bodies that is not a plain forward is load-bearing: reverting one alone to the basepopBack(1)reddens a named chain.Workflow [PR]
Sync PR [sync-upstream/pr/111287]
Version info
26.10.1.407-master(included in26.10and later)26.9.2.39,26.8.11.53,26.7.14.51,26.3.33.157