Skip to content

Unify hash and parallel_hash into a single join implementation - #115590

Closed
harikrishnan94 wants to merge 12 commits into
ClickHouse:masterfrom
harikrishnan94:uhj
Closed

harikrishnan94 wants to merge 12 commits into
ClickHouse:masterfrom
harikrishnan94:uhj

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #111307

hash and parallel_hash were two separate join classes running the same algorithm. Every fix, every new JOIN kind, every setting had to be done twice, and they still drifted apart. That is the motivation for this PR. The speedups are a side effect.

Behaviour changes:

  1. join_algorithm: listing hash or parallel_hash picks the same implementation and no longer decides anything by itself.
  2. parallel_hash_join_threshold now decides whether a hash join may run in parallel. Two consequences: hash on a large right table now builds in parallel where it used to be single-threaded, and parallel_hash on a right table estimated below the threshold now runs single-threaded where it always ran parallel.
  3. Parallel build and parallel non-joined-row emission cover INNER, LEFT, RIGHT and FULL. SEMI, ANTI and ASOF keep the single-slot layout.
  4. Multi-clause (OR) joins can use the parallel layout. More than one disjunct used to force the serial path.
  5. parallel_non_joined_rows_processing applies to hash joins in general, not only to parallel_hash. Unmatched right rows of a RIGHT/FULL join can come out in a different order than before.
  6. EXPLAIN prints Algorithm: HashJoin where it printed Algorithm: ConcurrentHashJoin.
  7. EXPLAIN PIPELINE can show a different number of FillingRightJoinSide processors, because the join now caps its own build threads.
  8. system.metrics loses ConcurrentHashJoinPoolThreads, ConcurrentHashJoinPoolThreadsActive and ConcurrentHashJoinPoolThreadsScheduled. HashJoinDestroyThreads, HashJoinDestroyThreadsActive and HashJoinDestroyThreadsScheduled are added for the pool that frees a large join's blocks.
  9. system.events gains HashJoinBuildMicroseconds, HashJoinBuildScatterMicroseconds, HashJoinBuildInsertMicroseconds, HashJoinBuildLockWaitMicroseconds, HashJoinProbeMicroseconds, HashJoinProbeLookupMicroseconds and HashJoinProbeGatherMicroseconds.
  10. The hash table size statistics cache now feeds the whole hash family, so plain hash also preallocates from it.
  11. The multiple-ORs rejection message is now "Only hash and parallel_hash joins support multiple ORs for keys in JOIN ON section".

Defaults are unchanged.

The changes:

  1. One HashJoin, parallel_hash is an alias of it. Parallelism moved inside: build threads take per-slot locks over a TwoLevelHashTable whose bucket count is a template parameter, and 0 buckets gives back exactly the old single-level layout. So serial and parallel are one code path now, and which of the two names you list no longer decides anything - parallel_hash_join_threshold is what controls whether the build runs in parallel. ConcurrentHashJoin is deleted. On master the same query could cost 1.02s via hash and 4.20s via parallel_hash; now there is one path and one number.

    One HashJoin now owns the maps, so it has to grow machinery ConcurrentHashJoin never had:

    • Per-bucket locks on a shared table, instead of a mutex per child HashJoin.
    • WorkerStoredData + one Arena per slot. Stored blocks and string/list nodes used to be "free" because each child HashJoin already had its own columns and pool. One object needs that split made explicit, because Arena is unsynchronized and two build threads cannot bump the same one.
    • SlotScatter into buckets of that one table, instead of scatter into N join objects.
    • PartitionedFixedHashMap. The direct-addressed maps (key8/key16) had no two-level variant, so a shared-table build had nothing to lock. Buckets now partition the one fixed buffer by key range: 256 under the parallel layout, 1 under the serial one, which is exactly the old FixedHashMap layout. parallel_hash used to build these as per-slot private maps and scatter the probe across them; now they run on the one shared map like every other type.
    • freezeMapsForProbing. After concurrent inserts, cell numbering for used flags (and min/max on a direct-addressed map) has to be settled once. The old merge did that implicitly by finishing in slot 0, then calling onBuildPhaseFinish on a quiet map.
    • Atomics for rows_to_join / keys_to_join / bucket_bytes. The old code summed after the merge; summing buckets while another thread is inserting would race.
  2. Multi-clause (OR) JOINs gain parallelism. More than one disjunct used to force the serial path, so the build stayed single-threaded no matter how many threads the query had. Now it scales: on a build-heavy join master is flat at ~2.5s from 8 threads up, while this builds 3.4x faster at 8 threads, 7.3x at 16 and 11.2x at 32. The flip side: a probe-heavy multi-clause join below ~32 threads pays 8-16% for the two-level layout; raising parallel_hash_join_threshold above the right table's size gives back the serial map.

  3. The per-lookup once-guard on two-level offsets is gone: the prefix sums are computed once when the build finishes, so the flagged probe reads them directly where master re-checks a once_flag on every found row. RIGHT JOIN ... count() over 1e8 x 2e6 rows at one thread: 9.9% faster than master, parity at 8 threads. Single-clause probes are at parity with master.

Changelog category (leave one):

  • Performance Improvement

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

The hash and parallel_hash join algorithms are now one implementation, with parallel_hash kept as an alias. Listing hash or parallel_hash in join_algorithm no longer controls how parallel the join is: parallel_hash_join_threshold decides whether a hash join may run in parallel, so hash on a large right table builds in parallel where it used to be single-threaded, and parallel_hash on a right table estimated below the threshold runs single-threaded where it always ran parallel. Multi-clause (OR-joined) JOINs can use the parallel layout, so their build scales with threads instead of staying single-threaded (up to 11x faster at 32 threads on a build-heavy join). RIGHT/FULL probes got cheaper per matched row. parallel_non_joined_rows_processing applies to hash joins in general rather than only to parallel_hash, so unmatched right rows of a RIGHT/FULL join can be emitted in a different order. EXPLAIN now prints Algorithm: HashJoin instead of Algorithm: ConcurrentHashJoin. The ConcurrentHashJoinPoolThreads, ConcurrentHashJoinPoolThreadsActive and ConcurrentHashJoinPoolThreadsScheduled metrics were removed; HashJoinDestroyThreads and its Active/Scheduled companions were added, along with seven HashJoin*Microseconds profile events. Setting defaults are unchanged.


Addendum

Why it is not "delete ConcurrentHashJoin and call it a day." parallel_hash was N private HashJoins. Each child already had its own map, arena, stored-block list and used flags, so scatter-then-merge was cheap. One object owning one map has to grow that split explicitly:

  • Serial and parallel are the same template. bits_for_bucket = 0 is one bucket; routing folds to a constant and it compiles as the old single-level table. That is why JoinHashMap is a TwoLevelHashMap even when the join is serial. The serial alias keeps HashTableGrowerWithPrecalculation: TwoLevelHashTableGrower starts a one-bucket map too small.
  • Slots, not one mutex per bucket. slotCountForThreads is bit_ceil(max_threads) capped at 256. A build thread scatters its own block and takes per-slot locks; two threads collide only when they both have rows for the same slot. insertIntoSlots try_locks from a block-number offset and yields rather than stacking everyone on slot 0.
  • WorkerStoredData is per worker_id (stored blocks, nullmaps) and needs no lock. addBlockToJoin takes that id because HashJoin now has unsynchronized per-thread state that master never needed: concurrent fill used to mean "call a different child join." Concurrent callers pass distinct ids in [0, getMaxBuildThreads()); a single-threaded filler passes 0; Grace / spilling / FillingRightJoinSide forward it.
  • One Arena per slot. Arena is an unsynchronized bump allocator; string keys and RowRefList nodes have nowhere else to go. Splitting is sound because neither allocation kind needs contiguity.
  • SlotScatter routes with the map’s own bucketRoutingHash, so scatter and insert cannot disagree. For key8/key16 it also gathers keys per slot so the insert loop is sequential.
  • PartitionedFixedHashMap. Direct-addressed maps had no two-level variant, and hashing the key itself would dump a dense range into one bucket. Routing hashes the key’s cache line: the range spreads, and two keys on the same line cannot be written under two locks. Storage is still one flat buffer; buckets only partition the locks. Min/max bounds are disabled during the concurrent fill and restored in freezeMapsForProbing.
  • freezeMapsForProbing after the last insert. Used flags are indexed by cell number, and those numbers are only well-defined once no bucket is still growing. The probe then uses offsetInternalUnsafe (master re-checked a once_flag on every found row). Direct-addressed min/max is restored in the same call.
  • rows_to_join / keys_to_join / bucket_bytes are atomics. Summing buckets while another thread is inserting would race.
  • Per-row used flags (RIGHT/FULL with extra ON filters, etc.) are appended to pending_per_worker during the build and compacted once. Resizing a shared vector from several fill threads would race.

Deliberately still serial. SEMI / ANTI / ASOF stay on the one-bucket layout: their non-joined / used-flag model does not partition across buckets. StorageJoin is filled on one thread then shared, so it pins serial. JoinSwitcher dumps blocks into MergeJoin and does the same. GraceHashJoin parallelizes by file bucket and builds each in-memory table serial: 256 empty two-level buffers would count against max_bytes_before_external_join and would not shrink as Grace adds file buckets. The pipeline caps FillingRightJoinSide at getMaxBuildThreads().

harikrishnan94 and others added 12 commits July 27, 2026 15:12
The table was fixed at 256 buckets and always routed on the high bits of the hash
a cell is placed by. Both are template parameters now.

`bits_for_bucket = 0` gives a single bucket: routing folds to a constant, the one
sub-table is stored inline, and every operation compiles down to what the
single-level table would do. A caller that wants no partitioning at all can
therefore stay on this template instead of switching to a different type, which is
what the hash join needs to build serially and in parallel through one set of map
types. `NUM_BUCKETS` becomes `numBuckets()` because the count is no longer a
property of the class alone; the call sites are updated with it.

`BucketHash` decouples bucket selection from cell placement. A `FixedHashMap`
places by the key itself, so routing on the high bits of that "hash" would drop a
dense key range into one bucket. `PartitionedFixedHashMap` gives it a routing hash
that hashes the key's cache line instead, which spreads the range and, as a side
effect, keeps two keys sharing a line in the same bucket - so they cannot be
written under two different locks.

The storage behind the buckets becomes a policy. The open-addressing tables keep
one sub-table per bucket as before; a direct-addressed table keeps its single flat
buffer and lets the buckets partition only the locks. That is also why the min/max
iteration bounds have to be switched off while several buckets are being filled,
and `restoreMinMaxOptimization` re-derives them afterwards.

The cell numbering `offsetInternal` produces is the last piece a partitioned build
needs, since the numbers have to stay distinct across buckets. The prefix sums move
behind `computeBucketPrefix` and `offsetInternalUnsafe`, which lets a probe loop
establish them once for a block rather than pay the "already computed" check on
every lookup.

Co-Authored-By: Claude Opus 5 <[email protected]>
The probe loop did a `findKey` and then emitted the match for the same row before
moving on. The emit therefore waits on that row's hash-table cell, and since the
cell is a cache miss for anything larger than the last-level cache, the next row's
lookup cannot start until the current one has landed.

Split the loop in two over a batch of rows: the lookup pass records where each key
landed, and a second pass over those records emits. Nothing in the emit pass touches
the hash table, so the misses of a batch overlap each other instead of serializing
behind their emits. The record for a row is a single 8-byte word - the mapped value
itself for the types that fit in one, a pointer into the cell for ASOF - and zero
means no match, since an occupied cell can never be all-zero.

