Skip to content

Pack fixed-width keys of 17 to 32 bytes with a narrow key once per block - #130251

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/keys256-narrow-key-batch-pack
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/keys256-narrow-key-batch-pack

Conversation

@groeneai

@groeneai groeneai commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123658
Related: #126098

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY, DISTINCT, IN and JOIN over several fixed-width keys that together take 17 to 32 bytes, one of them narrower than 8 bytes (for example UInt32, UInt64, UInt64), are faster: the keys of a block are packed at once instead of row by row. Such queries take up to 60% less time; with tens of millions of groups the gain disappears at 8 or more threads.

Description

A non-nullable keys256 key set is packed row by row: one narrow store per key into a 32-byte slot, which the hash and the hash table then read as 8-byte words. A word holding a key narrower than 8 bytes spans several in-flight stores and cannot be store-forwarded, so every row stalls. Smaller key sets are batch-packed per block, and nullable ones are since #126098.

useOrderedPreparedKeys now also accepts non-nullable keys256 sets with a key narrower than 8 bytes, packed once per block with packFixedBatchOrdered in clause order. Those are the per-row bytes, so hashes, two-level buckets, output columns and Join tables are unchanged. Sets of only 8- and 16-byte keys stay per row (their words forward). These states also get a sub-range variant, so aggregation and DISTINCT in order pack only their run (#120259); without it the new in-order perf queries take 9 s instead of 0.03 s.

Measured (release, Xeon 6975P-C, one NUMA node, 16 interleaved pairs, ratio to master): UInt32, UInt64, UInt64 with 91K groups 0.52x / 0.43x / 0.65x at 1 / 8 / 32 threads, ld_blocks.store_forward per row 9.2 -> 0.002; nine UInt16 keys 0.40x / 0.56x; three hits key sets 0.66x-0.74x; DISTINCT 0.40x / 0.48x; IN 0.48x; JOIN USING 0.50x-0.67x, with fan-out 100 0.92x; a, e, f of group_by_fixed_keys.xml (10M groups) 0.65x at 1 thread, 0.98x-0.99x at 8-32; aggregation in order over one-row runs 1.03x; controls on unchanged paths 0.99x-1.03x with equal cycles. This PR's own performance comparison is the arbiter for x86 and ARM.

Based on the patch by @ snelheidai in #123658 (comment).


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

groeneai and others added 2 commits November 9, 2026 02:46
A non-nullable `keys256` key set is packed row by row (`packFixed`): the
32-byte slot is zero-filled, each column is written with a 1/2/4/8/16-byte
store in clause order, and then the hash and the hash table read the slot back
as 8-byte words. A word holding a key narrower than 8 bytes spans several
in-flight stores and cannot be store-forwarded, so each row stalls. Sets of up
to 16 bytes are already batch-packed per block (`usePreparedKeys`), and
nullable sets have been since ClickHouse#126098, so this was the last per-row fixed-key
path outside LowCardinality.

`useOrderedPreparedKeys` now also accepts non-nullable `keys256` sets whose
widths are all in {1, 2, 4, 8, 16} and that contain a key narrower than 8
bytes. They are packed once per block with `packFixedBatchOrdered` in clause
order, which is byte for byte the per-row `packFixed` layout, so the hashes,
the two-level buckets, the unpacked output columns (`packedKeysOrder` stays
empty) and the `Join` engine read-back are unchanged. Sets of only 8- and
16-byte keys keep the per-row path: their words forward, and a longest-first
batch of `UInt64` x3 measured 1.024x with 10M unique keys. The short sub-range
fallback packs `keys256` in clause order too. `SubRangeStateOf` now gives every
non-LowCardinality fixed-key state a sub-range variant (no fixed key is wider
than `UInt256`), so aggregation and DISTINCT in order pack only their run, as
ClickHouse#120259 does for keys128; without it the new in-order perf queries take 9 s
instead of 0.03 s.

Measured: release without ThinLTO, Xeon 6975P-C, pinned to the physical
cores of one idle NUMA node, 16 interleaved pairs, geometric-mean ratio
fix/master with 95% CI:

  UInt32, UInt64, UInt64, 91K groups (numbers_mt 1e8)
    1 thread  0.515 [0.472, 0.563]   8 threads 0.426 [0.406, 0.447]
    32 threads 0.651 [0.636, 0.665]
  UInt64 x3, same rows and groups (path unchanged)
    1 thread  0.994 [0.987, 1.001]   8 threads 1.019 [0.972, 1.069]
  group_by_fixed_keys.xml `a, e, f` (1e7 groups, two-level)
    1 thread  0.645 [0.627, 0.663]   8 threads 0.991 [0.944, 1.042]
    32 threads 0.980 [0.934, 1.028]
  nine UInt16 keys, 804K groups   1: 0.395   8: 0.555
  hits (10M rows), 8 threads: UserID, CounterID, RegionID, EventDate 0.707;
    CounterID, RegionID, EventDate, SearchEngineID, OS, UserAgent,
    TraficSourceID 0.657; nine Int16/Date keys 0.743; UserID, CounterID
    (keys128, unchanged) 1.020
  DISTINCT a, e, f   1: 0.397   8: 0.480;   IN (a, e, f), 8: 0.478
  JOIN USING (UInt32, UInt64, UInt64), 20M x 1M: hash 0.499 / 0.588,
    parallel_hash 0.542 / 0.667 (8 / 32 threads); fan-out 100 at the default
    output block limits 0.920; with max_joined_block_size_rows = 1024 0.977
  in order, 1 thread: runs of 65536 GROUP BY 0.833, DISTINCT 0.361; unique
    sorting key GROUP BY 1.026 (+8 ns per run), DISTINCT 0.857
  group_by_fixed_keys.xml e,f / e,f,g / e,i / e,f,i (unchanged): 0.998-1.031,
    every CI includes 1

PMU, per input row, 1 thread, master -> fix: `ld_blocks.store_forward` 9.20
-> 0.002, cycles 173.5 -> 93.6 (UInt32, UInt64, UInt64); UInt64 x3 0.022 ->
0.022, cycles 85.3 -> 85.0. Unchanged-path controls with a timing shift have
identical cycles and instructions; one in-order DISTINCT control (+6.7%, 13
ms) runs a hot function that is byte-identical in both binaries and shows a
DSB-miss signature, i.e. code placement. `.text` grows by 168 KiB.

Based on the patch by @ snelheidai in
ClickHouse#123658 (comment)
(simplified `SubRangeStateOf`, oracle-based unit tests added).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the store-forwarding rationale in useOrderedPreparedKeys to one line.

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

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @nihalzp, could you review this and add the can be tested label so CI runs? Non-nullable keys256 key sets with a key narrower than 8 bytes are now packed once per block with the existing packFixedBatchOrdered in clause order (the per-row layout, so hashes and Join tables are unchanged), which removes the per-row store-forwarding stall when the hash reads the slot back as 8-byte words.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: ld_blocks.store_forward per input row on GROUP BY UInt32, UInt64, UInt64 is 9.20 on master and 0.002 with the patch (1 thread, 5/5 rounds); the layout gtests are deterministic (20/20 repeats).
b Root cause explained? A non-nullable keys256 key is packed per row with narrow stores into a 32-byte slot that the hash then reads as 8-byte words; a word holding a narrow key cannot be store-forwarded, so each row stalls.
c Fix matches root cause? Yes: such key sets are packed once per block with the existing packFixedBatchOrdered, the mechanism keys128 and nullable sets already use, so no row reads a slot it has just written.
d Test intent preserved / new tests added? Gtests compare every producer (whole block, long and short sub-range, rows outside a batched range) against the per-row packFixed oracle; a new SQL identity test; two perf tests extended (existing queries untouched).
e Both directions demonstrated? Gtests fail on 3 mutants (longest-first fallback, longest-first batch, batching off) and pass on the fix; the SQL test differs from the master-generated reference on 2 mutants and matches with the fix (50/50 randomized runs).
f Fix is general across code paths? One change in HashMethodKeysFixed covers GROUP BY (whole block, two-level, external, in order), DISTINCT, IN, LIMIT BY, INTERSECT/EXCEPT, the set index, hash and parallel_hash JOIN, the Join engine and joinGet; 2362-test related sweep shows no new failure.
g Fix generalizes across inputs (params/datatypes/wrappers)? Width mixes with 1-, 2-, 4-, 8- and 16-byte keys tested; Nullable unchanged, LowCardinality excluded at compile time, widths outside {1,2,4,8,16} keep the per-row path; 0 rows, 255/256-row sub-ranges and a range past the block end covered.
h Backward compatible? (maintainer-approved exception only) Yes: packed bytes and hashes are identical to the per-row path, so two-level merges, spilled aggregation and Join tables are unaffected; no setting or format change.
i Invariants and contracts preserved? Clause-order layout equals per-row packFixed on every producer; estimatePreparedKeysMemory equals the actual allocation for the new key sets (gtest); getKeyHolder stays const; no concurrency change.

Session id: cron:clickhouse-impl-slot-41:20261108-234100

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6df7a4f]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

Reviewed #130251 at 6df7a4f320f70b95f4e234585285a076a6d8488c, including all prior discussion. The change batch-packs non-nullable keys256 sets containing a narrow key and adds sub-range handling for in-order execution while preserving the existing packed layout. No actionable findings. The supplied before/after measurements support the performance claim, and the new SQL regression test passed in Fast test.

Missing context / blind spots
  • ⚠️ The broader unit, sanitizer, and x86/ARM performance jobs were pending at review time. No local build or test binary was available. Completed CI results would close the remaining platform and sanitizer coverage gap; the performance assessment currently relies on the reported x86 measurements.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 9, 2026
@nihalzp nihalzp self-assigned this Nov 9, 2026
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6df7a4f

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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The job was red the same way on 37 other PRs in the last 24 hours #129675 (mine, open)
PR praktika rollup of the row above #129675 (the owner above)

The other CIDB FAIL row on this head is Config Workflow / Pre Hooks of the run before the can be tested label.

Session id: cron:our-pr-ci-monitor:20261109-073003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #131393: its third commit packs the same keys256 sets without Nullable in cache-sized chunks right before use, and the PR also covers nullable keys256 and key columns of other widths.

@groeneai groeneai closed this 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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants