Repository navigation
Unify hash and parallel_hash into a single join implementation - #115605
Conversation
|
Workflow [PR], commit [bd131aa] Summary: ✅
AI ReviewSummaryReviewed Final VerdictStatus: ✅ Approve. |
|
cc: @rschu1ze |
|
Thanks for implementing the change and merging Hash join implementations. Questions/Asks
Can you pls also mark it as obsolete? This way, it will be clear to users what to use.
What will be a new way in EXPLAIN to understand when parallel mode is enabled? |
Good idea! Done.
One can't tell from the plan anymore. |
|
@groeneai Fix merge conflicts |
|
Closes: #107590 |
|
I cannot push to There is exactly one textual conflict now, The master side is I compiled all three arms on Keep your refactor shape and take master's bounds check at all three read sites: - const UInt64 * saved_hash = nullptr;
+ /// Dictionary positions outside it have no saved hash and are hashed from the key.
+ std::span<const UInt64> saved_hash;
/// in routingHashForRow
- if (saved_hash)
+ if (row < saved_hash.size())
return saved_hash[row];
/// in findKey
- auto it = saved_hash ? data.find(key, saved_hash[row]) : data.find(key);
+ auto it = row < saved_hash.size() ? data.find(key, saved_hash[row]) : data.find(key);
Two things I flagged on #115590 are now clean, so please ignore that advice.
Happy to review the PR itself once it is mergeable. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
@harikrishnan93: Thanks for this PR. It is also really big ... probably too big to get it reviewed properly. Would it be possible to split it into smaller pieces? |
|
@rschu1ze
There is also a readability cost to splitting. For eg: take the So this PR is the balance I settled on. I had more refactoring planned on top (a two-phase probe restructuring) and I dropped it to keep the diff smaller rather than split the PR. If we work out a way to stack PRs and still get CI on them, I'll happily split this. That gets both, small PRs and a short cycle. |
`TwoLevelHashTable`'s converting constructor is constrained with `requires(!std::is_arithmetic_v<Source>)`. That made the inherited ctor win over `AggregationDataWithNullKeyTwoLevel`'s unconstrained converting ctor, so `convertToTwoLevel` copied cells and discarded `hasNullKeyData`. Give the derived converting ctor the same constraint so it hides the inherited one and still copies the NULL group onto `impls[0]`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115605&sha=3f6c751bdb8b8fc439282754660f8789516118c2&name_0=PR&name_1=Fast%20test #115605 Co-authored-by: Cursor <[email protected]>
…`ORDER BY`. `ORDER BY number LIMIT 10` over unbounded `system.numbers` reads until `max_rows_to_read` (`TOO_MANY_ROWS` at 20.02 million). A prefix `LIMIT 10` without a sort still yields 0-9. Empty-right `ANY LEFT JOIN` must scan the left, so the bound belongs in the test. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115605&sha=3f6c751bdb8b8fc439282754660f8789516118c2&name_0=PR&name_1=Fast%20test #115605 Co-authored-by: Cursor <[email protected]>
…unmatched right rows. `joinPipelinesByShards` clones with `cloneNoParallel` and never adds `NonJoinedBlocksTransform`. After folding `parallel_hash` into `HashJoin`, that clone kept `use_parallel_layout`, so `JoiningTransform` skipped unmatched right rows. https: //github.com//pull/115605#discussion_r3859670439 Co-authored-by: Cursor <[email protected]>
`ExpressionAnalyzer` passed `nullopt` into `preferParallelHashLayout`, which treats a missing estimate as "use the parallel layout". Walk `joined_plan` with `estimateReadRowsCount` so a small MergeTree right side stays serial, same as the planner. #115605 (comment)
`BuildSlots` kept the size hint and the spill budget, and capped the reserve at the first insert of each slot into each map. All maps of a join have the same table type, so `HashJoin` now caps the reserve once in its constructor, and `BuildSlots` keeps only the capped number of keys. The reserved sizes do not change. The doc comment of `reserveOnFirstInsert` now says that only `HashJoinPreallocatedElementsInHashTables` uses the share it returns. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pool that frees a large right table got one more thread for each slot arena that holds memory. The arenas are pool jobs either way, and freeing one costs a few frees per chunk, so they need no threads of their own. The thread count now comes from the stored blocks and the `ASOF` buckets, and `BuildSlots::numArenasWithMemory` is gone. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The override locked `totals_mutex` only to return a reference, and every caller reads the totals after the build. `setTotals` keeps the lock. In a parallel build, every `FillingRightJoinSideTransform` without a totals port calls it with a zero-row block, as with `ConcurrentHashJoin` on master. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each build stream of a hash join appends to its own lists without a lock. Their names said worker, although no thread owns them: `JoinBuildContext::getStream` indexes them, and any pool thread can run the inserts of a stream. They now say build stream: `BuildStreamData`, `build_streams`, `spliceBuildStreamLists`, `releaseBuildStreamBlocks`, `HashJoinBuildLayout::num_build_streams`, `JoinUsedFlags::pending_per_build_stream` and `SpillingHashJoin::tryConvertBuildStreams`. This also keeps them apart from the threads of the `HashJoinDestroyThreads` pool. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
An empty `MergeTree` table is planned as `ReadNothingStep`, and `estimateReadRowsCount` gave it no estimate. A hash join with it on the right side then built on the parallel layout. To avoid that, `JoinStepLogical::buildPhysicalJoin` walked the right input to find a `ReadNothingStep`, and `tryCreateJoin` counted such an input as 0 rows for `INNER`, `RIGHT` and `LEFT SEMI` joins. Now `estimateReadRowsCount` returns 0 rows for `ReadNothingStep`, and `parallel_hash_join_threshold` picks the serial layout by itself. The walk, `JoinAlgorithmParams::rhs_known_empty` and the special case are gone. The estimate also reaches join reordering, as for an exact empty range of a `MergeTree` read or an empty `Memory` table. `LEFT`, `LEFT ANTI` and `FULL` joins with an empty right side now build serially too, as master does for any right side estimated at 0 rows. A join that is not reordered gets no estimate, so it keeps the parallel layout. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ings` `JoinSettings::updatePlanSettings` always sets `join_algorithm`, so the plan carries the value of the query and never reads this default. Changing it had no effect. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test pins `parallel_hash_join_threshold` to its largest value, so that `hash` builds serially as on master. A new query repeats the query with two joins under `join_algorithm = 'parallel_hash,hash'` and the default threshold. With both names listed, master picks the layout with the threshold too, so the comparison stays like-for-like. Without row estimates both builds are parallel. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The comments of `HashJoin::setTotals`, `shrinkStoredBlocksToFit`, `releaseBuildStreamBlocks` and `GraceHashJoin::makeInMemoryJoin` now say which build streams or threads they mean. The docs of `parallel_hash_join_threshold` state the 0-row estimate of an empty table before the cases without an estimate. The JOIN guide says that `parallel_hash`, as an alias of `hash`, supports `OR` keys. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`capReserveAtSpillBudget` now takes the cell size from the value that the visit returns, so it has no placeholder of 0. The comments of `BuildSlots::reserveOnFirstInsert` and the `HashJoin` class say who uses the reserved share and how the slot count is rounded. The docs of `parallel_hash_join_threshold`, the JOIN guide and the comments of `05326`, `05361` and `lazy_materialization_join` read in one pass. `04660_hashjoin_grace_parallel_fill_worker_capacity` is renamed after build streams. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_duplicate_names_merge_expression` The test looks for `t0_04516 × <database>.t4_04516` in the `EXPLAIN` of joins over empty tables. An empty table is now estimated as 0 rows, so the label reads `t0_04516[0] × <database>.t4_04516[0]`. The join order is the same. The check now allows an estimate in brackets after the name, and it still tells the merged shape from the unmerged one. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115605&sha=f831317fbae063620c753a7039617701c7a33dac&name_0=PR&name_1=Fast%20test PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without a row estimate, `hash` now builds its hash tables in parallel, while older versions always build them serially. The new query keeps that cost visible. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done. Kept the serial control and added your query as. Also added the same threshold with
|
The join cases check whether a join keeps its probe streams. Master's `hash` always builds the serial layout and `parallel_hash` alone always builds the parallel one. Here the layout follows the row estimate. Without an estimate the no-swap `hash` case builds in parallel and resizes its probe side. A cached estimate could also turn the `parallel_hash` case serial. The cases now pin the layout that master builds for each algorithm. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115605&sha=ddfe5d51cfdc07265bf0efcab8018cfef2087827&name_0=PR&name_1=Fast%20test PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`serial` and `parallel` force the layout of a hash join whatever the row estimate, for tests and debugging. The default `auto` keeps choosing it with `parallel_hash_join_threshold`, so nothing changes for users. Stateless tests now say `hash_join_layout = 'serial'` or `'parallel'` instead of pinning the threshold to its extremes. The perf tests keep the threshold pins: perf CI runs each test on master's binary too, and master rejects a setting it does not know. The plan setting is written only to peers at query plan serialization version 21 or above. PR: #115605 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's `SpillingHashJoin` can now spill through an order-preserving `MergeJoin` when the plan reads the left table in order. Here that path takes the collected build streams of the one `HashJoin`, as the grace hash join conversion does. The `parallel_hash` cases of the new tests pin `hash_join_layout = 'parallel'`, and the new perf test pins the layouts with the threshold, because `parallel_hash` alone no longer means the parallel layout. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cached size of a hash join counts the keys of all its disjunct maps, and each map reserved all of it. Once the cache was warm, a join with 8 `OR` clauses reserved 8 times what each map needs: with 262144 right keys and 16 threads, the first run peaked at 137 MB and the next ones at 540 MB. Master never preallocates such joins, because only `parallel_hash` with one disjunct did. Now only a join with one map uses the cached size. The `hash_join_layout` doc also said that the hash join `join_algorithm = 'auto'` starts with always builds one part. By default `auto` builds through a spilling hash join, which follows the layout. Only the hash join it uses when the join cannot spill, which can switch to a partial merge join, always builds one part. PR: #115605 Related: #115605 (comment) Related: #115605 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
#120513 sits on this.
Closes: #111307
Closes: #107590
hashandparallel_hashwere two classes running the same algorithm.On master the same query could be much slower via
parallel_hashthan viahash. Every fix, every new JOIN kind and every setting had to be done twice. The two classes still drifted. Whenjoin_algorithmlisted only one of the two names, that name decided parallelism. So a largehashstayed on one thread, and a smallparallel_hashalways ran parallel. More than oneORdisjunct forced the serial path.There is one
HashJoinnow.parallel_hashis an obsolete alias ofhash. Both names select this class, and neither name controls parallelism.ConcurrentHashJoinis deleted. The default ofparallel_hash_join_thresholdis unchanged. The new settinghash_join_layout(auto,serial,parallel) forces the layout, for tests and debugging.autois the default and leaves the choice toparallel_hash_join_threshold. The defaultjoin_algorithmlist dropsparallel_hashand isdirect,hash,ie_join. Existing configs that nameparallel_hashstill work.For a user:
hashorparallel_hashpicks the same implementation.parallel_hashreads back ashash, for example insystem.settingsand ingetSetting.parallel_hash_join_thresholddecides whether a hash join uses the parallel layout.hashon a large right table builds in parallel, where it used to be single-threaded.parallel_hashon a right table estimated below the threshold runs single-threaded, where it always ran parallel. If there is no right-table row-count estimate, the parallel layout is used, except with the largest value,18446744073709551615, which always gives the serial layout.0always gives the parallel layout.hash_join_layout = 'serial'or'parallel'forces the layout whatever the estimate. The old analyzer never has an estimate.max_threadsdoes not change the layout. It only sets how many threads can fill a table with the parallel layout, so withmax_threads = 1one thread fills all its buckets.JoinKind(INNER,LEFT,RIGHT,FULL).SEMI,ANTIandASOFuse that same gate, so aLEFT ASOForRIGHT ANTIjoin gets the parallel layout when the threshold allows it.ORdisjuncts can use the parallel layout. It used to stay single-threaded. A build-heavy join now builds faster with more threads. On master its build time did not change with the thread count. A probe-heavy multi-clause join can probe slower on the two-level layout. Settingparallel_hash_join_thresholdto its largest value gives back the serial map.parallel_hashdid.ANYcan pick a different right row for a key.ALLcan list the matches of a key in a different order. Unmatched right rows of aRIGHTorFULLjoin can come out in a different order too. UseORDER BYwhen the query needs a stable order.parallel_non_joined_rows_processingapplies to every hash join built in parallel, not only toparallel_hash. Setting it to 0 only serializes unmatched-row emission. It does not restore the old serial right-table order. The old analyzer does not pass this setting to the join. There, a join built in parallel always emits unmatched rows in parallel.key32orkey64map to a direct-addressed map. It can build a runtime filter from a direct-addressed map. A singleLowCardinalitykey can use a dictionary-aware map. So ahashjoin with the parallel layout loses them. Aparallel_hashjoin with the serial layout gains them.EXPLAINprintsAlgorithm: HashJoinwhere it printedAlgorithm: ConcurrentHashJoin. Insystem.query_log,used_join_algorithmsshowsHASHfor every hash join, including one built in parallel. On master, a join that ran asparallel_hashshowedPARALLEL_HASH. A query that filters onPARALLEL_HASHfinds no new rows.EXPLAIN PIPELINEcan show a different number ofFillingRightJoinSideprocessors. A hash join with the serial layout has one. A hash join with the parallel layout has up tomax_threads.system.metricsreplacesConcurrentHashJoinPoolThreads,ConcurrentHashJoinPoolThreadsActiveandConcurrentHashJoinPoolThreadsScheduledwithHashJoinDestroyThreads,HashJoinDestroyThreadsActiveandHashJoinDestroyThreadsScheduled. That pool is used only when a right table has at least 2000 heap objects. The count covers the columns of the stored blocks, the null maps and the keys of two-levelASOFmaps. The pool frees the stored blocks, the null maps, the arenas and the buckets of thoseASOFmaps, on up tomax_threadsthreads namedHashJoinDtor. The rest of the maps are freed on one thread. So is a join that the planner builds on one thread, in either layout.system.eventsgainsHashJoinBuiltWithParallelLayoutandHashJoinBuiltWithSerialLayout. They count the hash tables built with each layout. A table with the parallel layout counts as parallel even when one thread built it. A grace hash join adds one for each bucket that it loads into memory.join_algorithmlist with onlyhash. On master, only a list withparallel_hashgot entries. When the cache has an entry for the join, its right-table row count is the estimate thatparallel_hash_join_thresholdis compared with. A join with the parallel layout and a single disjunct also preallocates its map from the cache, even on one thread. A join with severalORdisjuncts does not, and neither does a join with the serial layout.MergeTreetable without data parts, the query plan estimates 0 rows. A hash join with such an input on the right side builds with the serial layout. Join reordering and the distributed plan see this estimate too, so such a table can move to the build side. A join that skips join reordering gets no estimate for such a table and uses the parallel layout. Examples are anASOFjoin, a join with a residualONcondition, and any join withquery_plan_optimize_join_order_limit = 0.A serial map has one bucket. Bucket routing and cell numbering fold away at compile time, so its probe runs as on a single-level map. A two-level map numbers its cells with prefix sums. They are computed after the last insert and before the probe starts. The probe of a
RIGHTorFULLjoin only reads them.Reading order:
HashJoin.h(HashJoinBuildLayout,RightTableDataand the class comment) ->HashJoin::addBlockToJoin->scatterBlockBySlot->BuildSlotsandHashJoinMethods::insertFromBlockImplTypeCase->onBuildPhaseFinishandfreezeMapsForProbing-> the planner's choice of layout (TableJoin::preferParallelHashLayout) -> the wrappers (SpillingHashJoin,GraceHashJoin,StorageJoin) ->~RightTableData.The one object:
BITS_FOR_BUCKET = 0is one bucket. The serialJoinHashMapis aTwoLevelHashMaptoo. The serial grower staysHashTableGrowerWithPrecalculation.TwoLevelHashTableGrowergrows a large bucket 2 times per rehash instead of 4. That suits the small buckets of a two-level map, but a single bucket would rehash more often.BuildSlotskeeps one lock and one arena per slot.HashJoinBuildLayout::twoLevelgives one slot per build stream, rounded up to a power of two and capped at 256. With more than one slot, a build thread scatters its own block and takes the slot locks. Two threads collide only when both have rows for the same slot.BuildSlots::inserttry-locks the slots that the block has rows for and skips a busy one. It yields only when a whole pass over the slots made no progress.BuildStreamDataholds the stored blocks and null maps of one build stream and needs no lock.onBuildPhaseFinishsplices the lists of all build streams into those of the first one. EachFillingRightJoinSidegets its stream number in aJoinBuildContext, belowgetMaxBuildThreads. A single-threaded filler usesJoinBuildContext::serial, which is stream 0. Grace, spilling andJoinSwitcherforward the caller's context.Arenaper slot.Arenais unsynchronized. String keys andRowRefListnodes have to go somewhere. Neither kind needs contiguity, so splitting is fine.scatterBlockBySlotroutes with the map's ownhashandgetBucketOfKey, so scatter and insert cannot disagree.key8,key16and therange*maps) arePartitionedFixedHashMap, from LetTwoLevelHashTablechoose its bucket count, and addPartitionedFixedHashTable#120024.freezeMapsForProbingruns 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 usesoffsetInternal. Min and max of the direct-addressed maps stay off during the concurrent fill, andfreezeMapsForProbingrestores them.rows_to_join,keys_to_joinandbucket_bytesare atomics. Summing buckets while another thread is inserting would race.pending_per_build_streamduring the build and get compacted once. Resizing a shared vector from several fill threads would race. ARIGHT,FULLorANY INNERjoin with severalORdisjuncts keeps such flags. So does aRIGHTorFULLjoin with an extraONcondition over both tables.Some joins always use the serial layout.
StorageJoinis filled on 1 thread, then shared. A join with a key-value storage on the right is serial too.JoinSwitcherbuilds itsHashJoinwith the serial layout.GraceHashJoinalready parallelizes by file bucket, so each of its in-memory tables has one bucket. A two-level table would bring 256 empty buffers. They would count againstmax_bytes_before_external_joinand could make Grace rehash pastgrace_hash_join_max_buckets.hash_join_layout = 'parallel'does not change any of these joins.SpillingHashJoingives itsHashJointhe same layout as a bare one. Its build threads fill it under a shared lock. When it reaches its memory limit, it switches toGraceHashJoinunder an exclusive lock. The build threads then move the stored blocks into Grace. Each thread takes the blocks of one build stream at a time.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
hashandparallel_hashare now one join implementation.parallel_hashis an obsolete alias ofhash: it is removed from the defaultjoin_algorithm, still accepted, and reads back ashash. A hash join now picks its layout fromparallel_hash_join_thresholdand the estimated size of the right table, not from the algorithm name. Below the threshold, one thread builds the hash table as one part. At or above it, and without an estimate, the join splits the hash table into parts that up tomax_threadsthreads fill. The largest value always builds one part. The new settinghash_join_layout(autoby default,serialorparallel) forces the layout, for tests and debugging. Joins withORinONcan build in parallel. A join built in parallel can return rows in a different order and pick a different row forANY; useORDER BYfor a stable order.EXPLAINshowsHashJoininstead ofConcurrentHashJoin; the profile eventsHashJoinBuiltWithParallelLayout/HashJoinBuiltWithSerialLayoutshow which layout a hash table was built with.used_join_algorithmsinsystem.query_logshowsHASHfor every hash join. TheConcurrentHashJoinPoolThreads*metrics are replaced byHashJoinDestroyThreads*.Workflow [PR]
Sync PR [sync-upstream/pr/115605]
Version info
26.11.1.1177-master(included in26.11and later)