Skip to content

Do not prefetch in a two-level GROUP BY that holds few keys - #125897

Merged
nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-two-level-few-keys-prefetch
Nov 6, 2026
Merged

nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-two-level-few-keys-prefetch

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125845
Closes: #126578
Related: #108655
Related: #108311

Changelog category (leave one):

  • Performance Improvement

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

A two-level GROUP BY that holds few keys no longer enables software prefetch only because its preallocated buckets are larger than the L2 cache. Such queries were up to 3x slower since 26.7, for example 13 keys with group_by_two_level_threshold_bytes = 1. Closes #125845.

Description

Since #108655 lowered the aggregation prefetch threshold from 4 x L2 to L2, the two-level GROUP BY from #125845 (13 keys) runs 2-3x slower on hosts with a small L2.

A two-level table allocates all 256 buckets up front, so getBufferSizeInBytes() is a constant however few keys it holds: 2 MiB for string keys with a saved hash, 2.5 MiB for keys256, about 6.5 MiB for Nullable(String). Above L2 that turns prefetch on for every row, which costs an extra key hash per row while the probes touch only 13 cells.

bytesForPrefetch measures a two-level table that is still at its initial allocation by its keys (2 * size * cell, the smallest table that holds them) instead of by its buffer. Grown two-level tables and all single-level tables keep the old measure. Both gates use it: Aggregator::executeImpl and HashMethodSerialized.

Validation on a release build, base vs fix, counting executed PREFETCH instructions (perf stat -e sw_prefetch_access.any) and timing. The issue query at an emulated 1 MiB L2: 301M -> 1.8M prefetches, 0.23 s -> 0.075 s (the same as with prefetch disabled). On this 2 MiB-L2 host: Nullable(String) with 13 keys 0.22 s -> 0.18 s, keys256 0.15 s -> 0.11 s. Unchanged: the #108311 shape (prefetch still wins 13%), 20K-key two-level tables at 1 MiB L2 (prefetch stays on), 2M-key tables. Results are identical. The JOIN gate was measured and left unchanged. The 1.6x memory in the issue is only accounting (#107490 tracks these tables; with max_untracked_memory = 1 both versions peak at 19 MB).

I could only measure on Intel; small-L2 hosts are emulated by setting getL2CacheSize().

New perf test: group_by_two_level_few_keys.xml.


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

Version info

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

A two-level hash table allocates all 256 buckets at their initial size up
front, so its getBufferSizeInBytes() is a constant however few keys it holds:
2 MiB for string keys with a saved hash, 2.5 MiB for keys256 with a mapped
value, about 6.5 MiB for TwoLevelStringHashMap. Since ClickHouse#108655 lowered the
aggregation prefetch threshold from 4 x L2 to L2, every host whose L2 is below
that constant prefetches every row of such a table, even with 13 keys. The
look-ahead then hashes each key a second time for probes that touch a handful
of cells (ClickHouse#125845: 2.3x slower on 26.8 than on 26.6).

bytesForPrefetch() measures a two-level table that is still at its initial
allocation by its keys, as the smallest table that holds them at the maximum
load factor 1/2, and every other table by its buffer as before. Both users of
the gate go through it: Aggregator::executeImpl and the self-prefetching
HashMethodSerialized. StringHashTable gets initial_buffer_bytes so that
TwoLevelStringHashTable is covered as well.

Measured on a release build, base vs fix (executed PREFETCH instructions via
perf sw_prefetch_access.any, and time):
- issue query at an emulated 1 MiB L2: 301M -> 1.8M, 0.23 s -> 0.075 s
- Nullable(String), 13 keys, 2 MiB L2: 99.9M -> 0.4M, 0.22 s -> 0.18 s
- keys256, 13 keys, 2 MiB L2: 58.9M -> 0.4M, 0.15 s -> 0.11 s
- unchanged: the ClickHouse#108311 shape, 20K-key two-level tables at 1 MiB L2
  (prefetch stays on), 2M-key single-level tables

Closes ClickHouse#125845

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The perf test never selects the HashMethodSerialized path changed in ColumnsHashing.h DISAGREE Measured on that path (String + UInt64 keys, two-level, 1 MiB L2): 0.415 s base vs 0.411 s fix, while PREFETCH instructions drop 99.3M to 1.7M. It hashes each row once and reuses the hash, so a query for it cannot show a change; the hunk keeps the two gates identical
2 💡 The JOIN gate has the same two-level floor Noted Measured with 13-row String and UInt64 right sides, prefetch on vs off: no consistent difference, so left unchanged
3 💡 GROUP BY lc in the perf test runs about 0.09 s on a 2 MiB-L2 host Noted 300M rows is already the issue's size; it runs 0.24 s on the base binary at 1 MiB L2

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261014-220300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue query (300M rows, 8 threads, group_by_two_level_threshold_bytes = 1) at an emulated 1 MiB L2 runs 0.23 s on base vs 0.075 s with enable_software_prefetch_in_aggregation = 0, on every run, and executes 301M PREFETCH instructions (perf stat -e sw_prefetch_access.any).
b Root cause explained? A two-level table preallocates 256 buckets, so its getBufferSizeInBytes() is a constant (2 MiB for string keys with saved hash, 2.5 MiB keys256, ~6.5 MiB Nullable(String)). Since #108655 the gate threshold is L2, so on hosts with L2 below that constant a 13-key table prefetches every row: one extra key hash per row for probes that touch 13 cells.
c Fix matches root cause? Yes. The gate now measures a two-level table that is still at its initial allocation by its keys (2 * size * cell) instead of by the constant buffer. No threshold change, no key-type guard, no setting.
d Test intent preserved / new tests added? New perf test group_by_two_level_few_keys.xml (LC(Nullable(String)), Nullable(String), keys256). No SQL test: prefetch never changes results. Existing aggregation tests pass (144 debug + 6 release-only), 8 two-level/prefetch tests 50x randomized: 400/400.
e Both directions demonstrated? Yes, base vs fix on the same release config: issue query 301M -> 1.8M prefetches, 0.23 s -> 0.075 s; Nullable(String) 13 keys 99.9M -> 0.4M, 0.22 -> 0.18 s; keys256 58.9M -> 0.4M, 0.15 -> 0.11 s.
f Fix is general across code paths? Both users of the gate go through the helper (Aggregator::executeImpl, HashMethodSerialized::initPrecomputedHashes; the latter checked on prealloc_serialized_void: 99.3M -> 1.7M). Merge gates prefetch per merged key by stored hash only and are unchanged. The JOIN gate was measured with no consistent effect and left unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked LC(Nullable(String)), Nullable(String) (TwoLevelStringHashMap), keys256, packed string, serialized; mapped and key-only cells; 13 / 5K / 20K / 100K / 2M keys; real and 1 MiB L2. Prefetch stays on where the keys exceed the threshold (20K keys at 1 MiB, the #108311 shape, single-level and grown tables).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format change. Single-level and grown two-level tables are unchanged by construction.
i Invariants and contracts preserved? The gate only decides whether to prefetch; results are identical (verified byte-for-byte on the issue query). The helper reads const members only; size() of a two-level table is O(256) per block and only evaluated when prefetch is enabled.

Session id: cron:clickhouse-impl-slot-7:20261014-203300

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2432bbd]

Summary: ✅


AI Review

Summary

This PR avoids unnecessary software prefetching for two-level GROUP BY tables with few keys by correcting the size estimate in both aggregation prefetch gates. No actionable findings at 2432bbd9ba6ee2b433407428ee25aed32a6545db. The supplied before/after measurements support the performance claim, and the new functional regression test passed in Fast test at this head.

Missing context / blind spots
  • ⚠️ AMD and ARM performance comparisons are pending at the reviewed head; the preceding commit's comparisons were dropped. No runnable clickhouse binary is available here to independently reproduce the reported Intel timings. Completed comparison reports would close this validation gap.
Final Verdict

Status: ✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @nihalzp, could you review this? A two-level hash table preallocates all 256 buckets, so its buffer size is a constant above L2 even with 13 keys, and since #108655 lowered the gate to L2 the GROUP BY from #125845 prefetches (and re-hashes) every row; the gate now measures such a table by its keys.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 14, 2026
@nihalzp nihalzp self-assigned this Oct 14, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aa59bda

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, parallel) / 05258_query_condition_cache_prewhere_attribution flaky, not from this PR (it changes only aggregation prefetching): the second query of each pair reads query condition cache entries that other tests clear in parallel; 8 PRs in 30 days. The fix is merged, but the tree this run built predates it #125702 (mine, merged)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 05346_distributed_insert_connection_buffers_freed_by_same_query flaky, not from this PR: the test counted frees sampled under a memory tracker blocker (a shared system log queue regrowing) as frees of the INSERT; 10 PRs and 2 master runs in 30 days. The fix is merged, but the tree this run built predates it #125909 (mine, merged)
Mergeable Check, PR praktika rollups of the rows above #125702, #125909 (the owners of the rows above)

Session id: cron:our-pr-ci-monitor:20261016-003007

fm4v added 2 commits November 4, 2026 12:54
The gate only decides whether to prefetch, so a functional test cannot observe it. The test instead runs every two-level table shape behind `bytesForPrefetch` with `enable_software_prefetch_in_aggregation` on and off and checks that the rows match: the `LowCardinality(Nullable(String))` key from ClickHouse#125845, `Nullable(String)` (`TwoLevelStringHashMap` and its new `initial_buffer_bytes`), `keys256`, serialized keys (the `HashMethodSerialized` gate), and a two-level table that has outgrown its initial allocation (the fallback branch).

Related: ClickHouse#126578
@fm4v
fm4v enabled auto-merge November 4, 2026 12:10
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2432bbd9b with master bdbd1b837 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b02fbee24; 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.

Compile time of recompiled translation units

815 translation units recompiled, 7746 s compile time in total, 814 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.1 s

Job report

`05498_group_by_two_level_few_keys_prefetch` failed the debug flaky check with
"Test runs too long (> 180s)" in 1 of 50 runs (201.7 s; the other 49 took at
most 58 s). Its `query_log` shows that run slow in every statement under heavy
MergeTree randomization (`auto_statistics_types`, sparse serialization), so
the cost follows the data size.

Insert 300000 rows instead of 1000000. The 6 reading streams (`EXPLAIN
PIPELINE`) still read about 50000 rows each, more distinct keys of `many`
than the 32768 a two-level table fits in its initial 256 x 256 cells at load
factor 1/2, so the grown case still grows. Pin
`max_block_size = 8192` for the queries: a thread converts to two-level only
after its first block, so the gate sees its two-level table only from the
second block on, and with fewer rows per thread a large random block size
would leave none.

Results do not depend on the data size, so the reference only changes its
counts. Measured on the CI debug binary of 70ff2d5: 2.1x less CPU
locally (2.8x with the failing run's settings); under the flaky-check shape
(8 jobs, 50 runs, thread fuzzer) the p50 drops by about 30%, and with the failing
run's settings it is at least 2.4x faster (600 s against the 1500 s timeout
of every old run).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
auto-merge was automatically disabled November 5, 2026 05:43

Head branch was pushed to by a user without write access

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

@fm4v 05498_group_by_two_level_few_keys_prefetch failed the debug flaky check with Test runs too long (> 180s) (201.7 s in 1 of 50 runs, under heavy MergeTree randomization). I pushed 4b94a8f, which inserts 300k rows instead of 1M and pins max_block_size = 8192 so that each thread still runs the gate on its two-level table; the reasoning and measurements are in the commit message. The push turned auto-merge off, and I can't re-enable it.

The previous run's jobs were cancelled by a self-hosted runner outage
and never re-ran, so the head could not finish CI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2432bbd

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05367_text_index_embedded_positions flaky, not from this PR (it changes only the two-level GROUP BY prefetch gate): the test's ProfileEvents check reads only the initiator's query_log row, so it prints 0 when a follower replica reads the positions; same diff on master and 2 other PRs #129610 (mine, open)
Mergeable Check, PR praktika rollups of the row above #129610 (same as above)

Session id: cron:our-pr-ci-monitor:20261105-203010

ylw510 pushed a commit to ylw510/ClickHouse that referenced this pull request Nov 6, 2026
The parallel-INSERT section compared the entries of the newest manifest list
(by file mtime) with the APPEND rows of system.iceberg_history. The insert
streams commit their snapshots about 1 ms apart, so the current manifest list
and its parent can share one coarse-clock mtime; `sort -n` then orders the
tie by the path, which carries the random snapshot id, and `tail -1` can
return the parent's list (one entry fewer), printing `0 1 1` instead of
`1 1 1`. CI query_log of both failures (ClickHouse#125897, ClickHouse#128995) shows the test
reading the parent snapshot's list.

Find the list the way a reader does: the newest v<N>.metadata.json, the
snapshot whose snapshot-id is current-snapshot-id, its manifest-list.
Forcing every manifest list to one mtime, the old helper picked a wrong list
in 23/40 trials and the new one in 0/40.

05496 and 05229 use the same mtime heuristic but write each snapshot from a
separate client call, so they are not changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat enabled auto-merge November 6, 2026 20:25
@nickitat
nickitat added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit c1c4e0b Nov 6, 2026
366 of 367 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 6, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #125897 to 26.10: Do not prefetch in a two-level GROUP BY that holds few keys
clickhouse-gh Bot added a commit that referenced this pull request Nov 7, 2026
Backport #125897 to 26.9: Do not prefetch in a two-level GROUP BY that holds few keys
robot-ch-test-poll added a commit that referenced this pull request Nov 11, 2026
Cherry pick #125897 to 26.8: Do not prefetch in a two-level GROUP BY that holds few keys
robot-clickhouse added a commit that referenced this pull request Nov 11, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 11, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 12, 2026
Backport #125897 to 26.8: Do not prefetch in a two-level GROUP BY that holds few keys
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

8 participants