Skip to content

Pack nullable fixed-width aggregation keys once per block - #126098

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:batch-pack-nullable-fixed-keys
Oct 16, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:batch-pack-nullable-fixed-keys

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120100
Related: #120259

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY and DISTINCT over several fixed-width keys, some of them Nullable, are faster: the keys of a block are packed at once instead of row by row. Such queries take 12-26% less time on typical nullable key sets and up to 2.5x less with few distinct groups. Closes #120100.

Description

HashMethodKeysFixed batch-packs the keys of a block only when usePreparedKeys holds, which excludes every key set with a Nullable column, so nullable_keys128 / nullable_keys256 build the NULL bitmap and pack the key row by row.

For a row without NULLs, the per-row nullable layout is a zero bitmap followed by the keys in clause order, which a strided batch copy produces (packFixedBatchOrdered). Only rows with a non-zero null-map byte are packed again by the per-row code, and a null map that is all zero over the range is skipped (memoryIsZero). The output side reads the clause order it always read. Nullable states also get a sub-range variant, so aggregation in order, DISTINCT in order and the set index pack only their run, with the 256-row threshold from #120259; the whole-block-only patch in the issue took GROUP BY a, nb in order from 0.045 s to 17.5 s with unique a. estimatePreparedKeysMemory covers these key sets. Non-nullable key sets are unchanged: keys256 is shared with the hash join, and its gain was small.

Measured (release, paired geometric mean against master, 9 interleaved runs, 4 threads): nullable pair with 7.7K groups 0.39x, with 60M groups 0.80x; group_by_fixed_keys.xml a, d 0.80x, e, i 0.88x, e, f, i 0.74x; (Nullable(Int64), Int64) with 50% / 100% NULL 0.74x / 0.89x; DISTINCT e, i 0.42x; non-nullable controls 0.96x-1.05x. In order (1 thread): unique a 0.97x-1.03x, runs of 300 rows 0.40x-0.87x, runs of 65536 rows 0.76x. Results match master (05401); the unit test pins what SQL cannot observe: that nullable sets batch, the 256-row threshold and the per-row fallback outside a batched run. Based on the patch in the issue.


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

Version info

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

groeneai and others added 4 commits October 15, 2026 15:34
`HashMethodKeysFixed` batch-packs a block's keys only when `usePreparedKeys` holds, which excludes
every key set with a Nullable column, so `GROUP BY` / `DISTINCT` over nullable fixed-width keys
(`nullable_keys128` / `nullable_keys256`, e.g. TPC-DS q65) builds the NULL bitmap and packs the key
row by row.

For a row without NULLs the nullable per-row layout is a zero bitmap followed by the keys in clause
order, which a strided batch copy produces. Nullable states now batch-pack that layout
(`packFixedBatchOrdered`) and re-pack with the per-row code only the rows that have a non-zero
null-map byte; null maps that are all zero over the range are skipped with `memoryIsZero`. A row
whose null-map bytes are all zero gets no bit from `createBitmap` whether a set byte is tested for
`== 1` or for non-zero, so the result is the per-row key either way. The only allocation stays
`prepared_keys`, so `estimatePreparedKeysMemory` (now true for these key sets) stays exact.

Nullable states also get a sub-range variant (`SubRangeStateOf`), so aggregation in order, DISTINCT
in order and the set skip index pack only the run they are built for, with the same 256-row
threshold as the non-nullable keys (ClickHouse#120259). Without it, a whole-block pack per run of the sorting
prefix made `GROUP BY a, nb` in order 0.045 s -> 17.5 s on 131072 rows with unique `a`.
The range selection is shared by both batching branches (`rowsToBatchPack`).

Non-nullable key sets keep their path: `keys256` is shared with the hash join, and its measured gain
was small.

Release A/B vs master (4 threads, 9 interleaved runs, paired geometric mean):
nullable pair 60M groups 0.80x, 7.7K groups 0.39x; group_by_fixed_keys.xml a,d 0.80x, e,i 0.88x,
e,f,i 0.74x; (Nullable(Int64), Int64) 40M rows with 50% NULL 0.74x, all NULL 0.89x; DISTINCT e,i
0.42x; non-nullable controls 0.96x-1.05x. In order (1 thread): unique-`a` arms 0.99x-1.03x, runs of
300 0.40x-0.87x, runs of 65536 0.76x.

Based on the patch in issue ClickHouse#120100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Whether a nullable key set is batch-packed, and the per-row fallback for a row
outside a batched sub-range, are not observable from SQL. Extend
`gtest_columns_hashing_prepared_keys.cpp` with a `Nullable(UInt32), UInt64`
keys128 set (NULL-free and NULL-bearing halves) and check, against the per-row
`packFixed` with a bitmap computed from the null map: the whole block and an
explicit whole-block range are batched and carry the NULL bit in the array;
long sub-ranges with and without NULLs are batched over their own rows and
rows outside them fall back to per-row packing; the sub-range threshold holds
on both sides.

Also cover `nullable_keys256` in the `estimatePreparedKeysMemory` oracle and
sort the `Columns/` includes in `HashMethod.h`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The three nullable cases in gtest_columns_hashing_prepared_keys.cpp built
only a keys128 state, so nothing pinned that a nullable_keys256 set is
batch-packed: if useOrderedPreparedKeys declined UInt256, every such set
would fall back to per-row packing with all tests green (the allocation
estimate case shares the same gate, and the SQL tests check results only).

Each case now runs for a keys128 set and for a keys256 set whose fixture
gains a third UInt64 column (20 key bytes: too wide for keys128 with its
2-byte bitmap, fits keys256 with its 4-byte one), against the per-row
packFixed<Key> oracle. A build whose useOrderedPreparedKeys also requires
sizeof(Key) <= 16 fails all three with the keys256 trace only; a build that
skips the NULL repack fails all three for both widths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the rowsToBatchPack doc comment to one line.

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; 2 findings over 3 rounds, the last round clean) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ No test asserts that nullable key sets are batch-packed; SQL cannot observe it (05401 checks results only) AGREE, fixed in 5c01688 nullable cases in gtest_columns_hashing_prepared_keys.cpp: whole block, long sub-range incl. rows outside it, threshold
2 ⚠️ Those cases instantiate only a keys128 state, so nullable_keys256 could stop batching unnoticed AGREE, fixed in bbd046b the same cases run for a keys256 set too wide for keys128; a build that stops batching keys256 fails all three
3 💡 ColumnsCommon.h include out of alphabetical order in HashMethod.h AGREE, fixed in 5c01688 include moved
4 💡 Estimate oracle covers only a nullable_keys128 set AGREE, fixed in 5c01688 {Nullable(UInt64), UInt64} added to PreparedKeysMatchActualAllocation
5 💡 No nullable sub-range state over an explicit whole-block range AGREE, fixed in 5c01688 covered by the whole-block gtest
6 💡 A unit test next to the SQL test noted, not blocking the unit test pins what SQL cannot observe (that nullable sets batch, the threshold, the per-row fallback); 05401 is the only end-to-end check of NULL groups on the output side; same gtest file as #120259

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

Session id: cron:clickhouse-review-slot-9:20261015-183700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Performance change, master is correct. Release A/B against master, 9 interleaved runs with 95% CIs (numbers in the description). Each new oracle fails deterministically on a mutant: the stateless test on a build that skips the NULL repack (9 of 9 hashed results change), the in-order perf arms on a build without the sub-range variant (13 to 22 s instead of 0.03 s).
b Root cause explained? usePreparedKeys excludes nullable key sets, so nullable_keys128/256 build the NULL bitmap and pack every row. For a row without NULLs that layout is a strided copy, so a batch pack plus a per-row repack of the NULL rows gives the same keys.
c Fix matches root cause? The batch writes exactly the per-row nullable layout and the rows with a non-zero null-map byte are packed by the unchanged per-row code. No new setting.
d Test intent preserved / new tests added? New 05401_aggregation_nullable_fixed_keys_batch_pack.sql (whole block, in order, DISTINCT), nullable arms in aggregation_in_order_partial_key.xml, and three nullable cases in gtest_columns_hashing_prepared_keys.cpp for what SQL cannot see, each run for a keys128 set and a 20-byte keys256 set: that the block or sub-range is batched (array size, NULL bit in the array), the per-row fallback outside a batched sub-range, and the 256-row threshold.
e Both directions demonstrated? Results identical to master on every query; the test and the perf arms each fail on the mutant described in (a). The gtests fail on a build that skips the NULL repack (3 of 3 nullable cases, both widths), on one that indexes the sub-range array by row (the sub-range case), and on one that stops batching keys256 (3 of 3, keys256 only).
f Fix is general across code paths? One hashing state serves every nullable fixed-key caller (aggregation incl. two-level and merge, DISTINCT, LIMIT BY, IN, INTERSECT/EXCEPT); the per-run callers get the sub-range variant. LowCardinality keys and the hash join are untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Widths 1/2/4/8/16, 16- and 32-byte keys, 9 nullable keys (2-byte bitmap), NULL in the first key, mixed widths, all-NULL / NULL-free / mixed blocks, runs shorter and longer than 256 rows. Other widths keep the per-row path.
h Backward compatible? (maintainer-approved exception only) No setting or format change; packed keys never persist.
i Invariants and contracts preserved? Every row's key equals the per-row packFixed with its bitmap; the column order of the packed key is unchanged; the only allocation is the key array, so estimatePreparedKeysMemory stays exact (DistinctSetFilterWorkspace.PreparedKeysMatchActualAllocation).

Session id: cron:clickhouse-impl-slot-5:20261015-150706

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a3881cf]

Summary: ✅


AI Review

Summary

PR #126098 batch-packs nullable fixed-width keys for GROUP BY, DISTINCT, and their shared hashing consumers, retaining the existing key layout and restricting in-order work to each run. Reviewed commit a3881cfab32025ffeebeb0f412fbb456fe087b16, the full diff, surrounding code, and all prior discussion. No actionable findings. The description supplies before/after measurements, and the new stateless test passes in the Fast test report.

Missing context / blind spots
  • ⚠️ This checkout has no ClickHouse build or test executable, so unit tests and benchmarks were not independently rerun. Validation of those runs relies on the author's reported results; execution of the new unit tests on the reviewed head would close the independent validation gap.
Final Verdict

Status: ✅ Approve. No new inline findings to post.

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

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @nickitat, could you review this? Nullable fixed-width key sets (nullable_keys128/256) are now batch-packed per block in the per-row nullable layout (zero bitmap, keys in clause order), only rows with a NULL are repacked per row, and nullable states get the sub-range variant from #120259 so the in-order paths pack only their run.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good.

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

GROUP BY with a nullable fixed-width key packs the key per row: packing once per block is 11% faster on TPC-DS query_65

3 participants