Skip to content

Faster hash joins on a single String key with a large right side - #128972

Merged
harikrishnan94 merged 13 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-keys-parallel-hash-join
Nov 11, 2026
Merged

harikrishnan94 merged 13 commits into
ClickHouse:masterfrom
harikrishnan94:packed-string-keys-parallel-hash-join

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #129329
Related: #129204
Related: #129328

A hash join on a single String key keeps its right rows in the key_string map. The build copies each distinct key into an arena. A cell holds the address and length of the copy, the saved hash and the row reference. A lookup compares the saved hash first, then the bytes of the copy. So a lookup that finds its key reads both the cell and the copy. These maps do not prefetch.

master, key_string and two_level_key_string maps
  build      copies each distinct key into the arena
  cell       the address (8 bytes) and length (8 bytes) of the copy, the saved hash (8 bytes), the row reference
  lookup     compares the saved hash, then the bytes of the copy in the arena
  prefetch   off: a prefetch would hash every key a second time

With this PR, such a join stores each key in 16 bytes, in the cell itself.

this PR, key_packed_string and two_level_key_packed_string maps
  key        16 bytes, no copy in the arena
             up to 15 bytes: the string itself, with its length in byte 15
             16 bytes or more: its 128-bit SipHash, with bit 7 of byte 15 set as a flag
  cell       the key and the row reference, no saved hash
  lookup     compares two 8-byte words
  hashing    the keys of up to 256 rows are built at once
             the long strings are hashed 8 at a time (NEON on aarch64, AVX2 on x86)
  prefetch   on: the prefetch and the lookup read the same built key
the 16-byte key, byte 15 is a tag byte
  up to 15 bytes     bytes 0..14   the string, then zeros
                     byte 15       bit 7 = 0, bits 3..6 = the length, bits 0..2 = 0
  16 bytes or more   bytes 0..15   the 128-bit SipHash of the string
                     byte 15       bit 7 forced to 1, so 127 bits of the hash are left
  empty string       all 16 bytes are zero

For a user:

  1. Hash joins on a single String key are faster when the right side is large. This covers hash, parallel_hash and grace_hash, and the spilling join that switches to grace_hash. It also covers ASOF joins, and OR joins whose every condition has a single String key. A Nullable(String) key compared with = counts as a String key.
  2. The hash table is smaller, so such a join reaches max_bytes_in_join and max_bytes_before_external_join later.
  3. enable_packed_string_keys_in_hash_join turns this on. It is on by default. With min_rows_for_packed_string_keys_in_hash_join, 100000 by default, a join whose right side is estimated at fewer rows keeps exact keys. A small hash table stays in the CPU cache, and there hashing the long keys costs more than packed keys save. The estimate is the one that parallel_hash_join_threshold uses. A join without an estimate uses packed keys. Some joins above the minimum are still slower with packed keys.
  4. Two different keys of 16 bytes or more match as equal when their hashes agree in the other 127 bits. For n distinct long keys the chance is about n^2/2^128, the same trade-off that Type::hashed already makes for composite keys. Keys of up to 15 bytes are compared exactly. With enable_packed_string_keys_in_hash_join = 0, all keys are compared exactly.
  5. Keys of 256 bytes or more can be slower than exact keys, when the left keys repeat and stay in the CPU cache. A packed key hashes the whole string, and SipHash costs more per byte than the hash and compare of an exact key. The packed key saves a cache miss on the right-side string, but only when that string is not cached. Long keys are rare in joins. enable_packed_string_keys_in_hash_join = 0 keeps exact keys.
  6. enable_software_prefetch_in_join now covers these joins too. The prefetch leaves out the rows that the join skips: those with a NULL key or a false ON condition.
  7. Tables with the Join engine, joinGet and joins that run from a serialized query plan keep exact keys. FixedString keys, LowCardinality(Nullable(String)) keys and a LowCardinality(String) key that uses the map of its dictionary keep their maps.
  8. Builds without NEON or AVX2 hash the long keys one at a time.
  9. The ProfileEvents JoinPackedStringKeysInline and JoinPackedStringKeysHashed count the keys that joins insert inline (up to 15 bytes) and as a hash (16 bytes or more). A join with OR counts a key for each condition. A row that is inserted again counts again: after a grace_hash join splits its buckets, or after a spilling join switches to grace_hash.
  10. Joins on other keys and IN sets are unchanged.

Sample joins on a single String key, clickhouse local, m8g.24xlarge (Graviton 4), median of 3 processes x 3 runs:

CREATE TABLE r (s String, v UInt64) ENGINE = Memory;
CREATE TABLE l (s String) ENGINE = Memory;
-- Short keys, 6-12 bytes, stored inline. The left side has 10M rows and every row matches.
INSERT INTO r SELECT concat('user_', toString(number)), number FROM numbers(10000000);
INSERT INTO l SELECT concat('user_', toString((number * 7919) % 10000000)) FROM numbers(10000000);
-- Long keys, 35-41 bytes, stored as their hash: concat('https://example.com/products/item/', toString(number)).
-- About 500 bytes: concat(repeat('x', 500), toString(number)), 200K right rows and 2M left rows.
-- No matches: the left keys come from another range, toString((number * 7919) % 10000000 + 100000000).

SELECT count(), sum(r.v) FROM l INNER JOIN r ON l.s = r.s
SETTINGS join_algorithm = 'parallel_hash', max_threads = 16,
    max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0, query_plan_join_swap_table = 'false';

Every left row matches, master → this PR:

