Skip to content

Separate the hash join key lookup from the match handling of the join kinds - #132628

Open
harikrishnan94 wants to merge 1 commit into
ClickHouse:masterfrom
harikrishnan94:hash-join-probe-split
Open

harikrishnan94 wants to merge 1 commit into
ClickHouse:masterfrom
harikrishnan94:hash-join-probe-split

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Related: #120515

The hash join probe looks up keys in code that knows no join kind. Join kinds that treat a match alike, such as RIGHT ANY and RIGHT SEMI, share their code. A join with an inequality condition in ON holds the keys of a left block until its output ends, so its peak memory is higher.

Major gains:

  1. Smaller binary: the .text of the server binary is 11.3 MiB (3.4%) smaller on ARM and 14.0 MiB (3.6%) smaller on x86. Master has a copy of the lookup for each join kind and kind of key.
  2. Code organization: the lookup of each kind of key is written once for all join kinds. The code of a join kind only says what it does with a found key and a missing one. What the probe keeps for a left block between calls is in one object, freed with the block.

Some join shapes are significantly faster in the CI performance tests, because the rewritten probe loops compile to better code.

How it works:

On master, one loop per join kind and key type looks up the key of each left row and adds its output, so each join kind has a copy for each of the 34 key types. Here a lookup method finds the keys and knows no join kind, and a match handling says what a join does with a found key and a missing one. A join with one disjunct, one side of an OR in ON, and no inequality condition between the tables runs one loop per key type and handling: 24 handlings serve the 32 join kinds. Otherwise a loop per join kind adds the output after the lookups: a row needs all its disjuncts, and the condition runs on many pairs at once. So the lookup first writes a match word per row and disjunct: 0, or the value stored with the key, its right row or a pointer to its rows.

  1. With one disjunct and no inequality condition, each left row has at most one entry in each output array: whether it stays, where its output ends, and its right rows. So the loop sizes them once per block and writes them through local pointers, where master appended each row's right rows through a call.
  2. max_joined_block_size_rows can split the output of a left block over several calls. Later calls reuse what the probe built for the block, such as two key columns packed into 16 bytes per row and the match words.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Nov 18, 2026
Copilot AI balanced review requested due to automatic review settings November 18, 2026 11:27
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1ffc63]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/8) FAIL Performance dashboard
estimate_compression_ratio_none #0 FAIL dashboard
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

PR #132628 separates hash join key lookup from join-kind match handling and retains probe state across continuation calls to reduce duplicated code and repeated preparation. Reviewed head a1ffc63710b5e2df16892396bab19bed217701ea, the full diff, surrounding implementations, and all prior discussion. No outstanding findings remain: the earlier dispatch and row-index issues are addressed. Both new regression tests, 05622_hash_join_probe_search_batches and 05837_hash_join_probe_resume_state, pass in the current head's Fast test report. Benchmark evidence is provided in the commit message and discussion; the wider CI suite remains pending. No new inline comments were warranted.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 18, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The broad rewrite of correctness-critical hash-join probing requires maintainer validation because static review could not establish equivalence and regression and benchmark results were unavailable.

No open issues 🎉

What changed in this PR

Refactors hash-join probing to separate key lookup from join-kind match handling, building on the earlier per-disjunct HashJoinTable refactor. This reduces duplicated compiled code without intended changes to query results or settings.

Changes:

  • Introduces shared lookup functions, batched probing, and reusable stateful key getters.
  • Centralizes match handling while retaining fused lookup-and-match loops where faster.
  • Adds stateless coverage comparing join results across six input block sizes.
