Skip to content

Faster top-K GROUP BY an ascending order or with a large LIMIT in Adaptive Aggregator - #130281

Merged
nihalzp merged 12 commits into
ClickHouse:masterfrom
nihalzp:adaptive-top-k-shared-bounds
Nov 12, 2026
Merged

nihalzp merged 12 commits into
ClickHouse:masterfrom
nihalzp:adaptive-top-k-shared-bounds

Conversation

@nihalzp

@nihalzp nihalzp commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Related: #123531

Background

For GROUP BY ... ORDER BY count() LIMIT n, and the same with uniqExact or uniqExactIf, ClickHouse does not sort every group: each part of the aggregation result keeps only its own n best groups, and the sort picks the top among them (query_plan_aggregation_bucket_top_k). The adaptive aggregator (enable_adaptive_aggregator) produces its result in many small parts, merged in parallel. When n is larger than a part, every part keeps all its groups, and nearly every group still reaches the sort:

SELECT URL, count() AS c FROM hits GROUP BY URL ORDER BY c DESC LIMIT 50000

hits has 18.34 million distinct URLs, and 18.15 million of them reach the sort to return 50,000. An ascending order is worse: ORDER BY c ASC LIMIT 10 merges every part, although 11.5 million URLs have one row, so the first parts already hold ten of them.

Changes

The parts now share what they find. Every finished part reports the exact counts of its groups, and the merge keeps a threshold that all its threads read: the n-th best count reported so far. A group ranked worse than the threshold already has n better groups ahead of it, so every later part drops it before the sort. In the query above, 716,482 groups now reach the sort.

  • A descending order drops the groups below the threshold. The existing pruning of the adaptive aggregator, which skips whole parts that cannot reach the top, now reads the same threshold.
  • An ascending order drops the groups above the threshold, and stops merging once the threshold reaches the smallest count a group can have: 1 for count(), 0 for count of a Nullable column, uniqExact and uniqExactIf. No group left can rank better, and LIMIT may return any of the tied groups, so the merge skips the parts left: ORDER BY c ASC LIMIT 10 at 64 threads now merges 56 of its 2,048 parts.

The threshold is exact, so every query returns the same counts as before. Keeping it is cheap: the descending queries with a small LIMIT, which gain nothing, run as fast as before.

Results

ClickBench hits (100M rows) on AWS c8a.16xlarge (64 cores, one thread per core), clickhouse-local, FORMAT Null, with compile_aggregate_expressions = 0. Master is the merge base 27662da641a. Peak memory is the peak of the query from --memory-usage.

Shape16 threads64 threads
TimePeak memoryTimePeak memory
GROUP BY URL: count, DESC LIMIT 10000461.7 → 432.0 ms, 1.07×6,173 → 5,748 MiB, −7%244.0 → 220.7 ms, 1.11×9,235 → 8,191 MiB, −11%
GROUP BY URL: count, DESC LIMIT 50000561.7 → 451.3 ms, 1.24×6,699 → 5,836 MiB, −13%324.0 → 223.3 ms, 1.45×9,821 → 8,237 MiB, −16%
GROUP BY URL: count, ASC LIMIT 10431.7 → 356.7 ms, 1.21×5,704 → 5,706 MiB, 0%201.7 → 176.7 ms, 1.14×8,077 → 8,010 MiB, −1%
GROUP BY URL: count, ASC LIMIT 10000484.3 → 364.0 ms, 1.33×5,793 → 5,725 MiB, −1%287.0 → 182.3 ms, 1.57×8,756 → 8,153 MiB, −7%
GROUP BY cityHash64(WatchID) % 4000037: count, ASC LIMIT 1000081.0 → 73.7 ms, 1.10×1,082 → 1,082 MiB, 0%51.3 → 49.7 ms, 1.03×1,655 → 1,597 MiB, −4%
GROUP BY cityHash64(WatchID) % 4000037: count, ASC LIMIT 5000082.0 → 76.7 ms, 1.07×1,082 → 1,082 MiB, 0%51.7 → 53.0 ms, 0.98×1,619 → 1,666 MiB, +3%
GROUP BY SearchPhrase: count(DISTINCT UserID), where SearchPhrase <> '', DESC LIMIT 10000143.0 → 133.0 ms, 1.08×1,580 → 1,434 MiB, −9%82.7 → 78.7 ms, 1.05×2,433 → 2,215 MiB, −9%
Geomean1.15×−4%1.17×−7%

Descending queries with LIMIT 10 or 1000 keep few groups per part anyway and stay the same, as do ClickBench's own queries, which all end in DESC LIMIT 10 (Q12-Q18 and Q30-Q35: 1.00× at both widths).

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) runs GROUP BY with ORDER BY count() LIMIT n faster when n is large or the order is ascending, and the same with uniqExact and uniqExactIf: the threads of its merge share the best counts found so far, drop the groups that cannot reach the top, and stop merging an ascending order once it holds n groups with the smallest possible count. On seven such queries over the ClickBench hits table, the geometric mean speedup is 1.15x at 16 threads and 1.17x at 64 threads, up to 1.57x, and peak memory drops by up to 16%.


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

Version info

  • Merged into: 26.11.1.2056-master (included in 26.11 and later)

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52d5cf1]

Summary: ✅


AI Review

Summary

The PR shares exact top-K thresholds across adaptive aggregation merge threads, filters groups that cannot enter the result, and stops ascending merges once enough groups have the smallest possible rank. Review of commit 52d5cf1a3a2cb405ff4bd492a21e030b32c13f1d found no actionable issues. The previous review points are addressed; focused regression coverage and the supplied before/after measurements support the change.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable or configured build was available, so regression tests and benchmarks were not rerun locally. Runtime validation relies on the PR's tests, reported measurements, and available CI reports.
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 9, 2026
@NIKTONIKTO717 NIKTONIKTO717 self-assigned this Nov 9, 2026

@ch-samuel-reviewer-1 ch-samuel-reviewer-1 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.

Thank you @nihalzp for such a nice PR! I left one small comment about the new test, otherwise it looks good to me.

This review was checked, modified and approved by human (@NIKTONIKTO717).

Move the two count-among-others cells of `05567_adaptive_aggregator_top_k_threshold`
into the first call, which also checks `rows_before_limit_at_least`. The counter
`AdaptiveAggregationCountFirstUnits` and the exact results were the same on master,
so the old cells passed without the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
[Review suggestion] Check that the threshold reaches the count-first units in 05567 (for ClickHouse#130281)

@NIKTONIKTO717 NIKTONIKTO717 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, thank you for another really nice PR!

Comment thread src/Interpreters/Aggregator.cpp Resolved
@nihalzp nihalzp mentioned this pull request Nov 10, 2026
7 of 33 tasks
# Conflicts:
#	src/Interpreters/Aggregator.cpp
#	src/Interpreters/Aggregator.h
#	tests/queries/0_stateless/05318_adaptive_aggregator_top_k_pruning.reference
#	tests/queries/0_stateless/05318_adaptive_aggregator_top_k_pruning.sh
#	tests/queries/0_stateless/05322_adaptive_aggregator_top_k_count_first.sh
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 52d5cf1a3 with master 11522cf73 (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

18 object files changed (+56.45 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.13 MiB 28.18 MiB +44.45 KiB (+0.15%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/AdaptiveTopKThreshold.cpp.o new 22.11 KiB +22.11 KiB

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.66, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.7 s 14.1 s +10.3 s (+274%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.4 s +5.2 s (+231%)
Compile time of recompiled translation units

91 translation units recompiled, 1007 s compile time in total, 90 of them have a recent master baseline.

Job report

@nihalzp
nihalzp added this pull request to the merge queue Nov 12, 2026
Merged via the queue into ClickHouse:master with commit 5ce1984 Nov 12, 2026
203 checks passed
@nihalzp
nihalzp deleted the adaptive-top-k-shared-bounds branch November 12, 2026 08:04
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 15, 2026
Queries 0, 2, 3 and 6 of tests/performance/adaptive_aggregation_top_k_threshold.xml
take 1.29-1.80 s on MasterCI amd (query 6 1.13 s on arm): each is a GROUP BY URL over
the 100M rows of hits_100m_single, and the top-K threshold the file measures is a part
of that time. They get disabled="1" and are appended as queries 7-10 with the table
changed to hits_10m_single, nothing else. No existing query number or text changes.

Measured with perf.py on official MasterCI release builds (ClickHouse#129258 series rig):
- size: each copy takes 0.124-0.138 of its original's time (3 A/A passes x 25 runs),
  projected 174-223 ms amd and 109-140 ms arm; about 64 s amd and 40 s arm less query
  time per master perf job;
- regime: the copies freeze every producer, merge, and the ascending ones settle
  (8-9 of 256 units merged at 8 threads, 9-13 at 12), like the originals do on CI;
- sensitivity, the builds before and after ClickHouse#130281: originals 1.252x / 1.308x /
  1.201x / 1.419x faster, copies 1.196x / 1.465x / 1.167x / 1.353x.

Query 1 stays enabled: its ClickHouse#130281 effect locally (1.066x) is below three times the
A/A noise, so there is no measurement that a copy keeps it.

Related: ClickHouse#129258

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

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.

4 participants