Skip to content

Reserve the destination hash table when merging two-level aggregation buckets - #117193

Merged
harikrishnan94 merged 14 commits into
ClickHouse:masterfrom
raimannma:agg-bucket-merge-reserve
Sep 16, 2026
Merged

harikrishnan94 merged 14 commits into
ClickHouse:masterfrom
raimannma:agg-bucket-merge-reserve

Conversation

@raimannma

@raimannma raimannma commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

The bucket merge of two-level aggregation (Aggregator::mergeBucketImpl) merged the per-thread tables into the first one while growing the destination one doubling at a time from within HashTable::mergeToViaEmplace; in a production CPU profile, 55% of Aggregator::mergeDataImpl (2.4% of all samples) was HashTable::resize. Now the destination bucket is reserved once, up front, from the measured result/input key ratio of the buckets that have already been merged: the buckets are uniform hash samples of one key set, so the ratio predicts the merged size regardless of how the per-thread key sets overlap. The reservation is capped by the bucket's own input, so it can never exceed what the merge would have grown to. The first buckets, merged while no ratio has been measured yet, grow as before.

This affects only the classic merge path, where every thread's full table is merged. With the adaptive aggregator engaged (enable_adaptive_aggregator = 1, the default), the per-thread tables freeze at adaptive_aggregator_freeze_threshold keys (16384) and the bulk of the keys reach the result through the bucket drain, so the merged destination barely grows and the reservation makes no measurable difference. The classic path runs when the adaptive aggregator does not engage (AggregatingStep::adaptiveAggregatorRejectionReason): enable_adaptive_aggregator = 0, a Nullable or LowCardinality key, the merging side of distributed queries (only_merge), max_rows_to_group_by with the break or any overflow mode, overflow_row, GROUPING SETS, aggregation in order, distributed_aggregation_memory_efficient, projections, TTL aggregation, or an aggregation method without a two-level form.

On the workload of the added performance test (50M rows, 20M groups, enable_adaptive_aggregator = 0, max_threads = 8), the CPU samples in HashTable::resize under mergeDataImpl drop from 9.7% of the query to 0.6%, and mergeDataImpl from 31% to 23%; perf.py measures -5.7% (keys128), -1.6% and -3.8% (keys256), with identical peak memory. In CI, group_by_fixed_keys shows the same split: the Nullable and LowCardinality key queries are 5-11% faster, while the plain-key queries, where the adaptive aggregator engages, are within 2%. Results are byte-identical across a randomized differential fuzz of the merge paths and the aggregation stateless tests.

Changelog category (leave one):

  • Performance Improvement

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

Speed up the merge phase of high-cardinality parallel GROUP BY by 5-10% on the classic (non-adaptive) aggregation path, for example with Nullable or LowCardinality keys or enable_adaptive_aggregator = 0, by reserving the destination hash table once instead of growing it one doubling at a time.


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

Version info

  • Merged into: 26.9.1.1571 (included in 26.9 and later)

… buckets

The bucket merge of two-level aggregation (`Aggregator::mergeBucketImpl`) and
the single-level merge (`mergeSingleLevelDataImpl`) merged N per-thread source
tables into the first one while growing it one doubling at a time from within
`HashTable::mergeToViaEmplace`, rehashing and copying the destination on every
step of the growth chain. In a production CPU profile, 55% of
`Aggregator::mergeDataImpl` (2.4% of all samples) was `HashTable::resize`.

Two complementary reservations remove that regrowth:

- The two-level buckets partition the keys by hash, i.e. they are uniform
  samples of one key set, so the result/input ratio measured on the buckets
  whose merge already completed (tracked in two relaxed atomics on the
  destination `AggregatedDataVariants`) predicts every remaining bucket's
  merged size almost exactly, regardless of how the per-thread key sets
  overlap; such buckets reserve the destination once, up front. The produced
  total is loaded first so a torn read can only under-reserve, and the
  reservation is capped by the bucket's input.
- The first buckets (merged while nothing has completed yet) and the
  single-level merge estimate the merged size after the first (largest)
  source was merged, from the observed overlap with the destination (the
  Lincoln-Petersen capture-recapture estimator, with exponential decay of new
  keys over the remaining sources), and reserve half the estimate: a
  single-source estimate is unreliable when the per-thread key sets are not
  exchangeable, and the grower rounds up to a power of two, so reserving a
  whole overestimate can double the final buffer.

Interleaved A/B (n = 21, Mann-Whitney), hash-distributed keys, `max_threads`
8: `keys128` with 50M distinct keys -10.3% (p < 1e-4), `keys256` with 25M
-4.6% (p = 0.003), 16 threads -8.4% (p < 1e-4), and the adversarial
range-correlated workload of the added performance test -4.0% (p = 0.018),
with identical peak memory; no statistically significant regression on any
measured workload. CPU samples under `Aggregator::mergeDataImpl` drop 47% on
the first of those workloads.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FgBhQPwETjrdwmTnf9Ctna
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [38597fa]

Summary: ✅


AI Review

Summary

This PR adds a ratio-based reserve in Aggregator::mergeBucketImpl and a performance workload for the classic two-level aggregation merge path. The steady-state optimization looks reasonable, but the current head reintroduces a throw-path memory regression: under multi-worker two-level merges with max_rows_to_group_by and group_by_overflow_mode = 'throw', a worker can still preallocate almost a whole bucket before the shared limit check/cancellation runs, so the query can now fail with MEMORY_LIMIT_EXCEEDED instead of the expected TOO_MANY_ROWS.

Findings

❌ Blockers

  • [src/Interpreters/Aggregator.cpp:4626-4643] The remaining ratio-based reservation is again uncapped on the shared two-level max_rows_to_group_by throw path. That limit is still enforced only later in ConvertingAggregatedToChunksWithMergingSource::generate, after the whole bucket was merged and converted, so a sibling worker can reach this reserve() while another bucket has already crossed the global limit but has not propagated is_cancelled yet. In that window this PR can allocate close to input_keys for a bucket that will be abandoned on the next loop check, which is new dead memory on the error path and can surface MEMORY_LIMIT_EXCEEDED instead of the expected TOO_MANY_ROWS. Suggested fix: restore a throw-mode cap for this reservation, or do the same shared-limit pre-start check before reserving/taking a bucket that the parallel single-level partition merge already does.
Tests
  • The new tests/performance/aggregation_two_level_bucket_merge.xml exercises successful classic-path merges, but it does not cover the shared two-level max_rows_to_group_by = 'throw' path, so it would not catch the regression above.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 38597fa.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.50% 80.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 30, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
If merging the first source already crosses `max_rows_to_group_by`, the
`checkLimits` on the next iteration stops the merge (`throw`/`break`) or
stops admitting new keys (`any`), so reserving for the remaining sources
only grows the destination hash table for keys that will never be
inserted.

Addresses: ClickHouse#117193 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SZHZVA8D4Ci7TrC3qr3ncq
Comment thread src/Interpreters/Aggregator.cpp Resolved
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

The reserve also fires for the string variants: can_reserve is satisfied because StringHashTable has a reserve, but StringHashTable::reserve (src/Common/HashTable/StringHashTable.h) blindly splits the hint as n/4 into each of the four size-class sub-maps m1/m2/m3/ms. Real key sets concentrate in one size class, so for StringHashMap/TwoLevelStringHashMap destinations this simultaneously under-reserves the hot sub-map about 4x (most of the doubling the reserve was meant to avoid still happens) and force-grows the three cold sub-maps to n/4 capacity each — up to roughly 1.5n wasted cells per bucket of peak memory that the pre-PR code never allocated. The benchmarks in the description are keys128/keys256, which don't exercise this path. It may be worth skipping the reserve for StringHashTable-backed variants, or making StringHashTable::reserve distribution-aware, so string GROUP BY keeps the old peak-memory profile.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 4 query(s) improved out of 38 analysed

This PR reserves the destination hash table once at the start of the two-level aggregation bucket merge, using the result/input key ratio of already-merged buckets, instead of letting it grow one doubling at a time. All four flagged ClickBench improvements (Q11 -15.6%, Q30 -10.7%, Q33 -6.6%, Q34 -6.6%) are high-cardinality parallel GROUP BY queries whose merge phase is exactly what the change accelerates, so the deltas are directly attributable and consistent with the author's own measurements (5-11% on the affected merge path). CPU time is flat or slightly lower on all four, matching a reduction in repeated resize work rather than added overhead. No regressions were flagged, and the gains land on the queries the change targets, so the improvements look real.

clickbench

🟢 4 improved

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 11 improvement 192 162 -15.6% <0.0001 aggregation: Q11 is a high-cardinality GROUP BY (MobilePhoneModel, COUNT DISTINCT UserID) that exercises the two-level bucket merge this PR reserves up front. The -15.6% improvement is consistent with cutting HashTable::resize doubling in the merge phase.
🟢 30 improvement 225 201 -10.7% <0.0001 aggregation: Q30 groups on a REGEXP-derived string key with HAVING, a high-cardinality parallel GROUP BY that hits the merge path the PR reserves. The -10.7% delta matches the expected merge-phase speedup.
🟢 33 improvement 1190 1112 -6.6% <0.0001 aggregation: Q33 is a high-cardinality GROUP BY (SearchEngineID, ClientIP) with parallel two-level merge. -6.6% is consistent with reserving the destination bucket up front instead of growing it one doubling at a time.
🟢 34 improvement 1194 1116 -6.6% <0.0001 aggregation: Q34 (WatchID, ClientIP high-cardinality GROUP BY) is the sibling of Q33 and hits the same two-level merge path. -6.6% matches the expected merge-phase gain from the up-front reservation.

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: fdb129d3-0dae-4491-aeb5-4856a05fe173
  • MIRAI run: f3ebb95f-f948-4598-975d-8e1f5d12b863
  • PR check IDs:
    • clickbench_303594_1789481412
    • clickbench_303600_1789481412
    • clickbench_303606_1789481412
    • tpch_adapted_1_official_303615_1789481412
    • tpch_adapted_1_official_303628_1789481412
    • tpch_adapted_1_official_303665_1789481412

Publish `merged_buckets_result_keys` with `memory_order_release` after
`merged_buckets_input_keys` and read it first with `memory_order_acquire`,
so a reader never observes a result contribution without its matching input
contribution and the reservation ratio can only under-estimate; with both
sides relaxed, an ARM reader could see a new result total with an old input
total, drive the ratio above 1 and reserve for all per-thread keys.

Skip the reservation for `StringHashTable`-backed variants: its `reserve`
splits the hint evenly over the four size-class sub-maps, while a real key
set concentrates in one of them, so it force-grows the cold sub-maps and
still leaves the hot one undersized.

ClickHouse#117193 (comment)
ClickHouse#117193 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015T96VYPSzYQd4ibPWLsJJU
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 38597fa06 with master e52381d19 (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.

Object file sizes

16 object files changed (+33.64 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 20.34 MiB 20.37 MiB +32.09 KiB (+0.15%)

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

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

Job report

Comment thread src/Interpreters/Aggregator.cpp Resolved
raimannma and others added 2 commits September 2, 2026 16:44
`mergeBucketImpl` reserves the destination table before its source loop
reaches the first `is_cancelled` check, and again after the first source
was merged. A bucket started after another worker or `onCancel` set the
flag could therefore allocate up to its full input capacity through the
tracked allocator and return on the next line, raising the peak memory of
an unwinding query and possibly throwing `MEMORY_LIMIT_EXCEEDED` on top
of the original error. Check the flag right before both reservations.

ClickHouse#117193 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ed29xEavfAZtWSkjA9jr8K
Comment thread src/Interpreters/Aggregator.cpp Resolved
raimannma and others added 2 commits September 2, 2026 20:55
`mergeSingleLevelDataImpl` skipped the reservation only once the table had
already crossed `max_rows_to_group_by`. Below the limit, `checkLimits` runs
between sources and a source is merged whole, so the table can still grow
to the limit plus the largest remaining source, but the reservation assumed
every remaining source could add keys. With many small sources and a small
limit that reserved several times the reachable size. Cap the reservation
by the limit plus the largest remaining source.

ClickHouse#117193 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ed29xEavfAZtWSkjA9jr8K
Comment thread src/Interpreters/Aggregator.cpp Resolved
raimannma and others added 2 commits September 3, 2026 09:52
`mergeBucketImpl` has no `checkLimits` of its own: a throw-mode
`max_rows_to_group_by` is enforced on the merged totals only after a
whole bucket was merged and converted, in
`ConvertingAggregatedToChunksWithMergingSource::generate`, and the
resulting cancellation reaches the sibling merge workers later still.
A worker could therefore preallocate close to its full bucket input
while another bucket had already crossed the global limit, adding a
dead buffer that did not exist before the reservation was introduced
and that can surface as `MEMORY_LIMIT_EXCEEDED` instead of the expected
`TOO_MANY_ROWS`.

Cap both reservations by `max_rows_to_group_by` when the overflow mode
is `throw`. A bucket whose merged result survives the shared check
holds at most that many groups, so the cap never binds on a query that
is going to succeed, and queries without a group limit keep the full
reservation. The dropping modes are deliberately not enforced during
this merge, so their buckets are merged whole and are left uncapped.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ed29xEavfAZtWSkjA9jr8K
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 4, 2026
@harikrishnan94 harikrishnan94 self-assigned this Sep 10, 2026

@harikrishnan94 harikrishnan94 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the PR @raimannma

The ratio path looks good, cheap and doesn't change correctness. Few things:

  1. Is the capture-recapture estimator worth keeping? With max_threads = 8 it only covers the first ~8 of 256 buckets; everything claimed after the first bucket finishes uses the ratio anyway. It also runs after source 1 is merged, and reserve(estimate/2) still leaves the last doubling, so on those buckets it saves at most half the rehash work. It's also the only part of the PR that can push peak memory up: if source 1's overlap with the destination isn't representative of the other sources, the reservation can overshoot the final size by up to N/2. Can you run one A/B, this PR vs ratio-only (first-wave buckets unreserved, no single-level change)? If the speedup is the same, then reservationForMerge, the /2 hedge, the two max_rows_to_group_by caps and the single-level changes can all go.

  2. The gain is coming from the queries where the adaptive aggregator doesn't engage. In CI, Nullable and LowCardinality keys in group_by_fixed_keys show −5…−11%, the same table with plain keys (adaptive engaged) shows −2%. So the description should say this improves the classic merge path, and list when that path runs: Nullable/LowCardinality keys, dropping overflow modes, GROUPING SETS, only_merge, etc. "Up to ~10%" without that reads like a default-case win, which it isn't.

  3. Perf test: 3 of the 4 queries run with the adaptive aggregator on. CI shows all 8 threads freeze at 16k keys, so the merge barely grows the destination and the numbers stay within ±2.6%. Only the enable_adaptive_aggregator = 0 query actually hits the path (−5.6% amd, −4.1% arm). Please set enable_adaptive_aggregator = 0 for the whole test, or use a Nullable key.

  4. Aggregator.cpp:4566-4572, cancellation in the single-level path. The two-level path checks is_cancelled before both reservations so an unwinding query doesn't get a dead buffer added. Single-level reserves without that check. Same guard please.

One gap: nothing tests the overestimate case (source 1 disjoint from the destination, later sources mostly duplicates). Hard to construct deterministically, so item 1 is the practical way to settle it.

raimannma and others added 2 commits September 15, 2026 11:53
The capture-recapture estimator covered only the buckets merged before the
first one completed (`max_threads` of 256) and reserved half its estimate,
and the single-level merge only runs for tables below the two-level threshold.
An interleaved A/B (n = 21) of this PR against the ratio-only variant is
within -1.9..+0.4% (p >= 0.05) with identical peak memory, and the CPU
profile puts `HashTable::resize` under `mergeDataImpl` at 0.35% vs 0.58%
of all samples (9.7% before the PR). So `reservationForMerge`, the
single-level reservation and the `max_rows_to_group_by` caps are removed;
the reservation from the completed buckets' ratio, capped by the bucket's
input, remains.

The performance test sets `enable_adaptive_aggregator = 0` for the whole
test, because the frozen per-thread tables of the adaptive aggregator leave
the merge nothing to grow, and replaces the duplicate query with a `Nullable`
key query at default settings.

Review: ClickHouse#117193 (review)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01M4untZ8m8j4GhujRmfqej3
@raimannma

Copy link
Copy Markdown
Contributor Author

@harikrishnan94 Thanks for the review!

  1. I benhed this: Ratio-only has smae performance as the whole PR on every query with the same peak memory. So the estimator, the /2 hedge, the max_rows_to_group_by caps and the single-level change are removed. What remains is the ratio reservation, capped by the bucket's input, with the cancellation check in front of it.
  2. Changed PR description 👍
  3. enable_adaptive_aggregator = 0 for the whole test; the duplicate query is replaced by a Nullable key at default settings. Locally with perf.py the fixed-key queries now show -5.7%, -1.6%, -3.8%
  4. I removed the single-level change and kept the guard to the remaining two-level reservation.

@harikrishnan94

Copy link
Copy Markdown
Contributor

Thanks, the ratio-only version looks good.

Could you go through the remaining bot comments and fix what's relevant?

On the AI review's blocker about the uncapped reserve on the throw path: I think it is not a regression. increaseSize steps size_degree by 2 below 2^23 cells, so growth lands in the same range anyway, just later in the bucket.

@raimannma

raimannma commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@harikrishnan94 Replied to all bot threads. Four are fixed or obsolete after the ratio-only rewrite. The throw-path one I left as is for the reason you gave.

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