Skip to content

Exempt zero-size aggregate states from the self-merge assertion - #130678

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-self-merge-assert-zero-size-state
Nov 12, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-self-merge-assert-zero-size-state

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129257
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):

Debug and sanitizer builds no longer abort with IAggregateFunction::merge called with the same source and destination state when a window function copies a zero-size aggregate state.

Description

CI: AST fuzzer (amd_debug), Logical error: 'IAggregateFunction::merge called with the same source and destination state' (STID: 2508-3fb0), https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104297&sha=88cddaf5fd5438d960957b64ba02fc174ee203b2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 (reproduces on master without that PR).

An aggregate over only-NULL arguments becomes nothing, whose state has sizeOfData() == 0, e.g. uniqArrayState([number % NULL]). A zero-byte arena allocation does not advance the arena, so distinct zero-size states share one address. Both window strategies copy the previous row's result for an unchanged frame with insertRangeFrom, which for ColumnAggregateFunction is insertDefault() plus merge(new, previous), so chassert(place != rhs) fires although the states have no bytes to alias. #129257 extended that copy to -State results; any/groupArray over a state column reached it before.

Since the assertion landed (#103543), all 12 CI rows of this message family (8 STIDs) had an only-NULL argument, i.e. a zero-size state, and several call sites were already patched one by one. Instead of patching another one, the predicate is refined once: IAggregateFunction::isSelfMerge (place == rhs && sizeOfData() != 0) is used at all six assertion sites. Only AggregateFunctionNothingImpl (empty merge) and the WindowFunction placeholders (merge throws) report a zero size; every combinator forwards the nested size or adds a non-zero prefix, so no exempted merge touches state bytes. Non-empty states are checked as before, mergeImpl is still called, and release builds are unchanged.

Validation: the new test aborts the unfixed debug build at IAggregateFunction.h:263 and passes with the fix, 50/50 randomized runs; reverting only the merge site makes it abort again.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/130678]

Version info

  • Merged into: 26.11.1.2042-master (included in 26.11 and later)

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test cannot detect a disabled guard and covers only the serial merge site (05620_window_aggregate_zero_size_state_copy.sql) DISAGREE For sizeOfData() != 0, !isSelfMerge(a, b) is exactly the old a != b, so only zero-size states change; the test aborts the unfixed debug build at IAggregateFunction.h:263 and again when only that site is reverted. A non-empty self-merge has no SQL path (all 12 CI rows of this message are zero-size states), so the only option would be a gtest death test of a debug-only assertion.
2 💡 The per-site zero-size guards from #108781 and #115008 become redundant DISAGREE No-op shortcuts in release builds; I left them as they are to keep this change to the assertion only.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261111-030800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test (or the CI query) on an unfixed debug build aborts every run at IAggregateFunction.h:263 via AggregateWindowFunctionPrefix.cpp:48 / AggregateWindowFunctionRecalculate.cpp:57; through clickhouse-test the server dies with the exact CI message.
b Root cause explained? Yes. An aggregate over only-NULL arguments becomes nothing (sizeOfData() == 0); zero-byte arena allocations do not advance the arena, so distinct states share an address. The window same-frame copy (insertDefault() + merge(new, previous)) then trips place != rhs although the states have no bytes to alias.
c Fix matches root cause? Yes. The assertion's premise (same address = same state) is false only for zero-size states, so the predicate exempts exactly those (place == rhs && sizeOfData() != 0); the call sites are correct.
d Test intent preserved / new tests added? Yes. New SQL test covering both window strategies, any/groupArray over a state, and a non-empty control. No existing test changed.
e Both directions demonstrated? Yes. Unfixed: abort (rc 134); fixed: output matches the reference, 50/50 randomized runs pass. Reverting only the merge site makes the test abort again.
f Fix is general across code paths? Yes. One predicate used at all six self-merge assertion sites (merge, parallel merge, mergeBatch, mergeAndDestroyBatch, mergeBatchOrDefer, mergeAndDestroyBatchOrDefer).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Only AggregateFunctionNothingImpl (empty merge) and the WindowFunction placeholders (merge throws) report a zero size; combinators forward it or add a non-zero prefix. Checked -Array, -ArrayIf, constant [NULL], -ForEach, -Map, -OrNull, -Merge: results equal the release build.
h Backward compatible? (maintainer-approved exception only) Yes. Debug/sanitizer assertion only; no setting, format or behavior change; release builds are unchanged.
i Invariants and contracts preserved? Yes. mergeImpl is still called; for an exempted pair it is the empty nothing merge, and the batch variants' destroy of such a state is a no-op. Non-empty states are asserted as before.

Session id: cron:clickhouse-impl-slot-40:20261111-022600

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fd71959]

Summary: ✅


AI Review

Summary

PR #130678 allows distinct zero-size aggregate states to share an address without triggering the self-merge assertion, while preserving the assertion for non-empty states. Reviewed commit fd719592b8fe7c667fa75d28601aeda89b80813d, the full diff, surrounding merge and window-copy paths, combinator state layouts, and all prior discussion. No actionable findings. The new 05620_window_aggregate_zero_size_state_copy regression test passes in Fast test; tests were not rerun locally.

Final Verdict

Status: ✅ Approve. No inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-ci can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fd719592b with master dec2c3c06 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.77, programs/clickhouse-keeper ×0.70 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.5 s 13.8 s +8.8 s (+175%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.1 s 9.0 s +5.8 s (+181%)
Compile time of recompiled translation units

334 translation units recompiled, 2696 s compile time in total, 334 of them have a recent master baseline.

Job report

@Algunenano

Copy link
Copy Markdown
Member

@Michicosun Could you please review. This has hit multiple PR CI fuzzer runs already. Also, please look at all the followups associated to #129257

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

Nice!

@alexey-milovidov alexey-milovidov self-assigned this Nov 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 12, 2026
Merged via the queue into ClickHouse:master with commit dd27997 Nov 12, 2026
551 of 553 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
Resolve the five conflicts of the 26.8 cherry-pick of ClickHouse#131595. They are
all regions where master has code that 26.8 does not have: the deferral
of large merges (ClickHouse#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (ClickHouse#130678), the
bound of zero-sized nested states (ClickHouse#130120), and the partition-by-partition merge of
the adaptive aggregator (ClickHouse#129565). None of them is labelled for 26.8, and
the resolution takes none of them.

26.8 has no catch around the per-function loop of the batch merge (master
got it in ClickHouse#117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.8 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of ClickHouse#131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.8 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.9 cherry-pick of #131595. They are
all regions where master has code that 26.9 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.9, and
the resolution takes none of them.

26.9 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.9 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.9 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.10 cherry-pick of #131595. They are
all regions where master has code that 26.10 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.10, and
the resolution takes none of them.

26.10 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.10 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.10 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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.

4 participants