Skip to content

Faster sipHash128 on String and FixedString columns - #129204

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
harikrishnan94:siphash128-many-strings
Nov 5, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
harikrishnan94:siphash128-many-strings

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #128972
Related: #129328

sipHash128 hashed a String column one row at a time. Inside one string SipHash is a serial chain of rounds, so most of the CPU’s width sat idle.

master, sipHash128 on String and FixedString columns
  rows     one string after another, with sipHash128Padded
  string   one 8-byte word at a time, two SipHash rounds per word
  rounds   one serial chain: each round waits for the one before

Now it hashes 8 rows side by side.

this PR
  group        8 strings hashed side by side
               aarch64: 4 strings in NEON lanes as two sets of 2, and 4 in general registers
               AVX2: all 8 in vector lanes, as two sets of 4
  String       blocks of 256 rows, sorted by length when that pays off
  FixedString  every 8 neighbouring rows form a group, with no sort
  hashes       the same as on master

For a user:

  1. sipHash128 is faster on String and FixedString columns. It is also faster on Nullable, LowCardinality, Array, Map and Tuple of them, because it hashes the String and FixedString columns inside them. The hashes do not change.
  2. There is no setting. Builds without NEON or AVX2 keep hashing one value at a time.
  3. sipHash128Keyed, sipHash128Reference and sipHash128ReferenceKeyed are unchanged. So are constant arguments, and the types that are serialized before hashing.

Sample queries, clickhouse local on m8g.24xlarge (Graviton 4), max_threads = 1, median of 5 runs:

CREATE TABLE strings_0_15 (s String) ENGINE = Memory;
INSERT INTO strings_0_15 SELECT substring(hex(cityHash64(number)), 1, number % 16) FROM numbers(20000000);
-- strings_16_64:     substring(repeat(hex(cityHash64(number)), 4), 1, 16 + number % 49) FROM numbers(4000000)
-- strings_0_300:     substring(repeat(hex(cityHash64(number)), 19), 1, number % 301) FROM numbers(1000000)
-- strings_1000_2000: substring(repeat(hex(cityHash64(number)), 125), 1, 1000 + number % 1001) FROM numbers(100000)
-- fixed_strings_16:  toFixedString(hex(cityHash64(number)), 16) FROM numbers(5000000), and the same for widths 8 and 64

SELECT count() FROM strings_0_15 WHERE NOT ignore(sipHash128(s)) SETTINGS max_threads = 1;
Table master this PR ratio
strings_0_15 226 ms 183 ms 0.81
strings_16_64 103 ms 57 ms 0.55
strings_0_300 77 ms 34 ms 0.44
strings_1000_2000 70 ms 27 ms 0.39
fixed_strings_8 63 ms 32 ms 0.51
fixed_strings_16 80 ms 38 ms 0.47
fixed_strings_64 188 ms 77 ms 0.41

The same query over 100M rows in one MergeTree part, master → this PR, by max_threads:

Column 1 16 96
FixedString(16) 1914 → 1075 ms (0.56) 125 → 73 ms (0.58) 34 → 27 ms (0.79)
FixedString(64) 5163 → 2911 ms (0.56) 329 → 189 ms (0.57) 78 → 55 ms (0.71)
String, 0-63 bytes 3277 → 2251 ms (0.69) 212 → 149 ms (0.70) 58 → 56 ms (0.97)

At 96 threads a query takes less than 80 ms, so the fixed cost of running a query weighs more.

Reading order: FunctionAnyHash::executeString, with hashes_many_strings and setHashes -> sipHash128PaddedStrings -> SipHashStrings::hashRows -> SipHashStrings::hashGroup -> LaneStates and ScalarState -> sipHash128PaddedFixedStrings.

How it works:

  1. SipHash reads a string one 8-byte word at a time. The rounds of each word depend on the state that the previous word left, so one string cannot be spread over vector lanes. Different strings do not depend on each other, though. So a group of 8 strings is hashed together, and every round runs on all of them at once.
  2. On aarch64 a group has 4 strings in NEON lanes, as two sets of 2, and 4 strings in general registers. So the vector units and the integer units both work. With AVX2 all 8 are in vector lanes, as two sets of 4. On Ice Lake the vector operations already fill the ports that the integer operations need, so no string goes in general registers. There are two sets because the rounds of one set form a chain, and the rounds of the other set fill its gaps.
  3. A group is hashed in three steps. First, all 8 strings compress their first words together, as many as the shortest string has. Second, the longer strings compress the rest of their full words. A vector cannot skip a lane, so a lane whose string has ended runs on the words of another string, then gets its state back. Its work is wasted. Third, all 8 strings take their last partial word, with the length in its top byte, and run the final rounds together again.
  4. The second step wastes work when the strings of a group differ in length. So a String column is hashed in blocks of 256 rows, and a block can first be sorted by the number of words in each string. A group then gets strings of similar lengths.
  5. The sort costs about as much as hashing one or two words per row, so a block is sorted only when that pays off. The block needs at least 16 rows, enough for two groups. At least 8 of its strings must have more words than the shortest one, enough to fill a group of their own. In a block of fewer than 32 rows, the longest and the shortest strings must also differ by at least 4 words.
  6. Strings shorter than 512 bytes count as equal only when they have the same number of words. When a block has at least 8 strings of 512 bytes or more, these count by length ratio. Each doubling of the length is split into 8 steps. With fewer than 8, all strings of 512 bytes or more count as one length.
  7. A FixedString column has one length, so it needs no second step and no sort. Every 8 neighbouring rows form a group, and the last rows that do not fill a group are hashed one at a time.
  8. To load the last partial word without a branch on its length, a lane reads the 8 bytes that end where its string ends. For a string shorter than 8 bytes, this read starts up to 8 bytes before the string. The strings in general registers, and the rows left after the last group, read up to 7 bytes past their end instead. The padding of ColumnString and ColumnFixedString covers both.
  9. sipHash128 of several arguments, or of a Tuple, combines the hash of each later column with the hashes so far. The batched hashes of such a column go to a temporary array first, and are then combined row by row.

Changelog category (leave one):

  • Performance Improvement

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

sipHash128 is faster on String and FixedString columns, and on Nullable, LowCardinality, Array, Map and Tuple of them: it hashes 8 values at a time with NEON on aarch64 and AVX2 on x86. The hashes do not change.


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

Version info

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

`sipHash128` hashes several strings of a `String` or `FixedString` column at
a time. The hashes do not change. On aarch64 a group holds 8 strings: 4 in
NEON lanes and 4 in general registers. With AVX2 all 8 are in vector lanes.

One loop compresses the first words of all the strings of a group, as many
as the shortest string has. Each vector then continues until its longest
string ends, so its shorter strings waste words. In a `String` column,
sorting the rows by length puts strings of similar lengths into the same
groups, at about the cost of hashing one or two words per row. So the rows
are sorted only when the longer strings can fill whole groups of their own.
That needs at least 16 rows, at least 8 of them with more words than the
shortest. With fewer than 32 rows, the longest and the shortest string must
also differ by at least 4 words. The strings of a `FixedString` column have
one length, so they waste no words and need no sort.

The code is in `SipHashStringsImpl.h`, written with clang vector extensions
and with plain loops that clang vectorizes. Its only intrinsic is the NEON
shift-and-insert `SRI` in the rotate, because clang does not generate it from
portable code. `sipHash128PaddedStrings` calls it 256 rows at a time.
`sipHash128PaddedFixedStrings` needs no offsets, length buckets or chunks. It
passes the strings to `hashGroup` 8 at a time and the last few rows to
`sipHash128Padded`. Builds without NEON or AVX2 hash the strings one by one.
The code reads up to 8 bytes before a string that is shorter than 8 bytes, and
up to 7 bytes past the end of any string. The padding of `ColumnString` and
`ColumnFixedString` covers both.

Every type that `sipHash128` hashes through a `String` or `FixedString` column
gets the faster path: `Nullable`, `LowCardinality`, `Array`, `Map` and `Tuple`
of them. `sipHash128Keyed`, `sipHash128Reference`, `sipHash128ReferenceKeyed`,
constant arguments and the types that are serialized before hashing keep
hashing one value at a time.

`sipHash128Keyed` with zero keys gives the same hashes, one string at a time.
The tests `05462_sip_hash_128_many_strings` and
`05493_sip_hash_128_fixed_strings` compare the two. The second one covers
`FixedString` widths 1 to 17 and 11 more up to 1000, in blocks with 0, 1 and
125 groups of 8 strings. `benchmark_sip_hash_strings` compares
`sipHash128PaddedStrings` and `sipHash128PaddedFixedStrings` with
`sipHash128Padded` per string. The performance test `sip_hash_128_strings`
measures `sipHash128` on `String` columns of several string lengths and on a
`FixedString(16)` column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 4, 2026 08:13
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de22684]

Summary: ✅


AI Review

Summary

PR #129204 accelerates sipHash128 for String and FixedString columns with NEON and AVX2 batching while preserving existing hashes. No actionable findings at head de2268436e1e0cf1898c88aa7d388f6740950b73. Both new compatibility tests passed in ARM CI; an additional 108 local ARM boundary cases matched the scalar implementation.

Missing context / blind spots
  • ⚠️ Native x86 AVX2 and sanitizer execution results were not yet available in the Praktika report. Completed compatibility-test runs on those builds would close this runtime-validation gap.
Final Verdict

Status: ✅ Approve. No required code changes identified; merge remains subject to normal CI completion.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 4, 2026

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

🔵 Needs a closer look

Stable hash equivalence and padded-read safety remain unverified for the NEON and AVX2 kernels because native regression and sanitizer results are unavailable on both architectures.

No open issues 🎉

What changed in this PR

This PR accelerates sipHash128 for String and FixedString columns by hashing eight values together, while preserving existing hash results. It separates the batched hashing work described in the related packed-string hash-join PR.

Changes:

  • Adds NEON and AVX2 hashing kernels, with length-based grouping for variable-length strings and scalar processing on other builds.
  • Integrates batched hashing into the SQL function, including supported nested column types.
  • Adds compatibility tests, performance queries, and microbenchmarks.
File Description
tests/​queries/​0_stateless/​05493_sip_hash_128_fixed_strings.sh Checks fixed-width hashes across widths, block sizes, and wrapper types.
tests/​queries/​0_stateless/​05493_sip_hash_128_fixed_strings.reference Records expected zero mismatches for fixed-width tests.
tests/​queries/​0_stateless/​05462_sip_hash_128_many_strings.sql Checks hash compatibility, nested types, multiple arguments, and batch boundaries.
tests/​queries/​0_stateless/​05462_sip_hash_128_many_strings.reference Records compatibility checksums and expected results.
tests/​performance/​sip_hash_128_strings.xml Benchmarks hashing across string lengths and realistic datasets.
src/​Functions/​FunctionsHashing.h Routes unkeyed sipHash128 string columns through batched hashing.
src/​Common/​SipHashStringsImpl.h Implements vector kernels, length buckets, and row grouping.
src/​Common/​SipHashStrings.h Declares batched hashing interfaces and padding requirements.
src/​Common/​SipHashStrings.cpp Implements column-level batching and scalar alternatives.
src/​Common/​benchmarks/​sip_hash_strings.cpp Compares batched and per-row hashing performance and results.
src/​Common/​benchmarks/​CMakeLists.txt Registers the hashing microbenchmark target.

Review effort: Balanced

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Nov 4, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Nov 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing de2268436 with master 7f11488e0 (stripped binary size, per-symbol sizes and ThinLTO time; 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

6 object files changed (+27.55 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/SipHashStrings.cpp.o new 23.60 KiB +23.60 KiB

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

13 translation units recompiled, 43 s compile time in total, 12 of them have a recent master baseline.

Job report

@harikrishnan94 harikrishnan94 changed the title Hash many strings at once in sipHash128 Faster sipHash128 on String and FixedString columns Nov 4, 2026
@alexey-milovidov alexey-milovidov self-assigned this Nov 4, 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.

Ok. I understand the algorithm. It is fairly clever. And the implementation is neat.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit dc0b52e Nov 5, 2026
366 of 367 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
@harikrishnan94
harikrishnan94 deleted the siphash128-many-strings branch November 5, 2026 02:50
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 7, 2026
…tring or IPv6

`uniqExact` stores `sipHash128Padded` of each `String` / `FixedString` value (IPv6 as its 16
bytes) and hashed one row at a time. Now a chunk of 256 rows first chooses the rows that get a
key exactly as before (NULL, false `-If`, null place and repeated (place, value) rows are
skipped), then hashes them with one call of the vectorized functions of ClickHouse#129204, and inserts the
keys in the same order. Fewer than 8 chosen rows are hashed one at a time, as those functions
would do anyway. The hashes, and so the serialized states, do not change. Builds without AVX2 or
NEON hash one row at a time inside the same functions.

Two row-list variants are added next to ClickHouse#129204's functions: `sipHash128PaddedStringRows`
(`SipHashStrings::hashRows` over a row list) and `sipHash128PaddedFixedStringRows`.

Converted call sites, chosen by measurement (ClickHouse#129436 item 5; 1, 16 and all threads, String
0-15 / 16-64 / 0-300 bytes, FixedString(16) / (64), IPv6, 3 ABAB rounds + 5-round re-runs of
cells above 1.03), fix / master time:
- GROUP BY without consecutive repeats (the ClickHouse#128190 fallback, before: one `add` per row):
  0.37-0.66 at 1 thread, 0.57-0.91 at 16 and all threads.
- `-If` true on 50-99% of the rows and `Nullable` without GROUP BY: 0.58-0.77 at 1 thread,
  0.63-0.92 at 16 and all threads.
- `-If` true on 1-10% of the rows without GROUP BY, 1-50% with GROUP BY: 0.77-1.03.
- No key, consecutive values rarely repeat (the last-value cache off), String and FixedString:
  0.69-1.02.
- GROUP BY with repeats (ClickHouse#128190) and no key with repeats (the last-value cache): 0.80-1.06.

Left out:
- No key without repeats for IPv6: 1.098 on 20M distinct values after a 5-round re-run.
- A `UInt8` key (`addBatchLookupTable8` is `final` in the data helper), `Nullable` with GROUP
  BY and `-If` with a `UInt8` key (combinator code), `-StateIf` (the `-State` inside `-If` adds
  one row at a time), the radix `uniqExact` (separate change), variadic `uniqExact` (ClickHouse#129435).

`sip_hash_128_strings.xml` gets an `IPv6` table and these shapes, including `-If` true on 50% and
on 1% of the rows, and no key without repeats.

Related: ClickHouse#129436

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Nov 24, 2026
The route of the radix partitioned `uniqExact` hashed each `String` of 16 bytes
or more, and each `FixedString` longer than 16 bytes (other than 32), with one
serial `sipHash128Padded` per row. Now the rows of a batch of 256 that need a
hash are collected and hashed together by the vector code of ClickHouse#129204
(`SipHashStrings::hashRows` for `String`, `hashGroup` for `FixedString`), on
x86 with AVX2 and aarch64 with NEON. The keys are unchanged (the same
`SipHash`, with `LONG_STRING_KEY_BIT` for strings), and so is their order:
the rows of a batch from its first long row on wait for the batch to be
hashed, so the inserts, the recent-keys cache and the statistics see the same
sequence of keys as before. Shorter strings stay packed and are routed by the
same loop as before until the first long row of a batch.

The hashing lambdas are out of line and capture by value: inlined, their
vector constants were kept in registers across the routing loops and reloaded
after every `memcmp` call of the duplicate check (+8% instructions on 64
repeated long strings), and the by-reference captures made the loops reload
the column pointers from the stack.

Debug builds cross-check every batched hash against `sipHash128Padded`.
Builds without AVX2 or NEON keep the per-row hashing.

Measured on Xeon 6975P-C, default settings, 1 thread: 16-64 byte strings
0.87x, 0-300 bytes 0.66x, `FixedString(64)` 0.74x of the time; strings of up
to 15 bytes +3% to +9% instructions, within 1-2% of the time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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... 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.

4 participants