Skip to content

Do not copy a constant aggregate function argument to the block size without GROUP BY - #131185

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:constant-argument-aggregate-without-key
Nov 20, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:constant-argument-aggregate-without-key

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

In a query without GROUP BY, an aggregate function whose arguments are all constants no longer copies them to the size of the block: a function that ignores repeated values (uniq, min, max, groupUniqArray, -Distinct, ...) adds the constant once, and any other function adds a copy of at most 1 MiB repeatedly. For example, SELECT count(toFixedString('', 1048576)) FROM t no longer requests 64 GiB of memory per thread with max_block_size = 65409.

Description

Related: #99639, #131697. Failing jobs (server OOM-killed at about 45 GB): AST fuzzer (amd_debug, targeted) on #99639 (COUNTOrDefaultDistinct), and AST fuzzer (amd_debug, targeted) and (..., old_compatibility) on #131697 (anyOrDefault and count of toFixedString(<constant>, 1048576)).

Without keys, Aggregator::prepareAggregateInstructions copied every constant argument to the size of the block: with max_block_size = 65409, a 1 MiB constant is a 64 GiB request in each AggregatingTransform thread. The analyzer does not fold a 1 MiB constant, so count keeps it.

Now, when all arguments of a function are constants, they are copied to at most max(1, 1 MiB / bytes of one row) rows (one row for a function with ignoresRepeatedValues(), #127940), and the copy is added repeatedly until the block is covered. The function gets the same values in the same order through the same batch API, so every function and combinator is covered; a constant of up to 16 bytes still gets one batch per default-size block. -Distinct forwards only unseen values, so it now reports ignoresRepeatedValues(), which also gives it the LowCardinality path of #127940.

Validation: the memory queries of the new test fail with MEMORY_LIMIT_EXCEEDED (requests of 0.5 to 64 GiB) on master and pass with the fix, 50 of 50 randomized runs; the rest compares constants with materialized copies, also split into several pieces.

Not covered: aggregation with keys (also the keyed sets of GROUPING SETS) and functions mixing constant and non-constant arguments. The targeted run's 64 GiB request passing max_server_memory_usage is the MemoryTracker problem of #131625.


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

Version info

  • Merged into: 26.12.1.67-master (included in 26.12 and later)

groeneai and others added 2 commits November 13, 2026 01:29
Without keys, `Aggregator::prepareAggregateInstructions` materialized every
constant argument to the size of the block. For
`COUNTOrDefaultDistinct(toFixedString('', 1048577))` with
`max_block_size = 65409` that is a 64 GiB request in each
`AggregatingTransform` thread: the AST fuzzer run on PR ClickHouse#99639 had 16 of
them, and the server was OOM-killed at 44 GB RSS.

A function whose state ignores repeated values (`ignoresRepeatedValues()`,
added by ClickHouse#127940) gets the same state from one row as from every row of a
constant. So, without keys, a single constant argument of such a function is
now passed as its one-row data column and added once per block, the way
ClickHouse#127940 adds the used values of a `LowCardinality` argument and the radix
partitioned `uniqExact` routes a constant once per block.

`-Distinct` forwards to the nested function only the values it has not seen,
so it ignores repeated values whatever the nested function is. It now reports
it, which also gives it the `LowCardinality` path without keys.

The JIT branch of `executeWithoutKeyImpl` is not affected: its only caller
passes `use_compiled_functions = false`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=00b62ef53d2811d1f363572394dbf8b9bb9ab2d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous last query of 05628 compared a LowCardinality column with
its plain copy, which gives the same result on master, so it could not
show that -Distinct now reports ignoresRepeatedValues() and takes the
LowCardinality path of ClickHouse#127940. The new query runs -Distinct functions
over a materialized LowCardinality(FixedString(100000)) column under a
100 MB query limit: master converts it to a full column (an 8 GiB
request, MEMORY_LIMIT_EXCEEDED), the fix adds its one used value.

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; 2 findings over 1 full pass + 1 delta recheck, the recheck found none).

# Sev Finding Verdict Evidence / action
1 ⚠️ -Distinct under an outer -OrDefault/-OrNull/-State (e.g. countDistinctOrDefault) still materializes the constant, so "every -Distinct function" was too broad AGREE, fixed in the description Claim narrowed to functions whose name ends with -Distinct; the other cases are listed under "Not covered" (measured: still MEMORY_LIMIT_EXCEEDED with and without this PR)
2 ⚠️ The LowCardinality -Distinct check compared results only, which also pass on master AGREE, fixed @ 3bf4e26 Added a memory-limit query over materialize(toLowCardinality(toFixedString('', 100000))): MEMORY_LIMIT_EXCEEDED (8 GiB request) on master, 1 1 100000 with the fix

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

Session id: cron:clickhouse-review-slot-10:20261113-021501

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cc1a69d]

Summary: ✅


AI Review

Summary

Reviewed #131185 at cc1a69df9662d2f7f306fa718e140599c650f188. The change bounds copies of constant aggregate arguments without GROUP BY, skips repeated values where supported, and enables the existing LowCardinality optimization for -Distinct. No outstanding findings remain; the prior expanded-size finding is fixed and covered by the regression test. The complete 05628_constant_argument_aggregate_without_key test passed on the PR-head CI binary using clickhouse local, with an exact reference-output match.

Consumers traced for the shortened arguments: executeWithoutKeyImpl bounds each repeated batch; addBatchSinglePlace translates array offsets and dispatches sparse arguments; nullable, conditional, state, and distinct adapters receive bounded ranges. Keyed aggregation, in-order aggregation, and adaptive staging retain full argument columns because shortening requires zero keys. The JIT path without keys remains disabled, and merge/finalization paths consume aggregate states rather than the shortened arguments.

