Skip to content

Start prefetching a set-based aggregation table at the same cardinality as a mapped one - #115840

Merged
thevar1able merged 4 commits into
masterfrom
agg-prefetch-set-threshold
Aug 31, 2026
Merged

thevar1able merged 4 commits into
masterfrom
agg-prefetch-set-threshold

Conversation

@nickitat

@nickitat nickitat commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Speeds up GROUP BY without aggregate functions when the number of distinct keys is around the point where the hash table stops fitting in the L2 cache: such queries now start prefetching at the same cardinality as a GROUP BY that does have aggregate functions.

Related: #108862


Screenshot 2026-08-24 at 16 21 30

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

Version info

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

…ty as a mapped one

The aggregation loop turns its software prefetch on once the hash table outgrows L2, and it decides
that on the table's size **in bytes**. A `GROUP BY` without aggregate functions runs on a `HashSet`
whose cells carry no mapped value, so the same number of cells takes half the bytes - and the number
of cells, one random lookup each, is what decides how many of those lookups miss. The set methods
therefore started prefetching only at twice the cardinality of an equivalent mapped table, and lost
the prefetch exactly in the range where the table stops fitting and it is worth the most.

Halve the threshold for a method whose cells hold no mapped value; nothing changes for the others.

Measured against a build of the parent commit, same checkout, through `perf.py`, 200M rows over 131k
distinct keys:

  max_threads = 1     3093 -> 2823 ms   (p = 2e-7)
  max_threads = 8      392 ->  363 ms   (p = 7e-9)
  max_threads = 32     112 ->  103 ms   (p = 4e-3)

and, single-threaded on the same shape at other cardinalities, -6% at 60k keys, -1% at 200k, unchanged
at 3M (where both prefetch anyway). Results are identical - this only decides a prefetch hint - and the
mapped path, with or without aggregate functions, is untouched.

Found while decomposing where #108862 gets its speedup
from: this window was the one place where the set methods were barely faster than the mapped ones.

Related: #108862

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a2cd997]

Summary: ✅


AI Review

Summary

This PR lowers the software-prefetch threshold for key-only aggregation tables by scaling min_bytes_for_prefetch to the actual cell width, and it now applies the same rule in the main aggregation loop, the single-level/two-level merge paths, and the serialized self-prefetch path. I found no remaining review issues in the current HEAD; the earlier inline findings about the coarse / 2 rule, the merge paths, and the serialized path are all addressed by the later commits now in the branch.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 25/25 (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 21, 2026
@nickitat
nickitat marked this pull request as draft August 21, 2026 18:56
Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a2cd9970b with master 83fede8f8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 632b80920; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 708.94 MiB 705.93 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

…merge paths too

`State::has_mapped ? min_bytes : min_bytes / 2` was too coarse: the ratio between
a key-only cell and its mapped counterpart is not 2 for every method, so the
halved threshold still started prefetching late for some methods and early for
others. Measured cell sizes, key-only vs mapped:

    key32     4 -> 16      keys128   16 -> 24
    key64     8 -> 16      keys256   32 -> 40
    serialized (saved hash)  24 -> 32

The mapped counterpart of a cell is that cell plus an aligned `AggregateDataPtr`,
which reproduces every one of those sizes, so the threshold can be scaled by the
exact ratio instead of a constant. `minBytesForPrefetch` does that, and returns
the threshold unchanged for a table that does carry the pointer.

The same correction now also applies to `mergeSingleLevelDataImpl` and
`mergeBucketImpl`, which kept comparing against the full threshold, so a threaded
key-only `GROUP BY` no longer prefetches on one rule while building and another
while merging.

Single-threaded, 100M rows, `GROUP BY` without aggregates, vs the full threshold:
`key32_void` -16.4% at 50k keys and -9.8% at 100k keys; `keys128_void` -1.9..-2.8%
across 100k..2M keys. At 32 threads, 200M rows: `key32_void` -14.0% and
`keys64_void` -14.1% at 100k keys, neutral above. The exact ratio measures the
same as the previous `/ 2` where the two differ.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
Comment thread src/Interpreters/Aggregator.cpp Resolved
…me rule

The threshold has two carriers. `Aggregator` gates its own prefetch, and the
serialized methods gate theirs inside `HashMethodSerialized::initPrecomputedHashes`,
because `has_cheap_key_holder` is false for them and the aggregation loop never
enables prefetch on their behalf. Only the first carrier got the cell-size
correction, so a key-only serialized table - `GROUP BY` over string or
multi-column keys without aggregate functions - still compared its bytes against
the threshold of a table wide enough to hold an aggregate-state pointer.

`minBytesForPrefetch` moves next to `PrefetchingHelper` so both carriers call it.
It no longer names `AggregateDataPtr`, which would have dragged
`AggregateFunctions` into `Common`; `void *` has the same size and alignment.
`initPrecomputedHashes` applies it lazily, at the one point where the cell type
of the table is known to that method.

For the serialized methods this is a correction of the rule rather than of the
generated behaviour: their cells are 24 bytes against a mapped table's 32, so the
threshold moves by a quarter, while `HashTable` quadruples its buffer at every
resize below 2^23 slots. Measured on a 2 MiB L2, the reachable buffer sizes are
384 KiB at 4k keys, 1.5 MiB at 16k and 6 MiB at 64k, and both the old and the new
threshold fall on the same side of every one of them. Prefetch is worth 15.2% at
64k keys, 18.4% at 256k and 22.5% at 1M (60M rows, 8 threads, key-only
`prealloc_serialized_void`), and it is enabled at all three either way.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XK6uvyssdB3uUmju6uZYxp
@nickitat

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

…reshold

# Conflicts:
#	src/Interpreters/Aggregator.cpp

Co-authored-by: nickitat <[email protected]>

Copilot AI commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved the merge conflicts in src/Interpreters/Aggregator.cpp:

  • Kept both #include <Common/HashTable/Prefetching.h> (from this branch) and the two new includes from master.
  • Preserved master's top_k restructuring of executeImpl (the execute/dispatch lambdas) while retaining the minBytesForPrefetch call from this branch inside the dispatch lambda.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ nickitat
❌ Copilot
You have signed the CLA already but the status is still pending? Let us recheck it.

@nickitat
nickitat marked this pull request as ready for review August 24, 2026 20:59
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=7 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d1aef19d-9056-4cd6-a931-daba44e91f47
  • MIRAI run: 21a940b6-3d88-4569-8764-536b0ec7ec0a
  • PR check IDs:
    • clickbench_257407_1787617075
    • clickbench_257508_1787617080
    • clickbench_257529_1787617081
    • tpch_adapted_1_official_257712_1787617094
    • tpch_adapted_1_official_257827_1787617160
    • tpch_adapted_1_official_257941_1787617199

@thevar1able
thevar1able added this pull request to the merge queue Aug 31, 2026
Merged via the queue into master with commit 619fe30 Aug 31, 2026
351 of 353 checks passed
@thevar1able
thevar1able deleted the agg-prefetch-set-threshold branch August 31, 2026 18:16
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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