Skip to content

Batch the -ForEach aggregate combinator's accumulation - #121137

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
valerypetrov:feature/promql-streaming-aggregation-memory
Oct 2, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
valerypetrov:feature/promql-streaming-aggregation-memory

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Speed up -ForEach aggregate functions (sumForEach, avgForEach, ...) and grouped multi-argument -If aggregate functions with a Nullable argument or condition, by processing rows in batches instead of calling add for each row.

Detailed Description:

Scope

This PR changes two combinators:

  1. -ForEach (AggregateFunctionForEach): all -ForEach functions, e.g. sumForEach, avgForEach, quantilesForEach, sumForEachIf.
  2. The Nullable adapter of -If (AggregateFunctionIfNullVariadic, commit e384de9), used with GROUP BY. It is used for every -If aggregate with a Nullable argument or condition, except one case: a single argument that is itself Nullable, like sumIf(nullable_x, cond). That case uses AggregateFunctionIfNullUnary and is not changed. So the change covers sumForEachIf(arr, toNullable(cond)), and also functions unrelated to -ForEach, such as sumIf(x, nullable_cond), covarPopIf(nullable_x, y, cond) and corrIf(...). Before, these went through add row by row in GROUP BY. Now they are batched.

Both changes only affect how rows are fed to the nested function. The state layout, serialization and merge are unchanged, and results are identical. Commit e384de9 is self-contained, so the -If part can be reviewed, or split out, on its own.

What is batched

  • AggregateFunctionForEach overrides addBatchSinglePlace, addBatchSinglePlaceNotNull, addBatch and addBatchWithNonNullPlaces. Before, all four went to the IAggregateFunctionHelper loop, which calls add once per row, and each call rebuilt the nested column list and looked up the offsets again. Now that setup happens once per batch. The per-row array-size check (SIZES_OF_ARRAYS_DONT_MATCH) is still done. So are -If flags, null maps and null places.
  • AggregateFunctionIfNullVariadic (a multi-argument -If with a Nullable argument or condition, e.g. sumForEachIf(arr, toNullable(cond)) or covarPopIf(nullable_x, y, cond)) already batched the single-place case. It now also overrides addBatch / addBatchWithNonNullPlaces. They fold the condition and the argument null maps into one UInt8 condition column and pass the batch to the nested -If, which forwards it to the nested function's addBatch. Before, GROUP BY went through add row by row.
  • Not changed: the nested function is still called once per array element (nested_func->add), so gains are small, around 5-20%, not a multiple. Merge, serialization and the state layout are untouched, and results are identical (see Testing).

Cache-line padding was tried and removed. alignas(64) on the state grew it from 16 to 64 bytes. Aggregator pads each state to the largest alignment in the per-key block, so sum(b), count(), sumForEach(a) went from 32 to 128 bytes per key. The padding also did not target a phase where states share cache lines: each aggregating thread has its own arena. Nothing in the state layout changes in this PR.

Measurement

Release build on macOS arm64. Master is the merge base 365470f5aba. Data: Memory table, 2M rows, k UInt32 (1000 keys), arr Array(Float64) with 32 elements, narr the same with ~9% NULL elements, cond UInt8, ncond Nullable(UInt8). max_threads = 1, best of 2 medians of 9 runs, ms:

query master this PR change
sumForEach(arr) 56 52 -7%
avgForEach(arr) 62 55 -11%
sumForEachIf(arr, cond) 29 27 -7%
sumForEachIf(arr, ncond) 29 27 -7%
sumForEach(narr) 109 106 -3%
k, sumForEach(arr) GROUP BY k 63 56 -11%
k, avgForEach(arr) GROUP BY k 71 63 -11%
k, sumForEachIf(arr, cond) GROUP BY k 34 30 -12%
k, sumForEachIf(arr, ncond) GROUP BY k 40 31 -22%
k, sumForEach(narr) GROUP BY k 115 109 -5%

Only the sumForEachIf(arr, ncond) row exercises the -If adapter change. Other functions that now take the batched -If path (covarPopIf, corrIf, ...) were checked for identical results but not timed.

With default max_threads (18 cores; 8M rows so the times are not near the ms resolution), the numbers are noisier: sumForEach 21 -> 19 ms, avgForEach 23 -> 21, grouped sumForEachIf(arr, ncond) 18 -> 14, the other queries within 1-2 ms.

CI tests/performance/aggregate_function_for_each.xml on the previous head: #0-#3 6-13% faster on amd and 2.5-12% on arm, quantilesForEach grouped (#4) -7% amd and -1% arm. None were flagged, because each move is below its threshold.

End to end, prometheusQueryRange('ts', 'sum by (dc) (m)', ...) over 2000 series x 2880 samples (max_threads = 1) takes the same time (150 ms) before and after. The sumForEach accumulation is a small part of that query, so this PR is not a PromQL speedup. It makes the combinator itself faster.

Testing

  • 05234_foreach_streaming_aggregation_batch: single-place and grouped paths, empty arrays, Nullable elements, mismatched array sizes, -If with UInt8 and Nullable(UInt8) conditions, null places (group_by_overflow_mode = 'any'), and a grouped multi-argument nullable -If (covarPopIf, corrIf) checked against the same aggregate over rows filtered in WHERE. 05234_promql_streaming_aggregation_memory covers PromQL aggregations.
  • Differential check against the master binary on 300k deterministic random rows: sum/avg/min/max/count/any/anyLast/groupArray/groupUniqArray/quantile(s)Exact/corr/covarPop -ForEach, -ForEachIf (UInt8 and Nullable conditions), sumArrayForEach over Array(Array), Array(LowCardinality(String)), -State / -Merge round trip, grouped multi-argument nullable -If, overflow mode, small blocks and 8 threads. The output is byte-identical (413 rows).
  • Local run of 156 related stateless tests (every test mentioning ForEach, plus -If / Nullable combinator tests). All pass except ones that need ZooKeeper or 127.0.0.2. The remote() ones pass once pointed at 127.0.0.1.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1235-master (included in 26.10 and later)

@clickhouse-gh clickhouse-gh Bot added comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization labels Sep 20, 2026
@SmitaRKulkarni SmitaRKulkarni added the can be tested Allows running workflows for external contributors label Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6c8e0f1]

Summary: ✅


AI Review

Summary

This PR batches AggregateFunctionForEach accumulation and the grouped AggregateFunctionIfNullVariadic path, then adds focused stateless coverage plus a dedicated performance test for the new -ForEach fast paths. I rechecked the previously raised correctness gaps against the current revision and did not find any remaining blocker or major issue.

Tests

⚠️ I did not run the queries or the performance harness locally in this environment. The review relied on the current code, the added stateless tests, the new performance test XML, and the full prior PR discussion.

Final Verdict

✅ No new findings. No inline review comments were posted.

LLVM Coverage Report

Measured on commit 6c8e0f1.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 88/92 (95.65%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

This PR adds batch versions of the add functions for the -ForEach combinator and batch grouped paths for multi-argument -If with a Nullable argument or condition. No ClickBench or TPC-H query uses -ForEach, and ClickBench columns are not Nullable, so none of the flagged queries runs the changed code. The Q30 regression (+21.0%) is inside master's current range, and the Q34 improvement (-10.8%) comes from a thin baseline after a recent master shift. Both are downgraded to not_sure, and Q28 stays borderline. To see this PR's real effect, look at the new aggregate_function_for_each performance test, not these benchmarks.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1109 1049 -5.4% <0.0001 This is a borderline shift and the two tests disagree. The query uses no -ForEach or Nullable multi-argument -If aggregate, so the changed batch paths never run.
⚠️ 30 not_sure 229 277 +21.0% <0.0001 aggregation: The +21.0% median of 277 ms is inside master's current range of 199-286 ms. This GROUP BY uses plain count/sum/avg on non-Nullable columns, so the changed -ForEach and -If code is never called.
⚠️ 34 not_sure 1269 1132 -10.8% <0.0001 aggregation: CPU time dropped along with the -10.8% change, but the baseline is thin after the recent master shift. This URL GROUP BY with count() does not use the changed -ForEach or -If batch paths.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: aca7d6c5-f388-411f-b999-fe4b42a273dc
  • MIRAI run: 5412cfbe-31a5-499d-8a55-fff4c0dab25f
  • PR check IDs:
    • clickbench_2481501_1790732009
    • clickbench_2481509_1790732009
    • clickbench_2481519_1790732009
    • tpch_adapted_1_official_2481525_1790732009
    • tpch_adapted_1_official_2481558_1790732009
    • tpch_adapted_1_official_2481572_1790732009

Build (arm_tidy) failed on both new overrides:

  AggregateFunctionForEach.h:293:10: error: default arguments on virtual or
  override methods are prohibited [google-default-arguments,-warnings-as-errors]
  AggregateFunctionForEach.h:331:10: same

`if_argument_pos = -1` has to stay, because the base declaration carries it and
every caller relies on it. `IAggregateFunction` annotates its own `addBatch` and
`addBatchSinglePlace` with `/// NOLINT` for this reason, and the Null, OrFill,
Tuple and UniqCombined overrides all follow it. This does the same.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
valerypetrov and others added 3 commits September 21, 2026 10:57
The row-at-a-time `add` rejects a row whose array arguments do not share
boundaries, throwing SIZES_OF_ARRAYS_DONT_MATCH. Both new batch paths read
`begin` and `end` from the first argument's offsets and then feed that slice to
every nested column without checking the others, so a mismatched row like
`corrForEach([1, 2], [3])` stopped being rejected and silently read the second
argument through the first argument's range instead.

The existing coverage could not catch it: every aggregate in the test is
single-argument, where there is nothing to disagree with. The new case uses a
two-argument `-ForEach` and asserts the error on both batch entry points, the
ungrouped one and the grouped one.

Verified against a build without this branch: both queries throw error 190, and
with the expected code changed to a wrong one the harness reports
"Expected server error code: 43 but got: 190", so the assertions are enforced
rather than silently accepted.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
`Aggregator` sends the ordinary grouped case through `addBatchWithNonNullPlaces`
as soon as the hash table has materialized every state, and
`IAggregateFunctionHelper` overrides that with a row-at-a-time loop over `add`.
Since this class did not override it, the new batch path never ran for a plain
GROUP BY, which is the case the PR is aimed at.

Delegating to `addBatch` is what the base declaration in `IAggregateFunction`
already does; only the helper's loop stood in the way. The null-place check
inside `addBatch` is harmless here, since no place is null on this path, and the
array-size guard now covers the grouped case as well.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
`sizeOfData()` returns `sizeof(Data)` and `alignOfData()` returns `alignof(Data)`,
so `alignas(64)` took the state from 16 bytes to 64. That is the opposite of the
memory improvement this PR claims, and the cost does not stop at this function.

`Aggregator` takes a single max over every function's `alignOfData()` for the
whole per-key block and pads each state up to the next one's alignment, so one
64-aligned state inflates its neighbours too:

  sumForEach(a), sum(b), count()   32 -> 80 bytes per key
  sum(b), count(), sumForEach(a)   32 -> 128 bytes per key

`Arena::alignedAlloc` then re-rounds the arena head to 64 for every key. Because
the external-group-by and two-level thresholds are driven by real query memory,
they trip at roughly a quarter of the distinct keys they used to.

The padding also prevents nothing. Every transform aggregates into its own
`AggregatedDataVariants` and its own arena, so two threads never write states
that could share a line. And the padded object is a 16-byte header: the hot
per-element writes go through its pointer into a separate arena block, which the
padding never touches.

The spelling was wrong as well. The codebase's constant is `CH_CACHE_LINE_SIZE`,
which is 128 on ppc64 and 256 on s390x, and no aggregate function state in the
tree is padded at all.

The arena allocation goes back to the nested function's own alignment for the
same reasons. The batch streaming work is untouched; that part is measurable.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
@valerypetrov valerypetrov changed the title Optimize PromQL and array aggregation memory with cache-line alignment and batch streaming Batch the -ForEach aggregate combinator's accumulation Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6c8e0f1b0 with master e28af044e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2d590f5bc; 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.

Object file sizes

4 object files changed (+40.57 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/Combinators/AggregateFunctionI… 690.50 KiB 720.23 KiB +29.73 KiB (+4.31%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

The outer column was renamed from `time_series` to `samples` for tables of
version 3 and later, so the INSERT no longer resolved and the test failed
with NO_SUCH_COLUMN_IN_TABLE.

Co-Authored-By: Claude Opus 5 <[email protected]>
valerypetrov and others added 2 commits September 21, 2026 22:11
No test in tests/performance exercised -ForEach, so the benchmark suite had
no way to show the batch paths. A Memory source keeps the wide Array column
read from dominating, which it does on MergeTree.

Co-Authored-By: Claude Opus 5 <[email protected]>
`-If` wraps `-ForEach`, so it always hands the batch methods a valid
if_argument_pos, and bailing out to the row-at-a-time helper meant the whole
`-If` surface skipped the fast path. Honour the condition column in the loops
instead, split in two so the unfiltered path keeps no per-row flag test.

Co-Authored-By: Claude Opus 5 <[email protected]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai , I suppose these CI failures are not caused by my changes here?

@groeneai

Copy link
Copy Markdown
Collaborator

@valerypetrov Correct, none of them can reach your diff, and the reason is structural rather than statistical.

In master_head mode the shard status no longer comes from the slower-query count: it is the performance dashboard's verdict, and one row tiered confirmed_regression fails the job (perf_dashboard_gate in ci/jobs/performance_tests.py). You have four, all on client_time:

  • amd 3/6: math_sqrt_erf #7, erf(number), 0.356 -> 0.442 s, +24.4%
  • arm 4/6: array_first_last #9, arrayLast(x -> x > 3, x), 0.0537 -> 0.0653 s, +21.5%
  • arm 4/6: optimize_time_filter_with_preimage #6, 0.486 -> 0.587 s, +20.8%
  • arm 4/6: optimize_time_filter_with_preimage #4, 0.592 -> 0.701 s, +18.5%

AggregateFunctionForEach.h is included by exactly one translation unit, AggregateFunctionForEach.cpp. Nothing in a MergeTree scan, in the array higher-order functions or in the scalar math functions can see your 127 lines, and there is no inlining fan-out to argue about. The comparison itself was fair, so this is not a stale-base artifact either: the left binary is master at c22d746de923, two commits behind 8842ee48d4, which is the base your head was merged onto for the build.

Three measurements agree with that. Every gated row is single-arch with the identical query flat on the other arch: math_sqrt_erf #7 is -1.6% on arm, array_first_last #9 is +0.0% on amd, preimage #4 is -1.0% and #6 is +0.1% on amd. The internal controls stay flat too: in optimize_time_filter_with_preimage only the two = 0 arms moved, while the = 1 arms of the same two predicates are +0.6% and -1.7%, and in math_sqrt_erf only the number argument variants moved, while erf(toFloat64(number)) and erf(toFloat32(number)) are -0.2% and -0.3%. And both shards swung in both directions on that run: amd 3/6 also moved uuid_ip_comparison #10 by +29.8% and #2 by -16.2%, and column_array_replicate by +13.8% and -11.0%; arm 4/6 moved set_index #1 by +76.2% and set_index #5 by -9.1%. The harness tiered the larger uuid_ip_comparison swing as unstable and gated on the smaller one.

For the two preimage queries that is just their own band. Over 14 days of arm_release, master_head, #6 moved by at least your +21% in 407 of 3228 runs spread over 307 different pull requests, and by at least as much in the faster direction in 746 runs; #4 is 366 of 3228. math_sqrt_erf #7 on amd and array_first_last #9 on arm are the two genuine outliers, in the 0.2 to 0.3% tail of their own distributions, though those tails are two sided (2 runs at or above yours and 1 below, for math_sqrt_erf #7). Re-running the two shards separates the last two cases: if they reproduce it is code layout rather than your algorithm, and worth a few minutes with perf; if they do not, it was the host. I would re-run.

Your change does measure what it should, and unlike the reds it reproduces on both arches: sumForEach -12.4% amd and -9.9% arm, avgForEach -12.4% and -9.4%, grouped sumForEach -12.9% and -8.5%.

One number on your own path, since it is the only movement in the run your diff can actually reach: aggregate_function_for_each #4, SELECT k, quantilesForEach(0.5, 0.9)(arr) ... GROUP BY k, is +7.4% on amd and +0.2% on arm. Same single-arch shape, so probably the same noise, but ungrouped quantilesForEach gains only 2.7% against 12% for sum and avg, so the batch path is doing much less for the variable size states than for the fixed size ones.

@groeneai

Copy link
Copy Markdown
Collaborator

One thing I should have linked above: the false-positive half of this is already being fixed in #121090, which makes a master_head shard fail only when the shard's own report also publishes the query as slower. The report's per-query threshold is raised by a month of that query's master history, while the dashboard classifies a single measurement episode, so the two verdicts disagree precisely on chronically noisy micro benchmarks.

It also predicts your two shards differently, which is a cheap way to check the reasoning above. arm 4/6 reported 5 too long, 1 unstable and no slower query at all, so its three confirmed regressions are dashboard-only and that shard would go green. amd 3/6 reported 1 slower, and that slower query is math_sqrt_erf #7 itself, so it would still fail. Same ordering as above: the three arm rows sit inside their own bands, and math_sqrt_erf #7 is the one worth the second look.

valerypetrov and others added 3 commits September 22, 2026 20:37
A `*ForEachIf` with a `Nullable` condition goes through
`AggregateFunctionIfNullVariadic`, which folds the condition into a null map
and calls `addBatchSinglePlaceNotNull` on the nested `-ForEach`. Without an
override that fell back to the row-at-a-time `add` loop of
`IAggregateFunctionHelper`, so the ungrouped nullable-condition case missed
the batch path. Add the override and cover it, including a NULL condition.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`AggregateFunctionIfNullVariadic` overrode only `addBatchSinglePlace`, so a grouped
`sumForEachIf(arr, toNullable(cond))` (and any other multi-argument `-If` with a `Nullable`
argument) went through `IAggregateFunctionHelper::addBatch`, one `add` per row. Fold the
condition and the argument null maps into one `UInt8` column and pass the batch to the nested
`-If`, which already forwards it to the nested function's `addBatch`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The earlier overflow case aggregated a single Memory block, so every key got a place. One-row
blocks under `group_by_overflow_mode = 'any'` leave a later key without one, which is the only
way `Aggregator` reaches `addBatch` rather than `addBatchWithNonNullPlaces`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Rerun CI on current master: the last run's reds were master-side, and
master has since changed the Nullable -If batch paths next to this branch's
grouped ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 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 comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance 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.

5 participants