Skip to content

Cover the remaining hash join uses with the partitioned hash join - #120585

Draft
harikrishnan94 wants to merge 27 commits into
pbnp-spillfrom
pbnp-coverage
Draft

harikrishnan94 wants to merge 27 commits into
pbnp-spillfrom
pbnp-coverage

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on #120579. #120595 sits on this.

partitioned_hash runs the plain hash join path. Mixed ON conditions, the in-memory buckets of GraceHashJoin, JoinSwitcher, and the Join table engine (including joinGet) still construct HashJoin.

plain SELECT ... JOIN              partitioned_hash
mixed ON, Grace buckets,
JoinSwitcher, Join engine, joinGet still HashJoin

It is not a stand-in for hash until those callers can build it. A mixed ON, a Grace bucket, auto, and JOIN ... ENGINE = Join would keep the old implementation even when partitioned_hash is the algorithm you asked for.

Those four now build a partitioned_hash join too. The Join table engine does so whatever join_algorithm says. A join whose ON has several OR disjuncts, or a mixed ON on a RIGHT or FULL join, still runs a HashJoin behind PartitionedHashJoin. That is the next layer.

partitioned_hash
+-- plain join
+-- mixed ON conditions, INNER and LEFT
+-- GraceHashJoin buckets
+-- JoinSwitcher
+-- Join table engine, including joinGet, always

Changelog category (leave one):

  • Improvement

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

partitioned_hash now covers mixed ON conditions on INNER and LEFT joins, GraceHashJoin buckets and JoinSwitcher. The Join table engine now keeps its table in the partitioned join.


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

@harikrishnan94 harikrishnan94 added the pr-improvement Pull request with some product improvements label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [495340a]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

The PR extends partitioned_hash to mixed ON conditions, GraceHashJoin, JoinSwitcher, the legacy planner, and all Join tables. Review of head 495340a18ec0902ea28fa67c50236b9c79777c2b confirms nine prior findings remain and identifies one additional cached-allocation issue. Incorrect results, persistent table corruption, an unsafe storage rollout, and incomplete spill accounting prevent approval.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available. Boundary examples below were validated by tracing the current code; focused executable regressions are still needed.
Findings

❌ Blockers

  • Delegated spills lose previously collected right rows. PartitionedHashJoin.cpp:170: mixed RIGHT/FULL joins insert into the delegated HashJoin, have no fill lanes, and report isSingleLaneBuild = false. The spill transition drains neither their stored blocks nor any lanes, silently dropping the collected right side. Transfer the delegate's blocks or retain the ordinary hash collector. Existing thread.

  • Failed growth corrupts a persistent Join table. HashJoinTable.h:330: the key and size are published before growth can throw, while the caller has not initialized the row reference. StorageJoin retains the table, and retrying with first-row semantics cannot repair the claimed key. Roll back the claimed cell and size on growth failure, preserving the existing HashTable exception guarantee. Existing thread.

  • Existing Join tables unconditionally adopt experimental storage. StorageJoin.cpp:74: construction, restore, mutations, truncation, and query clones all select the new table implementation. Neither join_algorithm = 'hash' nor compatibility preserves the previous implementation. Add a default-off experimental storage setting and carry the choice through the complete lifecycle. Existing thread.

  • Legacy RHS estimation finalizes indexes before filters are installed. ExpressionAnalyzer.cpp:1201: estimateReadRowsCount reaches selectRangesToRead on the unoptimized right plan, caching indexes before its WHERE predicate reaches applyFilters. This loses primary-key pruning and can raise INDEX_NOT_USED with force_primary_key, including for ordinary hash joins. Estimate without mutating index analysis, or wait until filters are installed. Existing thread with SQL reproduction.

  • Delegated mixed joins omit resize headroom from the spill prediction. PartitionedHashJoin.cpp:939: the delegate reports current hash bytes, but the partitioned wrapper skips the ordinary hash collector's headroom and planPostBuild always accepts delegates. Newly routed mixed RIGHT/FULL joins can therefore exhaust query memory during growth before spilling. Preserve the ordinary collector or account for the delegated resize peak. Existing thread.

  • Single-thread growth omits the still-live old buffer. PartitionedHashJoin.cpp:974: the bound uses stored bytes plus 2X, while doubling keeps the old X buffer alongside its new 2X replacement. With the internal grow budget disabled, a threshold between these footprints permits allocation beyond the spill budget. Include the full live table and arena footprint before growth. Existing thread.

  • Cached preallocation bypasses the first spill decision (new). PartitionedHashJoin.cpp:480: the new single-thread path reads cached distinct counts only after the wrapper's initial prediction. A warm million-key join can commit about 32 MiB on its first 1,000-row block despite a 100,000-byte spill threshold, failing before spilling. Load the cache before prediction or budget the initial reservation. New inline finding.

⚠️ Majors

  • Automatic switching ignores the deferred table allocation. JoinSwitcher.cpp:36: the collector has no memory budget, fill-time decisions count only currently allocated data, and the barrier does not recheck. For example, 10,000 sparse UInt64 keys can pass a 400,000-byte limit before allocating a table exceeding 524,288 bytes. Check the predicted completed footprint and the barrier before allocating. Existing thread.

  • Grace bucket zero bypasses completed-table limits. GraceHashJoin.cpp:1116: its deferred table is built after the last hard-limit check, unlike later buckets. Fill-time row accounting also counts input rows rather than distinct keys, so eleven repetitions of one key can exceed a ten-key limit. Check completed table statistics for every bucket and preserve key-count semantics. Existing thread.

  • Fixed-map conversion allocates outside the spill decision. HashJoinClause.cpp:1598: keys 1 and 1001 select a 65,536-entry destination whose mapped values alone occupy 524,288 bytes, even with a 100,000-byte spill threshold. The source remains live during allocation. This also affects the new Grace buckets. Skip conversion when its combined live footprint exceeds the budget. Existing thread.

Tests
  • ⚠️ Add mixed RIGHT/FULL adaptive-spill cases that compare complete results with hash, including a terminal-block switch and a resize boundary. Current mixed-condition tests disable spilling.
  • ⚠️ Add failed persistent-table growth followed by reinsertion and payload validation, and cover both storage implementation choices through restore and mutation.
  • ⚠️ Cover byte limits in JoinSwitcher and Grace bucket zero, duplicate-key row limits, sparse fixed-map conversion with spilling, and two-block resize peaks. Existing switching tests exercise row limits; conversion tests disable spilling.
  • ⚠️ Warm the statistics cache, then repeat a single-thread join with a small block size and lower spill/query-memory limits. Verify it spills before committing the cached table.
  • ⚠️ Add the legacy-analyzer regression using a filtered MergeTree RHS with force_primary_key = 1 and optimize_move_to_prewhere = 0.
Final Verdict

Status: ❌ Block. Preserve right-side rows on spill and persistent-table validity after exceptions; make experimental storage opt-in; fix legacy index estimation; and enforce the completed and transient allocation budgets described above, with focused regressions.

@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 Sep 17, 2026
= params.max_bytes_before_external_join > 0 && table_join->getTempDataOnDisk() && GraceHashJoin::isSupported(table_join);
/// The partitioned join serves this shape and `join_algorithm` lists it: `partitioned_hash` itself,
/// and the in-memory join of `auto` and the buckets of `grace_hash` when it is listed as well.
const bool partitioned_hash_wanted

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.

This widens partitioned_hash onto one-disjunct mixed RIGHT/FULL joins, but those shapes immediately flip into delegate_mode and still build through the inner serial HashJoin. When max_bytes_before_external_join is set, both planners now route them through SpillingHashJoin(PartitionedCollectingTag{}), whose partitioned_join branch assumes predictedResidentBytes() already covers future growth and therefore skips the hash-style * 2 headroom before HashJoin::addBlockToJoin.

That reopens the spill/OOM invariant for the newly supported path: a query like FULL JOIN ... ON a.k = b.k AND a.v < b.v can now exceed the configured spill ceiling on the next hash-table resize before the wrapper switches to GraceHashJoin, and planPostBuild() still returns Fits for this delegated build. Can we either keep these mixed RIGHT/FULL shapes on the ordinary HashJoin collecting path when spilling is enabled (same change is needed in ExpressionAnalyzer.cpp), or make the partitioned collector report hash-style peak bytes while delegate_mode is active?

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 495340a18 with master 2a4ae1408 (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, compile time of recompiled translation units.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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 ⚠️

144 object files changed (+10.18 MiB total), 14 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp.o new 9.91 MiB +9.91 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp.o new 6.35 MiB +6.35 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp.o new 5.86 MiB +5.86 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp.o new 2.68 MiB +2.68 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/HashJoinClause.cpp.o new 1.95 MiB +1.95 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp.o new 1.18 MiB +1.18 MiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o 3.36 MiB 4.23 MiB +882.78 KiB (+25.62%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 3.57 MiB 2.85 MiB -737.27 KiB (-20.18%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 3.38 MiB 2.70 MiB -699.49 KiB (-20.21%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnti.cpp.o 2.63 MiB 1.96 MiB -677.23 KiB (-25.19%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAny.cpp.o 2.68 MiB 2.02 MiB -673.27 KiB (-24.56%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 3.08 MiB 2.43 MiB -664.28 KiB (-21.07%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 3.31 MiB 2.67 MiB -662.55 KiB (-19.52%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 3.47 MiB 2.82 MiB -661.44 KiB (-18.64%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAnti.cpp.o 2.59 MiB 1.95 MiB -653.20 KiB (-24.61%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsSet.cpp.o 2.41 MiB 1.78 MiB -648.39 KiB (-26.29%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 2.64 MiB 2.01 MiB -646.48 KiB (-23.92%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAny.cpp.o 2.64 MiB 2.01 MiB -646.47 KiB (-23.92%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 3.05 MiB 2.43 MiB -639.04 KiB (-20.44%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 3.16 MiB 2.54 MiB -636.89 KiB (-19.66%)

720 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 ⚠️

2144 translation units recompiled, 13636 s compile time in total, 2129 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp: 41.8 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 29.3 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 27.6 s
  • src/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 18.4 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 16.8 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 10.7 s
  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.7 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 6.7 s
  • src/Interpreters/HashJoin/SharedFixedHashTableFilter.cpp: 5.6 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 13.38 MiB 13.56 MiB +192.00 KiB (+1.40%)
programs/clickhouse ProfileEvents::global_counters_storage 13.38 MiB 13.56 MiB +192.00 KiB (+1.40%)
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 135.97 KiB +135.97 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 135.97 KiB +135.97 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 130.41 KiB +130.41 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 130.41 KiB +130.41 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 129.52 KiB +129.52 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 129.52 KiB +129.52 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 127.25 KiB +127.25 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 127.25 KiB +127.25 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 127.25 KiB +127.25 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 127.25 KiB +127.25 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 126.96 KiB +126.96 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 126.96 KiB +126.96 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 120.11 KiB +120.11 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 120.11 KiB +120.11 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 115.33 KiB +115.33 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 115.33 KiB +115.33 KiB
programs/clickhouse std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 115.26 KiB +115.26 KiB
programs/clickhouse-keeper std::__1::unique_ptr<DB::IJoinResult, std::__1::default_delete<DB::IJoinResult> > DB::PartitionedHa… new 115.26 KiB +115.26 KiB

Job report

harikrishnan94 and others added 2 commits September 23, 2026 12:35
`repartitionCurrentBucket` arrived from upstream `GraceHashJoin`, where the
in-memory join is a `HashJoin`, so it calls `getPeakBuildBytes` and
`releaseJoinedBlocks` on it directly. This layer widens `InMemoryJoinPtr` to
`std::shared_ptr<IJoin>`, and `IJoin` declares neither member, so the two calls
no longer resolve.

Route them through `inMemoryPeakBytes` and `releaseInMemoryBlocks`, the helpers
this layer already declares for exactly this. They pick the arm on
`partitioned_buckets` and `assert_cast` it, so a wrong dynamic type throws
instead of yielding a substituted value.

`getTotalByteCount` would not serve here: the `HashJoin` arm still exists at
this layer and still tracks a build peak, and the comment above the call asks
for the peak from before the rehash splits the table away.

Co-Authored-By: Claude Opus 5 <[email protected]>
harikrishnan94 and others added 3 commits September 23, 2026 15:23
Keep the published cached-count sizing and preallocation event for spill builds. Read the cache before no-spill warm fill so it can skip sketches.

Keep spill reads in lane order and reuse unchanged lane sketches. Exercise the estimate and first-spill trace at 1, 2, 4, 8, and 16 lanes.
@harikrishnan94
harikrishnan94 removed this pull request from stack #120423 October 6, 2026 07:36
@harikrishnan94
harikrishnan94 removed this pull request from stack #124166 October 7, 2026 12:21
@harikrishnan94
harikrishnan94 removed this pull request from stack #124421 October 8, 2026 09:43
@harikrishnan94
harikrishnan94 removed this pull request from stack #124582 October 9, 2026 04:32
harikrishnan94 and others added 14 commits October 14, 2026 10:26
The parent now carries the rewritten `uhj` and the spilling mode. This branch's own changes are applied again on top of them:

- `JoinSwitcher` is the serial class of the new `uhj`. It gains the in-memory `PartitionedHashJoin` mode: the blocks are added one at a time, and the partitioned join still builds its table on up to `max_threads` threads. The old parallel fill of the switcher is not brought back.
- `GraceHashJoin` keeps its partitioned bucket mode, `StorageJoin` keeps the partitioned table, and the legacy planner keeps its `partitioned_hash` support. In the legacy planner the size estimate of the right table is only used as the build hint of the partitioned join. The layout of a `hash` join there stays the one of the new `uhj`.
- `HashJoin::restoreRightBlock` is used in `releaseJoinedBlocks` where `uhj` restores the blocks of a restructured join.
- `StorageJoin` keeps the memory tracker blocker around the table data that the new `uhj` added.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`createKeyGetter` is a free function in `KeyGetter.h` again, because the partitioned probe builds its key getter outside of `HashJoinMethods`. The Join table mode reads its row count from the table through `PartitionedHashJoin::getJoinTableRowCount`, and the legacy planner sizes the right side with the one-argument `estimateReadRowsCount`. The right-side flags of the statistics are sized from the stored blocks of the joined data, and the Join table insert checks the limits through the `JoinBuildContext`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`createKeyGetter` is a free function in `KeyGetter.h` again, because the partitioned probe builds its key getter outside of `HashJoinMethods`. The Join table mode reads its row count from the table through `PartitionedHashJoin::getJoinTableRowCount`, and the legacy planner sizes the right side with the one-argument `estimateReadRowsCount`. The right-side flags of the statistics are sized from the stored blocks of the joined data, and the Join table insert checks the limits through the `JoinBuildContext`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The row count of a Join table throws it for a key type without a table, and the style check wants every error code used in a file declared there.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the restored `isHashFamilyEnabled` checks of the planner.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… counts of the Join engine test

`JoinSwitcher` logs "Memory limit reached with `PartitionedHashJoin`..." again when it switches to `MergeJoin`, which the join switcher test counts. A Join table reports `HASH` as its algorithm, since the user chose no other one for it, and the `used_join_algorithms` tests of the new `uhj` expect that. `count()` of a Join table counts its rows since `uhj` changed it, so the reference of the Join engine test holds the row counts, not the key counts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the adjusted general join planning test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`max_bytes_in_join` is a hard cap in the new `uhj`, so it no longer makes `grace_hash` write buckets. The test starts the spill with `max_bytes_before_external_join`, as the spill switch part of it already does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the last two commits of `uhj`: the key and byte count of a slot insert that throws, and the rename of the `StorageJoin` count test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the adjusted tests and the fixes of the previous layers.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…itionedHashJoin`

The base moved `force_optimize` before `worker_id`. The call still passed `worker_id` first, so `0` converted to `force_optimize = false` and `true` converted to worker 1. It now passes `force_optimize = true` and leaves `worker_id` at its default of 0.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A join of the same right side that ran earlier leaves a size hint in the hash table statistics, and the hint replaces the build-row estimate of the next join. The `partitioned_hash` run of a `SEMI`, `ANTI` or `ANY` join then built one partition where the test expects one per thread. With the statistics off, the partition count follows the build rows.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj`. `GraceHashJoin` now spills on request through `ISpillable`, and the repartition runs inside the call. The in-memory bucket join, which can be the partitioned one, no longer has to look for a spill request that arrived after its last block, so the overflow check and the end of the build drop that test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the continuation of the partitioned join result.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Comment on lines +166 to +171
, delegate_mode(hash_join->needUsedFlagsForPerRightTableRow(table_join))
, join_table_mode(join_table_mode_)
, build_rows_hint(build_rows_hint_)
, single_fill_thread(!delegate_mode && build_rows_hint_ && *build_rows_hint_ < table_join->parallelHashJoinThreshold())
, single_fill_thread(
!delegate_mode && !join_table_mode
&& (num_threads == 1 || (build_rows_hint_ && *build_rows_hint_ < table_join->parallelHashJoinThreshold())))

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.

[P1] Transfer delegated builds before switching to grace

Mixed RIGHT/FULL joins now enter delegate_mode, which inserts their right rows directly into the inner HashJoin. However, single_fill_thread is explicitly false in this mode, and no fill lanes are created. When the spill threshold is reached, SpillingHashJoin::switchToGraceHashJoin therefore skips beginStoredBlockDrain/drainStoredBlocksInto because isSingleLaneBuild is false, and tryConvertFillLanes finds zero lanes. The new grace join receives none of the rows already collected.

For example, a FULL JOIN on a.k = b.k AND a.v < b.v with a right block larger than max_bytes_before_external_join can switch at the terminal barrier and lose the entire right side, silently changing the result. The new tests cover mixed conditions without spilling and spilling without a mixed condition, so they miss this combination.

Please transfer the delegated inner join's blocks when switching, or retain the ordinary hash collector for these shapes. Add a mixed RIGHT/FULL regression that crosses the spill threshold and compares the full result with hash.

++m_size;
if (m_size > maxFill()) [[unlikely]]
{
growSingleRange();

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.

[P1] Roll back the claimed key when table growth fails

The new key and m_size are published before growSingleRange, but its allocation/commit can throw before insertJoinTableRows initializes the mapped row reference. For example, growth on the 129th distinct nonzero key of the initial 256-cell table can throw MEMORY_LIMIT_EXCEEDED, leaving that key present with a zero row reference. StorageJoin::insertBlock retains this table after the exception.

This corrupts a persistent Join(ANY, LEFT, ...) table: joinGet returns a default for the claimed key, a scan can associate it with the first stored payload, and retrying the insert does not repair it because the key already exists and join_any_take_last_row defaults to false. This affects ordinary Join tables even with join_algorithm = 'hash'.

The existing HashTable::emplaceNonZeroImpl explicitly removes the new cell and decrements the size when resizing throws. Please preserve that exception guarantee here, and test a failed resize followed by reinsertion and payload validation.

std::max<size_t>(1, max_threads_),
any_take_last_row_,
stats_collecting_params_,
/*max_bytes_before_external_join_=*/0,

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.

[P2] Include the deferred table in the automatic switch decision

With multiple build threads, this collector stores blocks and routes during fill and allocates its hash table only in the post-build phase. JoinSwitcher::addBlockToJoin still compares only getTotalByteCount with its limits, so the table and duplicate arenas are absent from every switch decision. onBuildPhaseFinish does not recheck, and the zero budget here disables the collector's own memory gate.

For example, with join_algorithm = 'auto,partitioned_hash', max_threads = 8, parallel_hash_join_threshold = 1, both external spill settings disabled, and default_max_bytes_in_join = 400000, 10,000 sparse UInt64 keys plus a UInt64 payload fit below the limit during fill, but their final table alone needs at least 524,288 bytes. The join stays in memory instead of switching to MergeJoin, and larger instances can fail on query memory despite auto.

Please base the switch on the predicted completed footprint and retain a barrier check before the post-build allocation. Add a byte-limit regression; the new switching cases exercise only max_rows_in_join.

return;

hash_join->onBuildPhaseFinish();
finishInMemoryBuild(*hash_join);

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.

[P2] Check the first bucket's limits after its table is built

For partitioned buckets, finishInMemoryBuild now allocates the table after the last fill-time checkSizeLimits, but bucket zero never gets another hard-limit check. Later buckets already have an explicit checkSizeLimits immediately after finishInMemoryBuild in getDelayedBlocks.

With join_algorithm = 'grace_hash,partitioned_hash', one initial bucket, max_threads = 8, a large external spill threshold, and max_bytes_in_join = 400000, 10,000 sparse UInt64 keys plus payload can pass all fill checks while the final table alone exceeds 524,288 bytes. With one bucket, the query finishes without the exception required by the hard cap.

The prebuild accounting also changes max_rows_in_join from distinct keys to input rows: eleven repetitions of one key now exceed a limit of ten, although the previous hash bucket counted one key. Please enforce the limits against the completed bucket's table statistics, including bucket zero, without treating the collector's input-row count as a distinct-key count. Cover both the byte boundary and duplicate-key case.

Brings in the merge of `uhj` that repairs the `gtest_functions_stress` build.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
PartitionedHashJoinPtr makeStorageJoinTable(std::shared_ptr<TableJoin> table_join, Block right_sample_block, bool overwrite)
{
return std::make_shared<PartitionedHashJoin>(
PartitionedHashJoin::JoinTableTag{},

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.

[P1] Keep the experimental storage implementation opt-in

This helper unconditionally moves every Join table onto the new implementation, including existing tables loaded by restore, and also serves mutations, truncation and query clones. Although partitioned_hash is documented as experimental, selecting join_algorithm = 'hash' or using compatibility cannot preserve the previous storage implementation: the storage's TableJoin does not take that setting, and the planner handles a filled Join table before algorithm selection.

Consequently an ordinary server upgrade puts existing Join tables and joinGet onto the new table insertion and lookup paths without an opt-out. Please introduce a default-off experimental storage setting that retains the previous HashJoin implementation when disabled, and carry that choice consistently through restore, mutations and query sharing. Add a focused test for both settings.

const size_t blocks = storedBlocks().size();
const size_t rows_per_block = blocks == 0 ? rows : rows / blocks;
if (claimed + rows_per_block > clause.tableMaps().maxFill(type))
predicted = std::max(predicted, stored + 2 * clause.tableMaps().getBufferSizeInBytes(type));

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.

[P1] Include the old table in the single-thread resize prediction

The doubled buffer is allocated while the current buffer is still live: growHashJoinTable calls beginRehash and commitNewRange before adoptRehash releases the old table. Thus, for a current table of X bytes, the resize needs the stored blocks and arenas plus 3X, whereas this bound only includes the stored blocks plus 2X.

For example, with one build thread and no cached size hint, a first block of 128 distinct nonzero keys fills the initial 256-cell table to its maximum fill. The next block immediately doubles it. A spill threshold between stored + 2X and stored + 3X now passes the pre-insert check, although the resize exceeds it. The single-thread growth budget is disabled, so allocation can reach the query memory limit before the barrier can switch to grace. The previous prediction used getTotalByteCount() + 2 * table_bytes, which retained the old buffer and arenas.

Please preserve that live resize footprint in the prediction and add a two-block regression at this boundary, with statistics collection disabled.

Brings in the fix of the inserted row count of the single-lane build and the pinned settings of the tests.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
auto build = [&](auto & dest, HashJoin::Type new_type)
{
using RangeMap = typename std::decay_t<decltype(dest)>::element_type;
auto range_map = std::make_shared<RangeMap>();

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.

[P2] Check the spill budget before allocating the fixed table

This conversion runs after SpillingHashJoin::onBuildPhaseFinish has accepted the build and selected IN_MEMORY_JOIN, but it never checks the collector's memory budget. For example, with max_threads = 1, statistics disabled, two UInt64 keys 1 and 1001, and max_bytes_before_external_join = 100000, the small source table fits. The range of 1001 selects range16, whose 65,536 mapped values alone require 524,288 bytes; the source table also stays live during allocation. The optimization can therefore exceed the spill budget or throw MEMORY_LIMIT_EXCEEDED after the spill decision has finished.

Please check the combined live footprint before constructing the destination and skip conversion when it cannot fit. Add a sparse two-key regression with conversion and spilling enabled; the new conversion test disables both external spill settings.

harikrishnan94 and others added 2 commits October 17, 2026 11:32
Brings in the latest merge of `uhj`, the fixes of the scatter check and of the spill hand-over, and the test changes of the earlier branches.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`05220` no longer hashes the left payload of `ANY INNER`, because the left row that the join keeps for a key depends on the probe order. `05227` names its tables with a random suffix, because copies of the test in a flaky check share the statistics cache by table name and read each other's counts. `05218` carries the `long` tag like the other slow tests of this join.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
{
auto right_sample_block = joined_plan->getCurrentHeader();
/// The old analyzer has no join-order pass, so the right side is sized by walking `joined_plan`.
const std::optional<UInt64> rhs_size_estimation = QueryPlanOptimizations::estimateReadRowsCount(*joined_plan->getRootNode()).estimated_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.

[P1] Estimate the legacy RHS without finalizing its index analysis

This runs while the legacy right-side plan is still unoptimized, including for ordinary join_algorithm = 'hash'. For a MergeTree read, estimateReadRowsCount calls selectRangesToRead, which builds and caches indexes before optimizePrimaryKeyConditionAndLimit installs the right-side WHERE predicate. Later, ReadFromMergeTree::applyFilters skips filter installation because indexes already exists.

For example, after creating and populating t, this query should return 1, but the new estimation reaches INDEX_NOT_USED before the predicate is installed:

CREATE TABLE t (k UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t SELECT number FROM numbers(100000);

SELECT count()
FROM numbers(1) AS l
INNER JOIN (SELECT k FROM t WHERE k = 0) AS r ON l.number = r.k
SETTINGS enable_analyzer = 0, optimize_move_to_prewhere = 0,
         force_primary_key = 1, join_algorithm = 'hash';

Without force_primary_key, the same path loses primary-key pruning. Please keep the estimate unknown until filters are installed, or obtain it without mutating the read's index-analysis state, and add a legacy-analyzer regression for this case.

harikrishnan94 and others added 4 commits October 19, 2026 11:56
Brings in the budget of the `05139` row store test and the join order pin of the `04931` plan integration test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The flaky and targeted checks randomize `enable_parallel_replicas`. With it on, two replicas each build and preallocate a table, so the second run of `05227_partitioned_hash_join_statistics_cache_sizing` reported `HashJoinPreallocatedElementsInHashTables` as 2048000 instead of 1024000. The test now turns parallel replicas off.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`HashJoinTable.EmplaceGrowsAndFinds` expects a `LOGICAL_ERROR` exception from growing a partitioned table. Debug and sanitizer builds abort on a `LOGICAL_ERROR`, so the ASan, MSan and TSan unit test jobs died before writing a result. The check now sits under `DEBUG_OR_SANITIZER_BUILD`, as the other `LOGICAL_ERROR` checks in this file do.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The five `large` queries ran for 66 to 422 seconds each in the `amd_binary` flaky check, and the test hit the 1800 second limit. Locally the same queries take about 2 seconds each. The probe side is now 7000 rows and the build side 100000, which keeps matched and unmatched probe rows for every join type and runs the test in about 1 second. The reference holds the new counts, and `hash` and `partitioned_hash` still agree.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Comment on lines +480 to +482
const size_t keys = readDistinctKeysFromStatisticsCache() ? *cached_distinct_keys : 1;
clause.beginSinglePartitionInsert(
clause.reserveFor(*build_rows_hint, static_cast<double>(*build_rows_hint)),
clause.reserveFor(build_rows_hint.value_or(keys), static_cast<double>(keys)),

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.

[P1] Account for cached preallocation before the first spill decision

The new max_threads = 1 path leaves cached_distinct_keys unset until this first insert. Consequently, the preceding SpillingHashJoin call to predictedResidentBytes budgets only a minimum-sized table, but this cache read can immediately change the reservation to the entire previous build's distinct count. beginSinglePartitionInsert then commits that table without checking the spill budget.

For example, after warming the same join with 1,000,000 distinct UInt64 keys, repeat it with max_threads = 1, max_block_size = 1000, fixed-map conversion disabled, and max_bytes_before_external_join = 100000. The first 1,000 rows reserve a table for the cached million keys (about 32 MiB), so a 16 MiB query memory limit raises MEMORY_LIMIT_EXCEEDED before the wrapper can spill. The planner's cached row estimate does not prevent this: it also describes the full million-row build. Previously that estimate selected the deferred build, which could check its budget before allocating the table.

Please load the cached reservation before the wrapper's first prediction, or constrain/defer the initial allocation to the available budget. Add a regression that warms the statistics cache and repeats the query with a smaller spill and query-memory limit.

@harikrishnan94
harikrishnan94 removed this pull request from stack #124822 October 21, 2026 12:32

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

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant