Skip to content

Improve merging of low cardinality GROUP BY with Adaptive Aggregator - #129565

Merged
nihalzp merged 31 commits into
ClickHouse:masterfrom
nihalzp:adaptive-aggregator-adaptive-merge
Nov 13, 2026
Merged

nihalzp merged 31 commits into
ClickHouse:masterfrom
nihalzp:adaptive-aggregator-adaptive-merge

Conversation

@nihalzp

@nihalzp nihalzp commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Related: #123531

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. Master merges the tables in one of two ways:

  • When some table froze, the adaptive merge takes the 256 buckets of the two-level hash tables, a few partitions of a bucket at a time. It reads every source by bucket, so every producer that froze converts its table to two-level when it finishes, and the merge preparation converts the tables that never froze.
  • When no table froze, the tables take the ordinary merge. A table stays single-level while it learns, and the parallel single-level merge splits the keys into hash partitions, each of which walks every table for its own keys. With states wider than 16 bytes it takes twice as many partitions as threads: at 64 threads, 128 partitions walk 64 tables of 16 thousand cells, 131 million cell visits to merge one million cells.

The byte bound of the freeze counted the table's tracked memory, which includes the memory that its states own. A table of few keys with growing states, such as the sets of uniqExact or the samples of the timeSeries* functions, froze early and staged the rows of every key that came later, although its cells fit in the cache.

Changes

  • The byte bound of the freeze counts the hash-table buffer of the table (AggregatedDataVariants::hashTableBufferBytes): the cells that every probe walks. The memory of the states grows through the keys that a table already holds, which a freeze does not stop, so it no longer freezes a table.
  • Every producer indexes the cells of its table when it finishes (AggregatedDataVariants::CellIndex): a counting sort of the cell pointers and hashes by the partitions of the staged records, whose number grows with the threads up to 4096, 2048 at 64 threads. The adaptive merge reads the cells of a merge unit, a run of the partitions of one bucket, in place, so no table converts to two-level. The string hash table of a FixedString key, or of a String key with enable_packed_string_keys_in_aggregation = 0, cannot be indexed and still converts.
  • Tables that never froze merge partition by partition through their indexes, over all the partitions of the index instead of the buckets, so a partition reads only its own cells. A worker claims partitions one by one into one table, and emits it as one chunk once it holds about 4 MiB of states. So a few chunks pass the single output port of the merge, not one per partition.
  • The top-K pruning by count, uniqExact or uniqExactIf also serves an aggregation in which no table froze.

Results

On AWS c8a.16xlarge (64 cores, one thread per core), baseline → this PR.

State64 threads16 threads
MasterAdaptive offMasterAdaptive off
groupArray(2)(number), 15K keys36.4 → 27.3 ms, 1.33×34.5 → 27.3 ms, 1.26×49.2 → 47.2 ms, 1.04×67.5 → 47.2 ms, 1.43×
groupArray(4)(number), 16K keys36.6 → 27.4 ms, 1.34×34.2 → 27.4 ms, 1.25×49.8 → 48.2 ms, 1.03×67.6 → 48.2 ms, 1.40×
uniqExact(number % 3), 15K keys35.3 → 26.2 ms, 1.35×30.8 → 26.2 ms, 1.18×45.0 → 44.7 ms, 1.01×57.8 → 44.7 ms, 1.29×
any(toString(number)), 16K keys35.5 → 25.4 ms, 1.40×28.7 → 25.4 ms, 1.13×41.7 → 39.4 ms, 1.06×50.1 → 39.4 ms, 1.27×
argMax(toString(number), number), 16K keys33.4 → 25.0 ms, 1.34×26.1 → 25.0 ms, 1.04×36.3 → 33.1 ms, 1.10×39.0 → 33.1 ms, 1.18×
groupBitmap(number % 1000), 16K keys32.7 → 24.9 ms, 1.31×28.1 → 24.9 ms, 1.13×39.3 → 37.1 ms, 1.06×48.3 → 37.1 ms, 1.30×
Geomean1.34×1.16×1.05×1.31×

ClickBench hits (100M rows), one server per binary. Q8 and Q9 no longer freeze on the memory of their uniqExact sets, so no thread allocates staging buffers and no table converts to two-level.

QueryShape64 threads
TimePeak memory
Q8GROUP BY RegionID: count(DISTINCT UserID), top 1068.2 → 66.5 ms, 1.03×1,392 → 1,042 MiB, −25%
Q9GROUP BY RegionID: sum, count, avg, count(DISTINCT UserID), top 1076.1 → 71.8 ms, 1.06×1,385 → 1,093 MiB, −21%
Q14GROUP BY SearchEngineID, SearchPhrase: count, where SearchPhrase <> '', top 1058.1 → 56.0 ms, 1.04×
Q15GROUP BY UserID: count, top 1027.3 → 26.0 ms, 1.05×

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) merges the hash tables of its threads through an index of their cells, instead of converting them to two-level tables (see group_by_two_level_threshold) or walking every table for every hash partition (enable_parallel_single_level_merge). GROUP BY queries whose tables hold 15-16 thousand keys per thread without freezing, with states such as groupArray, uniqExact, any or groupBitmap, run 1.34x faster at 64 threads, and ClickBench Q8 and Q9 use 21-25% less memory at 64 threads. The byte bound of the freeze, adaptive_aggregator_freeze_threshold_bytes, now counts the hash-table buffer of a table instead of its tracked memory, so tables of few keys with growing states keep aggregating in place.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af91980]

Summary: ✅


AI Review

Summary

Reviewed PR #129565 at af91980a3aa51c14921e67a293b27c5ca69e933d, including all prior discussions. The change indexes adaptive aggregation tables, batches partition-merge output, extends top-K pruning to tables that never froze, and makes the freeze byte threshold measure hash-table buffers. No actionable findings remain; the earlier state-lifetime test finding is fixed. The PR supplies focused regression tests, a performance test, and before/after measurements supporting its performance claims.

Consumers traced for the indexed source representation:

  • Serial merging: mergeSingleLevelDataImpl drops the destination index before inserting keys.
  • Partition merging: mergeSingleLevelPartitionsImpl uses indexes only when every source has one; transferred states retain their source arenas.
  • Adaptive bucket merging and pruning: AdaptiveUnitSourceCells and addMergeCountedTablesToBounds handle indexed and two-level sources, including mixed sources after thawing.
  • External aggregation: remaining tables convert before serialization; AdaptiveStagedRecordsSource merges staged records into a fresh destination.
  • Conversion and cleanup: output columns retain state ownership where needed; cancellation leaves unconsumed states with their sources. The planner rejects adaptive aggregation when merging is skipped.

Validation used the current-head CI report, which reports 14,785 passed tests, zero failures, and 4,311 skipped tests. Focused artifacts from 6cee64c928f340e0d04e9d30fb5b070eb70bcf94 confirm all six SourceStateLifetimes cases pass under ASan/UBSan and 50 runs of 05498_adaptive_aggregator_cell_index pass. No local tests or benchmarks were run because this checkout has no ClickHouse binary or build.

Final Verdict

Status: ✅ Approve. No new inline findings to post. Normal CI checks still apply to the latest merge commit.

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

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing af91980a3 with master acd88ab8f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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

23 object files changed (+841.15 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/Merge.cpp.o 9.60 MiB 10.07 MiB +482.39 KiB (+4.91%)
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.30 MiB 28.56 MiB +265.72 KiB (+0.92%)
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregation/AdaptiveAggregation.cpp.o 186.68 KiB 248.37 KiB +61.70 KiB (+33.05%)
src/CMakeFiles/dbms.dir/Processors/Transforms/AggregatingTransform.cpp.o 608.72 KiB 626.61 KiB +17.89 KiB (+2.94%)

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.64, programs/clickhouse-keeper ×0.67 (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 _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.3 s +5.0 s (+220%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -47.6 s (-5%) in total before that adjustment.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse void DB::(anonymous namespace)::visitTwoLevelVariant<DB::Aggregator::mergeAndConvertAdaptiveBucket(… 142.29 KiB removed -142.29 KiB (-100.00%)
programs/clickhouse-keeper void DB::(anonymous namespace)::visitTwoLevelVariant<DB::Aggregator::mergeAndConvertAdaptiveBucket(… 142.23 KiB removed -142.23 KiB (-100.00%)
programs/clickhouse-keeper void DB::(anonymous namespace)::visitTwoLevelVariant<DB::Aggregator::mergeAndConvertAdaptiveBucket(… new 129.20 KiB +129.20 KiB
programs/clickhouse void DB::(anonymous namespace)::visitTwoLevelVariant<DB::Aggregator::mergeAndConvertAdaptiveBucket(… new 129.20 KiB +129.20 KiB
programs/clickhouse DB::Aggregator::mergeSingleLevelPartitionsAndConvertToChunk(std::__1::vector<std::__1::shared_ptr<D… new 100.07 KiB +100.07 KiB
programs/clickhouse-keeper DB::Aggregator::mergeSingleLevelPartitionsAndConvertToChunk(std::__1::vector<std::__1::shared_ptr<D… new 100.07 KiB +100.07 KiB
programs/clickhouse-keeper DB::Aggregator::mergeSingleLevelPartitionAndConvertToChunk(std::__1::vector<std::__1::shared_ptr<DB… 67.94 KiB removed -67.94 KiB (-100.00%)
programs/clickhouse DB::Aggregator::mergeSingleLevelPartitionAndConvertToChunk(std::__1::vector<std::__1::shared_ptr<DB… 67.94 KiB removed -67.94 KiB (-100.00%)

Job report

@nihalzp
nihalzp marked this pull request as ready for review November 8, 2026 10:15
@nihalzp
nihalzp marked this pull request as draft November 8, 2026 15:46
@nihalzp
nihalzp requested a review from diegomestre2 November 12, 2026 06:22

@diegomestre2 diegomestre2 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 answering the questions and for addressing what was good to add. No new remarks from my side. Once CI passes you can merge it! Great work again!

…-adaptive-merge

# Conflicts:
#	src/Interpreters/AdaptiveAggregation/AdaptiveAggregation.h
#	src/Interpreters/AdaptiveAggregation/AdaptiveTopKPruning.h
#	src/Interpreters/AdaptiveAggregation/Merge.cpp
#	src/Interpreters/Aggregator.h
#	src/Processors/Transforms/AggregatingTransform.cpp
@nihalzp
nihalzp enabled auto-merge November 13, 2026 07:31
@nihalzp
nihalzp added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 414302a Nov 13, 2026
204 checks passed
@nihalzp
nihalzp deleted the adaptive-aggregator-adaptive-merge branch November 13, 2026 08:59
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 13, 2026
Since ClickHouse#129565 the bucket top-K pass runs under `serialize_query_plan`, so the
pin and its comment are stale. The same lines were removed from the sibling
bucket top-K tests there. 20 runs with `serialize_query_plan = 1` pass, and
every pruned query converts with the bucket top-K.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 13, 2026
…s_estimation`

Since ClickHouse#129565 the merge by hash partitions packs the partitions a worker
claims into one table, and the `query_10` estimate randomly fell 2.7x..4x
below the expected value in every run with the randomized
`enable_parallel_single_level_merge = 1`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=12d028ce436f528850e5c8b021e5a28e52b8cd2c&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_release%2C%20parallel%2C%202%2F2%29

Related: ClickHouse#131357

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
…ated from PromQL"

This reverts commit 4d76414 (ClickHouse#128764),
reversing changes made to 8886954.

ClickHouse#129565 fixed the staging of the adaptive aggregator that made the grid
aggregation of the SQL generated from PromQL slower, so that SQL can use
the aggregator again.

The conflict in the includes of PrometheusHTTPProtocolAPI.cpp is resolved
by keeping `Server/PrometheusMetricsWriter.h`, added later by ClickHouse#125250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
Resolve the five conflicts of the 26.8 cherry-pick of ClickHouse#131595. They are
all regions where master has code that 26.8 does not have: the deferral
of large merges (ClickHouse#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (ClickHouse#130678), the
bound of zero-sized nested states (ClickHouse#130120), and the partition-by-partition merge of
the adaptive aggregator (ClickHouse#129565). None of them is labelled for 26.8, and
the resolution takes none of them.

26.8 has no catch around the per-function loop of the batch merge (master
got it in ClickHouse#117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.8 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of ClickHouse#131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.8 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.9 cherry-pick of #131595. They are
all regions where master has code that 26.9 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.9, and
the resolution takes none of them.

26.9 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.9 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.9 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit that referenced this pull request Nov 17, 2026
Resolve the five conflicts of the 26.10 cherry-pick of #131595. They are
all regions where master has code that 26.10 does not have: the deferral
of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges,
mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the
bound of zero-sized nested states (#130120), and the partition-by-partition merge of
the adaptive aggregator (#129565). None of them is labelled for 26.10, and
the resolution takes none of them.

26.10 has no catch around the per-function loop of the batch merge (master
got it in #117153), so a throw in the merge of one function would still
leak the queued states of every function after it. The resolution adds
a 26.10 mergeAndDestroyDetachedBatch, the master function without the
deferral: the per-function loop, and a catch that destroys the states of
the following functions. The map mergeDataImpl (also the JIT path) and
the flush of mergeSingleLevelPartitionImpl call it. The collection loop
of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it
is re-indented.

In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.10 assertion is
kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge
cleanly.

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