For lazy ALL joins that default their misses, the recorded word is already exactly
what the output array wants, so the lookup writes straight into it and the second
pass does nothing but the running offset and the used flags.

Multiple disjuncts become clause-major: every clause looks up the whole batch, then
one pass emits across all of them. The row-major loop used to `break` out of the
clause loop on the first match for SEMI and ANY; folding what has matched so far
into the next clause's skip bytes keeps that, and lets all the clauses share the
same lookup bodies as the single-clause probe.

The `fast_path` template parameter goes away with it. It existed to compile out the
per-row null-map and join-mask checks, which the lookup pass now gets from a byte
array prepared once per call, so the two variants of every probe body it used to
double are gone. Squeezing the emitted code back down is the reason the pieces are
keyed and outlined the way they are; the comments record what each choice measured.

Co-Authored-By: Claude Opus 5 <[email protected]>
`parallel_hash` was a second join class that owned N independent `HashJoin`s. It
scattered every right-side block by hash and handed each slot its own share, so each
slot ended up with its own maps, its own arena, its own stored-block list and its own
used flags, and a probe had to visit all N of them.

Keeping two implementations of one join in step turned out to be the expensive part.
The features only ever landed on one side: `StorageJoin` and `joinGet`, ASOF, the
dictionary-aware LowCardinality maps, the fixed and range maps, the runtime filters
published from a fixed map, right-table re-ranging - all of that lives in `HashJoin`,
and `parallel_hash` either fell back to the serial class or silently did without.

There is one class now. A clause has one map; when the build may run in parallel it is
the 256-bucket layout from the previous commit, otherwise the one-bucket layout, which
compiles to what the plain open-addressing table did. A build thread scatters its own
block's rows into per-slot selectors and inserts each slot under that slot's lock, so
two threads collide only when the same block sends rows to the same slot; the slots
are a power of two, at most one per bucket. Each slot also owns an arena, because
`Arena` is an unsynchronized bump allocator and the string keys and row-ref list nodes
have to be allocated somewhere. The stored blocks stay per build thread and need no
lock at all, which is what the `worker_id` on `addBlockToJoin` is for: it names the
caller's slice of that state, and `IJoin` documents that two live callers may not
share one.

Reading back what the build produced is what needed the most care. The running row,
key and byte counts are atomics rather than sums over the buckets, because a sum would
race with a concurrent insert; the per-bucket cell numbering that the RIGHT/FULL used
flags are indexed by has to be established once the last insert is done, which is what
`freezeMapsForProbing` does; and the unmatched-rows scan now partitions the map buckets
and the stored blocks across the parallel non-joined streams, with the nullmap rows -
which no bucket owns - left to one of them.

For the user, `hash` and `parallel_hash` are two names for this class from here on.
`parallel_hash_join_threshold` still decides whether a join runs in parallel, but it
now picks the map layout inside one implementation instead of picking a class, and it
applies whichever of the two names was listed in `join_algorithm`. `EXPLAIN` therefore
reports `HashJoin` where it used to report `ConcurrentHashJoin`. The three tests that
compared the two algorithms against each other have nothing left to compare and are
deleted; 04107 keeps its subject - nullable and ASOF keys under a parallel build - and
drops the comparison.

Co-Authored-By: Claude Opus 5 <[email protected]>
Freeing the right side of a big join is single-threaded work at the end of a query
that had every core busy a moment earlier. The maps themselves are cheap - their
cells are trivially destructible - but the stored columns and the slot arenas are
not, and there are now one list and one arena per build thread, which is exactly
the shape a parallel free wants.

Only above 100 MB, and only when the join actually had several build threads, so a
small join does not pay for a thread pool it cannot fill. A join whose data is
shared through `reuseJoinedData` leaves it to the last owner.

Co-Authored-By: Claude Opus 5 <[email protected]>
The probe loop is now two passes over a batch, and whether recording outcomes pays
for the traffic it adds depends on the key type, the cardinality, the map layout and
the thread count. Answering that from a SQL query means measuring the whole pipeline;
this harness measures the loop.

`--verify` first: it builds both map layouts over the same input and compares the
emitted row refs structurally, so a run that is faster because it emits the wrong
thing fails before any number is printed. Arena addresses differ between builds, so
the digest is over the row counts a cell word stands for, not the pointer bits.

`probeSequentialTwoPhase` mirrors `joinRightColumns`' batch loop rather than calling
it, because that loop is a member of a class template the harness cannot instantiate
without an `AddedColumns`. It picks between the fused and the recording arm with the
same predicate production does, so the two cannot drift silently - if they ever do,
`--verify` is what notices.

Co-Authored-By: Claude Opus 5 <[email protected]>
A slow join query says nothing about which half of the join is slow, and there was
no way to tell from `system.query_log` alone. Seven events, arranged so that each
phase has a total and its parts add up under it.

On the build side `HashJoinBuildMicroseconds` covers everything from
`addBlockToJoin` through `onBuildPhaseFinish`, with the scatter, the insert, and the
time a build thread spends yielding for a slot lock broken out. That last one is the
number to look at when a parallel build does not scale: it separates lock contention
from the work itself.

On the probe side `HashJoinProbeMicroseconds` covers the lookup and the draining of
the result, with the hash-map lookup and the gathering of the right-side column
values broken out separately, since those two have completely different remedies.

All of them are summed over every thread, so they measure CPU spent rather than wall
clock and can exceed the query's duration.

Co-Authored-By: Claude Opus 5 <[email protected]>
The join-algorithm guide still described `parallel_hash` as a variation of `hash`
that builds several hash tables, and the best-practices page named it as the default
algorithm. Both are now one class, and which of the two names appears in
`join_algorithm` no longer decides anything.

Co-Authored-By: Claude Opus 5 <[email protected]>
Autogenerated output only: the seven new `HashJoin` timing events and the renamed
destroy-thread metrics in the `system.events`, `system.metrics`,
`system.metric_log` and `system.query_metric_log` pages, and the reworded
`join_algorithm`, `parallel_hash_join_threshold` and
`parallel_non_joined_rows_processing` descriptions with their version-history rows.

Co-Authored-By: Claude Opus 5 <[email protected]>
`AggregateFunctionUniqCombined` gained a `ColumnType` template parameter,
but the two instantiations in `benchmark_statistics.cpp` were not updated,
so the benchmark stopped compiling. It is only built with
`ENABLE_BENCHMARKS=1`, which CI does not exercise, so the breakage went
unnoticed.

Pass `ColumnVector<UInt64>` and `ColumnVector<Float64>` as `ColumnType`,
the same way the dispatch in `AggregateFunctionUniqCombined.h` does.

Co-Authored-By: Claude Opus 5 <[email protected]>
Splitting the probe into a lookup pass and an emit pass paid for itself only
where a batch amortized the boundary over many emitted rows - multi-clause
probes. Everywhere else the recorded words cost more than they saved:
single-clause probes measured 12-25% behind the fused loop, 43% for RIGHT,
and making the lookup sink kind-aware recovered almost none of it, because
the cost lives in the loop machinery around the boundary, not in the emitted
work. Give the boundary back: one pass per row, `findKey` and the per-kind
emission fused, exactly as before the split, keeping only the `needs_offset`
key-getter parameterization (flag-free joins no longer compute a dead cell
offset per row). The multi-clause win the split bought (3.7x on a 2-disjunct
probe) is traded away with it; the multi-clause build still parallelizes,
which the single-level fallback it replaced never did.

The probe-loop microbenchmark goes with the flow it measured.

Co-Authored-By: Claude Fable 5 <[email protected]>
`markPerOffsetUsed` claimed the flag with an unconditional `exchange`, so a
key matched N times dirtied its flag's cache line N times where the pre-fold
code stored only once. The exchange exists for `unset_offset_flags` - the
counter behind the O(1) `allOffsetFlagsSet` - which must be decremented
exactly once per flag; but only the first mark needs to win it. Every other
marking path already had the check-first fast path, this one just missed it:
after warm-up a re-mark is a relaxed load again.

Co-Authored-By: Claude Fable 5 <[email protected]>
`BucketPrefixSums::offset` re-checked a `once_flag` on every lookup, and the
flag was never even armed by `computeBucketPrefix`, so the freeze-time
computation was recomputed once more at first probe and the acquire check
paid on every found row after. `HashJoin` freezes the maps before any probe
(both build-finish paths and `reuseJoinedData` for `StorageJoin`), so the
guard protected nothing: `offsetInternal` now reads the precomputed sums
directly and `offsetUnsafe` chasserts the invariant in debug builds.

Together with the previous commit this moves RIGHT JOIN `count()` at one
thread from 9.6% behind the pre-unification baseline to 9.9% ahead of it,
and to parity at eight threads: the baseline still pays its own once-flag
guard per found row.

Co-Authored-By: Claude Fable 5 <[email protected]>
@harikrishnan94 harikrishnan94 added pr-performance Pull request with some performance improvements pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard labels Aug 20, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Merge latest master into this PR and resolve conflicts.

@groeneai

Copy link
Copy Markdown
Collaborator

I cannot push to harikrishnan94:uhj, so the merge itself has to come from you. Here is the diagnosis so it is quick, against master 9965d6a with head 03d7441 (base is 643 commits behind).

Of 174 changed files there are only two textual conflicts, plus one problem that the merge creates without reporting a conflict.

1. src/Common/HashTable/TwoLevelHashTable.h - take your side.
Master added a forEachMapped in 9e8bf27b ("Give the set tables the missing mapped-value interface instead of guarding"), which collides with the forEachMapped you already have. Keep yours: it delegates to impls.forEachMapped, and the per-bucket loop from master would not compile against your restructured impls anyway. Just make sure both empty() and your new has() survive the resolution, the conflict markers straddle that brace.

2. docs/reference/settings/session-settings/join.mdx - do not resolve by hand.
The conflicting hunk is inside the {/*AUTOGENERATED_START*/} region. Those VersionHistory rows are generated by ci/jobs/scripts/docs/autogenerate/autogenerate_docs.py from sql/session-settings.sql, which reads system.settings_changes, i.e. from SettingsChangesHistory.cpp. Fix item 3 first, then regenerate with --write and the conflict resolves mechanically.

3. src/Core/SettingsChangesHistory.cpp - silent, and it will fail a test.
.gitattributes:5 marks this file merge=union, so git keeps both sides with no conflict shown. The merge therefore lands two join_algorithm rows in the same 26.8 block: master's ie_join row, and yours recording the aliasing with new_value direct,parallel_hash,hash. The compiled default merges cleanly to direct,parallel_hash,hash,ie_join.

03999_stateless_settings_history.sh takes the expected default as argMax(new_value, (vnum, idx)), so within one version the later entry wins, which is yours. I ran that aggregate over both rows and it returns direct,parallel_hash,hash, against a system.settings default of direct,parallel_hash,hash,ie_join. join_algorithm is not in 03999_settings_value_drift_ignore.txt, so the value-drift arm fires:

PLEASE RECORD THE DEFAULT CHANGE IN SettingsChangesHistory.cpp: join_algorithm
default is direct,parallel_hash,hash,ie_join but history last records direct,parallel_hash,hash

Fix is to carry ie_join into your row's values and keep your aliasing note as the comment, so the last recorded new_value matches the compiled default.

Happy to review the PR itself once it is mergeable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unify join hash table implementations across single-level / two-level / non-parallel variants

2 participants