Repository navigation
Faster hash joins on a single String key with a large right side - #128972
harikrishnan94 merged 13 commits into
Conversation
d13f011 to
9ad2223
Compare
|
Workflow [PR], commit [b21b312] Summary: ✅
AI ReviewSummaryPR #128972 introduces 16-byte packed keys for hash joins on a single Packed-key consumers traced: serial and parallel insertion, scatter, prefetch, single-map and Both broad regression scripts, Findings
Tests
Final VerdictStatus: Minimum required: prevent the default long-key regression described above and add the focused performance comparison. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 Object file sizes74 object files changed (+4.15 MiB total), 1 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units123 translation units recompiled, 1246 s compile time in total, 122 of them have a recent master baseline. |
a00ca4d to
022bfb5
Compare
022bfb5 to
8e5028a
Compare
String keys in hash joinsString keys in hash joins using 16-byte packed keys
8e5028a to
1dc367a
Compare
String keys in hash joins using 16-byte packed keysString key with a large right side
fc34396 to
4500124
Compare
`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]>
4500124 to
48fd0c9
Compare
|
Acknowledged. Since this is merged, I'll send the follow-up PR on master that puts |
|
The follow-up is #130750. It follows the six points: both settings are plan settings with defaults |
|
@groeneai Pls, perform Nihal's experiments (#128972 (review)) and post the results here. |
|
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. |
|
Results of the experiments from review #128972 (review), on master 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
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)
|
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]>
|
@groeneai please open a PR against master that replaces the descriptions of two settings in
Its 26.11 settings-history entry:
|
`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]>
|
Acknowledged. I'll open a PR against master that replaces both descriptions in |
|
Opened #131171. It replaces both descriptions and the 26.11 history entry of |
Text as requested in ClickHouse#128972 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai please open a PR against master that adds the two settings of this PR to the JOIN settings page, Requested by @ayakovlev-clickhouse in #131171 (comment) |
|
Acknowledged. I'm adding the two rows to the "Algorithm selection and tuning" table of |
|
@groeneai please open a PR against master that adds a performance test for hash joins on a single Settings of the test: Data: Every query is
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:
Use the changelog category |
|
Opened #132260: it adds the two rows right after the |
|
Acknowledged. I'm writing |
|
Opened #132288: it adds Your three checks, on a master release build: (1) results are equal with 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. |
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]>
`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]>
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]>
…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]>
Related: #129329
Related: #129204
Related: #129328
A hash join on a single
Stringkey keeps its right rows in thekey_stringmap. 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.With this PR, such a join stores each key in 16 bytes, in the cell itself.
For a user:
Stringkey are faster when the right side is large. This covershash,parallel_hashandgrace_hash, and the spilling join that switches tograce_hash. It also coversASOFjoins, andORjoins whose every condition has a singleStringkey. ANullable(String)key compared with=counts as aStringkey.max_bytes_in_joinandmax_bytes_before_external_joinlater.enable_packed_string_keys_in_hash_jointurns this on. It is on by default. Withmin_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 thatparallel_hash_join_thresholduses. A join without an estimate uses packed keys. Some joins above the minimum are still slower with packed keys.Type::hashedalready makes for composite keys. Keys of up to 15 bytes are compared exactly. Withenable_packed_string_keys_in_hash_join = 0, all keys are compared exactly.enable_packed_string_keys_in_hash_join = 0keeps exact keys.enable_software_prefetch_in_joinnow covers these joins too. The prefetch leaves out the rows that the join skips: those with aNULLkey or a falseONcondition.Joinengine,joinGetand joins that run from a serialized query plan keep exact keys.FixedStringkeys,LowCardinality(Nullable(String))keys and aLowCardinality(String)key that uses the map of its dictionary keep their maps.JoinPackedStringKeysInlineandJoinPackedStringKeysHashedcount the keys that joins insert inline (up to 15 bytes) and as a hash (16 bytes or more). A join withORcounts a key for each condition. A row that is inserted again counts again: after agrace_hashjoin splits its buckets, or after a spilling join switches tograce_hash.INsets are unchanged.Sample joins on a single
Stringkey,clickhouse local, m8g.24xlarge (Graviton 4), median of 3 processes x 3 runs:Every left row matches, master → this PR:
No left row matches:
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 = 0selects:Reading order:
PackedStringJoinKeyandHashMethodPackedStringJoinKeyinKeyGetter.h->PackedStringJoinKey::buildRangeandbuildChunk->SipHashStrings::hashRows->PreparedJoinKeys-> theprepareRowscalls ininsertSlotRows,joinRightColumnsandjoinRightColumnsWithAdditionalFilter->buildAllKeysinscatterImpl->usePrebuiltKeys-> the choice ofkey_packed_stringin theHashJoinconstructor ->tryCreateJoin.The keys:
UnhashedPackedStringRefof the string. A longer key is the unkeyedsipHash128Paddedof the string with the flag bit set. No short key has that bit set, so a hashed key never equals a short one.key_packed_stringandtwo_level_key_packed_stringhave the C++ types ofkeys128andtwo_level_keys128, so no new hash table type is instantiated. TheHashJoinconstructor picks them in place ofkey_stringandtwo_level_key_string, after it picks the layout.PackedStringJoinKey::buildRangebuilds 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::hashRowsthen hashes the long rows 8 at a time, assipHash128does for aStringcolumn. 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 ofColumnStringcovers them. Debug builds check every key againstPackedStringJoinKey::build.NULLkey or a falseONcondition. A loop callsprepareRowsbefore it creates its prefetcher. The getter keeps the last 32 keys of a chunk for the prefetch look-ahead.ASOFjoin with aNullableASOF 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.ORjoin with a condition inONlooks up every row that it does not skip in every map. So it prepares the keys of every map. Any otherORjoin prepares the keys of its first map, and with prefetch also those of each other map that it prefetches.scatterImplbuilds the keys of the whole block once, withbuildAllKeys. 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 aLOGICAL_ERROR.tryCreateJointurns packed keys off for a right side estimated belowmin_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. AJoinSettingsbuilt from a serialized plan turns packed keys off.StorageJoinbuilds itsTableJoinwithout the setting, because aJointable can be read back with its keys. A hashed key has no string to give back.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Hash joins on a single
Stringkey 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-bitSipHash, with one bit used as a flag. Two different long keys whose other 127 hash bits agree match as equal. Settingenable_packed_string_keys_in_hash_jointo 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
26.11.1.1924-master(included in26.11and later)