Skip to content

Serve hash, parallel_hash and auto with the partitioned hash join - #121707

Draft
harikrishnan94 wants to merge 31 commits into
pbnp-multi-clausefrom
pbnp-becomes-hash
Draft

harikrishnan94 wants to merge 31 commits into
pbnp-multi-clausefrom
pbnp-becomes-hash

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Second from the top of the join stack, on pbnp-multi-clause.

Related: #120595
Related: #115254

join_algorithm chooses between two in-memory hash joins today. hash, parallel_hash and auto run HashJoin. Its parallel build spreads the right table over the buckets of a TwoLevelHashMap, and each slot of buckets owns an arena and a lock. partitioned_hash runs PartitionedHashJoin, which scatters the right table into cache-sized partitions and builds one shared table from them. PartitionedHashJoin already calls HashJoin for the schema, the row store and result emission.

hash, parallel_hash, auto ---> HashJoin
                                 +-- build: TwoLevelHashMap buckets, per-slot arenas and locks
                                 +-- probe, non-joined rows

partitioned_hash ------------> PartitionedHashJoin
                                 +-- build: cache-sized partitions, one shared table
                                 +-- probe, non-joined rows
                                 +-- HashJoin for schema, row store, emission

So the same join has two implementations. A query gets the partitioned build only if it names partitioned_hash. Every join feature has to be written twice and kept in step.

This PR makes hash, parallel_hash and auto run PartitionedHashJoin. parallel_hash_join_threshold keeps its meaning: below it, the build runs on one fill thread. SpillingHashJoin, JoinSwitcher and the in-memory buckets of GraceHashJoin start from PartitionedHashJoin too.

hash, parallel_hash, auto ---> PartitionedHashJoin
                                 +-- build: cache-sized partitions, one shared table
                                 +-- probe, non-joined rows
                                 +-- HashJoin for schema, row store, emission

The partitioned_hash value of join_algorithm is deleted rather than aliased, because the only implementation needs no second name. Its two settings lose the prefix: partitioned_hash_join_max_fanout_per_pass becomes hash_join_max_fanout_per_pass, and partitioned_hash_join_cap_partitions_by_l1_descriptors becomes hash_join_cap_partitions_by_l1_descriptors. Both are no longer experimental, and the old names are not kept. HashJoin loses its parallel build: the bucket slots with their arenas and locks, the two-level and fixed-partition maps, the parallel used flags and the parallel non-joined emission. What stays of HashJoin is the helper that PartitionedHashJoin calls, and no query reaches it directly.

PartitionedHashJoin builds no key-only table, so enable_join_key_only_hash_tables becomes obsolete. It does not rerange the right table, so allow_join_right_table_sorting, join_to_sort_minimum_perkey_rows and join_to_sort_maximum_table_rows have no effect. A RIGHT or FULL join always scans its table for non-joined rows, so JoinNonJoinedHashTableScans and JoinNonJoinedHashTableScansSkipped stay at 0. HashJoinBuiltWithParallelLayout and HashJoinBuiltWithSerialLayout are removed. parallel_non_joined_rows_processing no longer depends on parallel_hash_join_threshold. EXPLAIN shows PartitionedHashJoin as the algorithm.

Measured on aarch64 against the parent, query_duration_ms, median of 5 pairs, milliseconds:

Right table Threads hash parallel_hash
32M UInt64 keys 16 83 -> 69 81 -> 69
16M 16-byte String keys 16 129 -> 88 134 -> 88
4M 64-byte String keys, 64-byte payload 16 63 -> 37 62 -> 39
32M keys plus 128M rows on one key 96 1447 -> 1090 1446 -> 836
8M keys, 16 rows each 1 4775 -> 3231 4945 -> 3239
RIGHT JOIN, 28.8M right rows not joined 96 214 -> 136

grace_hash at 64 threads goes from 636 ms to 117 ms.

Short joins at 64 and 96 threads are slower. Time to result from the server log, median of 20 pairs, milliseconds:

Join Threads Parent This PR
4.2M x 4.2M UInt64, hash 64 12.1 13.6
4.2M x 4.2M UInt64, hash 96 11.5 13.7
4.2M x 4.2M UInt64, parallel_hash 96 11.9 13.7
6M right keys, 64K left rows, parallel_hash 96 11.7 13.9
LEFT SEMI, 16M x 16M, half the keys match 64 19.9 29.1
LEFT ANTI, 16M x 16M, half the keys match 96 22.2 25.0

On the 4.2M and 6M joins this PR uses 16 to 34% less CPU. It runs 1.4 to 1.7 times as many thread-pool jobs, and its threads wait longer. The LEFT SEMI join takes 26 times the soft page faults when other queries run between its runs, and back to back it is only 5% slower. These joins take a few tens of milliseconds, and the slowdowns are accepted for now.

Changelog category (leave one):

  • Backward Incompatible Change

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

The hash, parallel_hash and auto join algorithms, and the in-memory buckets of grace_hash, now run on the partitioned hash join implementation, which splits the right table into cache-sized partitions and builds them into one shared hash table in parallel. The partitioned_hash value of join_algorithm is removed, as the implementation it selected is now the only one. The settings partitioned_hash_join_max_fanout_per_pass and partitioned_hash_join_cap_partitions_by_l1_descriptors are renamed to hash_join_max_fanout_per_pass and hash_join_cap_partitions_by_l1_descriptors. The setting enable_join_key_only_hash_tables is obsolete. allow_join_right_table_sorting no longer has an effect on these joins.


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

@harikrishnan94 harikrishnan94 added pr-performance Pull request with some performance improvements pr-backward-incompatible Pull request with backwards incompatible changes pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard labels Sep 23, 2026
harikrishnan94 and others added 2 commits September 23, 2026 12:35
Make the partitioned hash join the default `HashJoin` and remove the public
`partitioned_hash` join algorithm name, re-deriving the accepted layer onto the
refreshed published `pbnp-multi-clause` at 0be9a63.

The layer deletes `PartitionedFixedHashMap`, `PartitionedFixedHashSet` and their
test, and with them the `BucketHash` template parameter of `TwoLevelHashTable`,
`FixedRangeBucketHash` and `restoreMinMaxOptimization`, which existed only to
serve those types. It also deletes the parallel layout of `HashJoin`, the
fixed-map conversion and the filter publication, renames the two
`partitioned_hash_join_*` settings to `hash_join_*`, and marks
`enable_join_key_only_hash_tables` obsolete.

Why re-derive rather than rebase: the previously accepted result was built on a
parent that has since been rebased twice, so its delta no longer applies. Eleven
of the thirteen conflicting files have a parent blob byte-identical to the blob
at the sibling rebase 129f7a9, which the accepted re-derivation
2c943b6f63f already resolved, so that resolution is taken verbatim for them.
Two files moved beyond it and are resolved individually:

* `src/Core/Settings.cpp` keeps the two `allow_join_right_table_sorting`
  documentation lines the parent gained after the accepted result was made.
* `src/Interpreters/GraceHashJoin.cpp` keeps `getTotalByteCount` and
  `releaseJoinedBlocks` rather than the parent's `inMemoryPeakBytes` and
  `releaseInMemoryBlocks`. Those helpers are correct one layer below and are
  deleted here, so carrying the parent's form forward would not compile. The
  form differs by layer on purpose.

The two generated documentation files are left to master: they are generator
output, and the documentation autogeneration has to run against a build of this
layer instead.

Proved by `resume-NEXT/unit3-b6-rederive/gate-g3.sh`: no conflict marker and no
unmerged entry, `collectingJoin` reduced to zero references, `refWordRows`
returning `size_t`, the four gather and fill files present exactly once, both
generated documentation files byte-identical to the parent, and a name-level
sweep over the 498 identifiers this layer removes finding no surviving code
reference. `ConcurrentHashJoin` survives in two comments about an older peer,
which is correct there and is reported rather than edited.

