Skip to content

Use Adaptive Aggregator for single-stream GROUP BY - #131331

Open
nihalzp wants to merge 31 commits into
ClickHouse:masterfrom
nihalzp:adaptive-aggregator-single-stream
Open

nihalzp wants to merge 31 commits into
ClickHouse:masterfrom
nihalzp:adaptive-aggregator-single-stream

Conversation

@nihalzp

@nihalzp nihalzp commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Related: #130520
Related: #129565

Background

With the adaptive aggregator (enable_adaptive_aggregator), every thread aggregates into its local hash table until the table freezes at adaptive_aggregator_freeze_threshold keys or adaptive_aggregator_freeze_threshold_bytes bytes. A frozen table keeps updating the keys it holds and stages the rows of the other keys, which the merge aggregates one hash partition at a time, in tables that fit in the cache.

Master uses it only with several threads and several input streams. Otherwise the aggregation builds ordinary hash tables, and with one input stream a single table holds every key of the query. ClickBench Q32 at max_threads = 1:

SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10

Its 99,997,497 rows hold 99,997,493 groups, so the table outgrows every cache: the query peaks at 6,160 MiB and takes 6.9 s.

Master also leaves out every aggregation whose group_by_two_level_threshold and group_by_two_level_threshold_bytes are both 0, and ClickHouse sets both to 0 for an aggregation of one stream unless external aggregation is enabled.

Changes

The adaptive aggregator now takes a GROUP BY at max_threads = 1 and one over a single input stream. Its tables freeze as with several threads, and the merge aggregates the staged rows partition by partition.

  • A final aggregation with both two-level thresholds at 0 now takes the adaptive path too. Nothing in that path reads the thresholds: it decides on its own when a table freezes and how the merge partitions the keys.
  • A partial aggregation with both thresholds at 0 stays on the ordinary path, because it must send single-level blocks. An initiator older than 26.8 merges two-level blocks bucket by bucket with a different hash method, so bucketed blocks from a newer server would split its groups. Query plans serialized for older servers rely on the same rule. A partial aggregation is the remote side of a distributed query, or the one under WITH TOTALS, ROLLUP or CUBE. So a GROUP BY ... WITH TOTALS at max_threads = 1 takes the adaptive path by default, and keeps the ordinary path, as on master, when external aggregation is off.
  • An aggregation of several streams and threads with nonzero thresholds takes the same path as before.

Results

ClickBench hits (100M rows) on AWS c8a.16xlarge, clickhouse-local, max_threads = 1, FORMAT Null. Peak memory is the peak of the query from --memory-usage.

QueryShape1 thread
TimePeak memory
Q12GROUP BY SearchPhrase: count, where SearchPhrase <> '', top 101,090.0 → 850.7 ms, 1.28×774 → 644 MiB, −17%
Q13GROUP BY SearchPhrase: count(DISTINCT UserID), where SearchPhrase <> '', top 102,197.7 → 1,231.3 ms, 1.78×2,039 → 894 MiB, −56%
Q14GROUP BY SearchEngineID, SearchPhrase: count, where SearchPhrase <> '', top 101,511.3 → 1,250.0 ms, 1.21×1,025 → 783 MiB, −24%
Q15GROUP BY UserID: count, top 101,050.0 → 525.3 ms, 2.00×512 → 197 MiB, −62%
Q16GROUP BY UserID, SearchPhrase: count, top 103,826.7 → 2,255.7 ms, 1.70×2,056 → 1,318 MiB, −36%
Q18GROUP BY UserID, minute(EventTime), SearchPhrase: count, top 105,862.0 → 3,304.0 ms, 1.77×3,720 → 2,120 MiB, −43%
Q30GROUP BY SearchEngineID, ClientIP: count, sum, avg, where SearchPhrase <> '', top 10874.7 → 606.3 ms, 1.44×515 → 138 MiB, −73%
Q31GROUP BY WatchID, ClientIP: count, sum, avg, where SearchPhrase <> '', top 101,319.3 → 858.0 ms, 1.54×898 → 215 MiB, −76%
Q32GROUP BY WatchID, ClientIP: count, sum, avg, top 106,929.0 → 2,526.7 ms, 2.74×6,160 → 1,561 MiB, −75%
Q33GROUP BY URL: count, top 105,662.0 → 5,372.0 ms, 1.05×4,102 → 5,352 MiB, +30%
Q34GROUP BY 1, URL: count, top 105,688.3 → 5,218.0 ms, 1.09×4,102 → 5,352 MiB, +30%
Q35GROUP BY ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3: count, top 10835.0 → 456.3 ms, 1.83×256 → 119 MiB, −53%
Geomean1.56×−47%

Run time:

image

Memory usage:

image

Changelog category (leave one):

  • Performance Improvement

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

