Skip to content

Pack fixed-width keys in cache-sized chunks and batch-pack keys of any width - #131393

Open
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/keys-fixed-pack-in-chunks
Open

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:groeneai/keys-fixed-pack-in-chunks

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #130852
Related: #124955
Related: #126098
Related: #120259
Related: #130251

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 hash joins over several fixed-size key columns are faster when the keys take 17 to 32 bytes and no key column is Nullable, or when a key column has a width other than 1, 2, 4, 8 or 16 bytes (for example FixedString(3)), and GROUP BY over keys of 9 to 16 bytes in large blocks (e.g. of a Memory table): 3.4x for GROUP BY over UInt32, UInt64, UInt64 on x86 and 2.4x for GROUP BY over a FixedString(3) key on ARM in the CI performance comparison.

Description

HashMethodKeysFixed packed a whole block of keys before the first lookup: 65409 keys of 32 bytes take 2 MiB, a core's L2. Key sets with a column of another width (FixedString(3)) and keys256 without Nullable were packed row by row.

  1. Other widths are batch-packed per block in clause order: two overlapping power-of-two copies per value, the same bytes as packFixed.
  2. Nullable keys256 sets are packed one chunk of maxBytesInKeyChunk() (L2 / 8, as HashMethodSerialized) at a time, starting 32 rows behind the asked row for the look-ahead prefetch. Keys of 16 bytes or less keep their whole-block array, but GROUP BY (also in the adaptive aggregator), Set and DISTINCT pick chunks for keys128 when a block's keys take more than half the L2 (.text +412 KiB for that).
  3. keys256 without Nullable, same chunks. Supersedes Pack fixed-width keys of 17 to 32 bytes with a narrow key once per block #130251.

A caller that asks about fewer than one row in six of its block packs those rows one by one, as master does: Set, DISTINCT, a hash join probe or build whose keys are not prefetched, top-K with a heap boundary. So do a resumed hash join probe that skips rows and is not prefetched, and each slot insert of a parallel hash join build, which reads about one row in num_slots; the scatter, which reads the block in order, packs chunks.

Results are unchanged (the packed bytes are the per-row ones). Unchanged: LowCardinality, keys256 in order. Nullable keys256 is not faster: 1.01x-1.02x at 1 thread, 0.91x-0.99x at 16-32 threads (x86, local).

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

Measurements (ratio of times to master)

CI performance comparison:

query amd arm
GROUP BY k1, k2, k3 (UInt32, UInt64, UInt64) 0.30 0.47
GROUP BY f3, u, q (FixedString(3), UInt8, UInt32) 0.73 0.42
GROUP BY f3, u 0.79 0.41
GROUP BY a, b, c (Int64 x3) 0.82 0.91
JOIN ON f, u (FixedString(3), UInt8), parallel_hash 0.89 0.57
GROUP BY a, b, cn (Int64, Int64, Nullable(Int64)) 1.00

x86, release, 16 threads, 8-14 interleaved pairs: keys256 JOIN hash 0.83, parallel_hash 0.87, 10M-row parallel_hash build 1.01, 99% NULL probe 0.70 (500K-row right table) and 1.04 (1K rows); keys128 GROUP BY over 1M-row Memory blocks 0.81-0.84, over 65409-row blocks (not chunked) 0.99-1.08.


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

groeneai and others added 4 commits November 13, 2026 16:31
A fixed-width key set with a column whose width is not 1, 2, 4, 8 or 16 bytes (e.g. `FixedString(3)`), nullable or
not, was packed one row at a time: `packFixedBatchOrdered` had no code for such widths, so `useOrderedPreparedKeys`
rejected them. It now copies such a value as two overlapping copies of a power-of-two half (width 3: two 2-byte copies;
5-7: 4; 9-15: 8; 17-32: 16), byte-identical to the per-row `packFixed`, so these sets are batch-packed in clause order
per block like the nullable sets of ClickHouse#126098, and `packedKeysOrder` stays empty for them.

A set that was packed per row is batch-packed only for a caller that asks about every row it packs; a caller that
skips rows (`RowRange::skips_rows`), starts after row 0 or ends before the last row of the block keeps the per-row
path. The hash-join probe, build and the scatter of a parallel build pass the first and last rows of their selector
and whether they skip rows (NULL keys, NULL ASOF keys, an ON-section filter, a scattered selector), and GROUP BY top-K
with a heap boundary marks its whole-block state as skipping rows. Every `HashMethodKeysFixed` state but
LowCardinality ones has a sub-range variant, so the in-order paths pack only their run.

Measured against master (x86 Xeon 6975P-C, release, one NUMA node, ratio of times, 8 or 16 paired rounds):

| query | 1 thread | 16 threads | 32 threads |
|---|---|---|---|
| GROUP BY f3, u, q (FixedString(3), UInt8, UInt32) | 0.65 | 0.66 | 0.69 |
| GROUP BY f3, u | 0.75 | 0.76 | 0.78 |
| GROUP BY f3n, u, q (Nullable(FixedString(3))) | 0.29 | 0.32 | 0.33 |
| GROUP BY f20, w (FixedString(20), UInt16) | 0.29 | 0.31 | 0.32 |
| GROUP BY f20n, w (Nullable(FixedString(20))) | 0.38 | 0.36 | 0.37 |
| DISTINCT f3, u, q | 0.55 | 0.60 | 0.63 |
| (f3, u) IN | 0.66 | 0.66 | 0.70 |
| JOIN ON f3, u | 0.76 | 0.87 | 0.84 |
| JOIN ON f3, u, build of 10M rows | 0.79 | 0.89 | |
| GROUP BY w, v, u, q (same bytes, unchanged path) | 0.97 | 0.97 | 1.02 |

Related: ClickHouse#130852

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A nullable keys256 set was batch-packed as a whole block before the first lookup (ClickHouse#126098): 65409 keys of 32 bytes
are 2 MiB, the whole L2 of a core, so the early keys are evicted before they are read. Such a state now packs one
chunk at a time, when the first row past the current chunk is asked for: an eighth of the L2 (64 KiB to 1 MiB), as
`HashMethodSerialized` does (ClickHouse#124955). A chunk starts up to 32 rows before the asked row, so the look-ahead prefetch
of the aggregator moves it forward; the first chunk holds 256 rows and the next ones double up to the full length,
so a caller that stops early packs little; nothing is packed before the first asked row. A row asked behind the chunk
(e.g. the slot passes of a parallel hash join build) packs the whole block once. Only the buffer hit is inline; a
miss goes through one out-of-line call that returns a pointer.

Keys of 16 bytes or less keep their whole-block array: a block of them fits in the cache, and the chunk bookkeeping
in the lookup costs more than it saves there (4-13% measured with chunks there).

A `Set` with a null map or a `DistinctSetFilter` with a mask that asks about fewer than one row in six of its block,
and GROUP BY top-K whenever its heap has a boundary, build `SparseState<State>`, the sub-range variant, which packs as
master does. The threshold was chosen from 2, 3, 4, 6 and 8 by the worst ratio over `IN` probes and set
builds with 40% to 99% NULL keys (6: 1.00; 8: 1.02; 4: 1.03; 3: 1.09; 2: 1.07).

Measured against master, ratio of times (16 paired rounds):

| query | 1 thread | 16 threads | 32 threads |
|---|---|---|---|
| GROUP BY a, b, cn (Int64, Int64, Nullable(Int64)) | 1.02 | 0.88 | 0.98 |
| DISTINCT a, b, cn | 1.01 | 0.93 | 0.92 |
| GROUP BY c32, cn (nullable keys128, unchanged path) | 1.01 | 0.92 | 0.99 |

Related: ClickHouse#130852

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A keys256 set without Nullable columns and of widths 1, 2, 4, 8 and 16 bytes was packed one row at a time (only
keys of up to 16 bytes are packed longest first). Every whole-block keys256 state now packs in clause order one
cache-sized chunk at a time, as the nullable ones do since the previous commit; its other-width sets go from a whole
block to chunks. The sub-range variant keeps the per-row path for these sets, and so does the sparse state.

Supersedes ClickHouse#130251, which batch-packed the narrow keys256 sets per block; its test material is ported here (based on
the patch by @ snelheidai in ClickHouse#123658 (comment)).

Measured against master, ratio of times (8 paired rounds; 16 for joins):

| query | 1 thread | 16 threads | 32 threads |
|---|---|---|---|
| GROUP BY a, b, c (Int64 x3, 100100 groups) | 0.53 | 0.61 | 0.67 |
| GROUP BY c32, b, c (UInt32, Int64, Int64) | 0.32 | 0.33 | 0.33 |
| GROUP BY e, f, g (UInt64 x3, 10M groups) | 0.92 | 1.01 | 1.01 |
| DISTINCT a, b, c | 0.53 | 0.32 | 0.33 |
| JOIN USING c32, b, c | 0.36 | 0.42 | 0.39 |
| JOIN, build of 10M rows | 0.41 | 0.66 | |
| JOIN, probe with 90% NULL keys, small right table | 0.50 | 0.54 | |
| (a, b, cn) IN | 0.56 | 0.59 | 0.60 |
| (a, b, c50) IN, 50% NULLs | 0.70 | 0.79 | |
| (a, b, c99) IN, 99% NULLs | 1.02 | 1.06 | |
| GROUP BY f20, w (FixedString(20), UInt16) | 0.28 | 0.28 | 0.30 |

The binary's `.text` grows by 144 KiB.

Related: ClickHouse#130852

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove comments that repeat the code or narrate the design (chunk size, chunk growth, the join getter's rows), shorten the chunk and lookup comments, and state the sparse state's packing without referring to master.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds before publication)
Finding Verdict
⚠️ Hash-join build batch-packs other-width keys of rows it skips (NULL keys, ON filter) AGREE: build passes the same row range as the probe
⚠️ Join build over a prefix selector (NULL ASOF suffix) or an empty one packs the whole block AGREE: the row range ends at the selector's last row
⚠️ The scatter of a parallel ASOF build packs the rows with a NULL ASOF key AGREE: probe, build and scatter take their rows from one helper
⚠️ 1-thread verdicts measured on mixed binaries next to concurrent runs AGREE: re-measured on the final binaries, one batch per socket
❌ arrayUniq / arrayEnumerateUniq over an other-width composite key pack every nested element up front DISAGREE: master already packs 16 bytes per nested element for standard-width composites in the same state (UInt16, UInt8, UInt8 = the bytes of FixedString(3), UInt8); this gives other widths the same treatment
⚠️ A probe that stops at max_joined_block_rows has packed its whole block DISAGREE: the stop depends on fan-out, unknown when the getter is built; master packs a standard-width block on every resumed call, this packs other widths once
⚠️ A set(N) index that stops after N keys has packed its granule DISAGREE: master's standard-width sets pack the same sub-range; only an overfull granule stops
⚠️ (f3nn, u) IN probe 1.08x at 16 threads DISAGREE: its loop is master's, differing only in block layout (disassembly); n.s. at 1 thread and on the same code in commit 2
⚠️ Adaptive mid-block freeze packs the split block twice DISAGREE: once per producer; later frozen blocks ask every row; master's longest-first sets do the same
⚠️ Checked external DISTINCT packs a block it may reject DISAGREE: only on the spill path, at most one block per spill; chunked states pack lazily
⚠️ No caller-level oracle for the chosen state DISAGREE: the choice is performance-only; every state gives packFixed's bytes (gtests, 05640 == master)
💡 Sparse-state comments said "packs no keys ahead" AGREE: reworded
💡 Batch-pack comment said "asks about every row it packs" AGREE: reworded to the declared range
💡 Chunk budget shares a formula with HashMethodSerialized noted, not changed (different units)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? A performance change, so the repro is a paired measurement: release builds of master and of each commit, clickhouse local over Memory tables in 65409-row blocks, binaries interleaved per round on one pinned NUMA node, 8-16 rounds, geometric-mean ratio with a 95% CI (numbers in the PR description).
b Root cause explained? A whole block of 32-byte keys (65409 x 32 B = 2 MiB) is packed before the first lookup, so it fills the L2 and the early keys are evicted before they are read; sets with a FixedString(3)-like column or non-nullable keys256 were packed row by row, because packFixedBatchOrdered had no code for widths other than 1/2/4/8/16.
c Fix matches root cause? Yes: keys256 states pack one cache-sized chunk (L2/8) at a time right before use, and other widths get a batch packer that writes the same bytes as packFixed (a Set with NULLs, top-K, a join probe or build that skips NULL or filtered rows keep the per-row path). Keys of 16 bytes or less keep their whole-block array, where it fits in the cache.
d Test intent preserved / new tests added? New gtests (per-block, per-run and partial-reader layouts of other widths; chunk window access orders and policy; sparse state types), 05640_hash_method_keys_fixed_chunks (results equal master's for every changed key class), perf-test queries. Existing tests change only where they pinned the old packing.
e Both directions demonstrated? Mutants on the final tree: dropping the per-chunk zero fill, writing only the first half of an overlapping copy, and packing the clause-order sub-range fallback longest first each fail at least 2 gtests and change at least 2 lines of 05640; the unmodified tree passes 21/21 gtests x20 and 05640 50/50 with random settings.
f Fix is general across code paths? Aggregation (whole block, two-level, external, in order, top-k), Set/IN, DISTINCT (+ in order), set index, hash join build (serial and multi-slot, with the scatter of a parallel build) and probe (resumed probes, scattered selectors) all go through the same state, and every join key getter is built for the rows it asks about; the sub-range variant now exists for every non-LowCardinality state.
g Fix generalizes across inputs (params/datatypes/wrappers)? Widths 1-32 checked exhaustively against packFixed; Nullable (bitmap, NULLs moving between chunk slots), FixedString(N), 32-byte numerics; LowCardinality states are untouched. NULL densities 40-99% measured for the sparse-caller switch.
h Backward compatible? (maintainer-approved exception only) Yes: the packed bytes and hashes are the per-row ones, so two-level buckets, spilled aggregation files, distributed partial aggregation and Join tables are unchanged. No setting.
i Invariants and contracts preserved? A row's key is byte-identical to the per-row key from every producer (block, chunk, chunk after a jump, whole range after a backward read, per-row miss, sub-range, sparse state); packedKeysOrder stays empty for clause-order sets; nothing references the buffer across calls (getKeyHolder returns by value).

Session id: cron:clickhouse-impl-slot-5:20261113-110200

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [55537b4]

Summary: ✅


AI Review

Summary

Reviewed #131393 at 55537b43b6652179f84a081b46c8d43187f2965d, including all prior discussion and the complete diff. The change adds cache-sized fixed-key packing and batch packing for additional column widths across aggregation, DISTINCT, IN, and hash joins. The previous probe-continuation and memory-estimation findings are addressed. No remaining blocker or major finding; no new inline comments.

Missing context / blind spots
  • ⚠️ Performance comparisons for this exact head are still pending in the Praktika report. The PR supplies earlier CI measurements on both architectures and focused local measurements, but the completed comparisons are needed to confirm the final merged head.
  • ⚠️ No configured build directory or clickhouse executable is available in this checkout, so tests and benchmarks were not rerun locally. Review evidence comprises the source, regression tests, existing CI reports, and recorded measurements.
Final Verdict

Status: ✅ 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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 13, 2026
The `random` access order shuffles with a fixed seed so a failure is
reproducible; `Build (arm_tidy)` rejects that with
`bugprone-random-generator-seed`. Suppress it the way the other gtests do.

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

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 55537b43b with master c50de3b98 (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 ⚠️

52 object files changed (+9.65 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 33.63 MiB 34.99 MiB +1.36 MiB (+4.03%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAsof.cpp.o 2.25 MiB 2.54 MiB +300.05 KiB (+13.01%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAsof.cpp.o 2.25 MiB 2.54 MiB +300.05 KiB (+13.01%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAsof.cpp.o 1.98 MiB 2.26 MiB +286.54 KiB (+14.11%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAsof.cpp.o 1.98 MiB 2.26 MiB +286.53 KiB (+14.11%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 2.13 MiB 2.37 MiB +250.07 KiB (+11.46%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAny.cpp.o 2.13 MiB 2.37 MiB +250.05 KiB (+11.46%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAnti.cpp.o 2.09 MiB 2.33 MiB +249.95 KiB (+11.68%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinSemi.cpp.o 2.06 MiB 2.31 MiB +249.93 KiB (+11.83%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnti.cpp.o 1.88 MiB 2.12 MiB +246.64 KiB (+12.82%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinSemi.cpp.o 1.86 MiB 2.10 MiB +246.54 KiB (+12.94%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAny.cpp.o 1.92 MiB 2.16 MiB +246.50 KiB (+12.52%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemi.cpp.o 1.88 MiB 2.12 MiB +246.45 KiB (+12.79%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAny.cpp.o 1.88 MiB 2.12 MiB +246.45 KiB (+12.79%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 2.87 MiB 3.11 MiB +245.73 KiB (+8.36%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 2.94 MiB 3.18 MiB +245.70 KiB (+8.16%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnti.cpp.o 1.78 MiB 2.02 MiB +245.64 KiB (+13.47%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o 2.85 MiB 3.09 MiB +245.62 KiB (+8.42%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o 2.87 MiB 3.11 MiB +245.59 KiB (+8.36%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 2.87 MiB 3.11 MiB +245.59 KiB (+8.36%)

716 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

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

Job report

The test ran too long in the sanitizer flaky checks: 3 of 50 runs in
amd_asan_ubsan and 2 of 50 in amd_tsan were over 180 s (p50 142 s and
105 s). Its time there grows with the rows each statement reads, plus a
fixed cost for each two-level aggregation.

- The main table has 50000 rows (16700 keys, about 3 rows each) instead
  of 300000; a block still holds several chunks of a set packed in
  chunks. The FixedString(3) keys are built from n * 1003, so that all
  three bytes vary.
- The fan-out table has 50000 rows, and the ASOF build side has 30000
  rows read in 10000-row blocks: still one block with a NULL ASOF suffix
  and one block of NULL ASOF keys only.
- One two-level external aggregation instead of three: the two-level
  methods use the same HashMethodKeysFixed state as the single-level
  ones.

The reference is generated by a master build. On a rig shaped like the
flaky check (this PR's amd_asan_ubsan binary, 16 vCPUs, 8 jobs, the CI
thread fuzzer settings) the new file takes 0.35 of the old file's time
(median of 25 paired runs). Dropping the reset of the chunk buffer, the
tail of the overlapping copy or the sub-range packing order still changes
8, 9 and 2 result lines.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b116f16

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
Performance Comparison (amd_release, master_head, 6/6) / Query group_by_fixed_keys #23 time keeps growing with each run not a run-state effect of the test: query #23 (added here) only reads a table that does not change (merges stopped by --stop-merges, no disk reads) and did the same work in every run (100M rows, 1.2 GB from the page cache, CPU time within 6%). The slower runs 4-6 are OS CPU wait (OSCPUWaitMicroseconds 31-78 ms in runs 0-3, 0.28-1.3 s in runs 4-6) on both servers in the same seconds, so it is CPU contention on the host, which the run-trend check reads as growth #131251 (mine, open)
Mergeable Check, PR praktika rollups of the row above #131251 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:clickhouse-maint-slot-21:20261114-052100

@harikrishnan94 harikrishnan94 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai few comments inline. The main one is the keys256 join: its parallel build packs the whole block, and CI doesn't measure it.

@groeneai can you fix the changelog entry:

  1. "more than 16 bytes" should be 17 to 32 bytes. Wider keys are serialized and don't change.
  2. Nullable keys256 is 1-2% slower at 1 thread by your numbers, so the entry shouldn't call it faster.
  3. pls add numbers from CI, e.g. 3.4x for GROUP BY over UInt32, UInt64, UInt64, and 2.4x on ARM for FixedString(3).

Comment thread src/Interpreters/Set.cpp Resolved
Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
@harikrishnan94

Copy link
Copy Markdown
Contributor

Also resolve the merge conflicts and make CI green. Specifically the performance tests and dashboard

Comment thread src/Common/ColumnsHashing/HashMethod.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, working on all of it. I'm merging master first: the conflicts are in the hash join, so the join part of this PR moves onto HashJoinTable.h from #120515.

  • Parallel build: each slot pass reads about one row in num_slots of the block, so the slot passes will pack their keys one by one, as master does, and only the scatter, which reads the block in order, packs chunks. hashjoin_packed_keys.xml gets keys256 joins with hash and parallel_hash and a probe with 99% NULL keys. If that probe is slower than master, the join probe gets the same 1-in-6 rule as IN.
  • One helper next to SparseState for the switch, with how 6 was picked.
  • One byte-budget helper shared with HashMethodSerialized.
  • rows_begin and the chunk_rows = 0 store go.
  • Changelog entry: 17 to 32 bytes, Nullable keys256 not called faster, and the CI numbers (3.4x for GROUP BY over UInt32, UInt64, UInt64 on amd, 2.4x for FixedString(3) on ARM).

I'll reply in each thread with the commit once it's pushed.

groeneai and others added 5 commits November 18, 2026 10:55
The hash join moved to `HashJoinTable.h` (ClickHouse#120515), so the rows that the join key getters are asked about are passed
there now: `createJoinKeyGetter` takes the `RowRange`, built by `joinKeyRows` for the probe, the build and the slot
scatter. `min_rows_to_batch_pack_sub_range` is the namespace constant of master.

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

Both pack or serialize the keys of a block one chunk of an eighth of the L2 (64 KiB to 1 MiB) at a time. The budget
is now `ColumnsHashing::maxBytesInKeyChunk`, and the rows of a `HashMethodKeysFixed` chunk are that budget divided by
the size of the key.

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

`ColumnsHashing::withStateForAskedRows` builds the `SparseState` for a caller that asks about fewer than one row in
`max_rows_per_asked_row` of its block, and the state otherwise. The `Set` insert and lookup and the `DISTINCT`
filter call it, and the constant says how 6 was picked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xed` chunks

A state that packs in chunks is never a sub-range state, so its rows start at 0. After a read behind the chunk packs
the whole block, every row of the block is read from it, so nothing has to stop the chunks.

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

Each slot insert of a parallel build reads the rows of its buckets, about one row in `slots.size()` of the block, and
prefetches a look-ahead of its own rows, so its next insert landed behind the chunk that the prefetch packed, and the
whole block was packed into one array: 2 MiB of `keys256` keys at 65409 rows. The slot inserts now use the
`SparseState` of the key getter, which packs the keys of `keys256` one by one, as master does; the scatter of the
block, which reads it in order, still packs chunks.

`hashjoin_packed_keys.xml` gets `keys256` joins with `hash` and `parallel_hash`, and a probe with 99% NULL keys.

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

Copy link
Copy Markdown
Collaborator Author

Ledger update for the group_by_fixed_keys #23 run-trend line above: its owner is now #132631 (#131251 was closed unmerged).

…one by one

A probe with NULL in most of its keys asks about few of the rows of its block, yet a `keys256` key getter packed
all of them in chunks. With a small right table (1000 rows, no prefetch) and 99% NULL keys this was 1.14x (`hash`)
and 1.27x (`parallel_hash`) slower than master, which packs the asked rows one by one. Such a getter now does the
same: `RowRange::asks_few_rows`, set by the 1-in-6 rule of `Set` and `DISTINCT` (`asksAboutFewRows`) over the rows
of the selector that have no NULL key and pass the `ON` section, makes a state that packs in chunks pack the asked
rows on their own. A getter whose keys are prefetched still packs chunks: the prefetch reads the key of every row of
the selector, also of a row with a NULL key, and there chunks win. Each getter of a multi-clause probe gets the
prefetch status of its own map.

x86, release, 16 threads, 14 paired rounds, ratio of times to master [95% CI]:

| query | ratio |
|---|---|
| 99% NULL probe, 1K build, `hash` | 1.04 [0.91, 1.19] |
| 99% NULL probe, 1K build, `parallel_hash` | 1.00 [0.87, 1.15] |
| `LEFT JOIN` with an `ON` filter passing 1% of the probe, 1K build | 1.02 [0.95, 1.10] |
| `OR` of two clauses, 99% NULL probe, 1K build | 1.05 [0.98, 1.13] |
| 99% NULL probe, 500K build (prefetched), `hash` | 0.70 [0.63, 0.79] |
| 99% NULL probe, 500K build (prefetched), `parallel_hash` | 0.78 [0.72, 0.85] |
| `OR` of two clauses, 99% NULL probe, 500K build | 0.76 [0.70, 0.82] |

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits November 18, 2026 12:43
Master enabled `modernize-use-nodiscard` for clang-tidy.

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

The scatter reads the key of every row of its selector, and the selector of an ASOF build leaves out the rows with a
NULL ASOF key, so with mostly NULL ASOF keys it asks about few rows of the block. Its getter now gets
`asks_few_rows` from the density of the selector, as the probe and the serial build do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` filter with `countBytesInFilter`

A probe that is resumed for its next output block builds its getters again for the rest of the block, so the count of
the asked rows is repeated per output block. Without an `ON` filter it is now one pass over the null map.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 25d8af5. Master is merged (01f61fd), so the join part of this PR now sits in HashJoinTable.h. The changelog entry now says 17 to 32 bytes, no longer calls Nullable keys256 faster, and has the CI numbers (3.4x for UInt32, UInt64, UInt64 on amd, 2.4x for FixedString(3) on ARM). 75196ab adds the [[nodiscard]] that master's clang-tidy now asks for.

The group_by_fixed_keys #23 growth failure on the last head had the same work in every run and the extra time all in CPU wait, on both servers; this push runs it again.

groeneai and others added 3 commits November 18, 2026 15:26
…cache

`sizeof(Key) > 16` stood in for "the key array does not fit in the L2": a `Memory` table filled by `INSERT SELECT`
returns blocks of about 1M rows, so a keys128 state packed a 16 MiB array, and a 1 MiB L2 (Zen 4) already overflows
at 65409 rows. `HashMethodKeysFixed` gets an `in_chunks` parameter, and `ChunkedState<State>` is the variant of a
state of 16-byte keys that packs in chunks, in the layout of the state that packs the whole block
(longest first when that one is). `GROUP BY` (`Aggregator::executeImpl`, the slices and the frozen kernels of the
adaptive aggregator) and `withStateForAskedRows` (`Set`, `DISTINCT`) pick it when
`rows * sizeof(Key) > getL2CacheSize() / 2` (`keysOutgrowCache`), and the memory estimate of a `Set` follows that choice. Narrower keys keep their whole-block array: each
key class that can pick chunks doubles its aggregation loops (`.text` +412 KiB for the 16-byte ones).

x86, release, 16 threads, 8 pairs, ratio of times to the whole-block state, `Memory` table with 1M-row blocks:
`GROUP BY a, b` (`UInt64, UInt64`, 1M groups) 0.84, 100K groups 0.81, `UInt32, UInt64` 0.83, `DISTINCT a, b` 0.99;
65409-row blocks (1 MiB of keys, not picked): 0.99, 1.04, 1.08, 0.98.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A probe whose output fills `max_joined_block_size_rows` is resumed for the rest of its block, after as few as one row
with a high fan-out, and counting the asked rows of the rest again on every resumption is quadratic in the block. A
resumed probe whose keys are not prefetched now packs the asked rows one by one, as master does, without counting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A caller that asks about few rows of a big block gets the state that packs the whole block, so pricing one chunk
for a 16-byte key underestimated it. The whole-block price is an upper bound for both states, as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/SetVariants.cpp Resolved
…LL map

A probe whose output fills `max_joined_block_size_rows` is resumed for the rest of its block, after as few as one row
with a residual condition, and `joinKeyRows` scanned the NULL map of the whole rest with `memoryIsZero` on every
resumption before it checked for one, so a nullable key without NULLs made such a probe quadratic in the block. A
resumed probe now reads none of the rest: a nullable key counts as skipping rows, so a getter that packs in chunks and
does not prefetch packs the asked rows one by one, as master does.

LEFT JOIN with a residual condition over a nullable keys256 key without NULLs, `max_joined_block_size_rows = 100`,
`hash_join_layout = 'serial'`, one probe block, 1 thread, median of 3 (ms): 500K rows master 702 / before 1055 /
now 766; 1M rows master 1497 / before 2568 / now 1443.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
`withStateForAskedRows` now passes the chosen state type instead of a
state, and the loops of `Set::insertFromBlockImplCase`,
`Set::executeImplCase` and `buildDistinctFilter` construct it as on
master. Running those loops inside a lambda changed the code of methods
that have no other state: on aarch64 the `IN` probe over a `UInt64` key
took one more taken branch per row, and `Performance Comparison
(arm_release)` measured `set` ClickHouse#1 9.7% slower (#0 7.0%, ClickHouse#2 6.5%; amd
flat).

Compiled for aarch64 with the CI compiler (clang 23.1.6) and release
flags, ThinLTO backend run on the object, the per-row loops of all six
`UInt64` instantiations of `Set::executeImplCase` and
`Set::insertFromBlockImplCase` are the same instructions as in the CI
master binary; with the lambdas all six differed.

x86 release, 1 thread, 20 paired rounds, this commit / previous: `IN`
with 1 and 16 elements 1.00, `UInt64` set builds 0.98, `keys256` and
`keys128` `IN` probes and set builds 0.94-1.00, `DISTINCT` over
`keys256`, `nullable_keys256` and `keys128` 0.94-0.99.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 19, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

Can you look at #132628 and see if you can borrow some code that is not dead code for this PR and make the merge easy instead of re-write or either, incase one merges?

…-pack-in-chunks

Conflict in `src/Interpreters/AdaptiveAggregation/Producer.cpp`: master moved the
argument-miss loop of the frozen kernel into `collectArgumentMisses` (ClickHouse#132740),
which takes the find state's type from its argument, so master's side is kept and
`executeFrozenImpl` still builds the state type its caller picks.

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

Copy link
Copy Markdown
Collaborator Author

I looked at #132628. A trial merge of the two heads (ef42356 and 0cb94f1) conflicts only in HashJoinTable.h, in two hunks (probe with probeAll, and prepareProbeAll): this PR passes their key getters the rows they are asked about (joinKeyRows), and #132628 removes these functions. Everything else merges cleanly, including this PR's build side in the same file.

I found no code in #132628 that would be live here: its new code is the key search and the match step, and this PR does not change the probe loop, only the last argument of the probe's createJoinKeyGetter. So neither PR needs a rewrite: whichever merges second takes #132628's side of the two hunks. I checked that tree: its join files (FindKeysMaps*.cpp, JoinRightColumns.cpp, HashJoin.cpp, HashJoinTable.cpp and three join kinds) compile with -fsyntax-only, and PrefetchingLookup instantiates this PR's HashMethodKeysFixed. The new RowRange argument has a default, so makeKeyGetter and keyGetterOf compile unchanged.

That drops one rule: a probe that asks about fewer than one row in six (NULL keys or the ON filter, no prefetch) packs those rows one by one. Without it, my x86 A/B of the 99%-NULL keys256 probe with a 1K-row build was 1.14x and 1.27x of master. On #132628 it is joinKeyRows<KeyGetter>(args.keys.null_map, args.keys.join_mask_column, rows, use_prefetch) as the fourth argument in makeKeyGetter and keyGetterOf, with rows the rows of the call ([first_row, first_row + rows), not the first search batch) and use_prefetch decided before the getter in PrefetchingLookup::run. If #132628 merges first, I'll add that here when I merge master. If this one merges first, #132628 keeps its side and I'll restore the rule in a small PR after it merges.

This PR conflicted with master again, in Producer.cpp (#132740 moved the loop it edits into collectArgumentMisses). Merged in ef42356, keeping master's side there.

@clickhouse-gh
clickhouse-gh Bot dismissed stale reviews from themself November 19, 2026 05:16

AI review of a later commit does not approve the PR, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ef42356

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
Performance Comparison (arm_release, master_head, 2/8) / set_index_check_in_range #0 code layout, not this diff: 228.6 -> 247.1 ms (+8%). I compared the two CI binaries function by function (addresses masked): the per-row code of this query (the Set probe loop for these keys, the compact part reader, CompressedReadBuffer, LZ4, deserializeBinaryBulk) is the same machine code, only per-block setup differs. In the same shard, queries whose per-row code is also unchanged are slower by the same amount: parallel_index #0 160.1 -> 175.0 ms (+9.3%), math_exp #8 88.7 -> 96.2 ms (+8.4%). The restart confirmation could not demote it: its three stack placements are set with GLIBC_TUNABLES, which the static musl binary ignores, so all three are the same placement (+7.8%, +7.5%, +7.8%) a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (amd_release, master_head, 6/6) / Query group_by_fixed_keys #22 time keeps growing with each run a query that only reads, and both servers grow (tested 0.585 -> 0.745 s, reference 0.771 -> 0.906 s) #132631 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05829_autopr_skip_index_on_read_in_subquery fails on master too (35 master runs and 53 PRs since 2026-11-19 00:41Z) #132867 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #132631, #132867 (mine, open) and a fix task is created (the first row)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:clickhouse-maint-slot-16:20261119-081600

@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai make CI green

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merging master now: it has #132867, which fixed 05829_autopr_skip_index_on_read_in_subquery (no failure on master since it merged). The push re-runs both performance comparisons.

group_by_fixed_keys "time keeps growing" (amd, 4 of the 5 heads it ran on) comes from the harness, not from the queries. In #22 on ef42356 each run reads the same 100M rows from the page cache with flat CPU time; only the wait for a CPU grows (right server: 0.05 s in runs 0-3, 0.7-1.3 s in runs 4-6). Every query whose time changed gets profile runs with allocation sampling, and the next trace_log flush symbolizes all those samples on the same 8 CPUs both servers are pinned to, while the next query is measured. Here the right server's flush of 346949 rows took Block=6766ms (07:56:47-54) and the left's 245666 rows Block=5571ms (07:56:50-56), right over runs 4-6 of #22. compare.sh never reads these symbols (it resolves addresses through *-addresses.tsv), so I'll send a separate PR that sets <symbolize>false</symbolize> for trace_log in the perf config, and merge master here once it lands.

set_index_check_in_range #0 (arm, +8%): in the two CI binaries the per-row loop of this query is identical to master's, and queries with unchanged code were as much slower in the same job (parallel_index #0 +9%, math_exp #8 +8%). The run after this push will show whether it repeats; if it does, I'll treat it as real.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The separate PR for the group_by_fixed_keys "time keeps growing" trips: #133126 sets <symbolize>false</symbolize> for trace_log in the perf config. On the reference binary of the failing job, the largest trace_log flush went from Block=4733ms to Block=133ms. I'll merge master here once it lands.

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-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.

HashMethodKeysFixed: pack keys in chunks that fit in the cache, for every key set

2 participants