This layer alone still makes `EXPLAIN` report `Algorithm: PartitionedHashJoin`
for a plain `hash` join. The following layer unifies the class and removes that
difference.
`partitioned_hash` is no longer a value of `join_algorithm` here, and `hash` is the partitioned
join, so the test the parent added for the several-clause probe runs on `hash`. Its `hash` oracle
is gone with the second implementation, so the reference pins the `(count, checksum)` of every
shape as the parent's standard hash join computes them, the way `05229` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 23, 2026
harikrishnan94 and others added 4 commits September 23, 2026 15:30
This branch deletes the fixed-range code, so its side wins the conflicts.
`SlotScatter.cpp`, `PartitionedFixedHashMap.h`, `PartitionedFixedHashSet.h`
and `gtest_partitioned_fixed_hash_map.cpp` stay deleted. The conflicting hunks
of `HashJoin.h`, `HashJoin.cpp`, `HashJoinTable.h`, `BucketPartitionedTable.h`
and `gtest_two_level_hash_table_buckets.cpp` keep this branch's version.
`TwoLevelHashTable.h` takes the version of `two-level-hash-table-buckets`,
which drops the fixed-range storage too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The merge brought it in, but `JoinFixedHashMap` is a plain fixed map on this
branch and nothing uses it. The trait `is_partitioned_fixed_table` goes too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ptyCell` test

The merge of #120024 kept the concept requirements on `computeBucketPrefix` and the iterator's `getBucket`, but
lost the two sentences of `BucketPartitionedTable` that explain them. They are back, without the mentions of
`PartitionedFixedHashTable`, which this layer deletes.

`IsEmptyCellFindsTheBucketFromTheCellHash` tests the plain `TwoLevelHashTable` only, so it applies here unchanged
and is restored as #120024 has it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Carry the lane sketch, cache sizing, and gated spill estimate fixes into this layer. Keep sketch updates active when `max_rows_in_join` checks live distinct keys.
@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
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [021326e]

Summary: ⏳

job_name test_name status info comment
Unit tests (asan_ubsan) FAIL
PartitionedHashJoin.DestructionWithAllocationFailure FAIL cidb
AllTests FAIL cidb
Unit tests (msan) FAIL
PartitionedHashJoin.DestructionWithAllocationFailure FAIL cidb
AllTests FAIL cidb
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

The PR makes PartitionedHashJoin the implementation of hash, parallel_hash, and the in-memory stages of auto and grace_hash, removing the previous parallel layout and renaming its settings. Reviewed head 021326e77aa789c26adedcc5fce7b05f6f1d6200. Seven findings remain: spill statistics can dereference released state, exact limits use approximate counts, unused build blocks accumulate, large joins lose supported capacity, and three deferred-allocation paths mishandle byte limits. Changes are required before merging.

Findings

❌ Blockers

  • src/Interpreters/SpillingHashJoin.cpp:172: Spill statistics outlive the collector's data. With max_threads = 2 and parallel_hash_join_threshold = 18446744073709551615, spilling a nonempty single-fill collector drains its stored blocks and resets hash_join->data. The next statistics read still calls getTotalByteCount, which dereferences that pointer through storedData. Scheduler and memory-reservation polling make this reachable without a race. Preserve a valid, synchronized statistics view after draining. Existing thread.

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp:578: Approximate cardinality rejects valid exact limits. A parallel fill of repeated UInt8 keys 0..99 produces a DenseHyperLogLog estimate of 100.61536453962009, rounded to 101. Thus max_rows_in_join = 100 throws despite only 100 distinct keys; break with a limit of 101 stops prematurely. A later exact check cannot restore discarded input. Verify the exact count before rejecting or stopping the build. Existing thread.

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp:512: Single-fill ANY joins retain duplicate-only payload blocks. Unlike the previous implementation, this path stores every block even when no table entry references it. For 65,536 rows over 100 keys in 1,024-row blocks with a materialized FixedString(64) payload, a LEFT ANY JOIN selecting that payload retains roughly 4 MiB instead of the representative block's roughly 64 KiB. With join_any_take_last_row = 0, one thread, and spilling disabled, a previously sufficient 1 MiB join limit now fails. Reclaim unreferenced blocks in the eager build. Existing thread.

  • src/Planner/PlannerJoins.cpp:1269: Mandatory partitioned tables reduce supported join capacity. HashJoinClause::sizeDegreeFor rejects reservations requiring more than 2^32 cells. A parallel build of three billion distinct UInt64 keys therefore fails with LIMIT_EXCEEDED even with adequate memory, unlimited join sizes, and both external-join thresholds disabled. The previous implementation distributed keys across 256 independently growing maps. Neither parallel_hash nor compatibility restores that capacity. Extend the geometry or retain a configurable implementation supporting those joins. New thread.

⚠️ Majors

  • src/Interpreters/JoinSwitcher.cpp:50: auto omits the future table from its switch decision. For a parallel build of 65,536 distinct UInt64 keys, stored keys and routes fit below 1 MiB while the completed table alone occupies at least 2 MiB. Inserts use callerChecksLimits, disabling the inner final check, and neither wrapper phase rechecks the limit. Consequently auto stays in memory above max_bytes_in_join. Include the impending table allocation while blocks can still be transferred to MergeJoin. Existing thread.

  • src/Interpreters/GraceHashJoin.cpp:1052: The initial completed bucket escapes the hard cap. Inner inserts disable their own checks, and the outer fill checks cannot see the deferred table. Unlike delayed buckets, the initial bucket receives no completed-size check. With one initial bucket, 65,536 distinct UInt64 keys, two threads, parallel_hash_join_threshold = 0, a 1 MiB join cap, a 1 GiB spill threshold, fixed-table conversion disabled, and legacy_join_size_limits_trigger_spilling = 0, the join can finish above its hard cap. Check the initial completed bucket and latch the stop for break. Existing thread.

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp:946: Ordinary parallel hash joins ignore the final break decision. For join_overflow_mode = 'break', the final SizeLimits::check returns false, which is discarded. A 65,536-key UInt64 build in 64 blocks of 1,024 rows occupies about 656 KiB during filling, so every block passes a 1 MiB cap; its table subsequently occupies at least 2 MiB, yet all keys remain available for probing. The previous eager build stopped after the block crossing the cap. Account for table growth while input can still be stopped, or build and check incrementally. New thread.

Tests
  • ⚠️ Add a focused single-fill spill case with max_threads > 1 and statistics polling after handover.
  • ⚠️ Add duplicate-key row-limit boundaries for both throw and break, plus a duplicate-heavy ANY payload case under a byte limit between representative-block and full-input storage.
  • ⚠️ Cover a byte cap between fill footprint and completed-table footprint for auto, the initial grace_hash bucket, and ordinary parallel hash with break. Disable fixed-table conversion to retain the intended table layout.
  • ⚠️ Exercise large-reservation sizing without allocating billions of rows, proving that the replacement preserves supported table capacity.
Missing context / blind spots
  • ⚠️ No ClickHouse binary or build is available locally, so SQL reproductions were not executed. The HLL value was independently reproduced using an exact Python translation of the current header; byte boundaries and failure paths were traced in source. Focused server tests on the reviewed head would close this validation gap.
Final Verdict

Status: ❌ Block. Fix the released-state access, exact-limit enforcement, unreferenced-block retention, capacity regression, and deferred byte-limit handling; add the focused regression coverage above. The two new findings were submitted in one batched inline review. The five existing threads remain unresolved without duplicate replies.

@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 2 commits October 14, 2026 12:44
Brings the rewritten `uhj` base and the layers below into this branch, and ports `PartitionedHashJoin` and its callers to the new APIs: `addBlockToJoin` takes a `JoinBuildContext`, `IJoin` has a pure virtual `getAlgorithm`, the row store is a gather source, and `JoinSwitcher` fills serially. `HashJoin` stays the plain serial helper, so the `HashJoin` collecting mode of `SpillingHashJoin` and the two-level key getters are removed again. The `HashJoin` build and probe profile events that `uhj` dropped are no longer used, and the settings history of `join_algorithm` and the renamed `hash_join_*` settings moves into their declarations.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`03356_threshold_for_parallel_hash` and `04356_threshold_for_parallel_hash_2` only check which hash table layout a join built, through `HashJoinBuiltWithSerialLayout` and `HashJoinBuiltWithParallelLayout`. The join has one layout now and those events no longer exist, so the tests have nothing left to check.

`04234_explain_pipeline_compact_repeated_processor_chains` prints the pipeline of a hash join. The join emits blocks of the right size, so no `SimpleSquashingTransform` follows it, and the reference no longer lists one.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
harikrishnan94 and others added 3 commits October 16, 2026 16:49
Brings in the fixes of the previous layers. This layer already removes the `05219` and `05220` tests of the `partitioned_hash` algorithm and the layout selection in `ExpressionAnalyzer`, so the merge keeps both removed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…hash join

`EXPLAIN` of a hash join names `PartitionedHashJoin` in this layer, so the five references of the tests that print the algorithm change from `HashJoin`. The settings explorer still listed `enable_join_key_only_hash_tables` with a link to a page that no longer documents the obsolete setting.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj` and the port of the spilling joins to `ISpillable`. This layer has one join to spill, so `SpillingHashJoin` reports its memory and spills through `ISpillable` with the partitioned join alone. The partitioned join takes over the rule of `uhj` for `parallel_hash_join_threshold` without a row estimate: the largest value builds on one thread and `0` in parallel. The settings docs keep this layer's wording, and the generated routes and explorer take the new settings of master. The two tests of `uhj` that count the removed layout events are adapted in the next commit.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
harikrishnan94 and others added 8 commits October 16, 2026 17:39
…t events from test 00184