File Description
tests/​queries/​0_stateless/​05622_hash_join_probe_search_batches.sql.j2 Tests block-size invariance across join kinds and key types.
tests/​queries/​0_stateless/​05622_hash_join_probe_search_batches.reference Records expected counts and checksums.
src/​Processors/​QueryPlan/​Optimizations/​Cascades/​Rules/​AggregationPushdown.cpp Updates a comment to reference MatchRules.
src/​Interpreters/​HashJoin/​RightHashJoinSemi.cpp Includes the new match implementation for right semi joins.
src/​Interpreters/​HashJoin/​RightHashJoinRightAny.cpp Includes the new match implementation for legacy right any joins.
src/​Interpreters/​HashJoin/​RightHashJoinAsof.cpp Includes the new match implementation for right ASOF instantiations.
src/​Interpreters/​HashJoin/​RightHashJoinAny.cpp Includes the new match implementation for right any joins.
src/​Interpreters/​HashJoin/​RightHashJoinAnti.cpp Includes the new match implementation for right anti joins.
src/​Interpreters/​HashJoin/​RightHashJoinAll.cpp Includes the new match implementation for right all joins.
src/​Interpreters/​HashJoin/​LookupMethod.h Defines lookup contracts, match words, and key-getter reuse.
src/​Interpreters/​HashJoin/​LeftHashJoinSemiMapsSet.cpp Connects set-backed left semi joins to the match implementation.
src/​Interpreters/​HashJoin/​LeftHashJoinSemiMapsAll.cpp Connects list-backed left semi joins to the match implementation.
src/​Interpreters/​HashJoin/​LeftHashJoinSemi.cpp Includes the new match implementation for left semi joins.
src/​Interpreters/​HashJoin/​LeftHashJoinRightAnyMapsAll.cpp Connects list-backed legacy left any joins to match handling.
src/​Interpreters/​HashJoin/​LeftHashJoinRightAny.cpp Includes the new match implementation for legacy left any joins.
src/​Interpreters/​HashJoin/​LeftHashJoinAsof.cpp Includes the new match implementation for left ASOF joins.
src/​Interpreters/​HashJoin/​LeftHashJoinAnyMapsAll.cpp Connects list-backed left any joins to match handling.
src/​Interpreters/​HashJoin/​LeftHashJoinAny.cpp Includes the new match implementation for left any joins.
src/​Interpreters/​HashJoin/​LeftHashJoinAntiMapsSet.cpp Connects set-backed left anti joins to match handling.
src/​Interpreters/​HashJoin/​LeftHashJoinAntiMapsAll.cpp Connects list-backed left anti joins to match handling.
src/​Interpreters/​HashJoin/​LeftHashJoinAnti.cpp Includes the new match implementation for left anti joins.
src/​Interpreters/​HashJoin/​LeftHashJoinAll.cpp Includes the new match implementation for left all joins.
src/​Interpreters/​HashJoin/​KnownRowsHolder.h Adds reusable clearing and relocates match-output helpers.
src/​Interpreters/​HashJoin/​JoinUsedFlags.h Adds direct atomic flag access for match loops.
src/​Interpreters/​HashJoin/​JoinRightColumnsImpl.h Implements match rules, output handling, and function selection.
src/​Interpreters/​HashJoin/​JoinRightColumns.h Defines probe orchestration and batch interfaces.
src/​Interpreters/​HashJoin/​JoinRightColumns.cpp Implements batch setup and unmatched-row tracking.
src/​Interpreters/​HashJoin/​JoinFeatures.h Clarifies whole-key output behavior in comments.
src/​Interpreters/​HashJoin/​InnerHashJoinSemi.cpp Includes the new match implementation for inner semi instantiations.
src/​Interpreters/​HashJoin/​InnerHashJoinRightAnyMapsAll.cpp Connects list-backed legacy inner any joins to match handling.
src/​Interpreters/​HashJoin/​InnerHashJoinRightAny.cpp Includes the new match implementation for legacy inner any joins.
src/​Interpreters/​HashJoin/​InnerHashJoinAsof.cpp Includes the new match implementation for inner ASOF joins.
src/​Interpreters/​HashJoin/​InnerHashJoinAnyMapsAll.cpp Connects list-backed inner any joins to match handling.
src/​Interpreters/​HashJoin/​InnerHashJoinAny.cpp Includes the new match implementation for inner any joins.
src/​Interpreters/​HashJoin/​InnerHashJoinAnti.cpp Includes the new match implementation for inner anti instantiations.
src/​Interpreters/​HashJoin/​InnerHashJoinAll.cpp Includes the new match implementation for inner all joins.
src/​Interpreters/​HashJoin/​HashJoinTable.h Replaces probe loops with lookup accessors and flag sizing.
src/​Interpreters/​HashJoin/​HashJoinMethodsImpl.h Delegates probing to JoinRightColumns and removes old loops.
src/​Interpreters/​HashJoin/​HashJoinMethods.h Removes obsolete probe-method declarations.
src/​Interpreters/​HashJoin/​HashJoin.cpp Updates flag allocation and a filter-handling comment.
src/​Interpreters/​HashJoin/​FullHashJoinSemi.cpp Includes the new match implementation for full semi instantiations.
src/​Interpreters/​HashJoin/​FullHashJoinRightAny.cpp Includes the new match implementation for legacy full any joins.
src/​Interpreters/​HashJoin/​FullHashJoinAsof.cpp Includes the new match implementation for full ASOF instantiations.
src/​Interpreters/​HashJoin/​FullHashJoinAny.cpp Includes the new match implementation for full any instantiations.
src/​Interpreters/​HashJoin/​FullHashJoinAnti.cpp Includes the new match implementation for full anti instantiations.
src/​Interpreters/​HashJoin/​FullHashJoinAll.cpp Includes the new match implementation for full all joins.
src/​Interpreters/​HashJoin/​FindKeysMapsSet.cpp Instantiates shared lookups for set maps.
src/​Interpreters/​HashJoin/​FindKeysMapsOne.cpp Instantiates shared lookups for single-row maps.
src/​Interpreters/​HashJoin/​FindKeysMapsAsof.cpp Instantiates shared lookups for ASOF maps.
src/​Interpreters/​HashJoin/​FindKeysMapsAll.cpp Instantiates shared lookups for row-list maps.
src/​Interpreters/​HashJoin/​FindKeys.h Implements prefetching lookup and match-word collection.
src/​Interpreters/​HashJoin/​AddedColumns.h Retains key getters across searches and removes obsolete helpers.

Review effort: Balanced

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Nov 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a1ffc6371 with master cb694c085 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

🎉 Smaller binary: programs/clickhouse-stripped -15.47 MiB (-1.90%).

Binary sizes 🎉

🎉 programs/clickhouse-stripped is smaller than the master baseline by 18.96 MiB; 3.49 MiB of that is the known offset between the two builds, so this pull request makes it smaller by about 15.47 MiB (1.90%).

Binary Master PR Δ
programs/clickhouse-stripped 812.37 MiB 793.41 MiB -18.96 MiB (-2.33%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

36 object files changed (-29.66 MiB total), 4 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 2.94 MiB 1.39 MiB -1.55 MiB (-52.78%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 2.91 MiB 1.39 MiB -1.52 MiB (-52.22%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 2.87 MiB 1.39 MiB -1.48 MiB (-51.69%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o 2.87 MiB 1.39 MiB -1.48 MiB (-51.56%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 2.87 MiB 1.39 MiB -1.48 MiB (-51.56%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o 2.85 MiB 1.38 MiB -1.47 MiB (-51.49%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 2.75 MiB 1.37 MiB -1.38 MiB (-50.16%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp.o 2.68 MiB 1.36 MiB -1.32 MiB (-49.16%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp.o 2.68 MiB 1.36 MiB -1.32 MiB (-49.14%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 2.64 MiB 1.33 MiB -1.31 MiB (-49.69%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinRightAny.cpp.o 2.49 MiB 1.37 MiB -1.12 MiB (-45.12%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 2.48 MiB 1.37 MiB -1.11 MiB (-44.83%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAnti.cpp.o 2.40 MiB 1.31 MiB -1.10 MiB (-45.54%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp.o 2.43 MiB 1.36 MiB -1.07 MiB (-44.13%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp.o 2.43 MiB 1.36 MiB -1.07 MiB (-44.12%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 2.41 MiB 1.35 MiB -1.06 MiB (-44.08%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FindKeysMapsAll.cpp.o new 870.85 KiB +870.85 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAsof.cpp.o 2.25 MiB 1.41 MiB -864.36 KiB (-37.46%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAsof.cpp.o 2.25 MiB 1.41 MiB -864.34 KiB (-37.46%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 2.13 MiB 1.30 MiB -856.74 KiB (-39.24%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

66 translation units recompiled, 472 s compile time in total, 62 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.75 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -140.8 s (-24%) in total before that adjustment.

Translation units without a recent master baseline:

  • src/Interpreters/HashJoin/FindKeysMapsAll.cpp: 6.9 s
  • src/Interpreters/HashJoin/FindKeysMapsOne.cpp: 6.1 s
  • src/Interpreters/HashJoin/FindKeysMapsSet.cpp: 5.8 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 229.45 KiB removed -229.45 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 229.18 KiB removed -229.18 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 224.48 KiB removed -224.48 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 218.02 KiB removed -218.02 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 217.85 KiB removed -217.85 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 205.53 KiB removed -205.53 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 167.22 KiB removed -167.22 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 165.89 KiB removed -165.89 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 165.19 KiB removed -165.19 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 164.15 KiB removed -164.15 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 164.15 KiB removed -164.15 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 158.67 KiB removed -158.67 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 142.53 KiB removed -142.53 KiB (-100.00%)
programs/clickhouse COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::buildAdditionalFilter<DB::AddedColumns, DB::detail… 71.88 KiB removed -71.88 KiB (-100.00%)

Job report

@harikrishnan94 harikrishnan94 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Few comments inline. Main one is the probe time against master.

Description:

  1. item 2: each later batch has twice the rows of the one before, up to 8192 rows. As written, "up to twice as many" reads as twice the limit.
  2. item 3: an ASOF join with no row refs still takes two steps. So "every probe that records no row refs" is wrong for ASOF.

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

The perf check fails on join_runtime_filter query 18 (+33% on ARM). Below are the cause, measured on x86, and a possible fix.

I reproduced it on a 16-core x86 machine with the CI release builds of this PR and of master 2f06a79. Then I profiled both with perf.

Reproduction (median of 39 runs, master to PR):

  • Query 18: 25 to 32 ms (+28%).
  • Query 22, the ASOF form of query 18: 43 to 48 ms (+12%).
  • Query 20: 65 to 57 ms, faster.
  • Query 0: 25 to 26 ms.

Cause

  1. Every right key is unique, so HashJoin::onBuildPhaseFinish promotes the INNER ALL join to RightAny.
  2. The term o_totalprice > c_nationkey * 100 runs as a filter after the join. It needs c_nationkey from the right side, so record_row_refs is true.
  3. MatchRules::fused_with_one_disjunct covers is_any_join && inner. But is_any_join is true only for JoinStrictness::Any, so it is false for a promoted RightAny join.
  4. selectFunctions then picks the two-step path: findKeys for each search batch, then the branch-free MatchAdder::add.
  5. For a row whose key is missing, master's loop runs 7 instructions and stores nothing. The two-step path runs about 24 instructions with 4 stores: a 0 match word from findKeys, then filter[i], matched[...] and kept_words[...].
  6. In query 18, 99.99% of the probe rows miss. The probe went from 28,267 to 108,625 perf samples. That increase is 99% of the extra CPU time.

Dependence on the match rate. I varied how many probe rows find a key, and kept the filter after the join. The two-step path is 22% to 29% slower than master when up to 5% of the rows match. It breaks even at about 50%, and it is 15% faster at 100%. These numbers are for x86 and the range8_key32 key type.

Possible fix. The binary already has the fused function that query 18 needs: findKeysAndAddMatches<range8_key32, MapsAll, fast_path = true, MatchRules<Inner, RightAny, MapsAll>, need_filter = true, PrefetchingLookup>. Query 0 runs this same instance on the same data. It takes 20,000 samples there, against 26,338 for master's probe. On a miss, this function does the same work whether or not it records row refs. So on query 18 it would cost about what master costs, or less.

That suggests a fix: the probe chooses the fused or the two-step path per block, from the match rate seen so far. This needs no new instance. ASOF has no fused instance, so this choice does not help query 22. Its +12% stays until ASOF gets a fused instance. That costs one more instance per key type.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 19, 2026 04:57

AI review of a later commit does not approve the PR, see the AI Review comment.

@harikrishnan94 harikrishnan94 changed the title Split the hash join probe into a key lookup and a match step per join kind Separate the hash join key lookup from the match handling of the join kinds Nov 19, 2026
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 19, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 19, 2026 16:56

AI review of a later commit does not approve the PR, see the AI Review comment.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 19, 2026
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 19, 2026
@harikrishnan94 harikrishnan94 added the pr-performance Pull request with some performance improvements label Nov 20, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 20, 2026 04:32

AI review of a later commit does not approve the PR, see the AI Review comment.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 20, 2026 04:32

AI review of a later commit does not approve the PR, see the AI Review comment.

@harikrishnan94 harikrishnan94 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🕵 Description:

  1. there are no timings. CI at this head vs master, 57 hash join tests: median -0.7% on amd and -1.2% on arm, best -45% (join_squashing_blocks), worst outside noise +8.7% (join_runtime_filter 18 on amd, arm +1.7%). count() joins are 19% to 45% faster at every head CI ran. Isn't this a Performance Improvement entry?
  2. link #130344, and say LookupMethod and the search batches are there for its AMAC lookup. Today there's one lookup, and supports and retires_rows_in_order are always true.
  3. "With one disjunct, one pass ..." -> "With one disjunct and no additional filter". Also say that the ON condition like t1.a < t2.b is the additional filter, and define batch and search batch before point 1.

@clickhouse-gh clickhouse-gh Bot removed the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 20, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 24, 2026
… kinds

The probe of a hash join ran one loop per key type and join kind. The loop looked up a row and handled its match at
once, for one ON disjunct, for several, and for a mixed ON expression. So each join kind had a copy for each of the 34
key types, and a change to the lookup had to touch every join kind.

A lookup method now finds the keys. It visits the rows of a search and calls a functor for each row with what it found.
It knows no join kind, so another lookup method can replace it without touching the join kinds. `LookupMethod.h` has the
`LookupMethod` concept, the arguments of a key search, and `keyGetterOf`, which gives the key getter of a search.
`FindKeys.h` has the only lookup method, `PrefetchingLookup`. It is the probe loop of `HashJoinTable::probe` in the
parent commit.

With one disjunct and no additional filter, `findKeysAndAddMatches` is one pass. The lookup method finds the key of a
row, and `MatchAdder` adds the output of the row at once: the filter, the replication offsets, the row refs, the used
flags, the claims of the ANY joins, and the ASOF row. The pass is compiled per key type and match handling, not per join
kind. `MatchHandling` holds what the pass reads: the map, the used flag action, what a match adds, whether a row without
a match adds a default row or is kept, whether left rows are replicated, and whether the join always has a filter.
`MatchRules` derives it from `JoinFeatures`. Join kinds with the same handling share one pass per key type: INNER
RightAny and LEFT SEMI, RIGHT ANY and RIGHT SEMI, LEFT ANY and LEFT RightAny. A join that does not always have a filter
reads the filter flag of the block at run time.

The pass searches a block in search batches of at most `max_search_batch_rows` (4096) rows, of about equal size: 65409
rows are 15 search batches of 4089 rows and one of 4074. One `MatchAdder` adds the matches of the whole block, so the
filter, the replication offsets and the row refs come out as with one search of the block. Search batches bound the rows
that a lookup method and a key getter prepare in one call.

With several disjuncts or a mixed ON expression, the probe runs two steps per batch of left rows. `JoinProbe::findKeys`
looks up the key of every row in one disjunct and writes one match word per row: the cell word of the key, or 0 if there
is none. It depends only on the key type and the map, and sets no used flag. The match step then does what the join kind
does with the words, and it has no key type. With several disjuncts, `addMatchesOfDisjuncts` replaces `processMatch`. It
reaches the used flags of the right rows through the match words. A join that stops at its first matching disjunct looks
up a later disjunct only for the rows that no earlier one matched. With a mixed ON expression,
`addMatchesWithAdditionalFilter` collects the pairs that match on the keys and runs the filter on them, as before.

On these two paths the row limit `max_joined_block_size_rows` applies. The first batch has at most as many rows as the
limit, and each later batch doubles, up to `max_disjunct_batch_rows` (8192) rows, or up to the whole block for a mixed
ON expression. With a mixed ON expression, and for a join that replicates left rows, the key search of the first
disjunct stops once the right rows it found reach the limit. So a block that the limit splits into several calls looks
up few rows it does not use. The probe always finishes at least one row of a non-empty block, so the check of
`joinBlockImpl` for a result of 0 is removed.

Some key getters hold state for the rows of a block: `HashMethodKeysFixed` can pack the keys of all the rows into a
buffer, a getter that builds the keys of many rows at once (`PreparedJoinKeys`) fills its buffers, and the
`LowCardinality` getter fills its lookup cache per dictionary index. The probe searches a block once for each disjunct
of each batch or search batch, and the row limit can cut it into several calls of `joinBlockImpl`. So each left block
has a state, `JoinProbe::LeftBlockState`, which `HashJoin::ContinuationResult` keeps for all the calls of the block. It
holds what the probe of the block keeps or works in, apart from the block and the output. For each disjunct that is the
key columns, the kept key getter (`keptKeyGetter`) and the skip bytes (`skipBytesOf`). For the block it is the work
buffers of a batch: the match words, the key offsets, the unmatched rows, the pairs of an additional filter and the
right rows that a disjunct added. The contents of a work buffer do not outlive a batch; only its capacity lasts across
the calls, and each call poisons the buffers for MemorySanitizer. So a call that resumes a block does not pack the keys
of the whole block, convert its constant and `LowCardinality` key columns, merge its null maps, convert its ON mask or
allocate its work buffers again. The call that finishes the block frees the state before the output of the block is
built. `AddedColumns` no longer copies the key columns; it gets only the ASOF key column. The walk of `addFoundRowAll`
for a join with a used flag per row is in `addFoundRowAllWithFlagPerRow`, out of line as `addFoundRowAll` was.

A `PreparedJoinKeys` getter builds the keys of a search in chunks of 256 rows. A search that is likely to stop at the
row limit starts with chunks of 8 rows that double, so that it builds few keys it does not read. `prepareRange` picked
the small chunks for every range that starts after the first row of a block. In the parent commit, such a range was
always the rest of a block that the limit cut. Here, most search batches and batches also start after the first row. So
the lookup method now asks for the small chunks only for a search that can stop at the limit and starts after the first
row of the block. The key search of a later disjunct prepares a list of rows once per batch, so `skipUnlisted` sets the
skip bytes only from the first listed row: a fill from row 0 each time is quadratic in the block size.

`JoinProbe::JoinRightColumns` runs the probe of one block through function pointers, which `selectFunctions` picks for
each block. The pass, the match steps and `selectFunctions` are in `JoinRightColumnsImpl.h`. Only
`HashJoinMethodsImpl.h` includes it, so only the files of the join kinds compile it. `HashJoinTable::probe`,
`HashJoinTable::probeAll`, `detail::probeAllRows`, `processMatch`, `MultiMapLookupSampler`, the `setUsed` and
`setUsedOnce` overloads that take a find result, `JoinUsedFlags::headRowFlag` and `getUsed`, the per-key branches of
`JoinUsedFlags::setUsed` and `setUsedOnce` (the flag of a key is set with `setUsedAt` and `setUsedOnceAt`),
`JoinOnKeyColumns::isRowFiltered` and `JoinFeatures::emits_whole_key_per_word` lost their last callers and are removed.
Against the parent commit, the `.text` of the server binary is 11.3 MiB (3.4%) smaller on ARM and 14.0 MiB (3.6%)
smaller on x86.

The benchmark compares with the parent commit on ARM (Neoverse-V2) and x86 (Xeon 8488C), 96 cores each, at 1, 16 and 64
threads. It runs 158 joins on Memory tables with 1 thousand to 100 million right keys, unique and duplicate, at 1 %, 50
% and 100 % of left rows matched. They cover INNER, LEFT, RIGHT, ANY, SEMI, ANTI and ASOF joins, joins with two
disjuncts and joins with a mixed ON expression. The median time against the parent commit is 0.94 on x86 and 0.92 on ARM
for one disjunct, and 0.92 and 0.90 for the other two paths.

The stateless test `05622_hash_join_probe_search_batches` runs 21 joins on left blocks of 1000, 4095, 4096, 4097, 12288
and 20001 rows, and on blocks of 4097 rows with a row limit of 61. It expects one result per join. The joins cover ALL,
ANY, SEMI and ASOF joins, ALL joins on unique keys that run as `RightAny`, several key types, conditions in ON, and two
disjuncts, also with two key columns each.

The stateless test `05837_hash_join_probe_resume_state` runs 18 joins without a row limit and on left blocks that the
limit cuts into many calls, and expects one result per join. They cover packed fixed-width, `hashed`, packed `String`,
`String`, `LowCardinality` and constant keys, `Nullable` keys and conditions, RIGHT and FULL joins, two disjuncts, and a
grace hash join. It also drops a result in the middle of a block, and throws in a call that resumes a block. The
performance test `hash_join_split_output` runs LEFT joins with a condition in ON, at the default row limit and at a
limit of 8192, and INNER joins with two disjuncts, for seven key types, on left blocks that the limit cuts into several
calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>

@m-selmi m-selmi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the change. Nice to see the binary size reduction! I left some first comments, not a complete review yet.

Comment on lines +55 to +60
/// Several disjuncts or an additional filter: the key search, [later disjunct][fast_path].
FindKeysFn find_keys[2][2]{};
/// Several disjuncts or an additional filter: the match step, [need_filter].
AddMatchesFn add_matches[2]{};
/// One disjunct and no additional filter: the pass that finds the keys and adds the matches, [fast_path].
AddMatchesFn find_keys_and_add_matches[2]{};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Instead of preparing this matrix of functions, what about computing fast_path and need_filter first then call selectFunctions that returns only the needed functions.
And maybe at the same time we can split find_keys into find_keys_first and find_keys_later to make it a bit more clear what each represents?

Comment on lines +107 to +108
= JoinProbe::JoinRightColumns(functions, join.data->tables, added_columns, left_block_state, *join.used_flags, block.getSelector())
.run();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

would this maybe be clearer as a free function like runProbe() with a passed context?

using Maps = typename Handling::Maps;
static_assert(Lookup::retires_rows_in_order, "`MatchAdder` adds rows in row order");
MatchAdder<Handling> adder(join);
for (size_t begin = 0; begin < join.batch_rows; begin += join.search_batch_rows)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why did we have to add search_batch_rows? Since this is changing the probe behavior can we have some benchmark results added to the PR description.

This branch has not been deployed

No deployments
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-not-for-changelog This PR should not be mentioned in the changelog pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants