Repository navigation
Unify hash and parallel_hash into a single join implementation - #115590
harikrishnan94 wants to merge 12 commits into
Conversation
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]>
|
@groeneai Merge latest master into this PR and resolve conflicts. |
|
I cannot push to Of 174 changed files there are only two textual conflicts, plus one problem that the merge creates without reporting a conflict. 1. 2. 3.
Fix is to carry Happy to review the PR itself once it is mergeable. |
Closes: #111307
hashandparallel_hashwere 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:
join_algorithm: listinghashorparallel_hashpicks the same implementation and no longer decides anything by itself.parallel_hash_join_thresholdnow decides whether a hash join may run in parallel. Two consequences:hashon a large right table now builds in parallel where it used to be single-threaded, andparallel_hashon a right table estimated below the threshold now runs single-threaded where it always ran parallel.INNER,LEFT,RIGHTandFULL.SEMI,ANTIandASOFkeep the single-slot layout.OR) joins can use the parallel layout. More than one disjunct used to force the serial path.parallel_non_joined_rows_processingapplies to hash joins in general, not only toparallel_hash. Unmatched right rows of aRIGHT/FULLjoin can come out in a different order than before.EXPLAINprintsAlgorithm: HashJoinwhere it printedAlgorithm: ConcurrentHashJoin.EXPLAIN PIPELINEcan show a different number ofFillingRightJoinSideprocessors, because the join now caps its own build threads.system.metricslosesConcurrentHashJoinPoolThreads,ConcurrentHashJoinPoolThreadsActiveandConcurrentHashJoinPoolThreadsScheduled.HashJoinDestroyThreads,HashJoinDestroyThreadsActiveandHashJoinDestroyThreadsScheduledare added for the pool that frees a large join's blocks.system.eventsgainsHashJoinBuildMicroseconds,HashJoinBuildScatterMicroseconds,HashJoinBuildInsertMicroseconds,HashJoinBuildLockWaitMicroseconds,HashJoinProbeMicroseconds,HashJoinProbeLookupMicrosecondsandHashJoinProbeGatherMicroseconds.hashalso preallocates from it.hashandparallel_hashjoins support multiple ORs for keys in JOIN ON section".Defaults are unchanged.
The changes:
One
HashJoin,parallel_hashis an alias of it. Parallelism moved inside: build threads take per-slot locks over aTwoLevelHashTablewhose 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_thresholdis what controls whether the build runs in parallel.ConcurrentHashJoinis deleted. On master the same query could cost 1.02s viahashand 4.20s viaparallel_hash; now there is one path and one number.One
HashJoinnow owns the maps, so it has to grow machineryConcurrentHashJoinnever had:HashJoin.WorkerStoredData+ oneArenaper slot. Stored blocks and string/list nodes used to be "free" because each childHashJoinalready had its owncolumnsand pool. One object needs that split made explicit, becauseArenais unsynchronized and two build threads cannot bump the same one.SlotScatterinto 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 oldFixedHashMaplayout.parallel_hashused 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 callingonBuildPhaseFinishon a quiet map.rows_to_join/keys_to_join/bucket_bytes. The old code summed after the merge; summing buckets while another thread is inserting would race.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; raisingparallel_hash_join_thresholdabove the right table's size gives back the serial map.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_flagon 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
hashandparallel_hashjoin algorithms are now one implementation, withparallel_hashkept as an alias. Listinghashorparallel_hashinjoin_algorithmno longer controls how parallel the join is:parallel_hash_join_thresholddecides whether a hash join may run in parallel, sohashon a large right table builds in parallel where it used to be single-threaded, andparallel_hashon 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/FULLprobes got cheaper per matched row.parallel_non_joined_rows_processingapplies to hash joins in general rather than only toparallel_hash, so unmatched right rows of aRIGHT/FULLjoin can be emitted in a different order.EXPLAINnow printsAlgorithm: HashJoininstead ofAlgorithm: ConcurrentHashJoin. TheConcurrentHashJoinPoolThreads,ConcurrentHashJoinPoolThreadsActiveandConcurrentHashJoinPoolThreadsScheduledmetrics were removed;HashJoinDestroyThreadsand itsActive/Scheduledcompanions were added, along with sevenHashJoin*Microsecondsprofile events. Setting defaults are unchanged.Addendum
Why it is not "delete ConcurrentHashJoin and call it a day."
parallel_hashwas N privateHashJoins. 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:bits_for_bucket = 0is one bucket; routing folds to a constant and it compiles as the old single-level table. That is whyJoinHashMapis aTwoLevelHashMapeven when the join is serial. The serial alias keepsHashTableGrowerWithPrecalculation:TwoLevelHashTableGrowerstarts a one-bucket map too small.slotCountForThreadsisbit_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.insertIntoSlotstry_locks from a block-number offset and yields rather than stacking everyone on slot 0.WorkerStoredDatais perworker_id(stored blocks, nullmaps) and needs no lock.addBlockToJointakes that id becauseHashJoinnow 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 passes0; Grace / spilling /FillingRightJoinSideforward it.Arenaper slot.Arenais an unsynchronized bump allocator; string keys andRowRefListnodes have nowhere else to go. Splitting is sound because neither allocation kind needs contiguity.SlotScatterroutes with the map’s ownbucketRoutingHash, so scatter and insert cannot disagree. Forkey8/key16it 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 infreezeMapsForProbing.freezeMapsForProbingafter 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 usesoffsetInternalUnsafe(master re-checked aonce_flagon every found row). Direct-addressed min/max is restored in the same call.rows_to_join/keys_to_join/bucket_bytesare atomics. Summing buckets while another thread is inserting would race.RIGHT/FULLwith extra ON filters, etc.) are appended topending_per_workerduring the build and compacted once. Resizing a shared vector from several fill threads would race.Deliberately still serial.
SEMI/ANTI/ASOFstay on the one-bucket layout: their non-joined / used-flag model does not partition across buckets.StorageJoinis filled on one thread then shared, so it pins serial.JoinSwitcherdumps blocks intoMergeJoinand does the same.GraceHashJoinparallelizes by file bucket and builds each in-memory table serial: 256 empty two-level buffers would count againstmax_bytes_before_external_joinand would not shrink as Grace adds file buckets. The pipeline capsFillingRightJoinSideatgetMaxBuildThreads().