Skip to content

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

Merged
harikrishnan94 merged 109 commits into
masterfrom
uhj
Nov 3, 2026
Merged

harikrishnan94 merged 109 commits into
masterfrom
uhj

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

#120513 sits on this.

Closes: #111307
Closes: #107590

hash and parallel_hash were two classes running the same algorithm.

hash              one HashJoin, one map, one thread
parallel_hash     N private HashJoin objects
                  each child has its own map, arena, blocks, used flags
                  scatter into the children, merge at the end

join_algorithm    the name you list picks the class

On master the same query could be much slower via parallel_hash than via hash. Every fix, every new JOIN kind and every setting had to be done twice. The two classes still drifted. When join_algorithm listed only one of the two names, that name decided parallelism. So a large hash stayed on one thread, and a small parallel_hash always ran parallel. More than one OR disjunct forced the serial path.

There is one HashJoin now. parallel_hash is an obsolete alias of hash. Both names select this class, and neither name controls parallelism.

one HashJoin
  parallel_hash is an obsolete alias of hash
  both names select this class and do not control parallelism

  parallel_hash_join_threshold picks the layout, max_threads does not
        large right table, or no estimate -> parallel layout
        below the threshold               -> serial layout

  parallel layout
  +-- one two-level table, 256 buckets
  +-- per-slot locks
  +-- up to max_threads threads fill it

  serial layout
  +-- the same template, 1 bucket
  +-- BITS_FOR_BUCKET = 0 behaves as the old single-level table

ConcurrentHashJoin is deleted. The default of parallel_hash_join_threshold is unchanged. The new setting hash_join_layout (auto, serial, parallel) forces the layout, for tests and debugging. auto is the default and leaves the choice to parallel_hash_join_threshold. The default join_algorithm list drops parallel_hash and is direct,hash,ie_join. Existing configs that name parallel_hash still work.

For a user:

  1. Listing hash or parallel_hash picks the same implementation. parallel_hash reads back as hash, for example in system.settings and in getSetting.
  2. parallel_hash_join_threshold decides whether a hash join uses the parallel layout. hash on a large right table builds in parallel, where it used to be single-threaded. parallel_hash on 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. 0 always gives the parallel layout. hash_join_layout = 'serial' or 'parallel' forces the layout whatever the estimate. The old analyzer never has an estimate. max_threads does not change the layout. It only sets how many threads can fill a table with the parallel layout, so with max_threads = 1 one thread fills all its buckets.
  3. Parallel build and parallel non-joined-row emission follow JoinKind (INNER, LEFT, RIGHT, FULL). SEMI, ANTI and ASOF use that same gate, so a LEFT ASOF or RIGHT ANTI join gets the parallel layout when the threshold allows it.
  4. A join with several OR disjuncts 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. Setting parallel_hash_join_threshold to its largest value gives back the serial map.
  5. A join built in parallel fills its table from several streams, as parallel_hash did. ANY can pick a different right row for a key. ALL can list the matches of a key in a different order. Unmatched right rows of a RIGHT or FULL join can come out in a different order too. Use ORDER BY when the query needs a stable order.
  6. parallel_non_joined_rows_processing applies to every hash join built in parallel, not only to parallel_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.
  7. Three optimizations work only with the serial layout. After the build, the join can convert a key32 or key64 map to a direct-addressed map. It can build a runtime filter from a direct-addressed map. A single LowCardinality key can use a dictionary-aware map. So a hash join with the parallel layout loses them. A parallel_hash join with the serial layout gains them.
  8. EXPLAIN prints Algorithm: HashJoin where it printed Algorithm: ConcurrentHashJoin. In system.query_log, used_join_algorithms shows HASH for every hash join, including one built in parallel. On master, a join that ran as parallel_hash showed PARALLEL_HASH. A query that filters on PARALLEL_HASH finds no new rows.
  9. EXPLAIN PIPELINE can show a different number of FillingRightJoinSide processors. A hash join with the serial layout has one. A hash join with the parallel layout has up to max_threads.
  10. system.metrics replaces ConcurrentHashJoinPoolThreads, ConcurrentHashJoinPoolThreadsActive and ConcurrentHashJoinPoolThreadsScheduled with HashJoinDestroyThreads, HashJoinDestroyThreadsActive and HashJoinDestroyThreadsScheduled. 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-level ASOF maps. The pool frees the stored blocks, the null maps, the arenas and the buckets of those ASOF maps, on up to max_threads threads named HashJoinDtor. The rest of the maps are freed on one thread. So is a join that the planner builds on one thread, in either layout.
  11. system.events gains HashJoinBuiltWithParallelLayout and HashJoinBuiltWithSerialLayout. 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.
  12. The hash table size statistics cache now also covers a join_algorithm list with only hash. On master, only a list with parallel_hash got entries. When the cache has an entry for the join, its right-table row count is the estimate that parallel_hash_join_threshold is 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 several OR disjuncts does not, and neither does a join with the serial layout.
  13. For an input that reads nothing, such as a MergeTree table 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 an ASOF join, a join with a residual ON condition, and any join with query_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 RIGHT or FULL join only reads them.

Reading order: HashJoin.h (HashJoinBuildLayout, RightTableData and the class comment) -> HashJoin::addBlockToJoin -> scatterBlockBySlot -> BuildSlots and HashJoinMethods::insertFromBlockImplTypeCase -> onBuildPhaseFinish and freezeMapsForProbing -> the planner's choice of layout (TableJoin::preferParallelHashLayout) -> the wrappers (SpillingHashJoin, GraceHashJoin, StorageJoin) -> ~RightTableData.

The one object:

  1. Serial and parallel are the same template. BITS_FOR_BUCKET = 0 is one bucket. The serial JoinHashMap is a TwoLevelHashMap too. The serial grower stays HashTableGrowerWithPrecalculation. TwoLevelHashTableGrower grows 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.
  2. Locks are per slot, not per bucket. BuildSlots keeps one lock and one arena per slot. HashJoinBuildLayout::twoLevel gives 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::insert try-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.
  3. BuildStreamData holds the stored blocks and null maps of one build stream and needs no lock. onBuildPhaseFinish splices the lists of all build streams into those of the first one. Each FillingRightJoinSide gets its stream number in a JoinBuildContext, below getMaxBuildThreads. A single-threaded filler uses JoinBuildContext::serial, which is stream 0. Grace, spilling and JoinSwitcher forward the caller's context.
  4. One Arena per slot. Arena is unsynchronized. String keys and RowRefList nodes have to go somewhere. Neither kind needs contiguity, so splitting is fine.
  5. scatterBlockBySlot routes with the map's own hash and getBucketOfKey, so scatter and insert cannot disagree.
  6. The direct-addressed maps (key8, key16 and the range* maps) are PartitionedFixedHashMap, from Let TwoLevelHashTable choose its bucket count, and add PartitionedFixedHashTable #120024.
  7. freezeMapsForProbing runs 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 offsetInternal. Min and max of the direct-addressed maps stay off during the concurrent fill, and freezeMapsForProbing restores them.
  8. rows_to_join, keys_to_join and bucket_bytes are atomics. Summing buckets while another thread is inserting would race.
  9. Per-row used flags go to pending_per_build_stream during the build and get compacted once. Resizing a shared vector from several fill threads would race. A RIGHT, FULL or ANY INNER join with several OR disjuncts keeps such flags. So does a RIGHT or FULL join with an extra ON condition over both tables.

Some joins always use the serial layout. StorageJoin is filled on 1 thread, then shared. A join with a key-value storage on the right is serial too. JoinSwitcher builds its HashJoin with the serial layout. GraceHashJoin already 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 against max_bytes_before_external_join and could make Grace rehash past grace_hash_join_max_buckets. hash_join_layout = 'parallel' does not change any of these joins.

SpillingHashJoin gives its HashJoin the same layout as a bare one. Its build threads fill it under a shared lock. When it reaches its memory limit, it switches to GraceHashJoin under 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):

  • Backward Incompatible Change

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

hash and parallel_hash are now one join implementation. parallel_hash is an obsolete alias of hash: it is removed from the default join_algorithm, still accepted, and reads back as hash. A hash join now picks its layout from parallel_hash_join_threshold and 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 to max_threads threads fill. The largest value always builds one part. The new setting hash_join_layout (auto by default, serial or parallel) forces the layout, for tests and debugging. Joins with OR in ON can build in parallel. A join built in parallel can return rows in a different order and pick a different row for ANY; use ORDER BY for a stable order. EXPLAIN shows HashJoin instead of ConcurrentHashJoin; the profile events HashJoinBuiltWithParallelLayout / HashJoinBuiltWithSerialLayout show which layout a hash table was built with. used_join_algorithms in system.query_log shows HASH for every hash join. The ConcurrentHashJoinPoolThreads* metrics are replaced by HashJoinDestroyThreads*.


Workflow [PR]
Sync PR [sync-upstream/pr/115605]

Version info

  • Merged into: 26.11.1.1177-master (included in 26.11 and later)

@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
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd131aa]

Summary: ✅


AI Review

Summary

Reviewed bd131aa9c7166089c42d06d110406df8c290b00f. The PR unifies hash and parallel_hash in HashJoin, selects the build layout independently of the algorithm name, and adapts spilling and teardown. No new actionable findings remain. The previous multi-disjunct preallocation issue is fixed, and its review thread is resolved. The documented performance tradeoff for joins without estimates is accepted.

Final Verdict

Status: ✅ Approve.

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Aug 20, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

cc: @rschu1ze

@ayakovlev-clickhouse

Copy link
Copy Markdown
Contributor

Thanks for implementing the change and merging Hash join implementations.

Questions/Asks

hash and parallel_hash are aliases of the same join class. ...

Can you pls also mark it as obsolete? This way, it will be clear to users what to use.

EXPLAIN prints Algorithm: HashJoin where it printed Algorithm: ConcurrentHashJoin.

What will be a new way in EXPLAIN to understand when parallel mode is enabled?

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

hash and parallel_hash are aliases of the same join class. ...

Can you pls also mark it as obsolete? This way, it will be clear to users what to use.

Good idea! Done. parallel_hash is now an obsolete alias of hash. Dropped from the default join_algorithm list (direct,hash,ie_join), still accepted so existing configs don't break.

EXPLAIN prints Algorithm: HashJoin where it printed Algorithm: ConcurrentHashJoin.

What will be a new way in EXPLAIN to understand when parallel mode is enabled?

One can't tell from the plan anymore. Algorithm: ConcurrentHashJoin is gone, the join always prints HashJoin, same as aggregating or sorting not printing a thread count. Looking at EXPLAIN PIPELINE: more than one FillingRightJoinSide on the build means parallel (× N with compact_repeated_processor_chains = 1). A single one means serial: right table below parallel_hash_join_threshold, or SEMI/ANTI/ASOF, or max_threads = 1. That's how they already read the other operators, isn't it?

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

@groeneai Fix merge conflicts

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

Closes: #107590

@groeneai

Copy link
Copy Markdown
Collaborator

I cannot push to ClickHouse:uhj: my account has push: false on ClickHouse/ClickHouse and maintainerCanModify is false on this PR, so the merge has to come from you. Diagnosis below so it is quick, against master 590a91d with head f1c8c13 (base 489 behind).

There is exactly one textual conflict now, src/Interpreters/HashJoin/KeyGetter.h, and the obvious resolution does not compile. Worth reading before you resolve it.

The master side is 7b9a7b8, which fixed a heap-use-after-free by changing the IColumnUnique::tryGetSavedHash() signature from const UInt64 * to std::span<const UInt64>. The struct member declaration auto-merges to the span with no conflict shown, while the conflicted body is still your raw-pointer form. std::span has no operator bool, so keeping your side verbatim gives:

KeyGetter.h:105:13: error: value of type 'const std::span<const UInt64>' is not
contextually convertible to 'bool'

I compiled all three arms on InnerHashJoinAll.cpp.o (clang++-21, Debug): your side verbatim fails, the resolution below passes, and reverting to your side fails again.

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);

routingHashForRow and the emplaceKey delegation stay as you wrote them. Semantics are unchanged: a position inside the snapshot uses the memoized hash, one outside takes the hash-from-key branch that already exists there.

Two things I flagged on #115590 are now clean, so please ignore that advice. SettingsChangesHistory.cpp is fine: f1c8c13 leaves one join_algorithm row in the 26.8 block whose new_value is direct,hash,ie_join, matching the merged compiled default, so the 03999 value-drift arm does not fire despite the merge=union attribute. join.mdx no longer conflicts after 17de60a.

src/Common/ColumnsHashing.h already carries the span form and this PR does not touch it, so nothing to do there.

Happy to review the PR itself once it is mergeable.

@mintlify

mintlify Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 2, 2026, 8:13 PM

@rschu1ze

Copy link
Copy Markdown
Member

@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?

@harikrishnan94

harikrishnan94 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@rschu1ze
I did start out planning to split it. Two things stopped me.

  1. No stacked PRs here. CI only runs when the base is master, so a split means N refactoring PRs where each one has to merge before the next can even get checks. The unified path only exists after the last one lands, so CI on PRs 1..N-1 tells me nothing about the end state. As one PR I get one CI run over the whole thing.

  2. Serial review cycles. Every PR in the chain goes through its own review round, one after the other. 4 PRs is 4 sequential rounds, and on a change this size that is weeks of wall clock before any of it is in.

There is also a readability cost to splitting. For eg: take the TwoLevelHashTable change (bucket count and bucket hash as template params, PartitionedFixedHashMap for the direct-addressed maps). On its own it shows the new API but not a single use of it, so you would have to wait for the next PR to see how the structure is actually driven. Reviewing it in isolation is harder, not easier, IMHO.

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.

harikrishnan94 added a commit that referenced this pull request Aug 25, 2026
`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]>
harikrishnan94 added a commit that referenced this pull request Aug 25, 2026
…`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]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Interpreters/ExpressionAnalyzer.cpp Resolved
Comment thread src/Interpreters/HashJoin/HashJoin.h Resolved
harikrishnan94 added a commit that referenced this pull request Aug 26, 2026
…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]>
Comment thread src/Interpreters/JoinSwitcher.cpp Resolved
harikrishnan94 added a commit that referenced this pull request Aug 26, 2026
`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)
harikrishnan94 and others added 12 commits November 1, 2026 03:27
`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]>
@harikrishnan94

harikrishnan94 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Done. Kept the serial control and added your query as. Also added the same threshold with join_algorithm = 'parallel_hash,hash'.
CI, master -> PR:

  1. serial pin: AMD 120 -> 120 ms, ARM 89 -> 89 ms
  2. parallel_hash,hash: AMD 174 -> 168 ms, ARM 117 -> 115 ms
  3. hash: AMD 143.2 -> 202.7 ms, ARM 89.4 -> 116.5 ms (the earlier run you quoted; the code it runs hasn't changed) is slower by design. Master's hash is always serial, and without an estimate this PR builds in parallel, at the same cost as master's parallel_hash.

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]>
@CLAassistant

CLAassistant commented Nov 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
harikrishnan94 and others added 2 commits November 2, 2026 20:18
`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]>

@nickitat nickitat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

otherwise, lgtm

Comment thread src/Core/Settings.cpp Resolved
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-backward-incompatible Pull request with backwards incompatible changes pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

9 participants