Repository navigation
Store only the keys in the join hash table when no right row is read - #115301
Conversation
…read `LEFT ANTI` emits a left row only when its key is missing from the right side, and fills the right columns with defaults; `LEFT SEMI` emits the matched left row alone. Neither ever reads a right row, so the table only has to answer whether a key is present and the mapped `RowRef` in every cell is dead weight. Add a third flavour of the join maps, `HashJoin::MapsSet`, whose tables are the set counterparts of the mapped ones (`HashSet`, `TwoLevelHashSet`, `FixedHashSet`, ...), selected by instantiating `MapsTemplate` with `VoidMapped`. It is used for `LEFT ANTI`, and for `LEFT SEMI` when no right column is selected. `MapGetter`'s `prefer_use_maps_all` flag becomes the `JoinMapsKind` enum, and the two routines that would read a right row - `processMatch` and the non-joined-rows fill - are split into constrained overloads. The cell of a fixed-width key halves: 16 to 8 bytes for a `UInt64` key. On top of that, a set map holds no reference into a right block, so the blocks are dropped as they are built rather than kept for the whole query - unless another algorithm may take them back out of the join with `releaseJoinedBlocks`, which is what `mustKeepRightBlocks` tracks. Measured on 10M left rows joined to 5M right rows, `max_threads = 8`: ANTI, count only 76 -> 65 ms, 321.4 -> 187.4 MiB ANTI, right column selected 84 -> 75 ms, 436.6 -> 305.6 MiB SEMI, count only 98 -> 90 ms, 324.5 -> 197.1 MiB and with spilling off, where the right blocks are dropped as well: ANTI, count only 237 -> 142 ms, 347.2 -> 178.9 MiB SEMI, count only 192 -> 164 ms, 356.6 -> 186.6 MiB The new setting `enable_join_key_only_hash_tables`, on by default, turns it off. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LJmHFQH2TPX9kHnwtWZe7f
|
Workflow [PR], commit [4f6d203] Summary: ✅
AI ReviewSummaryThis PR introduces key-only hash-join maps for Missing context / blind spots
Findings💡 Nits
Final Verdict✅ No new blocking issues in the current code. One previously raised, non-blocking test-coverage gap remains unresolved. LLVM Coverage ReportMeasured on commit 4f6d203.
Changed lines: Changed C/C++ lines covered: 357/370 (96.49%) · Uncovered code |
Build profile diff (arm_release)Comparing 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 sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsSet.cpp.o |
new | 2.46 MiB | +2.46 MiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsSet.cpp.o |
new | 2.34 MiB | +2.34 MiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o |
3.69 MiB | 4.26 MiB | +589.05 KiB (+15.59%) |
src/CMakeFiles/dbms.dir/Interpreters/ConcurrentHashJoin.cpp.o |
863.94 KiB | 1018.21 KiB | +154.27 KiB (+17.86%) |
716 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
495 translation units recompiled, 4605 s compile time in total, 493 of them have a recent master baseline.
Translation units without a recent master baseline:
src/Interpreters/HashJoin/LeftHashJoinAntiMapsSet.cpp: 16.1 ssrc/Interpreters/HashJoin/LeftHashJoinSemiMapsSet.cpp: 15.9 s
Six shapes that run on `HashJoin::MapsSet`: `LEFT ANTI` on a `UInt64` key under `hash` and under `parallel_hash`, the same with `max_bytes_before_external_join` set so that the right blocks have to be kept and only the smaller cell is left to win, `LEFT ANTI` with a right column selected, `LEFT SEMI` with nothing selected from the right, and `LEFT ANTI` on a `String` key. Measured locally with `enable_join_key_only_hash_tables` off and on, 20M left rows joined to 5M right rows, min of five runs: ANTI, hash 158 -> 125 ms, 334 -> 199 MiB ANTI, parallel_hash 48 -> 37 ms, 316 -> 183 MiB ANTI, right blocks kept 157 -> 124 ms, 339 -> 174 MiB ANTI, right column selected 164 -> 127 ms, 331 -> 174 MiB SEMI, hash 166 -> 137 ms, 475 -> 315 MiB ANTI, String key 593 -> 523 ms, 907 -> 747 MiB Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…orce the analyzer The test spawned a `clickhouse-client` per query per setting value, about sixty of them, which took 192 s under ASan and tripped the 180 s limit in the flaky check. Send every query in one invocation per value of `enable_join_key_only_hash_tables` instead, and diff the two outputs: the run is down to ~1 s. Two blank lines go away from the reference along with the per-check `echo` of an empty result. The two queries with a mixed join expression are unsupported by the old analyzer (`INVALID_JOIN_ON_EXPRESSION`), which failed the whole file there - and now would cut the single invocation short. Pin `enable_analyzer = 1` on those two so the rest keeps running under both analyzers. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115301&sha=b6ab80e4de4275757a62341e395259848447d1d4&name_0=PR #115301 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
The eviction of the stored right blocks was keyed off `flag_per_row`, which is true for every multi-disjunct join (`... ON a = b OR c = d`). A `LEFT ANTI` on such a join runs on a set map, which is never `flagged` - `MapGetter<Left, Anti, Set>::flagged` is false, so `reinit` stores no per-row flags and nothing reads them - yet every right block was kept for the whole query, and the blocks are what dominates the memory of that shape. Key the eviction off what actually points into the block instead: a map cell (`is_inserted`), a nullmap, or per-row used flags on a mapped map. With several clauses the block goes once the last one has read its keys out of it. For the mapped maps nothing changes: several clauses always mean `flag_per_row`, so the condition is the one that was there before. `LEFT SEMI` does not reach this: with several disjuncts every right column - the keys included - lands in `sample_block_with_columns_to_add`, so `canUseSetMaps` rejects it before the maps are even chosen. Measured on 10M left rows joined to a 5M-row `MergeTree` right side, `ON k = k OR k2 = k2`, with the right payload column selected: peak memory 643 MiB (mapped) -> 386 (set map, blocks kept) -> 293 (set map, blocks dropped) and on the perf-test shape (`Memory` tables, count only) 540 -> 297 ms, 577 -> 291 MiB. The perf test gets the multi-disjunct query, and the functional test the `ANTI`/`SEMI` results for it, including the shape where the blocks are dropped as they are built. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
`LEFT ANTI` had five shapes in the test and `LEFT SEMI` one. Add the three that were missing: `parallel_hash`, the one where spilling keeps the right blocks so only the smaller cell is left to win, and one with several disjuncts. Measured with `enable_join_key_only_hash_tables` off and on, 20M left rows joined to 5M right rows, min of five runs: SEMI, parallel_hash 54 -> 45 ms, 307 -> 188 MiB SEMI, right blocks kept 148 -> 124 ms, 470 -> 316 MiB SEMI, several disjuncts 388 -> 408 ms, 577 -> 577 MiB (unchanged) The last one does not run on a set map yet: with several disjuncts every right key column is added to the result whether or not the query asks for it, so `canUseSetMaps` refuses. It qualifies as soon as #115465 stops adding the ones nobody asked for - with both changes in place the same query goes 298 -> 218 ms and 577 -> 289 MiB - and the query is here to measure that. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…sjuncts With one disjunct the right keys are split out of the block the join adds to the result and put back only where the query needs them - a value restored from the left key column, which is the same thing under an equality. With several disjuncts that restoration is invalid, because a row matched through another clause has a right key of its own, so the whole right header became the block the join adds: `sample_block_with_columns_to_add`. Needing to *read* a key when it is asked for is not a reason to *add* it when it is not, and the plan drops those columns right after the join with a `ColumnPermuteTransform` anyway. Keep the keys the query asks for - `requiredRightKeys` already tracks them, the planner fills it in `setUsedColumns` - and add nothing else. Without the analyzer nothing fills it, so there every key is kept, as before. `right_table_keys` stays whole either way, so the stored right blocks and the mixed `ON` condition evaluated against them are untouched. For a `count()` over `... ON a = a OR b = b` the join used to emit `__table2.a` and `__table2.b` for every result row and the permutation threw them away; now it emits neither. That is not measurable on a 20M x 5M join - 892 vs 903 ms with four disjuncts - so it is worth having for what it removes rather than for what it saves. It also settles the `LEFT SEMI` half of the key-only join hash tables: `canUseSetMaps` asks whether the join has to produce any right value at all, which with several disjuncts could never be false. Related: ClickHouse#115301 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
…ld analyzer too `rightColumnsToAddWithSeveralDisjuncts` was gated on `enableAnalyzer()`, so on the legacy planner a join with several disjuncts still adds every right key column to its result. `canUseSetMaps` asks whether the join produces any right value at all, so with `enable_analyzer = 0` a query like `SELECT count() FROM l SEMI LEFT JOIN r ON l.k = r.k OR l.s = r.s` stayed on the mapped tables while the same query on the analyzer got the key-only ones. The gate is not needed: `requiredRightKeys` works on both paths, because `TreeRewriter::collectJoinedColumns` fills `columns_added_by_join` through `addJoinedColumn` exactly as the planner fills it through `setUsedColumns`. Checked with `enable_analyzer = 0`: the results of seven `OR` join shapes - `ALL`/`SEMI`/`ANTI`, `LEFT`/`RIGHT`/`FULL`, with and without a right key or payload column selected - are the same as with the analyzer; `04926_join_key_only_hash_tables` and `05023_join_several_disjuncts_right_keys` pass; and the `join` tests have the same six reference mismatches as the build without this change, all of them tests that read differently on the legacy planner (`00826_cross_to_inner_join`, `01115_join_with_dictionary`, `02220_array_join_format`, `02784_parallel_replicas_automatic_decision_join`, `04653_distributed_plan_auto_rewrite_in_to_join`, `04670_any_join_take_last_row_no_swap`). Related: #115465 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016QJvAjMfovbKtDsMW9mDbF
|
@copilot resolve the merge conflicts in this pull request |
# Conflicts: # src/Interpreters/HashJoin/HashJoinMethodsImpl.h Co-authored-by: nickitat <[email protected]>
Done. There was one conflict in |
|
|
|
@copilot pls fix the style check |
…angesHistory Co-authored-by: nickitat <[email protected]>
A set map keeps no reference into a right block, so `HashJoin` only stores them for the algorithm that may take them back out. That algorithm decides during the build phase - `JoinSwitcher` and `SpillingHashJoin` both take the blocks out of `addBlockToJoin`, and `GraceHashJoin` while it rebuckets - so once the build phase is over and the wrapper has settled on this join, the blocks are dead weight for the whole probe phase. They were kept for it anyway, and `max_bytes_ratio_before_external_join` is non-zero by default, so `SpillingHashJoin` wraps almost every join: in the default configuration a key-only join kept every right block it had read. `SpillingHashJoin::onBuildPhaseFinish` is where the question is settled - it either hands the blocks to `GraceHashJoin` or promotes the in-memory join - so it tells the join it can let them go, for both the single-threaded `HashJoin` and the slots of a `ConcurrentHashJoin`. `GraceHashJoin`'s own per-bucket joins are left alone: it can still rebucket one after its build phase ends.
`mustKeepRightBlocks` read `join_algorithm`, which lists the algorithms that may be chosen rather than the one that was. `hash,grace_hash` with no external-join threshold, or `parallel_hash,auto`, gave a plain `HashJoin` or `ConcurrentHashJoin` that nothing wraps - and it kept every right block for the whole query anyway, because the list mentioned an algorithm that could have taken them. `JoinSwitcher` had the opposite problem: it really can take them, but it only forwarded `onBuildPhaseFinish` and so never let them go afterwards. So the wrapper says it now. `keepRightBlocksForAnotherAlgorithm` is off by default and set by the three algorithms that can call `releaseJoinedBlocks`: `SpillingHashJoin` for the join it collects into (single or concurrent), `JoinSwitcher` for its `HashJoin`, and `GraceHashJoin` for each bucket's join - that last one keeps them for good, since rebucketing can read them back at any point. `JoinSwitcher` drops them when its build phase ends without a switch, as `SpillingHashJoin` already did. Asking a key-only join for blocks it was never told to keep now throws instead of handing back an empty list and quietly losing the right side. Measured on Zen5, 10M x 5M LEFT ANTI on String keys with a GROUP BY over its output, median peak of 5 runs: `hash,grace_hash` without the external threshold 1458 -> 1189 MiB, `auto` 1450 -> 1190 MiB; `hash`, `parallel_hash,auto` and `grace_hash` unchanged. Every configuration returns the same rows, spilling ones included: with `max_bytes_before_external_join` at 32 and 8 MiB, `hash`, `parallel_hash`, `grace_hash` and `auto` all still answer 2000000. Came out of review of #115301
Five files had to be resolved by hand, all of them places where master reworked
the same lines the set maps touch:
* `HashJoin.cpp`, the per-row used flags: master reads the block's row count
through `blockRows()` now, and the branch passes the maps kind rather than a
"is this MapsAll" flag, since a set map is a third answer. Both.
* `HashJoin.cpp`, the non-joined stream: master wraps the fill in
`dispatchOutputs` and hands `fillColumnsFromMap` its row-store and columns
flags; the branch refuses a set map there, because only RIGHT and FULL joins
have non-joined rows and those never get one. Both, with the refusal inside.
* `ConcurrentHashJoin.h`: master's `onProbePhaseFinish` and the branch's two
right-block methods land side by side.
* `JoinSwitcher.cpp` and `SpillingHashJoin.cpp`: the `HashJoin` constructor
lost `use_two_level_maps_` and gained `is_concurrent_hash_join_`, and the
branch tells the join it may have to hand its right blocks over. Both.
`LEFT ANTI` and `LEFT SEMI` over 3M x 1M rows return 2000000 and 1000000 for
every algorithm - `hash`, `parallel_hash`, `grace_hash`, `auto` - with the
external-join threshold off and at 8 MiB, so the wrappers still get the blocks
they were promised. The join tests come out at 982 passed against 978 before the
merge; the two tests failing that did not before are a `ReplicatedMergeTree`
without ZooKeeper and one that reads `system.text_log`, neither of which this
configuration has.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@m-selmi, you know this code very well, maybe you could have a look? |
| static constexpr bool is_maps_all = std::is_same_v<std::decay_t<Map>, HashJoin::MapsAll>; | ||
|
|
||
| /// Whether the map stores no right row at all, so nothing of the right side can be read from it. | ||
| static constexpr bool is_maps_set = std::is_same_v<std::decay_t<Map>, HashJoin::MapsSet>; |
There was a problem hiding this comment.
I think this is not used anywhere.
There was a problem hiding this comment.
I will do it in a follow up if you don't mind.
| template <typename Key, typename Allocator = HashTableAllocator> | ||
| class FixedHashSet : public FixedHashTable<Key, FixedHashTableCell<Key>, FixedHashTableStoredSize<FixedHashTableCell<Key>>, Allocator> | ||
| template <typename Key, typename Allocator = HashTableAllocator, size_t size_bits = sizeof(Key) * 8> | ||
| class FixedHashSet : public FixedHashTable<Key, FixedHashTableCell<Key>, FixedHashTableStoredSize<FixedHashTableCell<Key>>, Allocator, size_bits> |
There was a problem hiding this comment.
We could even try to improve the FixedHashSet even more in a follow-up by making it a bitset instead of a byte flag per row. And we can allow large FixedHashSet than usual.
…squashed `LEFT ANTI JOIN` and `LEFT SEMI JOIN` without right columns build a hash table that stores the keys alone. This is ClickHouse#115301 (`join-set-maps`) squashed into one commit, so that the `SEMI JOIN` rewrite of `INTERSECT` can be benchmarked against the parallel operator on one branch. Drops out of the diff once ClickHouse#115301 is merged. Co-authored-by: nickitat <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
LEFT ANTI JOIN, andLEFT SEMI JOINwhere no column of the right table is selected now build a hash table that stores the keys alone, without a reference to a right row, and release the right-hand blocks as they are built. This makes them up to 1.5x faster and can halve the memory they use. Controlled by the new settingenable_join_key_only_hash_tables, which is enabled by default.Workflow [PR]
Sync PR [sync-upstream/pr/115301]