Repository navigation
Add IAggregateFunction::merge self-aliasing chassert (follow-up to #103536) - #103543
Conversation
Pre-PR validation (per process)Session id:
StackingStacked on #103536. Once #103536 merges into master, GitHub will recompute the PR's base and the diff will narrow to just the chassert commit (79 files, +136/-102). Until then it shows both commits. Sibling-symmetry check
So the four |
|
cc @alexey-milovidov @rschu1ze — could you review this? Follow-up to #103536 per @alexey-milovidov's directive: NVI wrapper on |
|
Workflow [PR], commit [8b033d1] Summary: ✅
AI ReviewSummaryThis PR turns Findings💡 Nits
Final VerdictStatus: ✅ Approve |
|
This is perfect! Even more, it uncovered, that the original fix was lacking (see the test). |
f7dd195 to
bc8f5fc
Compare
|
@alexey-milovidov - good catch! Pushed two updates after the rebase (force-pushed
To confirm the chassert still does its job: building this branch with the master version of Pre-PR validation update for the test ref change is captured in the PR #103536 comment. Session id: |
Wrap the public `merge` method of `IAggregateFunction` in a non-virtual NVI entry point that asserts `place != rhs` (in debug or sanitizer builds) before forwarding to a new pure-virtual `mergeImpl`. The same hazard motivated PR ClickHouse#103536 (heap-use-after-free in `executeAggregateMultiply` self-merge, STID 0988-40af). For aggregate functions whose `merge` reallocates the destination's internal storage and then reads from the source (`quantilesExact`, `groupArray`, `groupUniqArray`, `windowFunnel`, `sequenceMatch`, …), passing the same pointer as both source and destination is undefined. The new `chassert(place != rhs, …)` aborts on this in DEBUG_OR_SANITIZER_BUILD, catching future occurrences of the entire bug class at the call site instead of letting them surface as memory corruption. Same wrapper added for the parallel `merge` overload (with `ThreadPool`) and for the `mergeBatch` / `mergeAndDestroyBatch` paths in `IAggregateFunctionHelper` (which devirtualise the call and so bypass the public wrapper). 71 concrete aggregate-function overrides renamed from `merge` to `mergeImpl`. Callers are unchanged — they still call `merge`, which now performs the check. Closes the follow-up requested by @alexey-milovidov on PR ClickHouse#103536.
bc8f5fc to
8b033d1
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 177/206 (85.92%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 25 line(s) · Uncovered code |
An aggregate over Array(Nothing) (all-NULL arrays, e.g.
arrayReduce('uniqStateForEach', [[NULL], [NULL, NULL, NULL]])) collapses
the nested aggregate to AggregateFunctionNothing, whose state is zero
bytes. When AggregateFunctionForEach::ensureAggregateData grows the
per-element state array, the zero-byte arena allocation does not advance
the arena, so the new buffer aliases the old one. The old-state migration
loop then called nested merge() with new_state == old_state, tripping the
IAggregateFunction::merge self-aliasing assertion added in ClickHouse#103543 and
aborting debug/sanitizer builds (the AST fuzzer found this). In release
builds the assertion compiles out and the no-op self-merge was harmless.
Skip the migration loop when the nested state is zero-sized: there is no
data to migrate and merge() with aliasing source/destination is undefined.
…ReduceInRanges An aggregate over only-NULL arguments collapses to AggregateFunctionNothing, whose sizeOfData() is 0. Arena::alignedAlloc advances the arena by size, so every zero-byte allocation returns the same address. arrayReduceInRanges allocates one pre-aggregation state per 64 rows plus one state per range from a single arena, so with a zero-size aggregate all of those states alias and both the pairwise level merge and the per-range merge call merge(place, place), tripping the assertion added in ClickHouse#103543. Allocate max(sizeOfData(), 1) bytes for the pre-aggregation states. They then have distinct addresses, every merge still runs, and for an aggregate with a non-empty state the allocation is byte-identical to before. Only the pre-aggregation allocation needs padding. The per-range merge runs only when the range spans a whole 64-row block, which is also the condition for at least one pre-aggregation state to exist, and that state's one-byte allocation has already advanced the arena. Both merges remain reachable, at 64 elements for the per-range one and at 128 for the pairwise level loop, and the test covers each. Merging is not suppressed for zero-size states. sizeOfData() == 0 does not imply that a merge is a no-op: StatelessWindowFunction is also zero-size and its mergeImpl throws. Since the aggregate here is caller-supplied, there is no way to tell a genuinely empty state from one whose merge enforces a contract, so skipping the call could drop that enforcement. The -ForEach guard in ClickHouse#108781 is not a counter-example: it was written for AggregateFunctionNothing, whose merge is empty, and it keys on state size alone, so it would skip a throwing zero-size merge too. Padding the allocation avoids that question. The test pins that with an empty range list: the per-range loop does not run, so the pairwise level merge over the pre-aggregation places is the only remaining path to the aggregate's merge, and a build that skips zero-size merges returns an empty array instead of reporting the error. Found by the AST fuzzer (amd_debug, targeted), STID 2508-5153: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114747&sha=95a67283e1b33c000dba21cddefcd4418c4a2c94&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 Carrier: ClickHouse#114747 Related: ClickHouse#108781
…e-self-alias-assert-on-103536 Add IAggregateFunction::merge self-aliasing chassert (follow-up to ClickHouse#103536)
An aggregate over Array(Nothing) (all-NULL arrays, e.g.
arrayReduce('uniqStateForEach', [[NULL], [NULL, NULL, NULL]])) collapses
the nested aggregate to AggregateFunctionNothing, whose state is zero
bytes. When AggregateFunctionForEach::ensureAggregateData grows the
per-element state array, the zero-byte arena allocation does not advance
the arena, so the new buffer aliases the old one. The old-state migration
loop then called nested merge() with new_state == old_state, tripping the
IAggregateFunction::merge self-aliasing assertion added in ClickHouse#103543 and
aborting debug/sanitizer builds (the AST fuzzer found this). In release
builds the assertion compiles out and the no-op self-merge was harmless.
Skip the migration loop when the nested state is zero-sized: there is no
data to migrate and merge() with aliasing source/destination is undefined.
An aggregate over only-NULL arguments collapses to `nothing`, whose state has `sizeOfData() == 0`. A zero-byte arena allocation does not advance the arena, so distinct zero-size states allocated back to back share one address. Copying such a state, e.g. the same-frame copy of both window strategies (`AggregateWindowFunctionPrefix`, `AggregateWindowFunctionRecalculate`) through `ColumnAggregateFunction::insertFromWithOwnership`, which is `insertDefault()` followed by `merge(new, previous)`, then trips `chassert(place != rhs)` although the two states are distinct and have no bytes for `mergeImpl` to read or write. Every CI firing of this assertion family since it was added (ClickHouse#103543) is such a zero-size state. The window site is reached for `-State` results since ClickHouse#129257 and, before that, for `any`/`groupArray` over a state column. Refine the predicate once (`IAggregateFunction::isSelfMerge`) and use it at all six assertion sites instead of patching call sites one by one. `mergeImpl` is still called, non-empty states are checked as before, and release builds are unaffected (`chassert` is compiled out there). STID: 2508-3fb0 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Motivation
Follow-up to #103536 (heap-use-after-free in
executeAggregateMultiplyself-merge, STID 0988-40af). The original UAF was triggered byfunction->merge(state, state, arena.get());For aggregate functions whose
mergeimplementation reallocates the destination'sinternal storage and then reads from
rhs(quantilesExact,groupArray,groupUniqArray,windowFunnel,sequenceMatch,intervalLengthSum, …), passingthe same pointer as both source and destination is undefined —
PODArray::insertreallocates and
insert_assume_reserved'smemcpythen reads from the freedsource buffer.
#103536 fixed the one site that hit it. @alexey-milovidov asked for a runtime
check that catches the entire bug class so future occurrences abort at the call
site instead of surfacing as memory corruption:
Approach
NVI (non-virtual interface) wrapper. The public
mergeis now a non-virtualmethod on
IAggregateFunctionthat asserts the source and destination states donot alias and forwards to a new pure-virtual
mergeImpl:Same wrapper added for the parallel
mergeoverload (withThreadPool) and forthe
mergeBatch/mergeAndDestroyBatchpaths inIAggregateFunctionHelper(those devirtualise the virtual call via
static_cast<const Derived *>(this),so they bypass the public NVI wrapper — the assert is repeated there before the
devirtualised call to keep the check in place).
71 concrete aggregate-function overrides renamed from
merge→mergeImpl.Every existing caller still calls
merge(unchanged), which now performs theself-aliasing check before forwarding.
chassertis a no-op outsideDEBUG_OR_SANITIZER_BUILD, so release builds payzero runtime cost. Debug, ASan, MSan, TSan, and UBSan builds gain an
out-of-the-box check that catches
func->merge(state, state)at the call site.Sibling check
The same
chassert(place != rhs)covers every aggregate-functionmergecallthat goes through the public interface — including all combinator chains
(
-Array,-State,-Merge,-If,-Null,-OrFill,-Map,-Distinct,-Resample,-ForEach,-SimpleState,-ArgMinArgMax), allIAggregateFunctionHelperbatch entry points, and any external callers (
Aggregator, query pipeline,StorageMergeTreemutations, replication merge tasks, etc.). A singlechokepoint, no per-call sites to maintain.
grep "function->merge\\(([^,]*),\\s*\\1"oversrc/returned only thesingle executeAggregateMultiply site that #103536 fixed; no other callers
currently self-alias. The assert is preventive — it locks in the invariant for
future code.
Pre-PR validation
quantilesExactState(0.5)(number) FROM numbers(50) * N(N >= 2) when the executeAggregateMultiply fix from #103536 is reverted. With #103536 in place no callers self-alias.func->merge(state, state)withmergeimplementations that appendrhs.array.begin()..end()into a destination that may reallocate.place != rhsenforced at the only entry point that all callers go through. No band-aid (no widened bounds, nono-random-*tag, no data-size reduction).04117_aggregate_state_multiply_self_merge_uafregression test (added by #103536) continues to pass; it now would fail loud on a debug build instead of silently corrupting memory if #103536's fix were ever regressed.clickhouse local) with both #103536 + this PR applied. Existing aggregate-function smoke tests (groupArrayMerge,quantilesExactMerge,windowFunnelMerge,sumMapMerge,topKMerge,corrMatrixMerge,uniqMerge,sequenceMatchMerge,groupUniqArrayMerge) all continue to produce the same results.mergeBatch,mergeAndDestroyBatch, and their twostatic_cast<Derived *>-devirtualised internal calls) repeat the assert at the devirtualised call site.Stacking note
This PR is stacked on top of #103536. While #103536 is open, GitHub renders the
diff as both commits; once #103536 lands, the diff narrows to just the chassert
commit. The chassert depends on #103536's
executeAggregateMultiplyfix beingin master — without it, debug-build CI on
04117_aggregate_state_multiply_self_merge_uaf(and any aggregate-state
* Nquery) would abort on the new chassert.Changelog category (leave one):
Version info
26.7.1.141