Skip to content

Fix -ForEach self-merge assertion for zero-size nested states - #108781

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-arrayreduce-foreach-self-merge
Jun 29, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-arrayreduce-foreach-self-merge

Conversation

@groeneai

@groeneai groeneai commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #103543

Changelog category (leave one):

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

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

An aggregate over Array(Nothing) (all-NULL arrays) collapses the nested aggregate to AggregateFunctionNothing, whose state is zero bytes. When AggregateFunctionForEach::ensureAggregateData grows the per-element state array, arena.alignedAlloc(0) does not advance the arena, so the freshly "allocated" buffer aliases the old one. The old-state migration loop then called the nested merge() with new_state == old_state, tripping the IAggregateFunction::merge self-aliasing assertion added in #103543 and aborting debug/sanitizer builds. In release builds the assertion compiles out and the no-op self-merge was harmless, so there is no user-visible misbehavior.

Fix: skip the migration merge loop when the nested state is zero-sized. There is no data to migrate, and merge() with aliasing source/destination is undefined.

Found by the AST fuzzer: SELECT arrayReduce('uniqStateForEach', [[NULL], [NULL, NULL, NULL]]).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108436&sha=ee9a2c24d179f38af6886ee315c4dee833626425&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

The added test 04420_foreach_combinator_zero_size_nested_state covers the zero-size case for uniqStateForEach, groupArrayStateForEach, arrayReduceInRanges, and uniqForEach, and also asserts that non-zero-size -ForEach aggregates (sumForEach, uniqForEach, groupArrayForEach) still migrate growing states correctly.

Version info

  • Merged into: 26.7.1.259 (included in 26.7 and later)

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT arrayReduce('uniqStateForEach', [[NULL], [NULL, NULL, NULL]])" aborts every time on a debug/sanitizer build (the LIMIT -432 in the fuzzer report is irrelevant noise).
b Root cause explained? Yes. uniq over Array(Nullable(Nothing)) collapses the nested aggregate to AggregateFunctionNothing (sizeOfData() == 0). In AggregateFunctionForEach::ensureAggregateData, growing the state array does arena.alignedAlloc(0), which returns the current arena position without advancing, so new_state == old_state. The old-state migration loop then calls the nested merge(new_state, old_state) with equal pointers, tripping the IAggregateFunction::merge self-aliasing assertion (added in #103543).
c Fix matches root cause? Yes. The migration loop is skipped when nested_size_of_data == 0 (zero-size states carry no data to migrate, and the aliasing only ever occurs for the zero-byte allocation). It targets the exact mechanism, not the symptom.
d Test intent preserved / new tests added? New test 04420_foreach_combinator_zero_size_nested_state added. It asserts both the previously-aborting zero-size cases AND that non-zero-size -ForEach aggregates still migrate growing states correctly, so it also guards against future weakening of the migration path.
e Both directions demonstrated? Yes. Without the fix: the 5 zero-size queries abort (exit 134); with the fix: all return correct results (exit 0). The new test is 30/30 with randomization on.
f Fix is general across code paths? Yes. ensureAggregateData is the single chokepoint for all three -ForEach callers (add, mergeImpl, mergeStateFromDifferentVariant). The only other combinator with the same alloc-then-migrate pattern, AggregateFunctionMap, rejects zero-size/Nothing nested aggregates upfront (ILLEGAL_TYPE_OF_ARGUMENT), so it cannot reach this path; no speculative guard added there.
g Fix generalizes across inputs? Yes. Verified across uniqStateForEach, groupArrayStateForEach, uniqForEach, and arrayReduceInRanges over all-NULL (Nothing) inputs; the guard keys on the nested state size, so it covers any nested aggregate that collapses to a zero-byte state. Non-zero-size inputs are unaffected.
h Backward compatible? Yes. No setting, format, or behavior change. Release builds were already correct (the assertion compiles out and the self-merge was a no-op); this only removes the debug/sanitizer abort.
i Invariants and contracts preserved? Yes. IAggregateFunction::merge's place != rhs precondition is now honored on this path. For zero-size states there is no per-element storage to migrate, so skipping the loop preserves the -ForEach state invariant (array of dynamic_array_size nested states); non-zero-size migration is unchanged.

Session id: cron:clickhouse-worker-slot-3:20260628-235700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai — could you review? Fixes the IAggregateFunction::merge self-aliasing assertion (added in #103543) firing in -ForEach over Array(Nothing): a zero-byte arena allocation does not advance the arena, so the grown state buffer aliases the old one and the migration loop self-merges. Fix skips the no-op migration when the nested state is zero-sized.

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

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5581d5a]

Summary: ✅


AI Review

Summary

This PR fixes the zero-size nested-state self-merge assertion for -ForEach and adds the same guard for -Map, with focused stateless coverage for the migration and arrayReduceInRanges merge paths. The two prior bot-authored inline findings are addressed in the current code, and the remaining thread has been resolved. I did not find new inline findings in the changed code.

Missing context / blind spots
  • ⚠️ CI was still mostly pending at review time: Style check had passed, while Fast test, build, and aggregate PR checks were pending. A completed CI run would close this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 29, 2026
The previous guard only covered the old-state migration loop in
ensureAggregateData. The same zero-size aliasing trips mergeImpl: when
two distinct -ForEach states have a zero-byte nested state, every
arena.alignedAlloc(0) returns the same arena position, so the per-element
nested_func->merge(place, rhs) receives place == rhs and fires the
IAggregateFunction::merge self-aliasing assertion.

arrayReduceInRanges reproduces this once the input exceeds minimum_step
(64): it pre-aggregates one -ForEach state per 64 rows and then merges
those states. Skip the per-element merge loop in mergeImpl for zero-size
nested states (the merge is a no-op for an aggregate over Nothing).

Extend 04420 with > 128-element all-NULL arrayReduceInRanges cases that
exercise the pre-aggregation merge path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT arrayReduceInRanges('uniqStateForEach', [(1, 200)], arrayMap(x -> [NULL], range(200))) aborts every time on a binary that has only the ensureAggregateData guard (Build ID 63d40adc).
b Root cause explained? An aggregate over Array(Nothing) (all-NULL) collapses the nested aggregate to AggregateFunctionNothing whose sizeOfData()==0. arena.alignedAlloc(0) returns the current arena position without advancing, so distinct nested states alias the same address. arrayReduceInRanges over > minimum_step (64) rows pre-aggregates one -ForEach state per 64 rows then merges those states; mergeImpl's per-element loop calls nested_func->merge(place, rhs) with place == rhs, tripping the IAggregateFunction::merge self-aliasing assertion (added in #103543).
c Fix matches root cause? Yes. Skip the per-element merge loop in mergeImpl when nested_size_of_data == 0 — directly the aliasing mechanism from (b).
d Test intent preserved / new tests added? Test extended, not weakened. Added > 128-element all-NULL arrayReduceInRanges cases that force the pre-aggregation merge, plus a non-zero-size sumForEach arrayReduceInRanges case so the migration/merge path stays exercised.
e Demonstrated in both directions? Yes, Build-ID-verified. Without fix (63d40adc): all 4 new zero-size queries abort (exit 134). With fix (5fe1b638): all pass; 40/40 with randomization; 9 existing ForEach/arrayReduce tests pass.
f Fix general, not a narrow patch? Yes. Audited every nested merge call in the combinator: ensureAggregateData migration loop (already guarded) and mergeImpl (this fix) are the only nested_func->merge sites. mergeStateFromDifferentVariant calls nested_func->mergeStateFromDifferentVariant (no place != rhs assert) and is unreachable for zero-size states (AggregateFunctionNothing does not override canMergeStateFromDifferentVariant, default false), so no speculative guard added there.
g Generalizes across inputs / type wrappers? The trigger is the zero-byte nested state, independent of the outer -ForEach aggregate. Verified across uniqStateForEach, groupArrayStateForEach, uniqForEach and Array(Nothing) of varying inner lengths; non-zero-size states (sumForEach, groupArrayForEach) keep merging correctly.
h Backward compatible? Yes. Nothing::mergeImpl is a no-op, so skipping the loop for zero-size states preserves results exactly. No setting, format, or default change.
i Invariants/contracts preserved? Yes. Upholds the IAggregateFunction::merge precondition (source != destination). -ForEach array layout, per-element alignment, and the migration path are untouched; only the no-op merge of zero-byte states is skipped.

Session id: cron:clickhouse-worker-slot-2:20260629-051700

AggregateFunctionMap stores each key's nested state in a separate arena slot.
When the nested state is zero-byte (e.g. uniq over Nullable(Nothing), which
collapses to AggregateFunctionNothing with sizeOfData()==0), every
arena.alignedAlloc(0) returns the same arena position without advancing, so a
key shared between two states has its nested_place aliasing the other state's
nested place. mergeImpl then called nested_func->merge(place, place), tripping
the IAggregateFunction::merge self-aliasing assertion.

Skip only the per-key nested merge for zero-size nested states (the nested
Nothing::mergeImpl is a no-op, so this is behavior-preserving) while still
unioning the key sets. This is the -Map sibling of the -ForEach fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 20/21 (95.24%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 29, 2026
Merged via the queue into ClickHouse:master with commit 0351d31 Jun 29, 2026
174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
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
…reach-self-merge

Fix -ForEach self-merge assertion for zero-size nested states
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