Keys Right rows 1 thread 16 threads 96 threads
short 1M 958 → 379 ms (0.40) 72 → 32 ms (0.44) 41 → 29 ms (0.71)
short 10M 2326 → 1334 ms (0.57) 165 → 102 ms (0.62) 90 → 69 ms (0.77)
long 1M 1060 → 551 ms (0.52) 91 → 44 ms (0.48) 49 → 32 ms (0.65)
long 10M 2621 → 1838 ms (0.70) 211 → 122 ms (0.58) 111 → 73 ms (0.66)
500 bytes 200K 737 → 308 ms (0.42) 100 → 63 ms (0.63) 83 → 56 ms (0.67)

No left row matches:

Keys Right rows 1 thread 16 threads 96 threads
short 1M 409 → 339 ms (0.83) 33 → 29 ms (0.88) 31 → 28 ms (0.90)
short 10M 1684 → 1426 ms (0.85) 111 → 94 ms (0.85) 72 → 61 ms (0.85)
long 1M 477 → 454 ms (0.95) 39 → 37 ms (0.95) 32 → 29 ms (0.91)
long 10M 2111 → 1744 ms (0.83) 152 → 110 ms (0.72) 91 → 68 ms (0.75)
500 bytes 200K 260 → 237 ms (0.91) 64 → 56 ms (0.88) 70 → 58 ms (0.83)

Peak memory of the join query, master → this PR. The left side has one row, so only the build counts. The master column is the exact-key maps that enable_packed_string_keys_in_hash_join = 0 selects:

Keys Right rows 1 thread 16 threads 96 threads
short 1M 80 → 48 MiB (0.60) 90 → 70 MiB (0.78) 89 → 78 MiB (0.88)
short 10M 640 → 384 MiB (0.60) 657 → 416 MiB (0.63) 698 → 584 MiB (0.84)
long 1M 128 → 49 MiB (0.38) 143 → 71 MiB (0.49) 136 → 79 MiB (0.58)
long 10M 1024 → 384 MiB (0.38) 1041 → 414 MiB (0.40) 1087 → 576 MiB (0.53)
500 bytes 200K 144 → 12 MiB (0.08) 147 → 18 MiB (0.12) 147 → 19 MiB (0.13)

Reading order: PackedStringJoinKey and HashMethodPackedStringJoinKey in KeyGetter.h -> PackedStringJoinKey::buildRange and buildChunk -> SipHashStrings::hashRows -> PreparedJoinKeys -> the prepareRows calls in insertSlotRows, joinRightColumns and joinRightColumnsWithAdditionalFilter -> buildAllKeys in scatterImpl -> usePrebuiltKeys -> the choice of key_packed_string in the HashJoin constructor -> tryCreateJoin.

The keys:

  1. A key of up to 15 bytes is the UnhashedPackedStringRef of the string. A longer key is the unkeyed sipHash128Padded of the string with the flag bit set. No short key has that bit set, so a hashed key never equals a short one.
  2. key_packed_string and two_level_key_packed_string have the C++ types of keys128 and two_level_keys128, so no new hash table type is instantiated. The HashJoin constructor picks them in place of key_string and two_level_key_string, after it picks the layout.
  3. PackedStringJoinKey::buildRange builds the keys of up to 256 rows at a time. A short key needs no branch on the length. The code reads 16 bytes of the string and masks them with a table entry for that length. SipHashStrings::hashRows then hashes the long rows 8 at a time, as sipHash128 does for a String column. The rows that the caller skips are not hashed. The code reads up to 16 bytes past the end of a string, and the padding of ColumnString covers them. Debug builds check every key against PackedStringJoinKey::build.
  4. The join loops build the keys 256 rows at a time, just before they read them, so that the long keys of those rows are hashed together. With or without prefetch, a loop leaves out the rows with a NULL key or a false ON condition. A loop calls prepareRows before it creates its prefetcher. The getter keeps the last 32 keys of a chunk for the prefetch look-ahead.
  5. A list of rows in ascending order gets its keys built from the first listed row to the last, with the other rows skipped. An example is the build of an ASOF join with a Nullable ASOF column. These keys are built at once, not in chunks, because the rows left out can stretch the look-ahead past the 32 kept keys. A list in any other order builds each key where it is read.
  6. An OR join with a condition in ON looks up every row that it does not skip in every map. So it prepares the keys of every map. Any other OR join prepares the keys of its first map, and with prefetch also those of each other map that it prefetches.
  7. When a parallel build scatters a right block to its slots, scatterImpl builds the keys of the whole block once, with buildAllKeys. It routes the rows to the slots by these keys, and the slots insert the rows with them. Each slot builds the key of its first row again and compares it, and a mismatch throws a LOGICAL_ERROR.
  8. tryCreateJoin turns packed keys off for a right side estimated below min_rows_for_packed_string_keys_in_hash_join, before it chooses the algorithm. So the check covers every hash join. The settings are not part of the serialized plan settings. A JoinSettings built from a serialized plan turns packed keys off. StorageJoin builds its TableJoin without the setting, because a Join table can be read back with its keys. A hashed key has no string to give back.

Changelog category (leave one):

  • Performance Improvement

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

Hash joins on a single String key are faster when the right side is large, and their hash tables are smaller. Each key takes 16 bytes in the hash table. A key of up to 15 bytes is stored as it is. A longer key is stored as its 128-bit SipHash, with one bit used as a flag. Two different long keys whose other 127 hash bits agree match as equal. Setting enable_packed_string_keys_in_hash_join to 0 turns this off. min_rows_for_packed_string_keys_in_hash_join (100000 by default) keeps exact keys for a right side estimated at fewer rows.


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

Version info

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

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Nov 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Nov 3, 2026
@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch from d13f011 to 9ad2223 Compare November 3, 2026 13:39
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b21b312]

Summary: ✅


AI Review

Summary

PR #128972 introduces 16-byte packed keys for hash joins on a single String, with inline short keys, hashed long keys, and a default row-estimate threshold. Reviewed head b21b312a4a2d220d3ea0199dd4f97cf6ab3e05a8. The prior continuation and sparse-ASOF preparation findings are addressed. One existing performance concern remains; no new inline findings were identified.

Packed-key consumers traced: serial and parallel insertion, scatter, prefetch, single-map and OR probing, and ASOF use the corresponding UInt128 getter and maps. Key-only maps, unmatched-right output, and right-side reranging dispatch through the extended variants and retain row references independently of key encoding. Spilling and algorithm switching rebuild from preserved original columns. StorageJoin and joinGet reuse exact-key data; deserialized plans explicitly disable packing.

Both broad regression scripts, 05457_join_packed_string_keys and 05460_join_packed_string_keys_hash_grace, matched their references byte for byte on the current ARM Fast test binary. Four targeted fixtures also returned identical counts and checksums with packing disabled and enabled.

Findings

⚠️ Majors

  • src/Interpreters/HashJoin/HashJoin.cpp:532 — Default packing still regresses joins with repeated long keys. [dismissed by author -- https://github.com/Faster hash joins on a single String key with a large right side #128972#discussion_r4455857377]

    The row-count gate still selects packed keys for this workload, requiring the entire string to be hashed on every probe. Re-running the existing thread's fixture on the current ARM binary with 200,000 right rows, 1,000,000 matching probe rows, max_threads = 1, and the serial layout gives 176 ms disabled versus 213 ms enabled (+21%) for 1024-byte keys. These are medians of three alternating samples per mode after warmup; the default min_rows_for_packed_string_keys_in_hash_join = 100000 remains unchanged. Results agree.

    Reason retained: documenting the tradeoff and providing an opt-out does not prevent this default performance regression. Keep affected joins on exact keys through a suitable selection policy, or keep packing opt-in until that policy is available. The author-resolved thread is left unchanged.

Tests
  • ⚠️ Add a focused end-to-end performance comparison of packed versus exact keys for repeated long probe keys. The added key-building microbenchmark compares batched and scalar packed-key construction, so it cannot detect this complete-join regression.
Final Verdict

Status: ⚠️ Request changes.

Minimum required: prevent the default long-key regression described above and add the focused performance comparison.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 3, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b21b312a4 with master a62d3fd1e (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
Binary Master PR Δ
programs/clickhouse-stripped 809.88 MiB 808.19 MiB -1.70 MiB (-0.21%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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

74 object files changed (+4.15 MiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 2.48 MiB 2.63 MiB +161.59 KiB (+6.37%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 2.45 MiB 2.61 MiB +158.65 KiB (+6.32%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 2.42 MiB 2.57 MiB +157.11 KiB (+6.34%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 2.41 MiB 2.57 MiB +156.26 KiB (+6.33%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o 2.41 MiB 2.57 MiB +156.25 KiB (+6.32%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 2.29 MiB 2.44 MiB +154.95 KiB (+6.60%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o 2.39 MiB 2.54 MiB +154.59 KiB (+6.31%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp.o 2.24 MiB 2.39 MiB +150.29 KiB (+6.55%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp.o 2.24 MiB 2.39 MiB +150.20 KiB (+6.55%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 2.20 MiB 2.34 MiB +146.76 KiB (+6.52%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinRightAny.cpp.o 2.08 MiB 2.22 MiB +141.11 KiB (+6.62%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 2.07 MiB 2.21 MiB +140.27 KiB (+6.62%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp.o 2.03 MiB 2.17 MiB +137.52 KiB (+6.61%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp.o 2.03 MiB 2.16 MiB +137.47 KiB (+6.61%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAnti.cpp.o 2.00 MiB 2.13 MiB +135.25 KiB (+6.60%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 2.01 MiB 2.15 MiB +135.20 KiB (+6.55%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAsof.cpp.o 1.91 MiB 2.03 MiB +127.04 KiB (+6.50%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAsof.cpp.o 1.91 MiB 2.03 MiB +127.04 KiB (+6.50%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 1.78 MiB 1.90 MiB +122.93 KiB (+6.73%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAny.cpp.o 1.78 MiB 1.90 MiB +122.93 KiB (+6.73%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.73, programs/clickhouse-keeper ×0.91 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.6 s 14.9 s +10.0 s (+208%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.9 s 8.7 s +5.8 s (+207%)
Compile time of recompiled translation units

123 translation units recompiled, 1246 s compile time in total, 122 of them have a recent master baseline.

Job report

@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch 2 times, most recently from a00ca4d to 022bfb5 Compare November 4, 2026 04:28
@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch from 022bfb5 to 8e5028a Compare November 4, 2026 08:16
@harikrishnan94 harikrishnan94 changed the title Use 16-byte packed keys for single String keys in hash joins Speedup single String keys in hash joins using 16-byte packed keys Nov 4, 2026
@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch from 8e5028a to 1dc367a Compare November 4, 2026 16:10
@harikrishnan94 harikrishnan94 changed the title Speedup single String keys in hash joins using 16-byte packed keys Faster hash joins on a single String key with a large right side Nov 4, 2026
m-selmi added a commit that referenced this pull request Nov 4, 2026
@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch 2 times, most recently from fc34396 to 4500124 Compare November 4, 2026 22:07
harikrishnan94 and others added 6 commits November 5, 2026 07:53
`BasicPackedStringRef<hash_bytes>` stores 4 or 0 hash bytes. `PackedStringRef`
is the 4-byte variant and keeps its byte layout and behaviour.

`UnhashedPackedStringRef` is the 0-byte variant, for the packed `String` keys
of hash joins. It stores a string of 1 to 15 bytes inline from byte 0; the
4-byte variant fits at most 11. Every longer string uses the large encoding.
It has no medium encoding and is built by `build(ptr, len)` without a hash
function.

The header also gains the `<limits>` include it was missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The next commit uses the settings. When `enable_packed_string_keys_in_hash_join`
is on, a hash join on a single `String` key stores each key in 16 bytes.

`min_rows_for_packed_string_keys_in_hash_join`, 100000 by default, turns packed
keys off for a join whose right side is estimated at fewer rows. A small right
side keeps its hash table in the CPU cache, so packed keys save little there,
and hashing the keys of 16 bytes or more costs more. On Graviton4, Ice Lake and
Milan, such joins were up to 2.1-2.7x slower with packed keys. With the
minimum, the worst case is 1.3-1.5x, and the geometric mean over all measured
joins stays within 1% of the best minimum.

`tryCreateJoin` applies the minimum next to the row-store gate, before it
chooses the algorithm, so it covers every hash join. It uses the estimate that
`parallel_hash_join_threshold` uses to choose the layout of the hash table: the
right rows of an earlier run from the hash table statistics, or else the
optimizer's estimate. A join without an estimate uses packed keys.

The settings are not part of the serialized plan settings. A `JoinSettings`
built from a serialized plan turns packed keys off, so a node that runs a
deserialized plan compares `String` keys exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When `enable_packed_string_keys_in_hash_join` is on, a hash join on a single
`String` key stores each key in 16 bytes: `key_string` becomes
`key_packed_string`, and `two_level_key_string` becomes
`two_level_key_packed_string`. Their C++ types are those of `keys128` and
`two_level_keys128`, so no new hash table type is instantiated. This covers
the `hash`, `parallel_hash` and `grace_hash` joins, `ASOF` joins, joins with
`OR` whose every condition has a single `String` key, and the `grace_hash`
join that a spilling join switches to. Tables with the `Join` engine and
`joinGet` keep exact keys.

For a string of up to 15 bytes, the key, `PackedStringJoinKey`, is the
`UnhashedPackedStringRef` of the string. It holds the string exactly. For a
longer string, the key is the unkeyed `sipHash128Padded` of the string with
bit 7 of byte 15 set. The string is not copied to the arena.

So two different long strings match when their hashes agree in the other 127
bits. Joins on several `String` keys already accept this: `Type::hashed` keys
its hash table by the same unkeyed 128-bit SipHash of the key values and never
compares the values. SipHash mixes every output bit fully, so the constant bit
only halves the number of possible keys. For n distinct long strings, the chance
of a collision is about n^2/2^128 instead of n^2/2^129: about 2^-48 for 10^12
strings. Strings of up to 15 bytes are stored exactly, and the set bit keeps
them apart from the hashed keys, so they never collide. When more than about 29%
of the distinct keys are short, the chance is no higher than with
`Type::hashed`. Neither key is guaranteed to resist collisions crafted on
purpose, because the hash has no secret key. No practical collision attack on
SipHash with a public key is known.

The key getter `HashMethodPackedStringJoinKey` builds its keys ahead with
`PreparedJoinKeys`, so that long strings are hashed several at a time. When a
parallel build scatters the rows of a right block to its slots, it builds the
key of each row once, for both the scatter and the slot inserts. In the other
join loops, it builds the keys of a continuous range of rows 256 at a time,
and it does not hash the strings of the rows that a loop skips. Only a chunk
of 256 rows with strings longer than 15 bytes reads the skip bytes, because a
short key costs less than checking whether its row is skipped.

The key getter builds the keys of many rows with
`PackedStringJoinKey::buildRange`. On aarch64, and on x86 with AVX2, it builds
the short keys without branches, in plain C++ that clang compiles to vector
instructions. There it also hashes the long strings several at a time with
`SipHashStrings::hashRows`. Other builds build each key on its own.

The first query of `03277_join_adaptive_spill_oom` and of
`04695_spilling_hash_join_memory_spill_scheduler` must exceed the memory
limit. With packed keys, the hash tables are smaller and the query fits in
memory. So these tests disable `enable_packed_string_keys_in_hash_join`, and
`05458` and `05459` run the same queries with packed keys. They set
`min_rows_for_packed_string_keys_in_hash_join` to 0, because the random row
estimates of `query_plan_optimize_join_order_randomize` can fall below it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`JoinPackedStringKeysInline` and `JoinPackedStringKeysHashed` count the
single `String` keys that hash joins insert into a packed map. The first
counts the keys stored inline (up to 15 bytes), the second the keys stored as
a hash (16 bytes or more). They show which layout a join used.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The tests run each join with `enable_packed_string_keys_in_hash_join` off
and on, and compare the row counts and checksums of the results. `05457`
covers `parallel_hash` with 1 and 4 threads, the spilling `parallel_hash` join
that switches to `grace_hash`, and `full_sorting_merge`. `05460` covers
`hash`, `grace_hash`, the spilling `hash` join, joins with `OR` and `USING`,
and tables with the `Join` engine and `joinGet`. The `parallel_hash` joins of
the tests set `hash_join_layout` to `parallel`, because their right sides are
below `parallel_hash_join_threshold`.

These two cover `String`, `Nullable(String)`, `LowCardinality(String)` and
constant keys, ALL, ANY, SEMI, ANTI and ASOF joins of every kind, extra
conditions in `ON`, and `join_use_nulls`. The keys are around the 15-byte
inline limit: lengths 0, 1, 2, 8 and 14 to 17, keys that share their first
15 bytes, '\0' at byte 14, 'a' against 'a\0', 0xFF bytes and 100 KB keys. A
larger table makes the hash table exceed the L2 cache, so that the joins use
software prefetch.

`05457` and `05460` read the ProfileEvents `JoinPackedStringKeysInline` and
`JoinPackedStringKeysHashed` from `system.query_log`, and check that they are
non-zero in exactly the joins that should use packed keys. Both tests are
tagged `long`.
Their right tables are small, so both set
`min_rows_for_packed_string_keys_in_hash_join` to 0.

`05461` covers `PackedStringJoinKey::buildRange`, which builds the keys of
many rows at once and hashes the long ones in groups. It runs `parallel_hash`
and `hash` joins on keys of 0 to 5996 bytes: short keys, long keys of similar
lengths or of many lengths, short and long keys alternating, and long keys of
very different lengths mixed. Each left key is a right key, or a right key
with one byte changed, added or removed.

`05463` covers `min_rows_for_packed_string_keys_in_hash_join` in `hash`,
`parallel_hash`, `grace_hash` and spilling joins. A right side of 1000 rows
keeps packed keys with a minimum of 1000 and gets exact keys with 1001. A
minimum of 0 keeps packed keys. A join without an estimate keeps them too: one
without join reordering, and one whose right side is read from `numbers`. The
second run of a join takes its estimate, 500 rows, from the hash table
statistics of the first run, and gets exact keys.

BuzzHouse varies both settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`benchmark_packed_string_join_key` times `PackedStringJoinKey::buildRange` on
33 inputs. 23 of them cover the paths of `buildRange`: strings of at most 15
bytes only, mixes of short and long strings, long strings of similar and of
very different lengths, and strings of 512 bytes or more. 7 have the lengths of
`String` columns of the ClickBench `hits` table, such as `URL` and
`SearchPhrase`. Their long strings come in runs, as the rows of one site do in
that table. The last 3 have strings of one length with rare outliers.

It calls `buildRange` in the ways the hash join does. `buildRange/<input>`
builds the keys of a whole block in one call. `buildRange256/<input>` builds
them 256 rows per call into one reused buffer, starting at a row that is not a
multiple of 256. `buildRangeSmall/<input>` builds them in calls of 16 to 256
rows, as for small blocks and short ranges of rows. These calls pass skip
bytes that skip no row, as the join loops do for a block without skipped
rows. `buildPerRow/<input>` builds the same keys one row at a time with
`PackedStringJoinKey::build`.

`hashRange/<input>` times only the hashing in `buildRange`:
`SipHashStrings::hashRows` on the strings longer than 15 bytes, chunk by chunk,
listed as `buildRange` lists them. `hashPerRow/<input>` hashes the same strings
one by one with `PackedStringJoinKey::build`. The time of `buildRange/<input>`
minus that of `hashRange/<input>` is about the time of the rest of
`buildRange`. `hashRange/<input>` and `hashPerRow/<input>` exist only on
aarch64 with NEON and on x86 with AVX2, where `buildRange` hashes long strings
8 at a time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the packed-string-keys-parallel-hash-join branch from 4500124 to 48fd0c9 Compare November 5, 2026 02:50
@harikrishnan94
harikrishnan94 marked this pull request as ready for review November 5, 2026 02:50
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Since this is merged, I'll send the follow-up PR on master that puts enable_packed_string_keys_in_hash_join and min_rows_for_packed_string_keys_in_hash_join into the serialized query plan, following your six points with no other behavior change, and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The follow-up is #130750. It follows the six points: both settings are plan settings with defaults false and 0, written in updatePlanSettings and read in the plan-settings constructor, with no version gate; the gtest JoinPackedStringKeysPlanSetting.RoundTrip and the stateless test 05620_join_packed_string_keys_serialized_plan (serialize_query_plan = 1) are added, and the two texts are updated. The row estimate is not serialized, and Join tables and joinGet stay exact.

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Pls, perform Nihal's experiments (#128972 (review)) and post the results here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm running the experiments from Nihal's review on master (skip hashing adjacent duplicate long keys, reuse the prefetch/scatter hash in emplace, avoid the CRC32 re-hash of the hashed long key, skip lhs rows longer than the longest rhs key; the OR of lengths I'll cite from your numbers above). I'll post the results here, and open a PR for any idea that clearly helps.

@groeneai

Copy link
Copy Markdown
Collaborator

Results of the experiments from review #128972 (review), on master c9bc131848ab0.

Method: x86 (Xeon 6975P-C, shared box), release build without ThinLTO, one prototype per idea. Four servers with their own Memory tables, binaries rotated over the servers each round (Latin square), master twice as an A/A floor, server elapsed_ns, 4 rounds (8 for every cell that came out slower, and for the target cells of the batch that ran during a load spike). Ratio = variant / master, lower is faster. A cell counts as faster or slower only if it is past 5% against both master copies. Every result matched master's byte for byte, the packed-key stateless tests pass on every server variant, and the buildRange microbenchmark self-checks every key.

idea target cells, 1 / 16 threads worst other cell code verdict
skip hashing a long key equal to the previous row runs of 8, 500 B: 0.69 / 0.87; runs of 8, 40 B: 0.88 / 0.91 unique mixed keys 1 thread: 1.13 +33 lines regresses
one hash for prefetch + lookup + scatter build 10M short: 0.99 / 1.06; build 10M long: 1.02 / 0.87 (floor 8%) none +134 lines no gain
no CRC32 on the hashed long key probe long keys: 0.94 / 1.08 mixed keys 16 threads: 1.18 +18 lines regresses
skip left keys longer than the longest right key 0.94-0.97 (INNER) build 10M short: 1.06 / 1.09; mixed keys: 1.10 +99 lines regresses
OR of lengths microbenchmark only +12 lines regresses
  • Skipping adjacent duplicates is a big win on sorted keys: the microbenchmark drops to 0.36 for runs of 600-byte keys and 0.68 for 40-byte keys. The extra pass over the long rows is not free on unique keys, though: 1.13-1.30 on unique 16-256 byte keys in the microbenchmark, and 1.13 on the mixed-key join.
  • Computing the map hash once removes one or two crc32 per row, and that is below the noise everywhere.
  • Using the SipHash word as the map hash compiles to a branch on the hashed flag, not a cmov. It mispredicts on randomly mixed short and long keys (1.18 at 16 threads) and saves only 6% on long keys at 1 thread.
  • The longest-key bound works where the probe really sees the rows: 0.64-0.83 for a LEFT JOIN, and 0.62-0.78 for the same INNER JOIN with enable_join_runtime_filters = 0. With the default runtime filter, the INNER join's probe side is already filtered before the join, so only 3-6% is left. The bound also costs a pass over the offsets of every inserted block (+6-9% on a 10M-key build) and a length check per probe row (+10% on mixed keys).
  • OR of lengths, x86 microbenchmark: all keys under 16 bytes 0.82, one 20-byte key per 256 rows 1.15. Same direction as your numbers (5-8% faster when all keys are short, +20% with a single long key).

None of the five helps across the board as implemented, so I am not opening a PR for any of them. The two that win on their own workload (adjacent duplicates, longest key) lose it elsewhere to the extra work they add on every block; I did not try designs that avoid that work. ARM was not measured.

Per-cell ratios (variant / master; tables of 0.2M-10M rows, 1 and 16 threads)
cell master ms (batch 1) dups hash once no CRC max len
short keys t1 / t16 315 / 56 0.97 / 0.95 1.02 / 1.02 1.04 / 1.06 1.03 / 1.02
long keys t1 / t16 487 / 81 1.04 / 1.00 0.95 / 1.00 0.94 / 1.08 1.04 / 1.03
500 B keys t1 / t16 343 / 109 1.00 / 1.01 0.92 / 1.03 0.95 / 1.01 1.02 / 1.02
runs of 8, 40 B t1 / t16 268 / 47 0.88 / 0.91 0.99 / 1.00 0.95 / 0.99 0.99 / 1.05
runs of 8, 500 B t1 / t16 259 / 95 0.69 / 0.87 0.95 / 0.98 0.97 / 0.98 0.97 / 0.97
build side in runs of 4 t1 / t16 248 / 51 0.94 / 0.96 1.04 / 0.99 0.99 / 0.96 1.04 / 1.03
mixed short/long t1 / t16 372 / 70 1.13 / 1.02 0.95 / 0.99 1.20 / 1.18 1.10 / 1.02
build 10M short t1 / t16 566 / 99 0.99 / 1.01 0.99 / 1.06 0.93 / 0.99 1.06 / 1.09
build 10M long t1 / t16 780 / 111 1.06 / 1.02 1.02 / 0.87 1.01 / 0.92 1.01 / 1.00
half of left too long, INNER t1 / t16 239 / 47 1.01 / 0.97 0.97 / 1.01 1.00 / 1.04 0.95 / 0.94
same, LEFT JOIN t1 / t16 231 / 42 0.96 / 0.96 0.64 / 0.66

leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Nov 11, 2026
A node that runs a deserialized query plan (`serialize_query_plan`, distributed
plans) built its `JoinSettings` from the plan settings with
`enable_packed_string_keys_in_hash_join = false` and
`min_rows_for_packed_string_keys_in_hash_join = 0` hard coded, because ClickHouse#128972
left both out of `QueryPlanSerializationSettings`. Its hash joins on a single
`String` key therefore compared the keys exactly whatever the initiator set:
correct results, but no speedup on the remote nodes.

Add both to `QueryPlanSerializationSettings` with defaults `false` and `0`,
write them in `JoinSettings::updatePlanSettings` and read them in the
constructor that takes plan settings. A plan without the names keeps exact keys.

No version gate, as asked in
ClickHouse#128972 (comment):
plan settings are written by name with flags, and `BaseSettings::read` skips an
unknown name that is not declared `IMPORTANT`, so an older reader logs
`Unknown settings` and keeps its exact keys. Measured with a server built from
the previous master as the only shard (and as the initiator): the join succeeds
and the old node records no packed keys. The row estimate is not serialized,
and `Join` tables and `joinGet` stay exact.

The gtest round trips both values and reads plan settings without the names
back as `false` and `0`. The stateless test runs a `cluster()` join with
`serialize_query_plan = 1` and checks the remote queries' packed-key profile
events; on the previous master they are 0 with the setting on, while the same
join over the query text path counts them, so the test checks the plan path.

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

Copy link
Copy Markdown
Contributor Author

@groeneai please open a PR against master that replaces the descriptions of two settings in src/Core/Settings.cpp with the text below, word for word. Change nothing else.

enable_packed_string_keys_in_hash_join:

Makes `hash`, `parallel_hash` and `grace_hash` joins on a single `String` or `Nullable(String)` key faster and lowers their memory use. A join with `OR` qualifies when each of its conditions has a single such key.

Because the hash table is smaller, a join reaches `max_bytes_in_join` and `max_bytes_before_external_join` later.

The setting does not apply to `FixedString` or `LowCardinality(Nullable(String))` keys, to tables with the `Join` engine, or to `joinGet`. A join on a `LowCardinality(String)` key may use the key's dictionary instead. A join whose right side is estimated at fewer rows than `min_rows_for_packed_string_keys_in_hash_join` is not affected either.

Its 26.11 settings-history entry:

New setting to make hash joins on a single `String` key faster and use less memory.

min_rows_for_packed_string_keys_in_hash_join:

The minimum estimated number of rows in the right side of a join for `enable_packed_string_keys_in_hash_join` to apply. Smaller joins gain little from it, and can be slower with long keys.

The estimate is the number of right-side rows in an earlier run of the same join, if `collect_hash_table_stats_during_joins` is enabled. Otherwise it is the query optimizer's estimate. `parallel_hash_join_threshold` uses the same estimate. A join without an estimate always uses `enable_packed_string_keys_in_hash_join`.

0 means no minimum.

PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
`05457_join_packed_string_keys` and `05460_join_packed_string_keys_hash_grace` time out at 600 s in
`Stateless tests (amd_msan, parallel, 1/3)` on master. Under MSan each of their queries takes about one second, and
more than half of it is parsing, analysis and planning. `05457` runs 684 queries and `05460` runs 474.

Each test body is now a `.lib` file that runs the joins of the tables listed in `TABLES`. Eight tests source the two
files, one test per key type: `String`, `Nullable(String)`, `LowCardinality` and the large right table. The joins on one
thread now run only on `b_s` and `b_big`. The largest test runs 156 queries.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=f35452c8355834672b96abfe8005de7921a2bad5&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20parallel%2C%201%2F3%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=5252bd271c8031ae21176382769f0114ab200941&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20parallel%2C%201%2F3%29

Related: ClickHouse#128972

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

Copy link
Copy Markdown
Collaborator

Acknowledged. I'll open a PR against master that replaces both descriptions in src/Core/Settings.cpp, and the 26.11 history entry of enable_packed_string_keys_in_hash_join next to its declaration there, with your text word for word, and post the link here.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #131171. It replaces both descriptions and the 26.11 history entry of enable_packed_string_keys_in_hash_join in src/Core/Settings.cpp with your text, byte for byte. Nothing else changes: the 26.11 history entry of min_rows_for_packed_string_keys_in_hash_join stays as it is.

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 13, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai please open a PR against master that adds the two settings of this PR to the JOIN settings page, docs/concepts/features/operations/select/join-settings.mdx. Add these two rows to the "Algorithm selection and tuning" table, right after the enable_software_prefetch_in_join row, word for word. Change nothing else.

| [`enable_packed_string_keys_in_hash_join`](/reference/settings/session-settings/enable#enable_packed_string_keys_in_hash_join) | Makes hash JOINs on a single `String` key faster and lowers their memory use, by storing each key in 16 bytes in the hash table. |
| [`min_rows_for_packed_string_keys_in_hash_join`](/reference/settings/session-settings/min#min_rows_for_packed_string_keys_in_hash_join) | Sets the estimated number of rows in the right table below which a hash JOIN keeps exact `String` keys instead of packed keys. |

Requested by @ayakovlev-clickhouse in #131171 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm adding the two rows to the "Algorithm selection and tuning" table of join-settings.mdx, word for word; I'll follow up here with a PR (or my findings) shortly.

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai please open a PR against master that adds a performance test for hash joins on a single String key, as tests/performance/hash_join_packed_string_keys.xml. It should have one query for each of the 9 shapes below. The table and column names are yours to choose.

Settings of the test: join_algorithm = parallel_hash, max_bytes_ratio_before_external_join = 0, query_plan_join_swap_table = false (the right table is the build side) and enable_join_runtime_filters = 0 (a query then measures the hash table, not the filter). Do not set enable_packed_string_keys_in_hash_join in the test, so that CI compares the same default on both sides.

Data: Memory tables, filled with INSERT ... SELECT ... FROM numbers_mt(N). The build key of row id is made from the number id. A probe row with a hit takes an id below the build size, chosen with intHash64(number + 1) % build_rows. A probe row with a miss takes a larger id, so its key never occurs on the build side. Half of the probe rows hit, unless a shape says otherwise. A short key is toString(id). A long key is UUIDNumToString(sipHash128(id)), which is 36 bytes. Keep the fill short by giving several shapes one probe table with one key column per shape.

Every query is SELECT count(), sum(r.v) FROM probe AS l INNER JOIN build AS r ON l.k = r.k FORMAT Null. The 9 shapes:

  1. Short keys, 1 to 7 bytes. Build 8M rows, probe 20M.
  2. Long keys. Build 8M, probe 20M.
  3. Long keys, with a build side of 1M distinct keys. Probe 20M.
  4. Long keys, and no probe row hits. Build 8M, probe 20M.
  5. Long keys, with a skewed probe: every row hits, and the id is pow(intHash64(number) / 18446744073709551615., 3) * build_rows, so 1% of the build keys get 21% of the probe rows. Build 8M, probe 20M.
  6. Mixed lengths in one column, 2 to 40 bytes: concat(toString(id), ':', substring(hex(sipHash128(id)), 1, id % 33)). About a quarter of the keys are 15 bytes or less. Build 8M, probe 20M.
  7. A duplicate on the build side: 8M rows with 4M distinct long keys, so a hit matches 2 rows. Probe 20M.
  8. 256-byte keys: substring(repeat(hex(sipHash128(id)), 8), 1, 256). The build side has 100K rows, the smallest that min_rows_for_packed_string_keys_in_hash_join lets through. The probe table has 2.5M rows, and the query reads it 6 times with UNION ALL, so the run is long enough.
  9. 20-byte keys: substring(hex(sipHash128(id)), 1, 20). Build 100K rows. The probe table has 8M rows, read 4 times with UNION ALL.

Each query should take 0.1 to 1 s on 16 threads with packing on, and the fill should take no more than a few seconds. Please check these before opening the PR:

  1. Run each query with enable_packed_string_keys_in_hash_join = 0 and = 1. The results must be equal, and with 1 the ProfileEvents JoinPackedStringKeysInline and JoinPackedStringKeysHashed must count the build rows (0 with the setting off).
  2. Check that the count of each query is what its shape implies. Only shape 4 may return 0.
  3. The probe and the build side must hash the same integer type. number % 4000000 is a UInt32, and sipHash128 of it differs from sipHash128 of a UInt64, so cast with toUInt64.

Use the changelog category Not for changelog.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #132260: it adds the two rows right after the enable_software_prefetch_in_join row of the "Algorithm selection and tuning" table in join-settings.mdx, byte-equal to the rows in your comment; nothing else on the page changes. Both link anchors exist (enable.mdx and min.mdx).

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm writing tests/performance/hash_join_packed_string_keys.xml with the 9 shapes and the four settings, and I'll run your three checks before opening it; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #132288: it adds tests/performance/hash_join_packed_string_keys.xml with the 9 shapes and your 4 settings, Not for changelog.

Your three checks, on a master release build: (1) results are equal with enable_packed_string_keys_in_hash_join 0 and 1, and with 1 JoinPackedStringKeysInline + JoinPackedStringKeysHashed equal the build rows (0 with 0); (2) every count matches its shape, only shape 4 is 0; (3) every sipHash128 argument is a UInt64 on both sides. The fill takes 0.55 s.

At 16 threads, shapes 3 and 9 run slightly under 0.1 s (79 and 86 ms) on my host; I kept the sizes you specified. At 8 threads (the perf CI's amd setting) every shape takes 0.14 to 0.28 s. The per-shape table is in the PR description.

lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 17, 2026
Adds rows for `enable_packed_string_keys_in_hash_join` and
`min_rows_for_packed_string_keys_in_hash_join` to the "Algorithm selection
and tuning" table, right after `enable_software_prefetch_in_join`, with the
text requested in
ClickHouse#128972 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 17, 2026
`tests/performance/hash_join_packed_string_keys.xml` has one query for each
of the 9 shapes requested in
ClickHouse#128972 (comment):
short keys (1-7 bytes), 36-byte keys, a 1M-key build side, no probe hits, a
skewed probe, mixed lengths (2-40 bytes), a duplicate build side, and 256-byte
and 20-byte keys on a 100K-row build side.

The test sets `join_algorithm = parallel_hash`,
`max_bytes_ratio_before_external_join = 0`, `query_plan_join_swap_table = false`
and `enable_join_runtime_filters = 0`, and leaves
`enable_packed_string_keys_in_hash_join` at its default, so that both sides of
the comparison run the same default.

A probe row hits when `cityHash64(number) % 2 = 0`. A miss of the 8M build side
takes an id below 10M, so the short and the mixed probe keys keep the lengths
of the build side. The 256-byte and 20-byte shapes read the probe table 6 and 4
times with `UNION ALL` on the probe side, joined once to the build table.

Validated on master 45e6326 (release build): the results are equal with
the setting 0 and 1; with 1 `JoinPackedStringKeysInline` +
`JoinPackedStringKeysHashed` equal the build rows (0 with 0); every count and
sum equals the value computed from the generators; every id hashed by
`sipHash128` is a UInt64 on both sides; `perf.py` runs the test green, also
with `--table-engine iceberg_local`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 23, 2026
A hash join on a single `String` key packs its keys unless the right side is estimated below
`min_rows_for_packed_string_keys_in_hash_join` rows. A row count says little about the size of the hash table, and
it does not adapt to the CPU cache.

With the `basic` column statistics of the right key, the join now estimates the hash table with exact keys as
rows * (32 + average key length), and packs the keys only when that is larger than the L2 cache. A key of more than
15 bytes is hashed when it is packed, for every left row. So a join on such keys also needs the minimum number of
rows, unless it has a runtime filter: the filter drops the left rows without a match before the join. Without the
statistics the minimum decides alone, as before.

The host that creates the join decides, from its own statistics, its own cache size and its own runtime filter. The
serialized plan does not change. The bit that tells a receiver that the sender estimated a small right side is now
used only by a receiver without statistics.

Related: ClickHouse#128972

Co-Authored-By: Claude Fable 5.2 <[email protected]>
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 23, 2026
…istics

`hash_join_packed_string_keys_statistics` joins `MergeTree` right tables that have `basic` statistics on the key. It
has one query for each branch of the choice between packed and exact keys: short, 64-byte and 256-byte keys, right
sides that fit in the L2 cache and that do not, right sides below and above
`min_rows_for_packed_string_keys_in_hash_join`, `INNER` joins, which get a runtime filter, and `LEFT` joins, which do
not, with 0%, 50% and 100% of the left rows matching.

`hash_join_packed_string_keys` covers the right tables without statistics.

Related: ClickHouse#128972

Co-Authored-By: Claude Fable 5.2 <[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 ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.

6 participants