The adaptive aggregator (enable_adaptive_aggregator, enabled by default) now also handles GROUP BY at max_threads = 1 and over a single input stream, and final aggregations with both group_by_two_level_threshold and group_by_two_level_threshold_bytes set to 0. The thread stops growing its hash table at the freeze threshold and aggregates the rows of new keys at the end, one cache-sized partition at a time. On 12 ClickBench queries with millions of distinct keys at max_threads = 1, the geometric mean speedup is 1.56x, up to 2.74x, and peak memory drops by 47%.


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

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [63c177f]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, targeted) FAIL
test_storage_rabbitmq/test.py::test_rabbitmq_handle_error_mode_stream FAIL cidb
test_storage_rabbitmq/test.py::test_rabbitmq_reject_broken_messages_stream FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05340_adaptive_aggregator_nullable_keys FAIL cidb
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
timeseries_group_array #2 FAIL dashboard
Performance Comparison (arm_release, master_head, 3/8) FAIL Performance dashboard
timeseries_group_array #2 FAIL dashboard

AI Review

Summary

Enables adaptive GROUP BY for a single input stream and final aggregations with both two-level thresholds disabled, expands bucket-merge parallelism, and separates the thaw verdicts of single and multiple producers. No new actionable findings after reviewing the current diff, surrounding execution paths, and every prior thread. The earlier deltaSum admission and equal-boundary defects are corrected; the pre-existing 8-bit-key ordering defect is tracked in #132708. The author's explanation of the unspecified selection by any and anyLast is accepted.

Performance & Safety

The completed comparison at e0027503 contains 62 improvements with a 1.76× geometric mean speedup. Master history identifies the aggregation_overflow #0 slowdown as recurring: 23 slower and 41 unstable results in 1,299 runs. The other measured slowdowns add 6.5–9.0 ms to two amd sparse_column queries and 1.9 ms to an arm hash_table_sizes_stats_small query. These remain real costs, covered by the author's explicitly accepted tradeoff and requested follow-up; they are not re-raised as findings.

Missing context / blind spots
  • ⚠️ At head 63c177fc26630fb18d8c318b0b05c6f66a2371b8, Fast test reports 15,332 passed and zero failed, but the full suite and fresh performance comparisons are still pending or running. Their completion in the current Praktika report will close this validation gap. No local build or tests were run in this review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 63c177fc26630fb18d8c318b0b05c6f66a2371b8 was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
Queries 0 and 2 of tests/performance/group_by_dynamic_keys.xml take
2.79 / 1.56 s on MasterCI amd (3.51 / 1.90 s on arm); the String
control takes 0.13 s. Every row is its own group (the key moduli are
pairwise coprime), and 65-86% of CI's CPU samples are in the per-row
key serialization of the serialized method
(ColumnDynamic::serializeValueIntoArena), which the file measures.

No existing query number or text changes: 2 queries are disabled and
2 copies appended as 3 and 4. The copies run the same queries on 400k
rows (still one group per row). The JSON fill is read only by the
disabled query, so it is renamed and resized in place to
t_json_group_by_400k, the first 400k of the same rows. The String
control keeps its 2M rows.

Local A/B on official builds, two repetitions on different NUMA nodes,
L3 capped to one way (decide.py: every gate passes in both):
- user time per row of a copy 0.948 (Dynamic casts) and 1.009-1.016
  (JSON subcolumns) of its original;
- local time ratio copy/original 0.191 and 0.403-0.408 -> projected
  CI medians 0.53 / 0.63 s amd, 0.67 / 0.78 s arm;
- on the MasterCI builds before and after ClickHouse#112316 (7a9ada8 -> 6e89ba5,
  CI measured 1.26-1.32x on amd, 1.52x on arm), the copies keep
  0.836-0.919 of the original's speedup, both seat orders;
- on the build of ClickHouse#131331 each copy takes its original's adaptive
  aggregation path.
Below 500k groups a repeated run gets no hash table size hint
(HashTablesStatistics getSizeHint at max_threads = 1), so the copies
start their table single-level and unallocated where the originals
start it two-level and preallocated; that table is about 1% of CI's
samples.
Saving: about 32 s of query time per master perf job on amd and 40 s
on arm; the setup fills 400k JSON rows instead of 1M.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 04:46

AI review of a later commit does not approve the PR, see the AI Review comment.

…or-single-stream

# Conflicts:
#	src/Interpreters/Aggregator.cpp
#	src/Interpreters/HashTablesStatistics.h
@nihalzp nihalzp self-assigned this Nov 19, 2026
@nihalzp
nihalzp added this pull request to the merge queue Nov 19, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 19, 2026
@nihalzp

nihalzp commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

In the CI performance tests, 62 queries sped up by 1.76x and 95 use 51% less memory, both in geomean. Some queries slowed down by a few milliseconds due to the fixed cost of the adaptive aggregator, which is an acceptable tradeoff but can be improved. @groeneai Investigate it and propose fixes.

Discussed it with @Algunenano. Merging this to unlock further development.

@nihalzp
nihalzp added this pull request to the merge queue Nov 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the fixed-cost slowdowns of the adaptive aggregator on the single-stream GROUP BY queries in the CI perf tests; I'll follow up here with a PR (or my findings) shortly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants