Repository navigation
Half-a-radix-join: PBNP - #115254
Half-a-radix-join: PBNP#115254harikrishnan94 wants to merge 26 commits into
Conversation
|
Workflow [PR], commit [a32920e] Summary: ❌
AI ReviewSummaryThis PR adds the experimental Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. Correct the refinement buffer sizing and serialization compatibility first; enforce join limits, bound the three excessive-allocation paths, and address the remaining early-stop, threshold and ordering contracts with focused regressions. |
…blocks The lazy emit of a right-side column walks, per output row, the materialized StoredBlock pointer, then the ColumnPtr inside the block's column vector, then the column object, before the value itself. The first three loads are pure indirection: every stored block shares the saved-block structure, so the source of a given output position is a function of block_no alone. StoredColumnsIndex::resolveEmitColumns already caches the resolved const IColumn * per block for the fillFromRowRefs path. It now also caches that column's raw fixed-width base per block, and the two buildOutputFromBlocks builders copy the values from it directly off the encoded ref words, without expanding them into (StoredBlock *, row_number) pairs first. A zero ref word writes bitwise zero, which is what insertDefaultInto writes for every admitted type, so the values are bit identical. The mechanism is ported from harikrishnan94's draft ClickHouse#115254, where it lives on the PartitionedHashJoin probe path behind a flag. On master the flag's four guards (lazy emit, not joinGet, not ASOF, not ANY) are already the exact condition under which the emit table is resolved, so the gather needs no flag and no call-site special case, and HashJoinMethodsImpl.h is untouched. Admission is resolved once per probe rather than per output chunk, and requires a single-plane contiguous source of a uniform stride across blocks whose raw buffer holds exactly its own rows. That refuses a ColumnReplicated source (which needs an index indirection and has no raw data), a ColumnConst (which forwards its raw data to a one-element buffer), and Enum8/Enum16 destinations (whose default is the first enum value, not zero). Anything refused keeps the generic path, per column. The limit and offset builder is all or nothing, because its gather input is the subset of ref words the walk selects after applying the offset and the limits, and that sequence only exists if the walk records it. New ProfileEvent HashJoinDirectGatheredRows counts the values emitted this way, which is what lets a test tell the two paths apart. Related: ClickHouse#116833 Related: ClickHouse#115254 Co-Authored-By: Claude Opus 5 <[email protected]>
The arming assertions counted a boolean per arm: some column of that arm took the direct gather. That cannot see one admitted type quietly falling back to the generic path, because the two paths produce identical values by construction, so the result lines cannot move either, and some other column keeps the boolean at one. The optimization is the deliverable here, so a silent loss of it for one type has to fail the test. New arm 1d asserts the exact count of gathered values over the existing 30 payload column fixture. It pins enable_hash_join_row_store = 0 so that the count is an identity rather than a measurement of the planner: whenever the in-memory row store initializes it claims every fixed and contiguous column of stride 32 or less, and its initialization compares against an estimate that drifts with accumulated statistics, so four of the boolean arms were measured taking two different counts across 52 runs. With the row store out of the path all 30 columns stay columnar for all 1000 probe rows. Every other arm keeps its boolean, and no existing arm, setting, fixture or reference line changed. Also skip collecting block pointers and row numbers when every columnar destination was gathered. fillJoinOutputColumns skips exactly those destinations, so on the shape where a row store coexists with a fully gathered columnar set the two appends per output row were dead. The size invariant in resolveEmitColumns is a positive test rather than a list of column classes to refuse, so that a column class added later which delegates getRawData to a buffer that does not hold its own rows is refused without needing an entry here. Related: ClickHouse#116833 Related: ClickHouse#115254 Co-Authored-By: Claude Opus 5 <[email protected]>
| /// a build estimated small keeps the narrow pipeline on purpose. | ||
| bool supportParallelJoin() const override { return !delegate_mode && !single_fill_thread; } | ||
| /// Probe blocks are joined whole, never scattered across slots, and the result caps its own blocks. | ||
| bool emitsSizedOutputBlocks() const override { return true; } |
There was a problem hiding this comment.
probeImpl wraps the original block in ScatteredBlock{std::move(block)} and never scatters it), but PartitionedHashJoin never opts into preservesLeftBlockOrder(). Since IJoin defaults this to false, optimizeReadInOrder and topKThroughJoin will treat an explicit join_algorithm = 'partitioned_hash' as order-destroying and skip the through-join optimizations that plain HashJoin gets. If there is no hidden reordering path here, this class should override preservesLeftBlockOrder() and add a focused plan test.
| build_blocks.clear(); | ||
| build_blocks.shrink_to_fit(); | ||
| /// From here the byte count tracks only the stored blocks. | ||
| accumulated_bytes.store(hash_join->data->allocated_size, std::memory_order_relaxed); |
There was a problem hiding this comment.
max_bytes_in_join stops being enforced once the actual table allocation happens. Up to this point the only checks are at lines 319 and 344, and they look only at accumulated_bytes (stored blocks plus route bytes). After finishSinglePartitionInsert / postBuild, the shared table, duplicate arenas, and nullmaps can add a lot more memory, but here we only reset accumulated_bytes and never run sizeLimits().check() against the real total (getTotalByteCount()). A build that fits the buffered input but blows up while building the table will therefore ignore join_overflow_mode, unlike HashJoin, which checks the accounted table size after every insert.
Please re-check the limit after the post-build phase using the actual join size, and cover the single-fill-thread path as well.
| { | ||
| if (delegate_mode) | ||
| return hash_join->alwaysReturnsEmptySet(); | ||
| return isInnerOrRight(table_join->kind()) && accumulated_rows.load(std::memory_order_relaxed) == 0; |
There was a problem hiding this comment.
This regresses the "empty effective right side" fast path that the other hash-family joins expose through alwaysReturnsEmptySet(). HashJoin returns true not only for INNER / RIGHT, but also for LEFT SEMI on an empty right side, and it bases the answer on the rows that actually survived into the build. Here the check only looks at isInnerOrRight(kind) and raw accumulated_rows, so the pipeline will keep scanning the entire left input for cases like LEFT SEMI JOIN (SELECT ... WHERE 0) or when every build row was filtered out by null keys or ON conditions before insertion.
That is a large regression from the existing hash-join behavior. This should either delegate to the wrapped HashJoin's notion of effective emptiness, or reproduce the same condition against the rows that really made it into the build.
| /// The fill-phase analogue of `HashJoin`'s per-block limit check. Rows are the accumulated | ||
| /// input rows, an upper bound on the keys the map-based algorithms check; bytes cover the stored | ||
| /// blocks and the route transients. | ||
| return table_join->sizeLimits().check( |
There was a problem hiding this comment.
❌ max_rows_in_join is defined on the built right-side join structure, but both checks here and at line 314 use accumulated_rows, i.e. raw build rows before duplicate collapse and before null-key / ON filtering. That changes behavior relative to HashJoin: a duplicate-heavy build can stay at one hash-table key and still trip the limit here, and with join_overflow_mode = 'break' this stops reading later right blocks even though the actual table is still within the configured row cap. Please base the row-limit check on the built table size (clause.tableRowCount() / getTotalRowCount()) and add a regression that covers duplicates plus a fully filtered build.
Build profile diff (arm_release)Comparing Binary sizes
|
| Binary | Master | PR | Δ |
|---|---|---|---|
programs/clickhouse-stripped |
787.74 MiB | 778.93 MiB | -8.81 MiB (-1.12%) |
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 ⚠️
139 object files changed (-4.18 MiB total), 13 added.
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp.o |
new | 4.14 MiB | +4.14 MiB |
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp.o |
new | 3.14 MiB | +3.14 MiB |
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp.o |
new | 2.89 MiB | +2.89 MiB |
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/HashJoinClause.cpp.o |
new | 1.63 MiB | +1.63 MiB |
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp.o |
new | 1.36 MiB | +1.36 MiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o |
3.36 MiB | 4.23 MiB | +886.31 KiB (+25.72%) |
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%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o |
3.31 MiB | 2.69 MiB | -636.64 KiB (-18.79%) |
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
2142 translation units recompiled, 13427 s compile time in total, 2128 of them have a recent master baseline.
Translation units without a recent master baseline:
src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp: 20.0 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 16.5 ssrc/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 16.0 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 15.8 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 10.9 sprograms/keeper/Keeper.cpp (clickhouse-keeper): 7.6 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 6.9 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 5.9 s
Symbol sizes
| Binary | Symbol | Master | PR | Δ |
|---|---|---|---|---|
programs/clickhouse-keeper |
ProfileEvents::global_counters_storage |
13.38 MiB | 13.50 MiB | +128.00 KiB (+0.93%) |
programs/clickhouse |
ProfileEvents::global_counters_storage |
13.38 MiB | 13.50 MiB | +128.00 KiB (+0.93%) |
programs/clickhouse-keeper |
auto DB::HashJoinClause::insertPartitionSection(DB::HashJoinClause::PostBuildContext&, unsigned lon… |
new | 65.00 KiB | +65.00 KiB |
programs/clickhouse |
auto DB::HashJoinClause::insertPartitionSection(DB::HashJoinClause::PostBuildContext&, unsigned lon… |
new | 65.00 KiB | +65.00 KiB |
2a1766f to
4327787
Compare
01d5f96 to
4d2a427
Compare
4d2a427 to
93ac901
Compare
4327787 to
33df09b
Compare
The parent now carries the rewritten `uhj`. This branch's own changes conflicted with it in the metrics, the settings, `TableJoin` and the planner, and are applied again on top of the new text: - `parallel_hash` is an alias of `hash` now and `JoinAlgorithm::PARALLEL_HASH` is gone, so the `partitioned_hash` additions no longer list it. `TableJoin::isHashFamilyEnabled` is back and covers `hash` and `partitioned_hash`. - `TableJoin` keeps the `parallel_hash_join_threshold` member and its `parallelHashJoinThreshold` accessor, which the partitioned join reads. `preferParallelHashLayout` still takes the threshold as an argument. - The old per-phase `HashJoin` timers that `uhj` removed are not brought back, only the `HashJoinPartitioned*` events of this branch. - The history of the two new `partitioned_hash_join_*` settings and of the `partitioned_hash` value of `join_algorithm` moves into their declarations in `Settings.cpp`, which is where the history lives now. Code that this branch adds and the new `uhj` has not seen is not adapted here. The partitioned join still builds its `HashJoin` with the old constructor arguments. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`PartitionedHashJoin::addBlockToJoin` takes a `JoinBuildContext` and reads the fill lane and the limit check from it. The delegate `HashJoin` and the clone made by `cloneNoParallel` are built with `HashJoinBuildLayout::oneBucket(1)`. `getAlgorithm` reports `PARTITIONED_HASH`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…the new `uhj` `KeyGetterForType` and `LowCardinalityKeyGetterForJoin` take no offset flag any more, so the routing, probe and fill code no longer passes one. The row store is a gather source, so the non-joined scan emits the row store columns through `gatherJoinOutputColumns` together with the columnar ones instead of resolving row pointers itself. `JoinCommon::canBeExecutedByEnabledAlgorithm` treats `partitioned_hash` like `hash`, and the threshold argument of `preferParallelHashLayout` no longer shadows the member of the same name. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…t the new `uhj` rewrote The new `uhj` tests `isEnabledAlgorithm(HASH)` where this branch's earlier base asked `isHashFamilyEnabled`, so seven places stopped treating a `join_algorithm` list with `partitioned_hash` as a hash join: the mixed `ON` guard and the hash-enabled flag of the planner, general join planning in the logical planner, `JoinStepLogical`, the rewrite of a join to `IN`, the join on a constant of the legacy rewriter, and the cache keys check of `TableJoin`. They ask `isHashFamilyEnabled` again. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…join planning test The new `uhj` pushes the one-sided `ON` conditions into `PREWHERE` for both `hash` and `partitioned_hash`, so `EXPLAIN` prints `Prewhere filter column` for them instead of `Filter column`. The first query of the test matches both spellings. 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 fix of the join key getter template arguments. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The base now runs an `INNER ANY` join whose `ON` expression has no equality key as a block nested loop join, so `05220` expects the counts instead of an `INVALID_JOIN_ON_EXPRESSION` exception. The base also pushes the one-sided condition of the second `05219` query into `PREWHERE`, so its `EXPLAIN` line reads `Prewhere filter column`. The loop variable of the routing test is `size_t`, like `skip.size()`, and the argument comment in `ExpressionAnalyzer` names the parameter `threshold`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj`. Four files conflicted. `preferParallelHashLayout` takes the new rule of `uhj` under this layer's parameter name `threshold`: without an estimate, only the largest threshold keeps the serial layout. The old analyzer call passes the `parallel_hash_join_threshold` setting. The settings history keeps this layer's `26.9` row below the moved `26.11` row. The runtime filter check allows `partitioned_hash` and keeps the new `ASOF` exclusion for `grace_hash`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A probe that reaches `max_joined_block_size_rows` stops and leaves the rest of the left block in `next_block`. The join transform of the base no longer looks at it and asserts that it is empty, because `HashJoin` continues inside its own result. The partitioned join result did not, so the unprocessed rows were dropped without an error. It now probes the rest and adds up the matched right rows of the parts. 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]>
…6.11` The `settings_changes_history` style check requires a record for the current version, `26.11`, on every setting that a pull request adds. `partitioned_hash_join_max_fanout_per_pass` and `partitioned_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]>
| settings[QueryPlanSerializationSetting::grace_hash_join_max_buckets] = grace_hash_join_max_buckets; | ||
|
|
||
| settings[QueryPlanSerializationSetting::partitioned_hash_join_max_fanout_per_pass] = partitioned_hash_join_max_fanout_per_pass; | ||
| settings[QueryPlanSerializationSetting::partitioned_hash_join_cap_partitions_by_l1_descriptors] = partitioned_hash_join_cap_partitions_by_l1_descriptors; |
There was a problem hiding this comment.
❌ Gate the new plan-setting names by the negotiated serialization version.
These assignments mark both settings as changed even when their values equal the defaults (SettingFieldNumber::operator= always sets changed = true). Consequently, writeChangedBinary writes both names for every serialized join, including an ordinary hash join that never enables partitioned_hash. A peer predating this PR has neither name in its strict QueryPlanSerializationSettings schema, so BaseSettings::readBinary throws UNKNOWN_SETTING. This breaks distributed-plan joins during a rolling upgrade without opting into the new algorithm.
Add a release-appropriate plan serialization version and guard these assignments, as the surrounding code does for other newly introduced plan settings. Also handle sending the new join_algorithm value to an older peer explicitly. A downgrade serialization test should prove that a default hash join omits both new names for older versions.
| UInt64 group_overflow = 0; | ||
| for (const auto & overflow : ctx.overflow) | ||
| group_overflow += overflow.rows(); | ||
| maybeGrowForLoadFactor(claimedTotal() + group_overflow); |
There was a problem hiding this comment.
❌ Do not size the table from the number of overflow rows.
group_overflow includes duplicate rows, but this projection treats each row as a new distinct key. For a concrete CRC32C UInt64 case, keys 343 and 2317 both have home cell 1023 in a degree-11 table. With two partitions, insert 343 first and then one million rows of 2317: every later row reaches the partition boundary at 1024 and enters overflow. This line projects 1,000,001 distinct keys and grows to degree 21 before the drain discovers only one new key. The table expands 1024-fold for two distinct keys, including for LEFT ANY, which needs no duplicate spans. Larger hot-key builds can exhaust memory unnecessarily.
Drain with the existing last-free-cell growth guard, then base load-factor growth on the actual claimed-key count. Cover a duplicate-heavy key whose first insertion crosses its partition boundary; the existing duplicate-growth test keeps its hot key inside the owner range.
| /*allow_set_maps_=*/false)) | ||
| , delegate_mode(!table_join->oneDisjunct()) | ||
| , build_rows_hint(build_rows_hint_) | ||
| , single_fill_thread(!delegate_mode && build_rows_hint_ && *build_rows_hint_ < table_join->parallelHashJoinThreshold()) |
There was a problem hiding this comment.
parallel_hash_join_threshold = 18446744073709551615 is documented to build one part on one thread even without an estimate, and TableJoin::preferParallelHashLayout implements that rule for hash. Here the missing build_rows_hint_ forces single_fill_thread to false. With estimation disabled (query_plan_optimize_join_order_limit = 0, and no collected statistics), a build whose distinct-key table exceeds L2 still gets multiple partitions in decidePartitionPlan and parallel fill, ignoring the user's explicit serial setting.
Handle the maximum-threshold sentinel independently of estimate availability, including capacity initialization when there is no hint. Add a focused pipeline/partition-count test with estimation disabled.
`insertSingleLaneBlock` added every row of a block to `inserted_rows` and to `HashJoinInsertedRows`. Rows with a NULL key, and rows that the `ON` condition filters out, never reach the table. In debug and sanitizer builds `verifyPublishedTable` compares the rows of the table with `inserted_rows`, so a single-lane build with such rows failed with a logical error. The multi-partition path already counts only the rows it inserts. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
CI randomizes settings, and these tests assume the defaults. `04927`, `04928`, `05111` and `05137` need several build threads, so they set `max_threads`. `05138` needs build blocks of 100000 rows, so it sets `max_block_size`. `05141` needs the planner's row estimate, which a randomized join order drops, so it sets `query_plan_optimize_join_order_randomize`. `05219` expects a `Prewhere filter column`, so it sets `optimize_move_to_prewhere`. `05140` sets `collect_hash_table_stats_during_joins`, because a repeated run reads the hint that the first run left. `05139` orders the first rows by `b.a` as well. It also reads its `ANY` join with one thread, because the right row that a key keeps depends on the block order. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`05141` also sets `query_plan_optimize_join_order_limit`, because a limit of 0 leaves out the row estimate that the test needs. `04931` sets `parallel_non_joined_rows_processing`, because it asserts that the non-joined rows come from parallel sources. `05218` sets `optimize_move_to_prewhere`, because its reference shows the one-sided conditions as `Prewhere filter column`. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
| ColumnsScatter::ScatterScratch scratch; | ||
| scratch.init(sub_fanout, swwc_fanout); | ||
| PaddedPODArray<UInt16> pids; | ||
| PaddedPODArray<UInt32> hist(sub_fanout); |
There was a problem hiding this comment.
❌ Keep refinement bucket counts wide enough for the full build.
ctx.bucket_rows[g] aggregates multiple input blocks, but this histogram uses UInt32. For example, four distinct UInt64 keys with 2^32 rows of one hot key, max_threads = 4, parallel_hash_join_threshold = 0, and partitioned_hash_join_max_fanout_per_pass = 2 select four partitions and two scatter passes. All hot-key rows stay in the same child, so ++hist[p] wraps and undercounts that child by 2^32. The following resize_exact(hist[p]) allocates from the wrapped count, yet scatterPidChunk writes all n rows through its raw destination cursor. This produces out-of-bounds writes. The per-input-block UInt32 row limit does not bound a refinement bucket.
Use wide counts throughout refinement, including allocation and the generic scatter interface, or reject an oversized bucket before scattering. Add focused coverage of the counter boundary.
| /// every block still holds its keys. | ||
| void HashJoinClause::measureGenericKeyBytes() | ||
| { | ||
| generic_key_bytes = keyLayout().generic ? keyColumnBytes() : 0; |
There was a problem hiding this comment.
On the deferred build path, keyColumnBytes includes every duplicate key. With max_threads = 1 and parallel_hash_join_threshold = 0, a LEFT ANY build containing one million copies of one 1 KiB String sets generic_key_bytes to approximately 1 GiB. predictedArenaBytes passes that to emplaceSizedBuildArena, so persisting the first distinct key allocates an approximately 1 GiB arena chunk, although only 1 KiB of key data is needed. That chunk remains through probing after the prepared input keys are released. Equivalent hash key storage grows only with distinct keys; this can make the new algorithm exceed max_memory_usage unnecessarily.
Estimate the retained distinct-key bytes, or let key storage grow incrementally instead of giving it the full input-byte reserve. Please cover repeated long strings with a memory bound, independently of duplicate-row span storage.
Brings in the latest merge of `uhj` and the fix of the structure check in the scatter. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`SinglePartitionAsofGrowthFailureReleasesLookups` measures what a small `std::vector` costs the memory tracker and sets the limit from that. In the asan, tsan and msan builds the measured cost was 0, so the assertion failed. The test now skips in a build that does not charge small allocations. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…er settings A flaky check runs copies of the same test at once, which makes a test that takes a few seconds in a debug build exceed its limit. `04927`, `04928`, `04929`, `05111`, `05139` and `05140` now carry the `long` tag, which exempts a test from that limit. The planner's row estimate decides the build layout, and a randomized join order or a reordering limit of 0 loses it. The tests that assert on the layout now pin `query_plan_optimize_join_order_randomize` and `query_plan_optimize_join_order_limit`. `04929` also pins `max_threads`, because a single thread gives one partition. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The flaky check randomizes `query_plan_optimize_join_order_randomize`. With a random join order the planner plants no runtime filter for the join, so the first check of `04931_partitioned_hash_join_plan_integration` returned 0 instead of 1. The test now sets the setting to 0. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
| /// only costs doublings during the inserts. | ||
| if (!clause.hasTable()) | ||
| clause.beginSinglePartitionInsert( | ||
| clause.reserveFor(*build_rows_hint, static_cast<double>(*build_rows_hint)), |
There was a problem hiding this comment.
build_rows_hint estimates input rows, but passing it as the distinct estimate makes the first block allocate for every estimated row. For example, with parallel_hash_join_threshold = 100000000, an accurate estimate of 64,000,000 repeated UInt64 keys reserves 2^27 cells (2 GiB for the RowRef table), even for LEFT ANY with just one distinct key. beginSinglePartitionInsert commits the entire buffer before inserting anything, and it never shrinks. A high planner overestimate has the same effect on a small actual build. The serial HashJoin deliberately avoids reserving from a row estimate.
Use a bounded initial reserve and grow from actual distinct claims, or use a genuine distinct-key estimate. Please add a memory-bounded regression with a high row hint and few distinct keys; the existing below-threshold tests only assert results and partition count.
Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on #120515. #120579 sits on this.
Related: #104585
Related: #111305
parallel_hashprobes one shared two-level hash table. Build threads insert into it through slots. Each slot owns a share of the buckets.The bucket count says how the table is divided. It says nothing about the order the writes arrive in. Once the build side outgrows the last-level cache, every probe lookup is a cold miss. The two-level split does not shrink the working set a thread writes.
Both algorithms do random writes. What differs is the range those writes cover.
parallel_hashwrites across 2 MiB to 256 MiB. A cache-sized partition writes across 1 MiB.To take partition count and size out of the comparison, both were pinned to 256 partitions of the same size. The shape is 6M distinct
UInt64keys, INNER ALL, 6M build rows against a 64K probe. The machine is one Graviton 4: 96 cores, L1d 64 KiB, L2 2 MiB per core, L3 36 MiB shared.HashJoinPartitions= 256 andHashJoinTableBytes= 268435456, so 256 x 1 MiB.HashJoinPreallocatedElementsInHashTables= 6000000, so 6M / 256 = 23437 keys per bucket. The hash table reserves 65536 cells x 16 B = 1 MiB per bucket, 256 MiB in total. Same geometry, same 6M inserts, equal checksums. Wall time and build thread time are the minimum of 4 runs fromsystem.query_log. The counters areperf statover the whole query.stall_backend_memmax_threads = 1,parallel_hashmax_threads = 1,partitioned_hashmax_threads = 96,parallel_hashmax_threads = 96,partitioned_hashAt one thread there is no lock contention and no sharing.
parallel_hashstill takes 2.4 times the L2 refills and 8.2 times the page-table walks. Time barely moves (98 ms against 91 ms), because one core has enough memory-level parallelism to hide the misses.partitioned_hashspends more instructions for the same cycles (IPC 2.03 against 2.40). At 96 cores the misses show up. Memory stalls are 54.7% of cycles against 28.3%. Build CPU time is 4.4 times higher.Owning a slot is the smaller half. The build of
parallel_hashwas patched so slot i has one writer, thread i.stall_backend_memparallel_hashparallel_hash, one writer per slotpartitioned_hashOne writer per slot saves 38% of the build CPU and 35% of the page walks. L2 misses stay put (19.3 M to 19.0 M). At one thread it changes nothing (dTLB 6.06 M to 6.13 M), because
#slotsis 1. Each slot juggling its buckets carries the L2 misses. Any thread touching any slot carries the page walks and the lock traffic.A radix join shuffles both sides. Its memory floor is
|build| + |probe|, and it pays a partitioning cost on the side that is usually the bigger one. Nothing repays that cost.partitioned_hashscatters only the build side. A worker claims one partition, inserts all of it, then claims the next. The probe is not scattered.The table is one buffer, sized from the distinct-key estimate and split into ranges. The histograms and prefix sums size the scatter chunks. The table doubles in place if the estimate was low.
RangeCommittedBufferfrom the layer below zeroes and charges each range when its owner claims it.On a large build the partitions are not cache-resident. A 16 GiB build at 1024 partitions gives 16 MiB ranges against a 2 MiB L2. It still wins, for four reasons.
Build wall time is flat from 64 to 65536 partitions. The insert is already at its bandwidth floor, so what a deeper fanout saves per insert, the extra scatter pass takes back. The probe only pays. Going from 8192 to 32768 partitions adds about 6% to probe thread time at a fixed shape.
This layer is
PartitionedHashJoinandHashJoinClause, plus the planner and the settings. It covers INNER, LEFT, RIGHT and FULL, crossed with ALL, ANY, RightAny, SEMI and ANTI. It also covers ASOF, null maps, per-clauseONfilters andUSING. Anything outside that set is planned ontohashat plan time, and never fails at execution time. Output is emitted by the standardHashJoinmachinery over a shared row store. This layer is one clause. Spill, mixedON,GraceHashJoin,JoinSwitcherand the Join table engine are the next layers. SeveralORdisjuncts run on a plainHashJoininsidePartitionedHashJoin, built by one thread. Moving them onto the partitioned table is #120595.The numbers below are from the 2026-08-18 revision of this branch. The code has since been rewritten for readability without changing the algorithm. That rewrite was checked against the previous revision on ten shapes and is within measurement noise. The probe ring now lives in #120515. The typed gather of output columns lives in #117460. Both were in the revision that was measured.
Benchmarks
Two
Memorytables joined on one key. Both sides are drawn from a persistent key store. Six properties are swept on their own. Key type:UInt64, composites of 2, 4 and 8 columns,Stringat 8, 16, 32 and 64 bytes, andNullablevariants ofUInt64andString. Distinct build keys: 65K to 512M. Hit rate: 0.05 to 1.0. Match multiplicity on each side: 1 to 256. Payload width on each side: 0 to 64 bytes of extraUInt64columns, all projected.max_threads: 2 to 96. That is 335 cells, each one run on both aarch64 and x86_64. Each cell is five timed runs after a warmup. The median is reported.Every run asserts the execution path through profile events. A cell that fell back to
parallel_hashfails the run. It cannot report a speedup of one. Row counts are asserted exactly before timing.Hardware: two fleets of 96-vCPU servers, one server per shard. aarch64 is Neoverse V2 (Graviton 4), 96 cores on one socket and one NUMA node. L1d is 64 KiB and L2 is 2 MiB per core. Shared L3 is 36 MiB. RAM is 370 GiB. The 2 MiB private L2 is what the partition-count rule sizes each range against. x86_64 is Sapphire Rapids with 96 vCPUs. Settings pinned:
join_algorithmto the algorithm under test,enable_analyzer = 1,enable_join_runtime_filters = 0,max_bytes_before_external_join = 0,query_plan_join_swap_table = false.Speedup means
parallel_hashtime divided bypartitioned_hashtime, so above 1 is a win. Aggregates are geometric means.335 of 335 shapes are wins on aarch64. Geometric mean 1.77x, median 1.66x. The 10th percentile is 1.36x and the 90th is 2.51x. 219 shapes are at or above 1.5x, 85 at or above 2x, 19 at or above 3x. Pooled geometric-mean latency is 207 ms against 368 ms. The best single point is 4.79x (2-column
UInt64key, 64M distinct, 96 threads, 120 ms against 575 ms). The worst is 1.11x (UInt64, 32M distinct, 16 threads, 99 ms against 110 ms).On x86_64 every cell is a win too, except two. Both are the same shape at two thread counts: a 32M-key build with an extra 128M rows that all carry one hot key. There x86_64 loses 1.17x at 16 threads and ties at 96, while aarch64 wins 1.21x and 1.14x on the same shape.
max_threadsAt 96 threads
partitioned_hashreaches 131 ms pooled whereparallel_hashis at 277 ms. At 64 threads it is 91 ms against 185 ms.Every key type wins. The spread across key types is narrower than the spread across thread counts. It runs from 1.65x for an 8-column
UInt64composite to 2.18x for an 8-byteString.A 5% hit rate averages 2.01x, against 1.74x at a full hit rate. A miss ends inside the partition and does not emit. Probe-side multiplicity goes the other way: 1:1 averages 1.80x, and 256 probe rows per build key drops to 1.52x. That replication is shared cost, and partitioning does not touch it. Build-side multiplicity helps. 16 build rows per key averages 2.29x, because the duplicates of a key sit in one contiguous span the cell points to.
Those payload aggregates are thinly sampled away from 8 B. The next cells hold the key, the cardinality, the hit rate, the multiplicities, the probe payload and the thread count fixed, and change only the build payload.
UInt64UInt64UInt64UInt64x4UInt64x4At 48 threads and above, a key-only build side averages 1.57x and a 64-byte payload 2.48x. The build-side widening is the typed gather of output columns. That code is #117460, and it was in the revision these cells were measured on.
A single hot key is the shape that pulls the advantage down. Across the 13 skewed cells the geometric mean is 1.48x, against 1.78x on the uniform ones, with a floor of 1.14x. One partition ends up far larger than the budget, and because a partition has a single writer, that worker sits on the critical path. Largest-first claiming spreads uneven partitions but cannot split one. Both x86_64 exceptions live here.
Memory: 293 of 335 cells peak below
parallel_hash, geometric mean 0.85x, median 0.87x. Nothing on the probe side is held, and the scatter chunks of a partition are released as its table is filled. 12 cells are above 1.2x and the worst is 2.27x. All of them are duplicate-heavy build sides with wide keys, at 96 threads. The scattered key columns and row references are large next to the tables they feed.TPC-H SF100
SF100 on
MergeTree(lineitemhas 600,037,902 rows), one server, aarch64m8g.24xlarge: 96 vCPU, 370 GiB, the same Graviton 4.The same script with
join_algorithm = 'partitioned_hash'. Five runs per query. Time is the hot minimum ofquery_duration_msand memory the hot peak ofmemory_usage, both over runs 2 to 5 fromsystem.query_log. Q01 and Q06 are left out because they have no join.18 of 20 queries are wins, 2 are at parity, none is slower. Geometric mean 1.21x, median 1.15x, best 1.87x. Total hot time 11,966 to 10,374 ms, 13.3% less.
parallel_hashpartitioned_hashThe five queries below 1M build rows are where partitioning has nothing to buy. Four of them have a build side below
parallel_hash_join_thresholdand build one partition on one fill thread.Q20 is at parity, 2862 against 2859 ms, and it is about a quarter of the total. Without Q20 the other 19 queries take 17.5% less time, at a geometric mean of 1.22x. Its join is faster (build 409 ms less, probe 12 ms less thread time), but the query is not, because the JOIN runtime filter is harmful on this shape and both algorithms pay for it.
parallel_hashruns Q20 in 2907 ms with filters and 2107 ms without.Peak memory: 15 of 20 queries peak below
parallel_hash, median 0.88x, and none of the other five is more than 12% above it. Summed peak goes from 67.1 to 62.6 GiB. The largest single peak barely moves: Q18, 23.07 to 22.90 GiB.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New experimental join algorithm
partitioned_hash, enabled withSET join_algorithm = 'partitioned_hash'. It builds the hash table of a hash join in cache-sized partitions and probes it without partitioning the probe side. Compared withparallel_hashit was faster on all 335 measured shapes on aarch64 (geometric mean 1.77x) and on all but two of them on x86_64, and used less peak memory on most of them.Workflow [PR]
Sync PR [sync-upstream/pr/115254]