Skip to content

Lower software-prefetch threshold for aggregation and join hash tables - #108655

Merged
nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-aggregation-prefetch-l2-gate
Jun 30, 2026
Merged

nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-aggregation-prefetch-l2-gate

Conversation

@groeneai

@groeneai groeneai commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108311

Changelog category (leave one):

  • Performance Improvement

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

Lower the software-prefetch threshold for aggregation and join hash tables from 4 * L2 cache size to L2 cache size, so prefetch is enabled once the hash table no longer fits in L2. This recovers a regression on GROUP BY and JOIN over medium-sized hash tables (~1-8 MiB) on platforms whose reported L2 is large (e.g. aarch64 with a 2 MiB L2).

Description

Fixes the ARM topn_aggregation query 1 regression reported in #108311.

Root cause. getMinBytesForPrefetch() (aggregation) and getMinBytesForPrefetchInJoin() (join) gate software prefetch at 4 * L2 cache size. The L2 size used to be read via sysconf(_SC_LEVEL2_CACHE_SIZE), which is x86-only in glibc and unimplemented in musl. On aarch64 it failed and fell back to the 256 KiB default, so the effective gate was 4 * 256 KiB = 1 MiB. Once the real L2 size started being read on more platforms (CPUID on x86, sysfs on non-x86 Linux), aarch64 reported its true 2 MiB L2 and the gate jumped to 4 * 2 MiB = 8 MiB, disabling prefetch for medium hash tables and regressing ~100k-key GROUP BY workloads.

Fix. Set the gate to 1 * L2: enable prefetch exactly when the hash table no longer fits in L2 (lookups miss to slower levels / DRAM and prefetch hides the latency); below that the table is cache resident and prefetch is pure overhead. This is architecture-adaptive (scales with the real L2) rather than a fixed constant, and the same regression in the join path is fixed alongside it.

Measurements. On an x86 host with a 2 MiB L2 (same L2 size as the affected ARM Neoverse-V2 runner, so getL2CacheSize() returns the same value), query SELECT intHash32(number) % 100000 AS k, min(toDateTime(number)) FROM numbers_mt(1e8) GROUP BY k ORDER BY min ASC LIMIT 10 FORMAT Null, max_threads=32, median client time over 13 runs:

gate prefetch median
4 * L2 = 8 MiB (master) off 0.31s
1 * L2 = 2 MiB (this PR) on 0.27s (-13%)

Sweeping the gate and the key count puts the prefetch-on-vs-off crossover right at 1 * L2: prefetch wins by 13-17% whenever the per-group table exceeds L2 and is neutral below it. Tables that already exceed every candidate gate (e.g. ~1M keys) are unaffected. The direction and magnitude match the -17% the reporter measured on ARM.

Prefetch only changes when lookups are issued, not the computed result; aggregation and join outputs are byte-identical with prefetch on and off (verified locally).

Full performance-suite and ARM-hardware validation is left to CI (the reporter's ARM measurements + the public history at https://performance.ci.clickhouse.com/history/topn_aggregation/1?metric=client_time&arch=arm).

JOIN path measurements. The join gate (getMinBytesForPrefetchInJoin, default-on, used in both build and probe loops) was measured separately on the same 2 MiB-L2 host. With the gate isolated so enable_software_prefetch_in_join controls prefetch, the only join hash tables this change flips are those whose getBufferSizeInBytes() lands in (2 MiB, 8 MiB] (roughly 40k-100k distinct keys; smaller tables stay prefetch-off under both gates, larger were already prefetched). 200M-row probe with random keys, INNER JOIN, hash algorithm, max_threads=32, median of 11 runs:

build keys (8 MiB buffer) 1 * L2 (on, this PR) 4 * L2 (off, master) delta
40k 0.211s 0.254s -16.9%
50k 0.255s 0.293s -13.0%
60k 0.257s 0.291s -11.7%
80k 0.246s 0.289s -14.9%
100k 0.248s 0.284s -12.7%

Faster at every cardinality, no regression; join output byte-identical with prefetch on vs off.

Note: src/Common/ColumnsHashing.h also calls getL2CacheSize() but for a different decision (batch serialization, total_size <= 4 * L2), with an aarch64 short-circuit before the L2 logic, so it is intentionally left unchanged.

Version info

  • Merged into: 26.7.1.288 (included in 26.7 and later)

The threshold that gates software prefetch for aggregation and join hash
tables was 4 * L2 cache size. Enable prefetch once the table no longer fits
in L2 instead (threshold = L2 cache size), which is where the measured
benefit actually begins.

Background: the threshold historically read the L2 size via
sysconf(_SC_LEVEL2_CACHE_SIZE). That call is x86-only in glibc and
unimplemented in musl, so on aarch64 it failed and the code fell back to the
256 KiB default, making the effective gate 4 * 256 KiB = 1 MiB. Once the L2
size started being read on more platforms (CPUID on x86, sysfs on non-x86
Linux), aarch64 began reporting its real 2 MiB L2 and the gate jumped to
4 * 2 MiB = 8 MiB. That disabled prefetch for medium hash tables (roughly
1-8 MiB), e.g. a ~100k-key GROUP BY, and regressed those workloads.

Measurements on a host with a 2 MiB L2 (same L2 size as the affected ARM
Neoverse-V2 runner, so getL2CacheSize() returns the same value), query
"SELECT intHash32(number) % 100000 AS k, min(toDateTime(number)) FROM
numbers_mt(1e8) GROUP BY k ORDER BY min ASC LIMIT 10 FORMAT Null",
max_threads=32, median client time over 13 runs:

  gate = 4 * L2 = 8 MiB (prefetch off): 0.31s
  gate = 1 * L2 = 2 MiB (prefetch on):  0.27s   (-13%)

Sweeping the gate and the key count shows the crossover sits right at 1 * L2:
prefetch wins by 13-17% whenever the per-group hash table exceeds L2, and is
neutral below it (the table is cache resident, so prefetch is pure overhead).
4 * L2 sat far above that crossover. Tables that already exceed every
candidate gate (e.g. ~1M keys) are unaffected, and small cache-resident
tables stay below the gate and keep prefetch disabled.

The same threshold and the same regression existed in
getMinBytesForPrefetchInJoin (identical code from the same change), so both
are updated together. Prefetch only changes when lookups are issued, not the
computed result; aggregation and join outputs are identical with prefetch on
and off.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On an x86 host whose L2 is 2 MiB (= the affected ARM runner's L2, so getL2CacheSize() returns the same value), SELECT intHash32(number)%100000 AS k, min(toDateTime(number)) FROM numbers_mt(1e8) GROUP BY k ORDER BY min ASC LIMIT 10 FORMAT Null with max_threads=32 is deterministically 0.31s on master vs 0.27s with the fix (medians of 13 runs, ranges non-overlapping).
b Root cause explained? Yes. Gate = 4 * L2. L2 used to come from sysconf(_SC_LEVEL2_CACHE_SIZE) (x86-only in glibc, unimpl in musl) → on aarch64 it failed → fell back to 256 KiB → effective gate 4*256K = 1 MiB. When L2 began being read on more platforms, aarch64 reported its real 2 MiB → gate 4*2M = 8 MiB → prefetch disabled for the ~3-4 MiB / 100k-key table → +27% (ARM) / +13% (this host).
c Fix matches root cause? Yes. Set the gate to 1 * L2, the measured prefetch-on-vs-off crossover. Not a band-aid: it targets the exact mechanism (table-fits-in-L2 decision), is architecture-adaptive, and is not the prototype's blind 1 MiB constant.
d Test intent preserved / new tests added? This is a hot-path threshold change with no behavioral effect, so no .reference change and no new functional test (a perf test, tests/performance/topn_aggregation.xml q1, already exists and is the regression guard). Correctness is unchanged — see (e).
e Both directions demonstrated? Yes. master (gate 8 MiB, prefetch OFF) median 0.31s; fixed binary (gate 2 MiB, prefetch ON) median 0.27s, both with Build-ID-verified binaries on the same host/query.
f Fix is general across code paths? Yes. The identical 4 * getL2CacheSize() gate and identical regression existed in getMinBytesForPrefetchInJoin (same source change), so both aggregation and join paths are fixed. ColumnsHashing.h also calls getL2CacheSize() but for a different decision (batch serialization, with an aarch64 short-circuit) and is intentionally left unchanged.
g Fix generalizes across inputs? Yes. Swept gate ∈ {256K..16M} × key counts {1k,30k,50k,70k,100k,150k,200k,300k,1M}: prefetch wins 13-17% whenever the table exceeds L2, is neutral when it fits (small tables stay below the gate, large tables exceed every candidate gate). The fix is a single threshold, not input-specific.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Pure in-process heuristic; behavior is recoverable via the existing enable_software_prefetch_in_aggregation / enable_software_prefetch_in_join settings. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. Prefetch only changes WHEN cache lines are requested, never the computed result. Verified identical aggregation output (sum(cityHash64(k,m)) over a 200k-group GROUP BY) and identical join output (count/sum over a 500k JOIN) with prefetch forced on vs off.

Session id: cron:clickhouse-worker-slot-2:20260626-193800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @nickitat — could you review? Lowers the aggregation/join software-prefetch gate from 4 * L2 to 1 * L2, recovering the ARM topn_aggregation regression in #108311 (medium ~1-8 MiB hash tables stopped being prefetched once aarch64 began reporting its real 2 MiB L2, pushing 4 * L2 to an 8 MiB gate). Locally -13% on the affected query (x86 host with the same 2 MiB L2); the sweep puts the prefetch-on crossover right at 1 * L2. Result is unchanged; full perf-suite validation via CI.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dcb6d85]

Summary: ✅


AI Review

Summary

This PR lowers the software-prefetch gate for aggregation and hash join hash tables from 4 * getL2CacheSize to getL2CacheSize. The change is narrow, keeps the existing enable_software_prefetch_in_aggregation and enable_software_prefetch_in_join escape hatches, and the author has provided focused aggregation and join measurements plus CI/cloud benchmark evidence for the affected medium-table window. I found no new correctness, safety, or performance-blocking issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 26, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
@nickitat nickitat self-assigned this Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 38 analysed

This PR lowers the hash-table prefetch threshold from 4x L2 cache size to 1x L2 in both the Aggregator and HashJoin, so prefetching now kicks in for smaller tables. ClickBench Q15 is a high-cardinality GROUP BY that runs directly through the aggregation hash-table path the diff touches, making its 10.5% speedup plausible and on-path. The improvement is a large, consistent delta confirmed by both tests, so the verdict stands.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 15 improvement 247 221 -10.5% <0.0001 aggregation: PR lowers aggregation prefetch threshold (4*L2 to L2); Q15's high-cardinality GROUP BY hits this path

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f2682f74-d180-4e07-bace-02c3cf766bf5
  • MIRAI run: 7dd5e9a7-955f-4399-be91-6ddf39d74dd8
  • PR check IDs:
    • clickbench_440134_1782781141
    • clickbench_440140_1782781141
    • clickbench_440152_1782781141
    • tpch_adapted_1_official_440161_1782781141
    • tpch_adapted_1_official_440173_1782781141
    • tpch_adapted_1_official_440182_1782781141

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fa8b33d

CI fully finished (Finish Workflow passed 2026-06-27T00:29Z; Performance/coverage all completed; no checks queued or in progress; >20 min since the last check completed). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error 'Inconsistent AST formatting' (STID 1941-26fa) flaky (chronic AST-formatter round-trip assertion family; 26 hits / 21 unrelated PRs / 5 master in 30d; unrelated to this PR's prefetch-gate change in Aggregator.cpp / HashJoin.cpp) #107092 / #108354 (ours, open - in-flight fixes for the 1941 AST-formatter family)
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found deadlock (chronic server-shutdown hang family; cannot be caused by a software-prefetch threshold change) #101680 / #105905 (ours, open)
Performance Comparison (amd/arm_release) / 20 queries flagged slower perf-report noise on a single run, NOT a FAIL/ERROR test row (test_status='slower' label). The 18 flagged queries are unrelated benchmarks (rand, clickbench, numeric_indexed_vector, removing_group_by_keys, ...). The 2 prefetch_in_aggregation rows (#5: 10M keys old 0.128 -> new 0.145; #7: 50M keys old 0.376 -> new 0.476) are on tables whose hash buffers (>>32 MiB) far exceed BOTH the old 8 MiB and new 2 MiB gates, so prefetch was already ON before and after - the gate change cannot affect them mechanically. Aggregation-target queries that the gate change does affect were measured -13% (faster) in the PR's own A/B. not a failure (perf-report label; no PR-caused regression)
Mergeable Check / PR aggregators reflecting the two chronic stress reds n/a
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260627-013000

@nickitat

Copy link
Copy Markdown
Member

@groeneai, perf tests show mixed results. There are improvements and slowdowns. Investigate.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat investigated: no slowdown is caused by this change. The mixed signal is the real improvements plus run-to-run noise.

Decisive check: the gate is arch-identical here. Both the ARM Neoverse-V2 and the amd_release host report L2 = 2 MiB, so the gate moves 8 MiB -> 2 MiB identically on both, and a real gate-caused regression would have to appear on BOTH arches. The 10 flagged-slower queries are disjoint across arches (none appears on both):

The non-prefetch ones are clearly noise: rand = count() FROM (SELECT rand() FROM zeros(1e9)) has no hash table; the 3-21 ms ones are at the noise floor; removing_group_by_keys #1 slowed on arm but was faster on amd (369->364, gate-identical); clickbench #18 = COUNT(DISTINCT UserID) on the noisy arm 6/6 shard.

The feature's own test #5/#7 = select number from numbers_mt(10M/50M) group by number. These build ~512 MiB / ~2 GiB hash tables, far above BOTH the old 8 MiB and new 2 MiB gate, so prefetch is ON under both -> identical path. The per-block decision crosses 2 MiB at ~65k keys and 8 MiB at ~262k keys, both in the first few of ~760 blocks, so the gate differs for <1% of the work; it cannot yield a 20-27% delta. Local A/B (x86, L2=2 MiB == the arm host, instrumented gate, max_threads=32, medians): #5 0.13 vs 0.17, #7 0.77 vs 0.62 (ranges 0.58-0.84 vs 0.60-0.67, fully overlapping) -> noise. Same rig on the actual affected window (intHash32(number)%100000 ... group by k, ~4 MiB buffer): gate 2 MiB 0.29 vs 8 MiB 0.35 = -17%, so it does detect the real effect where the buffer lands in (2 MiB, 8 MiB].

The repeatable signal is the improvements on that window: cloud-benchmarks flagged ClickBench Q15 -13.7% and TPC-H Q4 (semi-join) -78.2%, verdict improvement, 0 regressions; the in-window prefetch_in_aggregation queries improved on arm (#0 -9.5%, #2 -8.8%, #6 -4.7%, #1 -3.3%).

Net: no-op for tables far above L2, a win for tables in the L2..4*L2 window (the #108311 regression, ClickBench Q15, TPC-H Q4), flagged slowdowns are arch-disjoint noise. Happy to gate it behind a setting if you prefer a more conservative rollout.

@nickitat
nickitat enabled auto-merge June 29, 2026 21:05
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 3/3 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code

Full report · Diff report

@nickitat
nickitat added this pull request to the merge queue Jun 30, 2026
Merged via the queue into ClickHouse:master with commit 067caf4 Jun 30, 2026
343 of 344 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 Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…gation-prefetch-l2-gate

Lower software-prefetch threshold for aggregation and join hash tables
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 6, 2026
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]>
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 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