Missing context / blind spots
  • ⚠️ The full current-head CI run, including sanitizer jobs, is still in progress. Those results will provide broader runtime validation beyond the focused local regression.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cc1a69df9 with master 463f45f5f (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.

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits November 15, 2026 04:48
The previous commits avoided the copy of a constant argument to the size of
the block only for functions that ignore repeated values. Every other
function still received the full copy, although all its rows are equal. The
AST fuzzer runs on PR ClickHouse#131697 hit exactly that case:
`anyOrDefault(toFixedString(<const>, 1048576))` and
`count(toFixedString(<const>, 1048576))` without keys asked for 64 GiB and
8 GiB per `AggregatingTransform` thread, and the server was OOM-killed. A
constant of 1 MiB is not folded by the analyzer, so `count` keeps its
argument and the copy happens.

Now, without keys, when all arguments of a function are constants, they are
copied to at most `max(1, 1 MiB / bytes of one row)` rows (one row for a
function that ignores repeated values), and that copy is added repeatedly
through `Aggregator::addBatchSinglePlace` until the rows of the block are
covered. The function sees the same values in the same order through the
same batch API, so every function and combinator is covered (`count`, `any`,
`-OrDefault`, `-If`, `-Array`, `-State`, Null adapters). A constant of up to
16 bytes still gets one batch of the whole block at the default block size.

The existing conversion pipeline (`convertToFullColumnIfConst`, replicated,
sparse and `LowCardinality` handling) is reused on a shorter constant
(`ColumnConst::cloneResized`), which replaces the separate one-row branch.

Not covered: aggregation with keys (keyed consumers, the JIT loop and the
adaptive producer's argument staging read arguments at block positions), and
a function with both constant and non-constant arguments.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131697&sha=af5e7aee158e8379e77dc757c0a1c04b91ea14d2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131697&sha=af5e7aee158e8379e77dc757c0a1c04b91ea14d2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comment narrating the new constant-argument copy in prepareAggregateInstructions; the field comment in Aggregator.h states the semantics.

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 of 2fcd5910eff5e by an independent model (engine: codex; 0 findings over 1 full pass), plus my own cold review (3 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 The JIT branch of executeWithoutKeyImpl would read past a shortened copy if compilation were enabled without keys DISAGREE Unreachable: its only call site, in Aggregator::executeOnBlock, passes use_compiled_functions = false
2 💡 Functions whose result depends on batch boundaries (floating-point sum/avg, estimateCompressionRatio) can change in the last bits for a constant whose block copy exceeds 1 MiB AGREE, noted Same effect as changing max_block_size today; constants of up to 16 bytes keep one batch per default-size block
3 💡 Aggregation with keys (also the keyed sets of GROUPING SETS) and mixed constant/non-constant arguments still copy the constant AGREE, noted Stated under "Not covered"; keyed consumers read arguments at block positions

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

Session id: cron:clickhouse-review-slot-8:20261115-050500

Comment thread src/Interpreters/Aggregator.cpp Resolved
groeneai and others added 2 commits November 15, 2026 06:50
The copy of a constant argument was sized from the encoded column, but the
copy is expanded by `recursiveRemoveLowCardinality` after it is made. A
constant `Array(LowCardinality(String))` that repeats one string of 1000
bytes 1000 times is small encoded and 1 MB per row expanded, so `count(c)`
over 5000 rows still requested 494.52 MiB instead of about 1 MiB. Measure
one row of the constant after removing `LowCardinality`, as the pipeline
materializes it.

Reported by the automated review:
ClickHouse#131185 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The case of the functions that do not ignore repeated values ran over
200000 rows of a 100 KB constant, so `argMax(c, c)` and `anyHeavy(c)`
compared 20 GB per run. It was 230 s of the 246 s per run in
`Stateless tests (amd_debug, flaky check)` and 493 s of 499 s under TSan,
over the 180 s limit. 5000 rows still make the copy to the block 500 MB
against the 100 MB limit, so the case still fails without the fix.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 55e5d03

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 3/6) infra, not from this PR (it changes only Aggregator code and its test): killed at the 7200 s job timeout, because the coverage-based test selection picked a coverage run that collected no test (cohort 79929b2c), so every test of the shard ran in full (--max-queries 0 on all 142 tests). The same shard timed out on 17 other PRs since 05:00Z #131772 (mine, open)

Session id: cron:our-pr-ci-monitor:20261115-110014

@alexey-milovidov alexey-milovidov self-assigned this Nov 19, 2026
…ggregate-without-key

Resolved a conflict in `AggregateFunctionDistinct.h`: kept the PR's
`ignoresRepeatedValues` override and master's `[[nodiscard]]` attributes.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into ClickHouse:master with commit b851614 Nov 20, 2026
195 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 21, 2026
The randomized Parquet writer settings (ClickHouse#132712) made the four 10M-row
fixtures of the test take up to 460 s in the tsan and msan flaky checks.
Write 1M rows and lower the memory limits from 40 MiB to 3 MiB. With
`max_block_size = 8192` and `max_untracked_memory = 0` a read in
`max_block_size` chunks peaks below 0.5 MiB, while one chunk of 1M UInt64
rows needs 7.63 MiB, so every case still fails when its exclusion is
removed.

Since ClickHouse#131185 an aggregation without GROUP BY copies at most 1 MiB of a
constant argument, so `count(x)` no longer materializes a one-chunk read.
The case counts `materialize(x)` instead, which still does.

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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-improvement Pull request with some product improvements 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