Skip to content

Do not alias pre-aggregation states of a zero-size aggregate in arrayReduceInRanges - #115008

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-arrayreduceinranges-zero-size-state-self-merge
Aug 17, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-arrayreduceinranges-zero-size-state-self-merge

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #108781

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

arrayReduceInRanges over an array whose elements are all NULL aborts a debug or sanitizer build
with Logical error: 'IAggregateFunction::merge called with the same source and destination state':

SELECT arrayReduceInRanges('groupArray', [(1, 64)], arrayMap(x -> (x + NULL), range(64)));

Found by the AST fuzzer:
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

An all-NULL argument collapses the aggregate to AggregateFunctionNothing, whose sizeOfData() is
0. Arena::alignedAlloc advances the arena by size, so every zero-byte allocation returns the same
address. The function allocates one pre-aggregation state per 64 rows plus one state per range from a
single arena, so all of those states alias and both the pairwise level merge and the per-range merge
become merge(p, p).

The fix allocates max(sizeOfData(), 1) bytes for the pre-aggregation states, so they are distinct
and every merge still runs. The per-range state needs no padding: that merge only runs when the range
spans a whole 64-row block, which is also the condition for a pre-aggregation state to exist, and its
one-byte allocation has already advanced the arena. For an aggregate with a non-empty state the
allocation is byte-identical to before.

I deliberately did not suppress the merge for zero-size states. sizeOfData() == 0 does not imply
that merging is a no-op: StatelessWindowFunction is also zero-size and its mergeImpl throws.
Since the aggregate is caller-supplied, a genuinely empty state cannot be told apart from one whose
merge enforces a contract, so skipping the call could drop that enforcement.

Two further places with the same allocation pattern are left alone. ColumnAggregateFunction can
hold zero-size states (the test builds one via nothingState) but its insertMergeFrom merges
across two different arenas. The Aggregator merge paths have one reported sighting of the sibling
assertion (mergeAndDestroyBatch, on #111459) that 15 probes did not reproduce.

Release behaviour is unchanged - the assertion compiles out and Nothing::mergeImpl is empty.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, all findings resolved)

An independent model reviewed every revision before publication and I adjudicated each finding
against the code. Final round: 0 findings.

# Finding Verdict Resolution
❌ The commit message called the -ForEach zero-size merge guard from #108781 "sound". It keys on state size alone (AggregateFunctionForEach.h:277, AggregateFunctionMap.cpp:209) with no check for which zero-size family is nested, so it would also skip StatelessWindowFunction::mergeImpl, which throws. AGREE Commit message now states only the mechanical fact. This is also why the fix pads the allocation instead of skipping the merge.
⚠️ The description claimed both allocation sites are padded, and that padding only the pre-aggregation array still aborts at 64 elements. Only the pre-aggregation allocation is padded, and that is sufficient. AGREE Description corrected. The per-range merge runs only when a range spans a whole 64-row block, which is also the condition for a pre-aggregation state to exist, and that state's one-byte allocation has already advanced the arena.
💡 Test comment on the Null combinator pre-empting the State combinator. Dropped Accurate as written (AggregateFunctionNull.cpp:100-114 returns before :124).

A position I got wrong and reversed: I twice rejected the finding that the per-range allocation
needs no padding, and it was correct. The fix is one changed allocation, not two.

Also noticed, not raised: those -ForEach and -Map guards would skip a throwing zero-size nested
merge. I have not produced a query with an observed wrong result, so I am not filing it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [51495e4]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) ERROR
Unknown job error ERROR cidb IGNORED
Check failed FAIL cidb IGNORED

AI Review

Summary

This PR fixes arrayReduceInRanges when the resolved aggregate state is zero bytes by padding the pre-aggregation arena allocation to one byte, which prevents the debug/sanitizer-only merge(p, p) assertion without suppressing any merge calls. I reviewed the current diff, the surrounding code, the prior PR discussion, and the new stateless regression test, and I did not find a remaining correctness or coverage gap in the patch itself.

Final Verdict

✅ No blocking issues found.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. arrayReduceInRanges('groupArray', [(1, 200)], arrayMap(x -> (x + NULL), range(257))) aborts a debug binary at arrayReduceInRanges.cpp:226 every run; [(1, 64)] over range(64) aborts at :302.
b Root cause explained? Yes. An all-NULL argument collapses the aggregate to AggregateFunctionNothing (sizeOfData() == 0). Arena::alignedAlloc advances by size, so every zero-byte allocation returns the same address; the per-64-row pre-aggregation states and the per-range state then alias, and both merges become merge(p, p), tripping chassert(place != rhs).
c Fix matches root cause? Yes. Padding the pre-aggregation allocation gives the states distinct addresses, which is what the aliasing bug is. No merge is skipped, no assertion weakened, no symptom guarded.
d Test intent preserved / new tests added? No existing test changed. New 04925_array_reduce_in_ranges_zero_size_state covers both merge sites, a genuine -State wrapper over a zero-size nested function (nothingState, result type Array(AggregateFunction(nothing, UInt16))), the collapsed-placeholder and -Tuple variants, a case below both thresholds, and non-zero-size controls. Three rankIf lines pin that BAD_ARGUMENTS is still reported; their comment states that the per-range finalize is what reports it for them, so they do not observe whether a merge ran. A fourth rankIf line uses an empty range list, where the per-range loop never runs and the pairwise level merge is the only remaining path to the aggregate's merge.
e Both directions demonstrated? Yes, on three binaries with distinct asserted Build IDs (base cb063176, fixed f774bf18, merge-skipping variant ff122605; each server's SELECT lower(buildId()) checked against its binary). Base aborts at :226 (range(257), and the empty-range line) and :302 (range(64)), including each new nothingState line; the test reddens by aborting the server mid-run, base's own fatal log carrying base's Build ID and git hash. Fixed: RC=0 on all, test [ OK ], 50/50 randomized pass. The variant that skips zero-size merges instead returns [] for the empty-range line and fails the test, so the suite discriminates that alternative design. The below-threshold range(63) control is clean on all three, so nothing is reddening indiscriminately.
f Fix is general across code paths? Yes, and it covers both merge sites with one padded allocation. The per-range merge runs only when a 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; measured over 259200 index/length/size combinations, which abort on base and are clean here. Sibling arrayReduce allocates the same way but never merges (measured clean). Two further places with the pattern were probed and do not reproduce: in ColumnAggregateFunction::ensureOwnership a zero-size state column is constructible (this test builds one) but the two states come from different arenas, so they cannot alias; the Aggregator merge paths have one reported sighting that 15 probes did not reproduce.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified over groupArray, uniq, count, sumTuple, groupArrayState, rankIf, the -If/-Array/-Distinct/-OrNull combinators, LowCardinality(String) arguments, materialized input, negative index, zero length, UInt64 max length, an empty range array, duplicate ranges, and multi-row blocks.
h Backward compatible? Yes. No setting, no serialization format, no default change, so no SettingsChangesHistory.cpp entry. For a non-empty state max(size, 1) == size, so those allocations are byte-identical; a 10-query control set produced identical output on both binaries.
i Invariants and contracts preserved? Yes. place != rhs now holds by construction. The destroy loop and SCOPE_EXIT_MEMORY_SAFE are driven by the place count, not by byte size. create/destroy are empty for both zero-size aggregates, so the padding byte is never written. Merging is not suppressed, so a zero-size aggregate whose merge enforces a contract (StatelessWindowFunction::mergeImpl throws) keeps that enforcement.

Session id: cron:clickhouse-impl-slot-7:20260816-115800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @george-larionov @azat, could you review this? An all-NULL argument collapses the aggregate to AggregateFunctionNothing whose state is zero bytes, and Arena::alignedAlloc advances by size, so every pre-aggregation state in arrayReduceInRanges returned the same address and both merges became merge(p, p); padding the allocation to max(sizeOfData(), 1) keeps the states distinct without suppressing any merge.

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 51495e440 with master 41453250d (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
Binary Master PR Δ
programs/clickhouse-stripped 694.55 MiB 691.54 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 51495e4

CI is fully finished on this head: 177 check-runs, 156 success / 20 skipped / 1 failed, 0 still
running. Config Workflow and Finish Workflow both succeeded, and the praktika report has 0
dropped jobs, so the matrix is a real run. CIDB has 336447 rows across 159 checks for this commit.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Unknown job error, Check failed infra: setup died fetching the previous release tag. get_previous_release_tag -> get_gh_api hit one read timeout plus three 504 Gateway Time-out from api.github.com/repos/ClickHouse/ClickHouse/releases, exhausted its fixed 3 s retry budget in 12 s (23:45:46Z to 23:45:58Z), exited 1 before any server started, so test_results.tsv was never written #112974 (ours, open)
Config Workflow / Pre Hooks (14:40:20Z, 15:51:05Z) superseded: can be tested label was not yet applied when the workflow first dispatched not applicable, the same job re-ran green at 21:21:46Z on this identical commit

The Upgrade check failure is not this PR's diff, which touches only
src/Functions/array/arrayReduceInRanges.cpp and one stateless test. #112974 replaces exactly the
get_gh_api retry policy that ran out here, growing the delay as sleep * 2 ** attempt capped at
60 s so a routine 5xx blip no longer outlasts the window. That PR is still open, and the fix is
absent from this build's tree (grep -c "GH.api_get" on tests/ci/build_download_helper.py at this
head is 0, matching master), so the failure predates it rather than surviving it.

The two Config Workflow rows are historical, not open: both predate the label being applied, the
same job then completed success at 21:21:46Z on the same commit_sha, and the praktika report
reports 0 dropped jobs at every depth.

The regression test 04925_array_reduce_in_ranges_zero_size_state ran 347 times across 21 distinct
jobs on this head with 0 failures. All ten Stress test (*) flavours are green. Counts come from an
aggregate CIDB query over this commit, not from a tally of the job list.

Session id: cron:our-pr-ci-monitor:20260817-020000

@PedroTadim PedroTadim self-assigned this Aug 17, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit b70af22 Aug 17, 2026
529 of 535 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 Aug 17, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 20, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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