This layer's `repartitionCurrentBucket` takes the leftover block and the build context only, so `spill` passes no key count. Test `00184` counted `HashJoinBuiltWithSerialLayout` and `HashJoinBuiltWithParallelLayout`, which this layer removed. It keeps the row comparison and loses the event check.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This layer has no build workers. What the switch leaves unconverted are the blocks of the fill lanes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The base made a two-level map always prefetch in the insert. This layer has no two-level maps, so the line stays as it was and asks `shouldUseJoinPrefetch` alone.

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]>
Test `05396` counts `HashJoinBuiltWithSerialLayout` and `HashJoinBuiltWithParallelLayout`, which this layer removed. The hash join of this layer has partitions, not layouts, and picks their number from the rows it builds.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The merge took the routes and the explorer of master, which still list `enable_join_key_only_hash_tables` and lack the renamed `hash_join_max_fanout_per_pass` and `hash_join_cap_partitions_by_l1_descriptors`. The generator, run on the binary of this layer, drops the first and adds the other two.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the merge of `uhj` that repairs the `gtest_functions_stress` build.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The `settings_changes_history` style check requires a record for the current version, `26.11`, on every setting that a pull request adds. `hash_join_max_fanout_per_pass` and `hash_join_cap_partitions_by_l1_descriptors` only had records for `26.10`, so the check failed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
/// Unconverted workers and fill lanes still own memory; releasing their blocks clears the counters.
const auto unconverted_bytes = collectingJoin().getTotalByteCount();
/// Unconverted fill lanes still own memory; releasing their blocks clears the counters.
const auto unconverted_bytes = partitioned_join->getTotalByteCount();

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] Stop reading the collector's data after draining it

With max_threads = 2 and parallel_hash_join_threshold = 18446744073709551615, the collector uses a single fill thread, but this condition still evaluates to true. When a nonempty build crosses the spill threshold, switchToGraceHashJoin drains its stored blocks; the final PartitionedHashJoin::releaseNextStoredBlock resets hash_join->data. This call then reaches PartitionedHashJoin::getTotalByteCount, which unconditionally dereferences that pointer through storedData.

This is reachable without a race: with enable_adaptive_memory_spill_scheduler = 1 and a nonzero max_memory_usage, the executor polls these statistics before the next filling operation. Memory reservations also poll them immediately after work or a scheduler spill. Thus a successful spill can terminate the server on the next statistics read.

Keep the statistics view valid and synchronized after the collector is drained, and add coverage for spilling a single-fill build with max_threads > 1.

if (!limits.hasLimits())
return true;
limits_requested = true;
return limits.check(rowCountForLimit(limits.max_rows), getTotalByteCount(), "JOIN", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED);

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] Use an exact distinct count before rejecting the row limit

In a parallel fill, rowCountForLimit reaches the HyperLogLog estimate in getTotalRowCount, so this enforces an exact limit using an approximate count. For the 100 distinct UInt8 keys 0..99, the actual DenseHyperLogLog header produces 100.6153645396201, rounded to 101. Repeating those keys therefore raises SET_SIZE_LIMIT_EXCEEDED with max_rows_in_join = 100, although the table contains only 100 distinct keys.

For example:

SELECT count()
FROM (SELECT toUInt8(number) AS k FROM numbers(100)) AS l
INNER JOIN (SELECT toUInt8(number % 100) AS k FROM numbers_mt(20000)) AS r ON l.k = r.k
SETTINGS join_algorithm = 'hash', max_threads = 4, max_block_size = 200,
    parallel_hash_join_threshold = 0, query_plan_join_swap_table = 0,
    enable_join_runtime_filters = 0, max_rows_in_join = 100, max_bytes_in_join = 0,
    max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0,
    join_overflow_mode = 'throw';

The valid result is 20000. With join_overflow_mode = 'break' and a limit of 101, the same overestimate can truncate the result prematurely. Verify the exact count before rejecting/stopping input; the final exact check cannot undo an earlier rejection. Add a duplicated-key boundary test.

Comment on lines 48 to 50
join->addBlockToJoin(block, num_rows, context.callerChecksLimits());
size_t rows = join->getTotalRowCount();
size_t rows = assert_cast<const PartitionedHashJoin &>(*join).rowCountForLimit(limits.max_rows);
size_t bytes = join->getTotalByteCount();

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 future hash table in the automatic switch decision

The collector now allocates its hash table in runPostBuildPhase, but this check still sees only stored blocks and routes. The insert uses callerChecksLimits, so the collector's limits_requested remains false and its final exact check is disabled. Neither wrapper phase method rechecks the limit. Consequently, auto can remain in memory beyond max_bytes_in_join instead of switching to MergeJoin.

A concrete boundary is a join against 65,536 distinct UInt64 keys with max_bytes_in_join = 1048576, max_threads = 2, parallel_hash_join_threshold = 0, both external-join thresholds disabled, and enable_join_fixed_hash_table_conversion = 0. Its stored keys and routes fit below 1 MiB; the subsequently allocated hash table exceeds it. The previous serial collector counted that allocation during insertion and switched.

Include the table prediction/budget in the switch decision while the right blocks can still be handed over, and cover a byte limit between the fill footprint and completed-table footprint.

join.onBuildPhaseFinish();
if (partitioned_buckets)
join.runPostBuildPhase();
join.runPostBuildPhase();

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] Enforce the initial bucket's hard cap after building its table

The new bucket implementation defers table allocation until this call. Every inner insert uses callerChecksLimits, so the outer per-block checkSizeLimits sees only stored blocks/routes and the inner final check is disabled. onBuildPhaseFinish finishes the initial bucket without checking its completed size. Later buckets do perform this check in getDelayedBlocks, leaving the initial bucket uncovered.

For example, use grace_hash with one initial bucket, 65,536 distinct UInt64 right keys, max_bytes_in_join = 1048576, a 1 GiB external-join threshold, legacy_join_size_limits_trigger_spilling = 0, max_threads = 2, parallel_hash_join_threshold = 0, and fixed-table conversion disabled. The fill fits below 1 MiB, but its completed table does not; there is no repartition or later bucket to catch the violation, so the query succeeds above its hard cap.

Apply the completed-bucket limit check to the initial bucket too, including the stop latch for join_overflow_mode = 'break', and add a focused regression test.

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]>
return HashJoin::create(
table_join, right_table_expression_header, build_layout, params.join_any_take_last_row, stats_collecting_params);
if (PartitionedHashJoin::isSupported(*table_join))
return make_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.

[P1] Reclaim duplicate-only blocks before replacing the default ANY join

Routing ordinary hash joins here loses the old HashJoin behavior of releasing a build block when none of its rows is referenced. In a LEFT ANY JOIN with join_any_take_last_row = 0, the old implementation retains the first block containing each key and drops subsequent duplicate-only blocks before checking the byte limit. The single-fill path of PartitionedHashJoin instead unconditionally stores every block (PartitionedHashJoin.cpp:505–531); insertSingleLaneBlock never reports that none of its rows was retained, so those payloads stay alive throughout the query.

For a concrete boundary, build a right side of 65,536 non-NULL rows over 100 repeated keys, delivered in 1,024-row blocks, with a materialized FixedString(64) payload, and select that payload from a LEFT ANY JOIN. With max_threads = 1, join_any_take_last_row = 0, max_bytes_in_join = 1048576, both external-join thresholds disabled, and table swapping disabled, the previous join keeps about 64 KiB of payload plus its small table. The new path retains 4 MiB and raises SET_SIZE_LIMIT_EXCEEDED. Selecting the payload makes this independent of the removed key-only-table optimization.

Preserve reclamation of blocks that contain no retained rows in the eager single-fill path, and add a duplicate-heavy ANY regression with a byte limit between the representative-block footprint and the full input footprint. Otherwise common duplicate-heavy joins acquire memory usage proportional to all right rows and can fail under previously sufficient limits.

@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 399682cb2 with master ae3bcc01c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 352c5ea60; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: binary sizes, object file sizes, compile time of recompiled translation units.

Binary sizes ⚠️
Binary Master PR Δ
programs/clickhouse-stripped 787.01 MiB 772.41 MiB -14.60 MiB (-1.86%)

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

158 object files changed (-15.04 MiB total), 14 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp.o new 12.87 MiB +12.87 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp.o new 8.08 MiB +8.08 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp.o new 7.54 MiB +7.54 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp.o new 3.44 MiB +3.44 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/HashJoinClause.cpp.o new 1.95 MiB +1.95 MiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 3.57 MiB 1.73 MiB -1.84 MiB (-51.58%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 3.47 MiB 1.71 MiB -1.75 MiB (-50.63%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 3.38 MiB 1.63 MiB -1.75 MiB (-51.71%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 3.31 MiB 1.60 MiB -1.72 MiB (-51.86%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o 3.31 MiB 1.63 MiB -1.68 MiB (-50.89%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 3.31 MiB 1.63 MiB -1.68 MiB (-50.89%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o 3.28 MiB 1.61 MiB -1.67 MiB (-50.90%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinRightAny.cpp.o 3.22 MiB 1.55 MiB -1.67 MiB (-51.83%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 3.16 MiB 1.51 MiB -1.65 MiB (-52.30%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp.o 3.13 MiB 1.50 MiB -1.62 MiB (-51.98%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp.o 3.12 MiB 1.50 MiB -1.62 MiB (-52.00%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 3.08 MiB 1.46 MiB -1.62 MiB (-52.54%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 3.05 MiB 1.46 MiB -1.59 MiB (-52.19%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp.o 3.02 MiB 1.45 MiB -1.57 MiB (-52.01%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp.o 3.02 MiB 1.45 MiB -1.57 MiB (-52.01%)

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

2162 translation units recompiled, 13315 s compile time in total, 2147 of them have a recent master baseline.

Translation unit Master PR Δ vs median
src/Interpreters/HashJoin/HashJoin.cpp 22.3 s 15.4 s -7.2 s (-32%)
src/Interpreters/HashJoin/FullHashJoinAll.cpp 18.9 s 12.4 s -6.8 s (-36%)
src/Interpreters/HashJoin/LeftHashJoinAll.cpp 18.5 s 12.2 s -6.6 s (-35%)
src/Interpreters/HashJoin/RightHashJoinAll.cpp 18.7 s 12.5 s -6.5 s (-34%)
src/Interpreters/HashJoin/RightHashJoinRightAny.cpp 18.1 s 12.0 s -6.4 s (-35%)
src/Interpreters/HashJoin/FullHashJoinRightAny.cpp 18.3 s 12.3 s -6.3 s (-34%)
src/Interpreters/HashJoin/RightHashJoinSemi.cpp 18.1 s 12.1 s -6.3 s (-34%)
src/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp 17.6 s 11.8 s -6.1 s (-34%)
src/Interpreters/HashJoin/InnerHashJoinAll.cpp 18.0 s 12.3 s -6.0 s (-33%)
src/Interpreters/HashJoin/FullHashJoinAny.cpp 17.5 s 11.9 s -5.9 s (-33%)
src/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp 17.5 s 11.9 s -5.9 s (-33%)
src/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp 17.6 s 12.0 s -5.9 s (-33%)
src/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp 17.6 s 12.0 s -5.9 s (-33%)
src/Interpreters/HashJoin/RightHashJoinAny.cpp 18.0 s 12.5 s -5.7 s (-31%)
src/Interpreters/HashJoin/InnerHashJoinAny.cpp 16.1 s 10.6 s -5.7 s (-35%)
src/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp 17.3 s 11.9 s -5.7 s (-32%)
src/Interpreters/HashJoin/LeftHashJoinRightAny.cpp 16.2 s 10.9 s -5.6 s (-34%)
src/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp 17.4 s 12.1 s -5.5 s (-31%)
src/Interpreters/HashJoin/LeftHashJoinAny.cpp 16.1 s 10.8 s -5.5 s (-34%)
src/Interpreters/HashJoin/FullHashJoinAsof.cpp 16.1 s 10.9 s -5.5 s (-33%)

Translation units without a recent master baseline:

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp: 51.1 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 37.2 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 32.2 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 18.6 s
  • src/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 17.9 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 10.6 s
  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 6.4 s
  • src/Interpreters/HashJoin/SharedFixedHashTableFilter.cpp: 5.6 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)3, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.13 KiB 256.89 KiB +239.76 KiB (+1399.43%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)3, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.13 KiB 256.89 KiB +239.76 KiB (+1399.43%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.13 KiB 249.82 KiB +232.69 KiB (+1358.16%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.13 KiB 249.82 KiB +232.69 KiB (+1358.16%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.20 KiB 242.09 KiB +224.90 KiB (+1307.91%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.20 KiB 242.09 KiB +224.90 KiB (+1307.91%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 17.13 KiB 239.17 KiB +222.04 KiB (+1295.99%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 17.13 KiB 239.17 KiB +222.04 KiB (+1295.99%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 17.13 KiB 239.17 KiB +222.04 KiB (+1295.99%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 17.13 KiB 239.17 KiB +222.04 KiB (+1295.99%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)3, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 17.13 KiB 237.46 KiB +220.33 KiB (+1286.02%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)3, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 17.13 KiB 237.46 KiB +220.33 KiB (+1286.02%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.20 KiB 235.71 KiB +218.52 KiB (+1270.81%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)3, DB::HashJoin::MapsTemplat… 17.20 KiB 235.71 KiB +218.52 KiB (+1270.81%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 17.13 KiB 221.60 KiB +204.47 KiB (+1193.43%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 17.13 KiB 221.60 KiB +204.47 KiB (+1193.43%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 17.13 KiB 218.83 KiB +201.70 KiB (+1177.27%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 17.13 KiB 218.83 KiB +201.70 KiB (+1177.27%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 17.54 KiB 216.90 KiB +199.36 KiB (+1136.41%)
programs/clickhouse-keeper unsigned long DB::HashJoinMethods<(DB::JoinKind)3, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 17.54 KiB 216.90 KiB +199.36 KiB (+1136.41%)

Job report

harikrishnan94 and others added 6 commits October 17, 2026 11:35
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]>
`03915` expects the non-joined rows of the small `RIGHT` and `FULL` joins to come from a transform of their own, which `parallel_non_joined_rows_processing` selects. A random `False` of the setting made the counters 0, so the test sets it. `04695` took more than the limit of a flaky check and now carries the `long` tag.

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

The test expects `MEMORY_LIMIT_EXCEEDED` from the per-thread layout of one `parallel_hash` join with 256 threads under a limit of 512 KiB. Here `hash` is the partitioned join and builds one shared table. That layout no longer exists, and the join finishes within the limit.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`integration_tests_configs.py` lists the duration of each integration test. The entry of `test_concurrent_hash_join_single_join_memory_limit` points to a test that no longer exists.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the fixes of the `05227`, `05218`, `05139` and `04931` tests and the sanitizer guard of the `HashJoinTable` unit test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
An earlier edit changed the `ANY INNER` projection of both loops to `a.k, b.k`. Only the first loop needed it, and there the projection is unused because that case builds its own checksum. The second loop, after the switch to `MergeJoin`, hashes `a.k, b.k` to 16998114804852841604 while the reference holds 8951636308818590699 for `a.k, a.v, b.k`, so the `Fast test` failed. Both loops use `a.k, a.v, b.k` again.

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

/// The fill checked the sketch's estimate of the distinct keys; this is the exact count.
if (limits_requested.load(std::memory_order_relaxed))
table_join->sizeLimits().check(getTotalRowCount(), getTotalByteCount(), "JOIN", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED);

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] Honor break before the deferred table exceeds the byte limit

For join_overflow_mode = 'break', SizeLimits::check returns false; this call discards it. In the parallel build, earlier checks see only stored blocks and routes, so they can accept the entire right input before the table allocation crosses max_bytes_in_join.

For example, with join_algorithm = 'hash', max_threads = 2, parallel_hash_join_threshold = 0, max_bytes_in_join = 1048576, both external-join thresholds disabled, and fixed-table conversion disabled, 65,536 distinct UInt64 keys delivered in 1,024-row blocks occupy about 656 KiB during filling. All 64 blocks pass. The completed table alone occupies at least 2 MiB, but the failed final check is ignored and all keys remain available for probing. The previous eager build stopped after the first block whose table crossed the limit.

Account for the table while input can still be stopped, or build and check incrementally, so break does not consume every block based only on its smaller fill footprint. Add a regression with several build blocks whose stored data fits below the cap while the completed table does not.

return HashJoin::create(
table_join, right_table_expression_header, build_layout, params.join_any_take_last_row, stats_collecting_params);
if (PartitionedHashJoin::isSupported(*table_join))
return make_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.

[P1] Preserve the capacity of existing large hash joins

Making this path mandatory also makes the partitioned table's fixed geometry limit apply to ordinary hash and parallel_hash joins. HashJoinClause::decidePartitionPlan calls sizeDegreeFor, which throws LIMIT_EXCEEDED for a reserve requiring more than 2^32 cells (HashJoinClause.cpp:1745–1753); HashJoinTable::checkedSizeDegree independently rejects degrees above 32.

For example, a parallel build with three billion distinct UInt64 keys, adequate memory, max_threads = 2, parallel_hash_join_threshold = 0, max_rows_in_join = 0, and both external-join thresholds disabled now fails when planning its table. The previous implementation distributed keys across 256 independently growing maps and had no corresponding aggregate cap. Selecting parallel_hash or an older compatibility value cannot restore that implementation after this change, so existing large in-memory joins lose support independently of their configured resource limits.

Extend the shared table's supported geometry or retain a configurable implementation with the previous capacity before making it the sole implementation. This can be covered with a sizing-boundary test without executing a multi-billion-row query.

harikrishnan94 and others added 3 commits October 19, 2026 14:33
The targeted check randomizes `query_plan_optimize_join_order_randomize`. A random join order loses the planner's row estimate that picks the build layout, and the `dups 8: duplicate storage bytes` check then reported 0 instead of 1. The test now sets the setting to 0.

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

With `enable_join_runtime_filters = 0` the planner shards a `hash` join by primary key ranges. That runs one join per range and none of them has parallel non-joined sources, so the check "non-joined rows come from parallel sources under hash" returned 0 instead of 1 in the targeted check. The pipeline query now sets `query_plan_join_shard_by_pk_ranges = 0`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…are untracked

`PartitionedHashJoin.DestructionWithAllocationFailure` injects a fault into a small allocation made while the join is destroyed. In the ASan build small allocations are not charged to the memory tracker, so no fault fired and `QueryMemoryLimitExceeded` stayed at 0. The test now probes the tracker first and skips, as `SinglePartitionAsofGrowthFailureReleasesLookups` does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
GitHub never computed the merge state of this pull request after the last push, so no workflow started. This empty commit triggers the checks.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant