Skip to content

Prefetch the hash table of LIMIT BY once it outgrows the L2 cache - #132328

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-by-prefetch-above-l2
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-by-prefetch-above-l2

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131355
Related: #131211

Changelog category (leave one):

  • Performance Improvement

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

LIMIT BY over many distinct numeric or fixed-size keys is faster: once its hash table no longer fits in the L2 cache, the row loop prefetches the cells of the rows ahead whenever the key changes, as the hash join probe does.

Description

limit_by_misc #3 and limit_by_in_pk_order #1 are red on ARM in #131355, a RabbitMQ-only PR (3/8, 2/8). In 45 days the pair was slower on ARM in 14 builds (2 on master), red in at least 5. The extra samples are in LimitByTransform::consumeImpl for keys64, identical machine code in both binaries, moved by 512 bytes. The same query with 1000 keys (limit_by_misc #2, cache resident) is not slower there: the mode needs lookups that miss the cache, and how many misses the core overlaps decides the loop's speed.

GROUP BY, the hash join probe and uniqExact prefetch rows ahead once the table outgrows L2. This PR does the same in LimitByTransform for the keys the join probe prefetches (has_cheap_key_calculation) except LowCardinality ones, and only where the key changes: a row inside a run finds the cell its run already loaded. String and LowCardinality keys keep the current loop: with the prefetch they ran up to 1.07 (String) and 1.23 (LowCardinality). The loop without prefetch keeps master's machine code apart from a log message's length (x86 release, all 69 methods). NegativeLimitByTransform is not changed.

x86, release, PR / master: limit_by_misc #3 0.60, limit_by_in_pk_order #1 0.66, limit_by #1 0.68, limit_by #10 0.67; String, LowCardinality and cache-resident queries 0.98-1.02; none of the 82 LIMIT BY perf queries confirmed above 1.05. A 24-byte key, packed per row: 1.04 with 100K keys, 0.83 with 1M; Nullable(FixedString(3)) + UInt32 0.80. Keys in runs longer than the look-ahead are not prefetched (runs of 64: one key 0.98, two keys 1.05). Keys repeating interleaved in a chunk prefetch on every change: 0.77 (GROUP BY on that shape: 0.82). ARM is measured only by this PR's CI. New: two limit_by queries (keys in long runs, a 24-byte key) and a stateless test of the prefetching loop (six key shapes).

🤖 Generated with Claude Code


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

groeneai and others added 7 commits November 17, 2026 05:41
`LimitByTransform::consumeImpl` looks up every row's key in a hash table
built with the Aggregator's hash methods, but its row loop issues no
software prefetch. When the table holds millions of keys every lookup
misses to memory, and how many of those misses overlap is left to the
out-of-order core: on ARM release binaries `limit_by_misc ClickHouse#3` and
`limit_by_in_pk_order ClickHouse#1` are 15-30% slower in some builds whose
`consumeImpl` machine code is byte-identical to the reference and only
sits at another address (seen as red performance checks on unrelated
PRs, e.g. ClickHouse#131355 and ClickHouse#131211). The same query at cardinality 1000,
whose table is cache resident, is not slower in those builds.

Use the look-ahead prefetch the Aggregator, the hash join probe and
`uniqExact` already use for large tables: when the method builds its
key holder cheaply and its table has a `prefetch` member, a chunk that
starts with a table larger than L2 runs `consumeImpl<true>`, which
prefetches the cell of row `i + look_ahead` with the adaptive look-ahead
of `PrefetchingHelper`. Otherwise the chunk runs `consumeImpl<false>`,
whose code is unchanged. `NegativeLimitByTransform` is not changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new prefetching row loop of `LimitByTransform` engages only once the
table outgrows L2, which no other LIMIT BY stateless test reaches. Cover
key64, keys64 (with and without OFFSET), keys128, a Nullable key and a
String key, checking each result against the arithmetic of `numbers`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With ThinLTO both `consumeImpl` instantiations were inlined into `consume`,
which recompiled the loop that runs for tables within L2. Out of line it is
master's machine code (x86 release: 69/69 methods identical up to the logged
function-name length), the convention `Aggregator::executeImplBatch` uses for
its own `prefetch` template parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…changes

String and LowCardinality keys paid the prefetch on rows the consecutive-keys
cache or the dictionary cache answer without a lookup (String key in runs of 64:
1.07x, LowCardinality(String) column in runs of 64: 1.19-1.23x on x86); use the
JOIN probe's `has_cheap_key_calculation` without the single LowCardinality
column method, and prefetch only when the key changes, since a row inside a run
finds the cell its run already loaded. Plus a perf query for keys in long runs;
the test's String query becomes a numeric key in runs of 3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`low_cardinality_keys128` / `low_cardinality_keys256` (a single
`LowCardinality` key of a 16- or 32-byte number, or a fixed-size
multi-key that contains a `LowCardinality` column) are
`AggregationMethodKeysFixed` with `has_low_cardinality = true`. Their
`low_cardinality_optimization` is false, so they took the prefetching
loop, and their key is rebuilt through the positions column and the
dictionary for the look-ahead row as well.

Measured on x86 (release, 10M rows, table above L2, 13-round
confirmation): a single `LowCardinality(UInt128)` key with distinct
keys ran at 1.195x master with the prefetch (+116 instructions and
+19 cycles per row). Exclude every method with
`has_low_cardinality = true`; all other methods are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three `UInt64` BY columns form a 24-byte fixed key (`keys256`), which
has no prepared key array and is packed column by column for every
row; the prefetching loop packs the look-ahead row again at each key
change. No existing performance query covers a fixed key wider than
16 bytes.

Measured on x86 (release, 10M rows, 8 cores): this query 0.965x
master (master 0.256 s). The same key over a 100K-key MergeTree table
was 1.037x in a 13-round confirmation (cycles per row +0.3%), over 1M
keys 0.825x, in runs of 64 rows 0.964x, so the method keeps the
prefetch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Clarify which reader of has_cheap_key_calculation uses join_prefetch_supported, and drop two cross-file citations from the LIMIT BY prefetch predicate.

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 in each of rounds 1-3, none in round 4), plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The local A/B did not cover other key types that now prefetch (a String key, LowCardinality, keys repeated in runs) AGREE, fixed Measured: String and single LowCardinality(String) keys in runs were 1.07 and 1.19-1.23. The prefetch is now limited to numeric and fixed-size keys and issued only where the key changes; those queries run the unchanged loop (0.98-1.02).
2 ⚠️ 05814_limit_by_large_hash_table passes with the change reverted DISAGREE A prefetch has no SQL-visible effect; a counter only for the test is not wanted. The perf tests limit_by_misc #2/#3 and limit_by #0/#1 sit on both sides of the threshold and run in this PR's perf check. The loop for small tables is master's machine code (x86 release and aarch64 object, all 69 methods). The new test runs the prefetching loop under the sanitizer builds.
3 ⚠️ LowCardinality columns inside a fixed-size key (and a single LowCardinality(UInt128)/UUID) still prefetch, unmeasured, while the text says LowCardinality keys do not AGREE, fixed Measured: distinct LowCardinality(UInt128) keys were 1.19 with the prefetch (a LowCardinality(FixedString(2)) + UInt32 key gained, 0.73, but shares the method). Every LowCardinality key now keeps the unchanged loop (0.98-1.01).
4 💡 consume reads getBufferSizeInBytes instead of bytesForPrefetch AGREE, not changed Same value for every table LimitByTransform can choose (single-level only).
5 💡 NegativeLimitByTransform has the same lookup loop AGREE, not changed Stated in the description; no perf test or CI red points at it.
6 💡 Two keys in runs of 64 over a table above L2 are 1.05 AGREE, not changed Stated in the description; about 6 more instructions per row in the prefetching loop; not a CI perf shape.
7 ⚠️ Fixed-size keys wider than 16 bytes (keys256: e.g. UUID + Date, three 64-bit columns) are packed for every row, so the prefetch packs them twice; unmeasured AGREE, measured, kept Three UInt64 keys: 1.04 with 100K keys (about 2% more cycles), 0.83 with 1M keys; Nullable(FixedString(3)) + UInt32, also packed per row, 0.80. Stated in the description; the new perf query limit_by #12 covers the shape.
8 💡 On ARM (no SSSE3 shuffle) a fixed-size key with an odd-width FixedString column is also packed per row AGREE, not changed The same per-row packing as row 7, measured on x86.

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

Session id: cron:clickhouse-review-slot-10:20261117-113500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The ARM red reproduces in its own CI job (+33% after restart, at all 3 stack placements). I have no ARM host; locally the checks are on demand: codegen identity of the loop without prefetch (x86 release binary, aarch64 TU) and an interleaved x86 A/B with cache-resident controls.
b Root cause explained? consumeImpl<keys64> has identical machine code in both binaries at a moved address, and is slower only when each row's lookup misses the cache (the 1000-key sibling query is not slower in the same binaries). The loop's speed then depends on how many misses the core overlaps, which changes with placement.
c Fix matches root cause? It issues the lookups' cache lines ahead, as Aggregator, the hash join probe and uniqExact do, for the keys the join probe prefetches and only where the key changes. On x86 limit_by_misc #3 drops from 166 to 103 cycles per row (IPC 0.92 -> 1.69). Tables within L2 and the other key types keep master's machine code.
d Test intent preserved / new tests added? New 05814_limit_by_large_hash_table: the prefetching loop for key64, keys64, keys64 with OFFSET, keys128, a Nullable key and a key in runs of 3, each result equal to independent arithmetic. New perf queries limit_by #11 (one key in runs of 64) and limit_by #12 (three UInt64 columns, a 24-byte key) cover the in-run rows and a key packed per row; the existing limit_by, limit_by_misc, limit_by_in_pk_order perf tests sit on both sides of the threshold. LowCardinality keys run the existing loop (checked with perf on four shapes), so the existing tests cover them.
e Both directions demonstrated? PR / master on the same CPUs: limit_by_misc #3 0.60, limit_by_in_pk_order #1 0.66, cache-resident controls 1.00, no LIMIT BY perf query confirmed above 1.05. The loop without prefetch matches master instruction for instruction except the logged function-name length (x86, 69/69 methods), plus the logged line number in the aarch64 TU. perf shows the test runs the prefetching loop. Results cannot differ (a prefetch is a hint), so the new test guards the new loop under the sanitizer builds and cannot fail on master.
f Fix is general across code paths? Every map method goes through consume. String, FixedString, serialized, hashed and all LowCardinality keys keep the plain loop: their key is not cheap to build twice, or their cache answers most rows without a lookup (measured: prefetching them made runs of 64 1.07-1.23x slower, and a distinct LowCardinality(UInt128) key 1.20x). Fixed-size keys packed per row (wider than 16 bytes, or with a Nullable column) keep the prefetch: measured 0.799-0.965, except three UInt64 columns over 100K keys within L3 at 1.037 (+2% cycles). LimitBySortedStreamTransform and the without_key path have no hash table. NegativeLimitByTransform is not changed: no perf test or red measures it.
g Fix generalizes across inputs (params/datatypes/wrappers)? Numeric keys, Nullable numeric keys and fixed-size key tuples without a LowCardinality column prefetch, including 17-32-byte tuples (0.825-1.037) and tuples with a Nullable column (0.799); a LowCardinality key, single or inside a tuple, keeps the plain loop (16- and 32-byte low_cardinality_keys excluded, distinct and run shapes measured at 0.98-1.01); Const and Sparse keys are removed before the dispatch, and two-level variants are never chosen. The look-ahead index is bounded by the chunk size, with 50 randomized max_block_size draws in the test. Run lengths 1, 2, 3, 8, 64 and interleaved repeats measured.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change, and results are unchanged.
i Invariants and contracts preserved? The transform gains no state. Cancellation batches, failpoint positions, processRun and the null-mapped insertion protocol are unchanged. An emplaceKey throw leaves the state it leaves today, and a resize mid-chunk only wastes prefetches.

Session id: cron:clickhouse-impl-slot-7:20261117-111100

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a96804e]

Summary: ✅


AI Review

Summary

The PR adds adaptive prefetching to LimitByTransform for numeric and fixed-size key hash tables larger than L2, retaining the existing loop for strings and LowCardinality keys. Reviewed head a96804e11ab6890a07603922280f66a3486bd7b9, the complete diff, surrounding lookup and packing code, and all prior discussion. No actionable findings; the supplied x86 measurements support the performance claim, and 05814_limit_by_large_hash_table passes Fast test.

Missing context / blind spots
  • ⚠️ ARM performance impact remains unverified: the relevant CI performance comparisons are pending. Their completed results would close this gap.
Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a96804e11 with master bab51f537 (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 ⚠️

3 object files changed (+295.40 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/LimitByTransform.cpp.o 1.45 MiB 1.74 MiB +295.38 KiB (+19.84%)

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.

Compile time of recompiled translation units

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

Job report

This branch has not been deployed

No deployments
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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant