Repository navigation
Cover the remaining hash join uses with the partitioned hash join - #120585
harikrishnan94 wants to merge 27 commits into
Conversation
|
Workflow [PR], commit [495340a] Summary: ❌
AI ReviewSummaryThe PR extends Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ 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. |
| = 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 |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 29.3 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 27.6 ssrc/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 18.4 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 16.8 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 10.7 sprograms/keeper/Keeper.cpp (clickhouse-keeper): 7.7 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 6.7 ssrc/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 |
8103c16 to
4260221
Compare
c85fc8d to
8e69471
Compare
8e69471 to
e5fa97b
Compare
4260221 to
1a19427
Compare
0b22791 to
9343d75
Compare
539e880 to
d44192c
Compare
Co-authored-by: Cursor <[email protected]>
`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]>
d44192c to
be10e76
Compare
9343d75 to
7432df3
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
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]>
| , 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()))) |
There was a problem hiding this comment.
[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(); |
There was a problem hiding this comment.
[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, |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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{}, |
There was a problem hiding this comment.
[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)); |
There was a problem hiding this comment.
[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>(); |
There was a problem hiding this comment.
[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.
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; |
There was a problem hiding this comment.
[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.
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]>
| 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)), |
There was a problem hiding this comment.
[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.
Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on #120579. #120595 sits on this.
partitioned_hashruns the plain hash join path. MixedONconditions, the in-memory buckets ofGraceHashJoin,JoinSwitcher, and the Join table engine (includingjoinGet) still constructHashJoin.It is not a stand-in for
hashuntil those callers can build it. A mixedON, a Grace bucket,auto, andJOIN ... ENGINE = Joinwould keep the old implementation even whenpartitioned_hashis the algorithm you asked for.Those four now build a
partitioned_hashjoin too. The Join table engine does so whateverjoin_algorithmsays. A join whoseONhas severalORdisjuncts, or a mixedONon aRIGHTorFULLjoin, still runs aHashJoinbehindPartitionedHashJoin. That is the next layer.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
partitioned_hashnow covers mixedONconditions onINNERandLEFTjoins,GraceHashJoinbuckets andJoinSwitcher. The Join table engine now keeps its table in the partitioned join.Workflow [PR]
Sync PR [sync-upstream/pr/120585]