Repository navigation
Reserve the destination hash table when merging two-level aggregation buckets - #117193
Conversation
… 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
|
Workflow [PR], commit [38597fa] Summary: ✅
AI ReviewSummaryThis PR adds a ratio-based Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 38597fa.
Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code |
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
|
The reserve also fires for the string variants: |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
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
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes16 object files changed (+33.64 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units83 translation units recompiled, 791 s compile time in total, 83 of them have a recent master baseline. |
`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
`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
`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
There was a problem hiding this comment.
Thanks for the PR @raimannma
The ratio path looks good, cheap and doesn't change correctness. Few things:
-
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.
-
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.
-
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.
-
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.
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
|
@harikrishnan94 Thanks for the review!
|
|
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 |
|
@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. |
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 withinHashTable::mergeToViaEmplace; in a production CPU profile, 55% ofAggregator::mergeDataImpl(2.4% of all samples) wasHashTable::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 atadaptive_aggregator_freeze_thresholdkeys (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, aNullableorLowCardinalitykey, the merging side of distributed queries (only_merge),max_rows_to_group_bywith thebreakoranyoverflow 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 inHashTable::resizeundermergeDataImpldrop from 9.7% of the query to 0.6%, andmergeDataImplfrom 31% to 23%;perf.pymeasures -5.7% (keys128), -1.6% and -3.8% (keys256), with identical peak memory. In CI,group_by_fixed_keysshows the same split: theNullableandLowCardinalitykey 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):
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 BYby 5-10% on the classic (non-adaptive) aggregation path, for example withNullableorLowCardinalitykeys orenable_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
26.9.1.1571(included in26.9and later)