Skip to content

Add IAggregateFunction::merge self-aliasing chassert (follow-up to #103536) - #103543

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:add-aggregate-merge-self-alias-assert-on-103536
Jun 27, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:add-aggregate-merge-self-alias-assert-on-103536

Conversation

@groeneai

@groeneai groeneai commented Apr 25, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Follow-up to #103536 (heap-use-after-free in executeAggregateMultiply self-merge, STID 0988-40af). The original UAF was triggered by

function->merge(state, state, arena.get());

For aggregate functions whose merge implementation reallocates the destination's
internal storage and then reads from rhs (quantilesExact, groupArray,
groupUniqArray, windowFunnel, sequenceMatch, intervalLengthSum, …), passing
the same pointer as both source and destination is undefined — PODArray::insert
reallocates and insert_assume_reserved's memcpy then reads from the freed
source 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:

please send an additional PR that will add an assert into IAggregateFunction::merge that it isn't called with the same state. The assert should be in a single place, e.g., it can go into IAggregateFunctionHelper. Or if it's not possible, change the virtual method merge to mergeImpl everywhere and make the merge method to check the assert and call mergeImpl - something on that theme.

Approach

NVI (non-virtual interface) wrapper. The public merge is now a non-virtual
method on IAggregateFunction that asserts the source and destination states do
not alias and forwards to a new pure-virtual mergeImpl:

void merge(AggregateDataPtr __restrict place, ConstAggregateDataPtr rhs, Arena * arena) const
{
    chassert(place != rhs, "IAggregateFunction::merge called with the same source and destination state");
    mergeImpl(place, rhs, arena);
}

virtual void mergeImpl(AggregateDataPtr __restrict place, ConstAggregateDataPtr rhs, Arena * arena) const = 0;

Same wrapper added for the parallel merge overload (with ThreadPool) and for
the mergeBatch / mergeAndDestroyBatch paths in IAggregateFunctionHelper
(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 the
self-aliasing check before forwarding.

chassert is a no-op outside DEBUG_OR_SANITIZER_BUILD, so release builds pay
zero 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-function merge call
that goes through the public interface — including all combinator chains
(-Array, -State, -Merge, -If, -Null, -OrFill, -Map, -Distinct,
-Resample, -ForEach, -SimpleState, -ArgMinArgMax), all IAggregateFunctionHelper
batch entry points, and any external callers (Aggregator, query pipeline,
StorageMergeTree mutations, replication merge tasks, etc.). A single
chokepoint, no per-call sites to maintain.

grep "function->merge\\(([^,]*),\\s*\\1" over src/ returned only the
single 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

# Question Answer
a Deterministic repro? The chassert fires deterministically on 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.
b Root cause explained? Yes — see Motivation. The class-of-bug is func->merge(state, state) with merge implementations that append rhs.array.begin()..end() into a destination that may reallocate.
c Fix matches root cause? Yes — runtime invariant place != rhs enforced at the only entry point that all callers go through. No band-aid (no widened bounds, no no-random-* tag, no data-size reduction).
d Test intent preserved? Yes — no test logic changed. The existing 04117_aggregate_state_multiply_self_merge_uaf regression 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.
e Both directions demonstrated? Yes — verified the new assert fires when #103536's fix is rolled back; verified the existing test passes (10/10 iterations on debug 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.
f Fix is general? Yes — single chokepoint covers every aggregate function and every combinator chain via the NVI wrapper. The four entry points that bypass the wrapper (mergeBatch, mergeAndDestroyBatch, and their two static_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 executeAggregateMultiply fix being
in master — without it, debug-build CI on 04117_aggregate_state_multiply_self_merge_uaf
(and any aggregate-state * N query) would abort on the new chassert.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Version info

  • Merged into: 26.7.1.141

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation (per process)

Session id: cron:clickhouse-ci-task-worker:20260425-231500

# Question Answer
a Deterministic repro? Yes. With #103536's outer fix reverted, SELECT finalizeAggregation(state * N) FROM (SELECT quantilesExactState(0.5)(number) AS state FROM numbers(50)); (N >= 2) deterministically aborts in debug/sanitizer builds with the new chassert(place != rhs) — same root cause as STID 0988-40af. With #103536's fix in place no callers self-alias, and the chassert is silent.
b Root cause explained? Yes. func->merge(state, state) calls array.insert(rhs.array.begin(), rhs.array.end()) with rhs == lhs for the entire family of aggregates that append rhs storage into lhs (quantilesExact, groupArray, groupUniqArray, windowFunnel, sequenceMatch, intervalLengthSum, …). PODArray::insert reallocates and insert_assume_reserved's trailing memcpy reads from the freed source buffer. The runtime invariant place != rhs rules this out at the source.
c Fix matches root cause? Yes. NVI wrapper at the single virtual entry point — every caller goes through merge and every override is mergeImpl. Same for the parallel merge overload. IAggregateFunctionHelper::mergeBatch/mergeAndDestroyBatch devirtualise the call and so the assert is repeated there before the devirtualised invocation. No bound widening, no no-random-* tag, no test weakening.
d Test intent preserved? Yes. No tests changed. The existing 04117_aggregate_state_multiply_self_merge_uaf regression test (added by #103536) continues to exercise the state * N path and would now also catch any future regression that re-introduces the alias on debug builds.
e Both directions demonstrated? Yes. (1) Verified the new chassert fires when #103536's column_temp copy is removed and state * 2 is run on debug clickhouse local. (2) Verified the existing regression test passes 10/10 iterations on debug clickhouse local with both #103536 and this PR applied. (3) Smoke-tested every combinator-bearing aggregate (groupArrayMerge, quantilesExactMerge, windowFunnelMerge, sumMapMerge, topKMerge, corrMatrixMerge, uniqMerge, sequenceMatchMerge, groupUniqArrayMerge) — all produce identical results with the assert in place.
f Fix is general? Yes. The NVI wrapper covers every aggregate function and every combinator chain in one place. The only paths that bypass the NVI wrapper are the two static_cast<Derived *>-devirtualised internal calls in IAggregateFunctionHelper::mergeBatch/mergeAndDestroyBatch; the assert is repeated at those call sites. grep "function->merge\\(([^,]*),\\s*\\1" over src/ returned zero call sites that currently self-alias (the only one was fixed by #103536), so the assert is preventive and locks in the invariant for future code.

Stacking

Stacked 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

IAggregateFunctionHelper exposes four other call sites that may invoke aggregate-function logic with potentially aliased arguments — none required the assert:

  • addBatch / addBatchSinglePlace etc.: never receive rhs of type AggregateDataPtr, only IColumn ** columns.
  • mergeStateFromDifferentVariant: separate virtual; only used by -Merge combinator across Window/Aggregation variants where place and rhs_place are necessarily different states.
  • parallelizeMergePrepare / parallelizeMergeMulti: receive a vector of places, but never the same place twice in the vector by construction (each is a distinct group's state).
  • serializeBatch / deserialize / createAndDeserializeBatch: do not perform merge.

So the four chassert(place != rhs) placements in IAggregateFunction::merge (×2: serial + parallel) and IAggregateFunctionHelper::mergeBatch / mergeAndDestroyBatch (×2) cover every aggregate-merge entry point.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @rschu1ze — could you review this? Follow-up to #103536 per @alexey-milovidov's directive: NVI wrapper on IAggregateFunction::merge that asserts place != rhs and forwards to a new pure-virtual mergeImpl; 71 concrete overrides renamed merge → mergeImpl so every caller goes through the assert. Stacked on #103536.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b033d1]

Summary: ✅


AI Review

Summary

This PR turns IAggregateFunction::merge into a checked non-virtual wrapper, moves concrete implementations to mergeImpl, and repeats the self-aliasing assertion in the devirtualized batch paths. I do not see a new correctness issue in the current diff; the remaining item is a low-severity comment cleanup that already has an inline thread.

Findings

💡 Nits

  • [src/AggregateFunctions/IAggregateFunction.h:629] The comment text is ungrammatical: "when calling mergeImpl directly bypasses the wrapper". Suggested wording: "when a direct call to mergeImpl bypasses the wrapper".
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This is perfect! Even more, it uncovered, that the original fix was lacking (see the test).

@groeneai
groeneai force-pushed the add-aggregate-merge-self-alias-assert-on-103536 branch from f7dd195 to bc8f5fc Compare April 26, 2026 22:11
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov - good catch! 03406_reservoir_sample_self_merging was the one to look at.

Pushed two updates after the rebase (force-pushed bc8f5fcc004):

  1. The middle reference value moves from 499.5 to 495. The original test reference was set in Fix ReservoirSampler self-merging #79031 against the no-op self-merge guard in ReservoirSampler::merge. With the squaring step in executeAggregateMultiply no longer self-aliasing (PR Fix heap-use-after-free in executeAggregateMultiply self-merge #103536), state * N for ReservoirSampler-backed aggregates now actually accumulates N copies. The middle case crosses the 8192 reservoir cap (10 × 1000 = 10000 inserts) and the seeded RNG yields 495. Small (100 inserts) and large (1_000_000 inserts) cases are unchanged.
  2. The fix lives logically in PR Fix heap-use-after-free in executeAggregateMultiply self-merge #103536 (commit 9da5e773e8d); this branch was rebased onto the new Fix heap-use-after-free in executeAggregateMultiply self-merge #103536 tip, so the chassert commit is now bc8f5fcc004 (same content as f7dd195af45).

To confirm the chassert still does its job: building this branch with the master version of FunctionBinaryArithmetic.h (i.e. without #103536's column_temp copy) and running SELECT finalizeAggregation(10 * (SELECT medianState(number) FROM numbers(1000))) still aborts on the chassert as expected. The chassert catches the original self-merge call site; the test value change is purely the consequence of the executeAggregateMultiply rework finally producing real state * N semantics.

Pre-PR validation update for the test ref change is captured in the PR #103536 comment.

Session id: cron:clickhouse-ci-task-worker:20260426-214500

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.
@groeneai
groeneai force-pushed the add-aggregate-merge-self-alias-assert-on-103536 branch from bc8f5fc to 8b033d1 Compare June 11, 2026 02:08
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

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

Full report · Diff report

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review June 27, 2026 00:13
@alexey-milovidov
alexey-milovidov merged commit 1bd7a2e into ClickHouse:master Jun 27, 2026
165 of 166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 27, 2026
pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jun 29, 2026
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.
zvonand pushed a commit to zvonand/ClickHouse that referenced this pull request Aug 17, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e-self-alias-assert-on-103536

Add IAggregateFunction::merge self-aliasing chassert (follow-up to ClickHouse#103536)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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.
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 12, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants