Skip to content

Avoid a store-forwarding stall in SipHash for short inputs - #123658

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:siphash-tail-in-register
Oct 13, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:siphash-tail-in-register

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117704

Changelog category (leave one):

  • Performance Improvement

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

SipHash builds the last incomplete 8-byte word of its input in a register instead of with byte stores, which avoids a store-forwarding stall on short inputs. This makes entropy and uniqExact with several arguments faster on short strings. Hash values are unchanged.

Description

entropy #2 (SELECT entropy(MobilePhoneModel) FROM hits_100m_single) in Performance Comparison (amd_release) flips between ~0.33 s and ~0.52 s with the build, not the diff (report on #117704): master was slow from 4f8c9f2 to a0b6517, and builds of #117704 and two unrelated PRs drew the slow mode.

SipHash kept its partial word as union { UInt64; UInt8[8]; }. update stored a short tail byte by byte, and finalize stored the cnt byte and then read the whole word with one 8-byte load. Such a load cannot be store-forwarded from narrower in-flight stores, so it waits until they reach L1 (ld_blocks.store_forward). In UniqVariadicHash::apply the state crosses the virtual updateHashWithValue call, so every row pays it, and how often the load is replayed depends on code placement.

Now current_word is a plain little-endian UInt64: the tail is assembled in a register (two overlapping 4-byte loads for 4 to 7 bytes, constant shifts for 1 to 3), and finalize folds cnt in a register. A throwaway differential test against the old class found 0 mismatches in 2.0M cases, and 808k with a planted bug that only affects 4-byte tails. 02534_keyed_siphash and 02552_siphash128_reference (official vectors) pass.

Local, release build without ThinLTO, 100M rows of a 92% empty sparse String, max_threads=16, counters over 15 queries:

binary cycles ld_blocks.store_forward
official 562bdc1 (fast layout) 1.38e11 1.54e9
official 4f8c9f2 (slow layout) 2.14e11 6.07e9
base of this PR 1.49e11 1.54e9
this PR 9.9e10 2.8e7

Cycles of other shapes, base -> this PR: uniqExact(String, UInt64) -48%, (String, UInt64) IN -24%; sipHash64 of UInt8 -2.5%, UInt16 -6%, UInt32 -7%, 1-3 byte strings -3%.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2315-master (included in 26.10 and later)

groeneai and others added 2 commits October 3, 2026 06:55
SipHash kept the current partial 8-byte word as a union of a UInt64 and
UInt8[8]. `update` wrote a short tail byte by byte into the byte array
(the remainder of a previous update too, which clang emits as a `memcpy`),
and `finalize` stored the `cnt` byte into the last position and then read
the whole word with one 8-byte load. An 8-byte load that overlaps several
narrower in-flight stores cannot be store-forwarded on x86: it waits until
the stores commit (`ld_blocks.store_forward`). When the hash state lives in
memory across a call, e.g. `UniqVariadicHash::apply` -> virtual
`IColumn::updateHashWithValue` -> `get128`, every row pays this. How often
the blocked load is replayed depends on code placement, so the same
machine code is fast in one build and ~55% slower in another: this is why
`entropy ClickHouse#2` of the performance comparison flips between ~0.33 s and
~0.52 s per build on amd (master builds 4f8c9f2..a0b6517, and
PR builds of ClickHouse#117704, ClickHouse#114690, ClickHouse#119760).

Now `current_word` is a plain UInt64 holding the received bytes of the
current word in little-endian order, the bytes not received yet being zero
(the same numeric value the union had on both endiannesses, so
CURRENT_BYTES_IDX is gone). `loadTail` assembles up to 7 bytes in a
register with overlapping 4/1-byte loads, the remainder path ORs it in at
the right shift, the main loop keeps the word in a local, and `finalize`
folds `cnt` into the top byte in a register. Every access to `current_word`
is now a whole-word store followed by a whole-word load. Hash values are
unchanged.

Validation (release build, CMAKE_BUILD_TYPE=None without ThinLTO, Xeon
6975P, `SELECT entropy(MobilePhoneModel)` over 100M rows of a 92%-empty
sparse String column, max_threads=16, medians of 18 runs):
- base 0.218 s, fix 0.150 s; official master builds 562bdc1
  0.204 s (fast layout) and 4f8c9f2 0.285 s (slow layout).
- 15 queries: ld_blocks.store_forward base 1.54e9, fix 2.7e7 (slow official
  6.07e9); cycles 1.44e11 -> 8.98e10; instructions 5.27e11 -> 4.71e11.
- `uniqExact(toString(number % 1000), toString(number % 7))` over 2e8 rows
  5.23 s -> 2.98 s; sipHash64/sipHash128 of 1..5-byte strings -6.4%/-4.8%;
  sipHash64 of 10..50-byte strings +1.1% (instructions +1.8%); GROUP BY
  two String keys unchanged.
- Hash identity: a throwaway differential gtest against the verbatim
  previous class (every length 0..80 x every 3-way split, 3 key pairs,
  get64/get128/get128Reference, double get, update after get, the
  ColumnString row shape, 300k random streams of raw and typed updates):
  2,038,362 cases, 0 mismatches; a planted mutation (wrong value for 4-byte
  tails only) gives 808,592 mismatches. 02534_keyed_siphash and
  02552_siphash128_reference (official vectors) pass, and SQL sums of
  sipHash64/128, keyed and reference variants over 2e7 strings are equal on
  both binaries.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) and a separate cold review of the diff (0 blocker/major findings).

# Sev Finding Verdict Evidence / action
- - none - Traced: loadTail for sizes 0..7 reads only [data, data + size); bytes at positions >= cnt & 7 of current_word are zero at every exit of update, so the remainder `

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

Session id: cron:clickhouse-review-slot-9:20261003-070500

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: ld_blocks.store_forward over 15 entropy(MobilePhoneModel) queries on a 100M-row sparse String column is stable to <0.5% per binary (base 1.54e9, slow official build 6.07e9, this PR 2.7e7).
b Root cause explained? finalize stored the cnt byte and update stored the tail byte by byte into a union, then the word was read with one 8-byte load, which cannot be store-forwarded from narrower in-flight stores. The state crosses a virtual call per row, and the replay count depends on code placement.
c Fix matches root cause? Yes: the tail is assembled in a register and cnt folded in a register inside SipHash, so every access to the word is a whole-word store and load.
d Test intent preserved / new tests added? No behaviour change, so no new test: hash values are pinned by 02534_keyed_siphash / 02552_siphash128_reference (official vectors 0..63) and gtest_sip_hash.cpp. A throwaway differential test against the old class found 0 mismatches in 2,038,362 cases (808,592 with a planted 4-byte-tail bug).
e Both directions demonstrated? Base vs this PR, same flags: 0.218 -> 0.150 s, blocks 1.54e9 -> 2.7e7, cycles 1.44e11 -> 8.98e10.
f Fix is general across code paths? All writers of the partial word changed (remainder of a previous update, main loop, tail, finalize); get128Reference and the typed/string overloads go through them.
g Fix generalizes across inputs (params/datatypes/wrappers)? Every length 0..80 and 3-way split, empty and nullptr input, exact-size buffers, keyed and reference-128, typed updates up to UInt128, the ColumnString row shape.
h Backward compatible? (maintainer-approved exception only) Yes: hash values are bit-identical (also checked end to end with SQL sipHash* sums); no setting or format change.
i Invariants and contracts preserved? The word holds the received bytes little-endian with the rest zero, on every path; finalize no longer mutates it, and a double get or an update after get match the old values; loadTail reads only [data, data + size).

Session id: cron:clickhouse-impl-slot-7:20261003-045600

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2fc5fc3]

Summary: ✅


AI Review

Summary

This PR rewrites SipHash's short-tail handling so streaming updates keep the incomplete word as a UInt64 assembled with little-endian loads instead of byte stores into a union. I did not find any blocker or major issue in the current diff: the new loadTail / current_word path preserves the same sequence of 8-byte words and the same final tail word across repeated update calls, so the promised contract of unchanged hash values with lower short-input overhead still holds.

Missing context / blind spots
  • ⚠️ Build (arm_tidy, 1/4) through Build (arm_tidy, 4/4) were still in progress at review time, so I do not have final cross-toolchain CI confirmation from this run.
Final Verdict

✅ No blocker or major issues found in the current patch.

LLVM Coverage Report

Measured on commit 2fc5fc3.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 33/33 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 32 queries analysed

This PR changes only SipHash: the last 1-7 bytes of input are now loaded straight into a register instead of being written one byte at a time, which avoids a store-forwarding stall. That should speed up hashing of short strings slightly. Two ClickBench queries got faster with lower CPU time: Q33 by -7.8% and Q34 by -10.7%. Both are rated not_sure because master's own timings for these queries shifted around 2026-10-08, so this comparison cannot credit the PR. I also could not confirm that these two GROUP BY queries spend much time in SipHash. No other queries moved in either clickbench or tpch_adapted_1_official, and no regressions were flagged.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1143 1054 -7.8% 0.0001 aggregation: CPU time fell from 16252 to 15025 ms (-7.8%), but master shifted on this query around 2026-10-08, so this baseline cannot pin the drop on the SipHash tail-load change.
⚠️ 34 not_sure 1141 1019 -10.7% <0.0001 aggregation: CPU time fell from 16235 to 14831 ms (-10.7%), matching Q33. Master shifted on this query around 2026-10-08, so the change cannot be attributed to this PR yet.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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: f1687e25-3f5b-45d6-9bb8-bdcbeebc8c3d
  • MIRAI run: cefc07d3-c4f5-490e-afb2-c66857a930da
  • PR check IDs:
    • clickbench_384596_1791474662
    • clickbench_384602_1791474662
    • clickbench_384608_1791474662
    • tpch_adapted_1_official_384619_1791474662
    • tpch_adapted_1_official_384632_1791474662
    • tpch_adapted_1_official_384667_1791474662

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2fc5fc32b with master 6c500b977 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4a89b4b71; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

422 object files changed (-483.46 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/FormatFactory.cpp.o 1.71 MiB 1.49 MiB -226.89 KiB (-12.92%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsJSON.cpp.o 4.30 MiB 4.24 MiB -58.22 KiB (-1.32%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsHashingMisc.cpp.o 5.47 MiB 5.52 MiB +52.73 KiB (+0.94%)
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryConditionCache.cpp.o 293.07 KiB 264.43 KiB -28.64 KiB (-9.77%)

719 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

2529 translation units recompiled, 14460 s compile time in total, 2528 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper DB::getFormatSettingsHash(DB::Settings const&) 527.28 KiB 430.57 KiB -96.71 KiB (-18.34%)
programs/clickhouse DB::getFormatSettingsHash(DB::Settings const&) 527.28 KiB 430.57 KiB -96.71 KiB (-18.34%)

Job report

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fa3bc48

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05218_timeseries_alp_codec flaky: timeSeriesSamples(ts_alp32) resolves the target as default.ts_alp32 on a parallel replica (Code: 60 UNKNOWN_TABLE); 11 PRs in the last 24 hours on this new job #118518 (external, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database (the rerun does not use one, so it passes there): the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 52 PRs in the last 24 hours on this new job a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #118518 and the fix task above

All 157 check runs completed and Finish Workflow is green; CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261003-143124

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@Algunenano

Copy link
Copy Markdown
Member
image

What? Need to verify this. BTW, I was doing something similar for #123552

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Verified, the speedups are from this PR: for 20 of the 21 rows, at most 2 of the 121 to 1348 runs of the same query on other PRs between 2026-10-02 and 2026-10-05 moved as much (their 2nd to 98th percentiles are within ±8%); the 21st, json_to_string on arm, is noise. These queries hash short values with the streaming SipHash (updateHashWithValue, e.g. UniqVariadicHash<true, ...> for entropy and uniqExact(Decimal32), the hashed method for (String, UInt64) IN), and each hash ended with an 8-byte load of a word just written byte by byte, which cannot be store-forwarded.

There is also a regression: distributed_aggregation queries 1 and 3, count(sipHash64(zero)) on a 1-byte UInt8, +15.5%/+13.5% on amd and +10.4%/+7.6% on arm, slower than any other run. Locally with the CI binaries: +11% instructions and +16% cycles, all in the out-of-line sipHash64Keyed (executeIntType is identical). There master already builds the tail in a register (the switch is a jump table of byte loads, no store), so for 1 to 3 bytes the variable shifts here only add instructions.

I'll push a fix: constant shifts for 1 to 3 bytes, overlapping loads kept for 4 to 7. Standalone benchmark of the one-shot function, 10^8 calls: UInt8 0.727 s on master, 0.807 s now, 0.736 s with the fix; UInt32 and random 0 to 7 byte strings stay 7% and 11% faster than master; the updateHashWithValue path keeps 2.1 -> 1.37 s.

#123552 does not conflict (git merge-tree is clean): sipHash128Padded may read past size thanks to the padding, the SipHash class may not, hence the overlapping loads here.

The out-of-line one-shot `sipHash64Keyed` gets a size that is not known at
compile time. On master its `switch` already compiled to a jump table of byte
loads into a register, so the overlapping loads with variable shifts only added
instructions for 1 to 3 bytes: `count(sipHash64(zero))` on `UInt8` in the
`distributed_aggregation` perf test was 8-16% slower (+11% instructions,
+16% cycles with the CI binaries).

Keep the two overlapping 4-byte loads for 4 to 7 bytes and switch on the size
below that. Hash values are unchanged (differential test against the previous
class: 2,038,362 cases, 0 mismatches).

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

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 2fc5fc3. Release build without ThinLTO, cycles over 5 queries, master base -> before -> now: count(sipHash64(zero)) 14.4e9 -> 16.5e9 -> 14.1e9; entropy 48.7e9 -> 30.8e9 -> 32.5e9; uniqExact(String, UInt64) 137e9 -> 70e9 -> 71e9. Hash values are unchanged (2.0M-case differential test, 02534/02552 vectors, and SQL hashes identical to the official master build).

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

Changes look good

@Algunenano
Algunenano added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit 7821529 Oct 13, 2026
152 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
@egor-click

Copy link
Copy Markdown
Contributor

@snelheidai add a small budget umbrella to check if this idea can be reused in any other places

@snelheidai

Copy link
Copy Markdown

@egor-click One more hot path writes a value in narrow pieces and reads it back as a wider word: fixed-width keys of 17 to 32 bytes (keys256) in GROUP BY, DISTINCT, IN and JOIN.

HashMethodKeysFixed packs such a key row by row into a 32-byte stack slot: it zero-fills the slot, writes each column with a 1-, 2-, 4- or 8-byte store, and the hash then reads the slot back as four 8-byte words. When a key is narrower than 8 bytes, some of those reads span several stores and cannot be store-forwarded. Non-LowCardinality keys of up to 16 bytes avoid this (they are batch-packed or built with an SSSE3 shuffle), and nullable keys have avoided it since #126098.

The patch below packs these key sets once per block with the existing packFixedBatchOrdered, in clause order, so the packed bytes and hash values are the same as on the per-row path.

Setup: hits (100M rows), Xeon 8375C with 4 vCPUs, Release build without ThinLTO. Server time, 12 interleaved pairs, ratio patch/master with 95% CI:

GROUP BY key bytes groups master, ms patch, ms ratio
UserID, CounterID, RegionID, EventDate 8+4+4+2 22.1M 1326 1140 0.858 [0.827, 0.890]
EventDate, OS, UserAgent, TraficSourceID, SearchEngineID, AdvEngineID, IsRefresh, ResolutionWidth, ResolutionHeight 9×2 794K 2445 2017 0.824 [0.815, 0.834]
CounterID, RegionID, EventDate, SearchEngineID, OS, UserAgent, TraficSourceID 4+4+5×2 8.0M 2008 1802 0.874 [0.836, 0.914]
numbers_mt(1e8): UInt32, UInt64, UInt64 4+8+8 91K 1983 1194 0.606 [0.569, 0.645]
same, UInt64 ×3 (path unchanged) 8+8+8 91K 1453 1452 1.001 [0.977, 1.026]
UserID, CounterID (keys128, path unchanged) 8+4 20.8M 628 637 1.031 [0.997, 1.066]

On master the 20-byte UInt32, UInt64, UInt64 key takes 36% longer than the 24-byte UInt64 ×3 key with the same rows and groups, and the per-row work differs only in the store width. That gap is the stall. This VM exposes no PMU, so I could not read ld_blocks.store_forward. The evidence is the disassembly (byte, word and dword stores into the slot followed by 8-byte reloads), this contrast, and the unchanged controls.

Sets made only of 8- and 16-byte keys stay per row, because their reads do forward. An earlier build batched every keys256 set longest first, which changes the packed bytes and their hashes, so I dropped it. It gave 0.81, 0.82, 0.86 and 0.53 on the first four rows. On UInt64 ×3 it gave 0.76 with 91K groups but 1.024 [1.004, 1.045] with 10M unique keys, which is the e, f, g query of group_by_fixed_keys.xml.

Results match master (hash of the full result) for these queries and also for DISTINCT and GROUP BY in order, external and two-level aggregation, JOIN, IN, and a UInt128 key inside keys256. The 250 related gtests pass, including a new one that checks the batch layout equals the per-row layout.

I found no other streaming hash state fed in small pieces on a hot path besides SipHash. Two places have the same pattern but were not measured:

  • LowCardinality fixed-width keys (low_cardinality_keys128/256) still pack per row.
  • Serialized keys that are serialized one row at a time are hashed right after being written. On x86 the default method does this when a block's keys exceed 4× L2 or average at least 128 bytes per row.
Patch (measured on master 7a516a1; applies unchanged to 7b5f2bf)
diff --git a/src/Common/ColumnsHashing/HashMethod.h b/src/Common/ColumnsHashing/HashMethod.h
index 66862cd66a5..bd59c475112 100644
--- a/src/Common/ColumnsHashing/HashMethod.h
+++ b/src/Common/ColumnsHashing/HashMethod.h
@@ -518,21 +518,30 @@ struct HashMethodKeysFixed
         return true;
     }
 
-    /// Nullable keys are batch-packed in clause order, the layout of the per-row nullable `packFixed`, so
-    /// `packedKeysOrder` stays empty for them.
+    /// Nullable keys, and non-nullable keys256 with a key narrower than 8 bytes, are batch-packed in clause
+    /// order, the layout of the per-row `packFixed`, so `packedKeysOrder` stays empty for them.
     static bool useOrderedPreparedKeys(const Sizes & key_sizes)
     {
-        if constexpr (!has_nullable_keys || has_low_cardinality)
+        if constexpr (has_low_cardinality || (!has_nullable_keys && sizeof(Key) <= 16))
             return false;
         else
         {
-            size_t packed_size = std::tuple_size_v<KeysNullMap<Key>>;
+            size_t packed_size = 0;
+            if constexpr (has_nullable_keys)
+                packed_size = std::tuple_size_v<KeysNullMap<Key>>;
+            bool has_narrow_key = false;
             for (auto size : key_sizes)
             {
                 if (size != 1 && size != 2 && size != 4 && size != 8 && size != 16)
                     return false;
                 packed_size += size;
+                has_narrow_key |= size < 8;
             }
+            /// Packing a row of a non-nullable keys256 writes a key narrower than 8 bytes with a narrow store, and
+            /// the hash then reads the 8-byte word holding it, which cannot be store-forwarded from the narrower
+            /// stores. Keys of 8 and 16 bytes are read back whole, and packing those per row is cheaper.
+            if (!has_nullable_keys && !has_narrow_key)
+                return false;
             return packed_size <= sizeof(Key);
         }
     }
@@ -592,6 +601,16 @@ struct HashMethodKeysFixed
                 }
             }
         }
+        else if constexpr (!has_nullable_keys && !has_low_cardinality && sizeof(Key) > 16)
+        {
+            if (useOrderedPreparedKeys(key_sizes))
+            {
+                const RowRange packed = rowsToBatchPack(key_columns, rows);
+                if (packed.end > packed.begin)
+                    packFixedBatchOrdered<Key>(
+                        keys_size, Base::getActualColumns(), key_sizes, 0, prepared_keys, packed.begin, packed.end);
+            }
+        }
 
 #if defined(__SSSE3__) && !defined(MEMORY_SANITIZER)
         else if constexpr (!has_low_cardinality && !has_nullable_keys && sizeof(Key) <= 16)
@@ -680,7 +699,11 @@ struct HashMethodKeysFixed
                     const size_t index = row - prepared_keys_begin;
                     if (index < prepared_keys.size())
                         return prepared_keys[index];
-                    return packFixedLongestFirst<Key>(row, keys_size, Base::getActualColumns(), key_sizes);
+                    /// keys256 is batch-packed in clause order (`useOrderedPreparedKeys`), keys128 and smaller longest first.
+                    if constexpr (sizeof(Key) > 16)
+                        return packFixed<Key>(row, keys_size, Base::getActualColumns(), key_sizes);
+                    else
+                        return packFixedLongestFirst<Key>(row, keys_size, Base::getActualColumns(), key_sizes);
                 }
             }
 
@@ -798,7 +821,7 @@ template <typename Value, typename Key, typename Mapped, bool has_nullable_keys,
 struct SubRangeStateOf<HashMethodKeysFixed<Value, Key, Mapped, has_nullable_keys, has_low_cardinality, use_cache, need_offset, false>>
 {
     using Type = HashMethodKeysFixed<Value, Key, Mapped, has_nullable_keys, has_low_cardinality, use_cache, need_offset,
-        !has_low_cardinality && (has_nullable_keys || sizeof(Key) <= 16)>;
+        !has_low_cardinality && (has_nullable_keys || sizeof(Key) <= 32)>;
 };
 
 /// Bitwise comparator of rows over fixed-width contiguous key columns, flattening tuples
diff --git a/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp b/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
index 3287816341f..1ea9615cc03 100644
--- a/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
+++ b/src/Interpreters/tests/gtest_columns_hashing_prepared_keys.cpp
@@ -21,11 +21,11 @@ namespace
 using WholeBlockState = SetMethodKeysFixed<ClearableHashSet<UInt128, UInt128HashCRC32>>::State;
 /// The state DISTINCT in order builds per equal-range of the sorting prefix (`SetVariants.h` keys128).
 using PreparedState = ColumnsHashing::SubRangeState<WholeBlockState>;
-/// Three of them need 24 bytes, which leaves that class, so they have no sub-range variant.
+/// Three of them need 24 bytes: a keys256 set without a key narrower than 8 bytes is packed per row.
 using UnpreparedState = ColumnsHashing::SubRangeState<SetMethodKeysFixed<ClearableHashSet<UInt256, UInt256HashCRC32>>::State>;
 
 static_assert(!std::is_same_v<PreparedState, WholeBlockState>);
-static_assert(std::is_same_v<UnpreparedState, SetMethodKeysFixed<ClearableHashSet<UInt256, UInt256HashCRC32>>::State>);
+static_assert(!std::is_same_v<UnpreparedState, SetMethodKeysFixed<ClearableHashSet<UInt256, UInt256HashCRC32>>::State>);
 
 /// Nullable keys128 and keys256 sets: packed in clause order after a 2- and a 4-byte NULL bitmap.
 using NullableWholeBlockState128 = SetMethodKeysFixed<ClearableHashSet<UInt128, UInt128HashCRC32>, true>::State;
@@ -362,6 +362,30 @@ TEST(ColumnsHashingPreparedKeys, WiderKeyIsNotBatched)
     EXPECT_FALSE(state.covers_sub_range);
 }
 
+/// Two 8-byte keys and a 4-byte one need keys256, and the 4-byte key makes the set batch-packed in clause
+/// order, the layout the per-row packer of a short sub-range produces.
+TEST(ColumnsHashingPreparedKeys, WiderKeyWithNarrowColumnIsBatched)
+{
+    KeyColumns keys(2, num_long_rows);
+    auto narrow = ColumnUInt32::create();
+    for (size_t row = 0; row < num_long_rows; ++row)
+        narrow->getData().push_back(static_cast<UInt32>(row * 7 + 1));
+    keys.holders.emplace(keys.holders.begin(), std::move(narrow));
+    keys.columns.insert(keys.columns.begin(), keys.holders.front().get());
+    keys.sizes.insert(keys.sizes.begin(), sizeof(UInt32));
+
+    Arena arena;
+    const size_t range_begin = 100;
+    UnpreparedState whole_block(keys.columns, keys.sizes, nullptr);
+    UnpreparedState below_threshold(keys.columns, keys.sizes, nullptr, {range_begin, range_begin + min_batched_rows - 1});
+
+    ASSERT_EQ(whole_block.prepared_keys.size(), num_long_rows);
+    ASSERT_TRUE(below_threshold.prepared_keys.empty());
+    ASSERT_TRUE(below_threshold.covers_sub_range);
+    for (size_t row = range_begin; row < range_begin + min_batched_rows - 1; ++row)
+        ASSERT_EQ(below_threshold.getKeyHolder(row, arena), whole_block.getKeyHolder(row, arena)) << "row " << row;
+}
+
 /// A nullable whole block is batch-packed, and the bitmap bit of a NULL row is in the array itself.
 TEST(ColumnsHashingPreparedKeys, NullableWholeBlockIsBatched)
 {

@egor-click

Copy link
Copy Markdown
Contributor

@groeneai take a look at the suggestion above and open pr if it is correct

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm verifying the keys256 batch-packing suggestion above (same packed bytes and hashes as per-row packing, plus single- and multi-thread A/B with store-forwarding counters, including GROUP BY in order and hash JOIN); I'll follow up here with a PR or my measured findings.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

@egor-click The suggestion holds up, so I opened #130251 based on @ snelheidai's patch. The batch-packed bytes and hashes equal the per-row ones (gtests against the per-row packFixed), ld_blocks.store_forward per row drops from 9.2 to 0.002 on GROUP BY UInt32, UInt64, UInt64, and that query takes 0.52x / 0.43x / 0.65x of master's time at 1 / 8 / 32 threads; with 10M groups the gain fades to 0.98x at 8+ threads.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I closed #130251 in favour of #131393. Its third commit packs the same keys256 sets without Nullable, now in cache-sized chunks right before use (0.32x-0.67x of master's time on x86), and the PR extends the same packing to nullable keys256 and to key columns of other widths such as FixedString(3).

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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants