Repository navigation
Add the spilling mode of the partitioned hash join - #120579
harikrishnan94 wants to merge 21 commits into
Conversation
|
Workflow [PR], commit [ddc8080] Summary: ❌
AI ReviewSummaryThis PR adds automatic spilling from Findings❌ Blockers
Tests
Missing context / blind spots
Final Verdict❌ Block. Fix the drained-state dereference, preserve spilling when a low estimate exhausts the table, and correct deferred-build eligibility and peak accounting. Add the focused regressions above. All four findings already have inline threads; no duplicate comments were posted. |
01d5f96 to
4d2a427
Compare
8103c16 to
4260221
Compare
4d2a427 to
93ac901
Compare
539e880 to
d44192c
Compare
86b8e57 to
601a479
Compare
Co-authored-by: Cursor <[email protected]>
d44192c to
be10e76
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the original row-based refresh cadence and complete-block sketch snapshot. A clean refresh advances its row stamp while reusing the identical estimate, so it cannot move the first spill decision.
Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - semantic merge fixes in non-conflicting files: src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.h Also resolved conflicts in: - `src/Interpreters/ConcurrentHashJoin.h` - `src/Interpreters/JoinSwitcher.cpp` - `src/Interpreters/SpillingHashJoin.cpp` `PartitionedHashJoin` implements `getAlgorithm`, which master made pure virtual in `IJoin`, and reports `parallel_hash` like the removed `ConcurrentHashJoin`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
The changeset in the PR is broken and contain several unrelated commits, I suggest fixing that (maybe with force push) before starting a human review |
|
@leshikus As you rightly noticed, the PR is draft and needs to be cleaned up for human review. I think the bot messed it up by requesting your review. |
The parent now carries the rewritten `uhj`. The spilling mode of this branch is applied again on top of it: - `SpillingHashJoin` keeps its partitioned collecting mode next to the `hash_join` member of the new class. It uses `JoinBuildContext` for the conversion of the fill lanes and for the drain into `GraceHashJoin`, and `PartitionedHashJoin::drainStoredBlocksInto` takes the context of the caller. - `JoinOutputSquashingTransform` derives from `SimpleSquashingChunksTransform`, so it keeps the maximum block size of the new squashing, and only adds the pass-through for a join that already emits sized blocks. - `PartitionedHashJoin` reports `PARTITIONED_HASH` as its algorithm. 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]>
Brings in the adjusted general join planning test. 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 key getter fix. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…form` `SimpleSquashingChunksTransform::consume` returns `void`, and `readability-avoid-return-with-void-value` rejects returning its result. The pass-through case now calls it and returns on the next line. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj`. `SpillingHashJoin` now reports its memory and spills through `ISpillable` instead of `getSpillableBytes` and `requestSpill`. The collecting join can be the partitioned one, so the memory stats read it through `collectingJoin`. A scheduler-requested spill hands the single-lane rows and the fill lanes over to the grace join before the state flips, as the base does for the workers of a `HashJoin`. The switch keeps the log text of the base. 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]>
| /// Unconverted workers still own memory; their counters are cleared by `releaseWorkerBlocks`. | ||
| const auto unconverted_bytes = hash_join->getTotalByteCount(); | ||
| /// Unconverted workers and fill lanes still own memory; releasing their blocks clears the counters. | ||
| const auto unconverted_bytes = collectingJoin().getTotalByteCount(); |
There was a problem hiding this comment.
[P1] Keep drained partitioned state readable by memory reporting
The collecting join is no longer safe to query after a stored-block drain: PartitionedHashJoin::releaseNextStoredBlock resets hash_join->data when it removes the last block, but getTotalByteCount still dereferences it through storedData. A build below parallel_hash_join_threshold with max_threads = 4 takes this drain on a spill, while this condition still passes because the wrapper reports four maximum build threads. With enable_adaptive_memory_spill_scheduler = 1 and a nonzero memory limit, the next filler work item calls getMemoryStats and dereferences the cleared data. The post-build MustSpill drain has the same lifetime problem when memory reporting follows it. Keep an empty accounting object alive, or make drained-state reporting safely return zero and clear the corresponding counters; cover a below-threshold spill followed by another scheduler memory report.
| const bool refused | ||
| = new_degree > 32 || (grow_budget != 0 && residentBytes() + need + allowance + extra_reserved > grow_budget); |
There was a problem hiding this comment.
[P2] Spill instead of throwing when a low estimate fills the table
The new grow_budget is the spill threshold, so refusing a mandatory grow here turns an ordinary underestimated build into LOGICAL_ERROR instead of spilling. For example, use the existing 05141 low-hint setup (16 estimated rows, 50000 actual distinct keys) with max_bytes_before_external_join = 20000. The wrapper's first pre-insert prediction is zero, so it admits the first block. The single-lane path stores the whole block, sizes a small table from the hint, then reaches this refusal while inserting that same block; there is no opportunity to return to the wrapper's next-block or barrier spill checks. Report the need to spill before exhausting the table and hand the retained blocks to GraceHashJoin. Add a regression combining the low estimate with a spill budget; the current low-hint test has spilling disabled.
Brings in the merge of `uhj` that repairs the `gtest_functions_stress` build. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
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]>
| partitioned_join->getTotalByteCount(), | ||
| partitioned_join->getTotalRowCount()); | ||
| chosen_join = partitioned_join; | ||
| state.store(State::IN_MEMORY_JOIN, std::memory_order_release); |
There was a problem hiding this comment.
[P2] Keep the deferred build eligible for adaptive spilling
The parallel collecting path still has to commit the hash table, scatter the keys, and allocate duplicate arenas in runPostBuildPhase. Publishing IN_MEMORY_JOIN here makes getMemoryStats return an empty report because there is no grace_join, so the scheduler check immediately before that work cannot spill this join. During collection the report reserves only the stored bytes, without the forthcoming table/scatter peak. With enable_adaptive_memory_spill_scheduler = 1, max_bytes_ratio_before_external_join = 0, and an absolute spill threshold above the query's remaining memory, collection can therefore fit while the deferred build raises MEMORY_LIMIT_EXCEEDED, despite the available spill path. Keep a spillable post-barrier state until those allocations are budgeted, account for their predicted peak, and use the stored-block drain if the scheduler requests a switch after the lanes have been consumed. Please cover memory pressure at this boundary with a focused regression.
Brings in the latest merge of `uhj`, the fix of the structure check in the scatter, the long tags and pinned settings of the tests, and the skip of the memory limit unit test. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`SpillingHashJoin::switchToGraceHashJoin` set the state to `GRACE_HASH_JOIN` and only then released the fill data of the partitioned join. A build thread that saw the new state at once converted the fill lanes. That raced with the release, which iterates the same lanes. ASan reported a container overflow, TSan a data race and MSan an uninitialized read. The hand-over now runs under the exclusive lock before the state changes, as it already did for a spill that the scheduler requests. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
|
||
| /// The ungrouped scatter never holds the whole chunk next to the whole table: an owner commits its | ||
| /// range and frees that partition's chunk in the same claim, so the peak sits at one end of the wave. | ||
| const size_t peak_ungrouped = floor_bytes + std::max(chunk_all + tables / partitions, tables + chunk_all / partitions); |
There was a problem hiding this comment.
[P2] Account for concurrent range commits in the scatter peak
This estimate assumes that only one owner holds a committed table range alongside its unconsumed chunk. However, runGroupStages runs ownerWaveWorker on ctx.workers threads, and each worker calls commitRange before inserting and releasing its partition's chunk. With as many workers as partitions, all ranges can therefore be committed while the whole scattered input is still live. The table and chunk can coexist in full, whereas this formula charges only one partition's overlap. The same assumption appears in partitionFloorFitsMemory.
Consequently, a budget between the predicted and actual peaks selects Fits (and may enable the parallel partition floor) instead of grouping or spilling. A query whose remaining max_memory_usage lies in that gap can then raise MEMORY_LIMIT_EXCEEDED during range commitment despite having a usable external join path; this also applies with adaptive spilling disabled. Account for all simultaneously active owners, including skewed partition sizes, or constrain the commit/release schedule to the overlap being budgeted. Please cover the case with one worker per partition and a query memory limit near the predicted peak.
Brings in the join order pin of the `04931` plan integration test. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Both spill queries of `05139_partitioned_hash_join_row_store` used a budget of 200000 bytes. That needs all 1024 grace buckets for the 100000-row build side, and one query ran for about 20 seconds in a release build, as long with `hash` as with `partitioned_hash`. The debug, MSan and TSan flaky checks ran it for the full 1800 second limit. A budget of 1000000 bytes still switches both queries to grace, keeps the reference output, and runs the whole test in about 2 seconds. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A budget of 1000000 bytes needs 64 grace buckets, not "few". The 200000 byte budget needs 1024. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
|
| Binary | Master | PR | Δ |
|---|---|---|---|
programs/clickhouse-stripped |
787.74 MiB | 779.01 MiB | -8.74 MiB (-1.11%) |
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 ⚠️
143 object files changed (-4.07 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.68 MiB | +1.68 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
2143 translation units recompiled, 12936 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: 19.3 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 16.2 ssrc/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 15.6 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 15.0 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 10.4 sprograms/keeper/Keeper.cpp (clickhouse-keeper): 7.3 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 7.1 ssrc/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 5.8 s
Symbol sizes
| Binary | Symbol | Master | PR | Δ |
|---|---|---|---|---|
programs/clickhouse |
ProfileEvents::global_counters_storage |
13.38 MiB | 13.56 MiB | +192.00 KiB (+1.40%) |
programs/clickhouse-keeper |
ProfileEvents::global_counters_storage |
13.38 MiB | 13.56 MiB | +192.00 KiB (+1.40%) |
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 |
…oracles `JSONDynamicPaths`, `JSONDynamicPathsWithTypes`, `JSONSharedDataPaths`, `JSONSharedDataPathsWithTypes` and `isDynamicElementInSharedData` report where a value is stored (its own subcolumn or shared data), which is a property of the column, not of the value. The hash join emits a required right key as a copy of the left key (`copyLeftKeyColumnToRight`), so the same right key has a different layout below and above the join, and NoREC compared a filter pushed below the join with `countIf` evaluated above it (`AST fuzzer (amd_release, oracle)` on PR ClickHouse#120579). The engine does the same for `isConstant`, which the oracles already skip because it is not deterministic. Add the five names to the backstop set. Also make `namesNonDeterministicRegularFunction` consult that set for a name that resolves to a regular function: the bare-name screen (a function passed by name to a higher-order function, or a `{param:Identifier}` holding one) read only `isDeterministic()`, so set members such as `materialize` passed in `arrayMap(materialize, arr)` form. Gating the lookup on `FunctionFactory::tryGet` keeps columns named like a table or aggregate function in the set (`url`, `sum`) checked. Marking the five non-deterministic instead was rejected: a sorting or partition key using one of them, which is accepted today, would then be rejected, and an existing table keyed on one would stop loading. ClickHouse#117187 carries the same five entries inside a larger oracle refactor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on #115254. #120585 sits on this.
partitioned_hashhas no spill path. Ifmax_bytes_before_external_joinis set and the join can spill, the planner builds ahashjoin instead.hashalready spills:SpillingHashJoinswitches it toGraceHashJoinwhen the limit is hit.parallel_hashis the same algorithm under another name. The spill path was taken out of #115254 so this layer can be read on its own.The planner wraps
partitioned_hashinSpillingHashJoinwhenmax_bytes_before_external_joinis set, temporary storage exists andGraceHashJoinsupports the join.Changelog category (leave one):
Workflow [PR]
Sync PR [sync-upstream/pr/120579]