Repository navigation
Avoid a store-forwarding stall in SipHash for short inputs - #123658
Conversation
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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261003-070500 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261003-045600 |
|
Workflow [PR], commit [2fc5fc3] Summary: ✅
AI ReviewSummaryThis PR rewrites Missing context / blind spots
Final Verdict✅ No blocker or major issues found in the current patch. LLVM Coverage ReportMeasured on commit 2fc5fc3.
Changed lines: Changed C/C++ lines covered: 33/33 (100.00%) · Uncovered code |
|
📊 Cloud Performance Report
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. clickbenchFlagged queries (2 of 43)
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
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes422 object files changed (-483.46 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units2529 translation units recompiled, 14460 s compile time in total, 2528 of them have a recent master baseline. Symbol sizes
|
CI finish ledger - fa3bc48Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 157 check runs completed and Session id: cron:our-pr-ci-monitor:20261003-143124 |
|
Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774 |
What? Need to verify this. BTW, I was doing something similar for #123552 |
|
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, There is also a regression: 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: #123552 does not conflict ( |
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]>
|
Pushed 2fc5fc3. Release build without ThinLTO, cycles over 5 queries, master base -> before -> now: |
|
@snelheidai add a small budget umbrella to check if this idea can be reused in any other places |
|
@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 (
The patch below packs these key sets once per block with the existing Setup: hits (100M rows), Xeon 8375C with 4 vCPUs, Release build without ThinLTO. Server time, 12 interleaved pairs, ratio patch/master with 95% CI:
On master the 20-byte Sets made only of 8- and 16-byte keys stay per row, because their reads do forward. An earlier build batched every 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 I found no other streaming hash state fed in small pieces on a hot path besides
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)
{ |
|
@groeneai take a look at the suggestion above and open pr if it is correct |
|
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. |
|
@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 |

Related: #117704
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
SipHashbuilds 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 makesentropyanduniqExactwith several arguments faster on short strings. Hash values are unchanged.Description
entropy #2(SELECT entropy(MobilePhoneModel) FROM hits_100m_single) inPerformance 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.SipHashkept its partial word asunion { UInt64; UInt8[8]; }.updatestored a short tail byte by byte, andfinalizestored thecntbyte 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). InUniqVariadicHash::applythe state crosses the virtualupdateHashWithValuecall, so every row pays it, and how often the load is replayed depends on code placement.Now
current_wordis a plain little-endianUInt64: the tail is assembled in a register (two overlapping 4-byte loads for 4 to 7 bytes, constant shifts for 1 to 3), andfinalizefoldscntin 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_siphashand02552_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:ld_blocks.store_forwardCycles of other shapes, base -> this PR:
uniqExact(String, UInt64)-48%,(String, UInt64) IN-24%;sipHash64ofUInt8-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
26.10.1.2315-master(included in26.10and later)