Skip to content

Run the post-build phase of the wrapped join in SpillingHashJoin - #111972

Merged
alexey-milovidov merged 5 commits into
masterfrom
spilling-hash-join-post-build
Aug 10, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
spilling-hash-join-post-build

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Hash joins have a "post-build phase": a step that runs once, after the right table has been fully built, and applies optimizations to the finished hash table — tryRerangeRightTableData, tryConvertToFixedHashMap and publishSharedRuntimeFilters.

Since 26.5 the planner does not hand a bare HashJoin to the pipeline. It wraps it in SpillingHashJoin, which keeps the join in memory while it fits and switches to GraceHashJoin only when it grows past the spill threshold. This wrapping happens for essentially every hash join, because the threshold setting max_bytes_ratio_before_external_join defaults to 0.5.

SpillingHashJoin overrode neither hasPostBuildPhase nor runPostBuildPhase, so it inherited IJoin's false/no-op pair. FillingRightJoinSideTransform schedules the post-build phase only when hasPostBuildPhase returns true, so it saw "no post-build phase" and skipped it. The result: a join that never spilled, and therefore ran entirely as an ordinary in-memory HashJoin, silently lost all three of those optimizations.

The fix is to forward both methods to chosen_join — the join SpillingHashJoin actually settled on — the same way JoinSwitcher already does. This is safe because hasPostBuildPhase is queried right after onBuildPhaseFinish has set chosen_join. In the spilled state, chosen_join is a GraceHashJoin, which does not override these two methods, so forwarding leaves the spilled path exactly as it is today.

To be precise about that path, since the wording above was misleading earlier: GraceHashJoin runs the post-build phase only when the right table ended up in a single bucket (GraceHashJoin::joinBlock calls it under getNumBuckets() <= 1). A multi-bucket spill skips it, because a hash table that holds only one bucket cannot produce a runtime filter that is valid for the whole right table. That is pre-existing behavior and is intentionally not changed here; this pull request only restores the phase for the wrapped-but-never-spilled in-memory HashJoin, which is the common case.

Measured on 26.7.1.1315, the same 200k-row join on the same data, varying only the threshold:

configuration JoinBuildPostProcessingMicroseconds
max_bytes_before_external_join = 100000000000 (wrapped) 0
max_bytes_before_external_join = 0 (not wrapped) 12371

The server log confirms the wrapped case takes the affected path: SpillingHashJoin: All blocks fit in memory (17577600 bytes, 200000 rows), promoting HashJoin.

The impact is limited to the single-threaded HashJoin path: HashJoin::hasPostBuildPhase requires a key32/key64 map whose range is within 4x the key count, and ConcurrentHashJoin does not implement a post-build phase at all. Giving ConcurrentHashJoin one is a separate question, not addressed here.

Related: #111248

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed hash joins losing their post-build optimizations (conversion to a fixed hash table, the shared runtime filter, right table reranging) whenever an automatic spill-to-disk threshold was configured, which is the default since 26.5.

Version info

  • Merged into: 26.8.1.1143 (included in 26.8 and later)

`SpillingHashJoin` overrode neither `hasPostBuildPhase` nor `runPostBuildPhase`, so it
inherited `IJoin`'s `false`/no-op pair. `FillingRightJoinSideTransform` only schedules the
post-build phase when `hasPostBuildPhase` is true, so as soon as an auto-spill threshold is
configured - and `max_bytes_ratio_before_external_join` defaults to `0.5`, which wraps every
hash join - an in-memory `HashJoin` silently lost `tryRerangeRightTableData`,
`tryConvertToFixedHashMap` and `publishSharedRuntimeFilters`.

Forward both to `chosen_join`, the way `JoinSwitcher` already does. This is safe because
`hasPostBuildPhase` is queried right after `onBuildPhaseFinish` has set `chosen_join`.
`GraceHashJoin` reports no post-build phase and runs it per bucket itself, so the spilled
state keeps behaving as before.
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [932ff90]

Summary: ✅


AI Review

Summary

This PR forwards hasPostBuildPhase and runPostBuildPhase from SpillingHashJoin to the join chosen in onBuildPhaseFinish, which is the right place to restore the missing post-build phase for the wrapped in-memory HashJoin path. I did not find a remaining issue in that forwarding logic, but the new regression test is still too weak: it proves that some post-build work ran, not that the query actually went through SpillingHashJoin, so it can miss the wrapper-specific regression this patch is meant to cover.

Tests
  • ⚠️ [tests/queries/0_stateless/04647_spilling_hash_join_post_build_phase.sql:35] JoinBuildPostProcessingMicroseconds > 0 with spills = 0 also passes on a plain HashJoin. Please add a direct assertion that the plan uses Algorithm: SpillingHashJoin(HashJoin) (for example via EXPLAIN PLAN) or an equivalent wrapper-specific check.
Final Verdict

Needs a stronger regression test before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.70% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 79.00% +0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
@rschu1ze

Copy link
Copy Markdown
Member

A question: What is this PR doing exactly? The PR message is barely understandable.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze Sorry — I've rewritten the description to be clearer. The short version:

A hash join has a post-build phase: a step that runs once after the right table is fully built, applying tryRerangeRightTableData, tryConvertToFixedHashMap and publishSharedRuntimeFilters to the finished hash table.

Since 26.5 the planner no longer hands a bare HashJoin to the pipeline — it wraps it in SpillingHashJoin, which keeps the join in memory while it fits and only switches to GraceHashJoin past the spill threshold. That wrapping applies to essentially every hash join, because max_bytes_ratio_before_external_join defaults to 0.5.

SpillingHashJoin did not override hasPostBuildPhase/runPostBuildPhase, so it inherited IJoin's false/no-op pair. FillingRightJoinSideTransform schedules the post-build phase only when hasPostBuildPhase returns true, so it skipped it. Net effect: a join that never spills — i.e. an ordinary in-memory HashJoin — silently lost all three optimizations.

The fix is five lines: forward both methods to chosen_join, exactly as JoinSwitcher already does. Safe because hasPostBuildPhase is queried right after onBuildPhaseFinish sets chosen_join. In the spilled state chosen_join is a GraceHashJoin, which reports no post-build phase and runs it per bucket itself, so that path is unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

Comment thread src/Interpreters/SpillingHashJoin.h Resolved
@m-selmi

m-selmi commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

This is already covered by #111244

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reopening because #111244 was not merged yet.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

This PR is clearly labeled as a bug fix. While the other PR is labeled as a performance improvement.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Fixing bugs obviously has a higher priority than performance improvements.
Merging small PRs obviously has a higher priority than merging large, complex PRs.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 932ff90b1 with master 5e52a0f26 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of b9d4064cb; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.92 MiB 687.90 MiB -3.03 MiB (-0.44%)

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.

Compile time of recompiled translation units

10 translation units recompiled, 38 s compile time in total, 9 of them have a recent master baseline.

Job report

The comment claimed that `GraceHashJoin` "runs it per bucket itself". It does not:
`GraceHashJoin::getDelayedBlocks` only calls `HashJoin::onBuildPhaseFinish` for a delayed
bucket, and the single `runPostBuildPhase` call in `GraceHashJoin::joinBlock` is guarded by
`getNumBuckets() <= 1`. Scope the comment to what the code actually does; the behavior of
this pull request is unchanged.

@m-selmi m-selmi left a comment

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.

Makes senes, I will make #111244 a follow up.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111972&sha=ab4c8d7574d7e0320756842165806efdc6668e10&name_0=PR&name_1=Stress%20test%20%28arm_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this pull request (a join change). The server terminates on an uncaught exception inside the noexcept MergeTreeData::Transaction::commit:

Terminate called for uncaught exception:
Code: 439. DB::Exception: Cannot schedule a task: fault injected (threads=29, jobs=0). (CANNOT_SCHEDULE_TASK)
  ThreadPoolImpl<ThreadFromGlobalPoolImpl<false, true>>::scheduleImpl<void>(...)
  DB::ThreadPoolReader::submit(DB::IAsynchronousReader::Request)
  DB::AsynchronousReadBufferFromFileDescriptor::nextImpl()
  DB::PackedFilesReader::readIndex(DB::ReadBuffer&)
  DB::DataPartStorageOnDiskPacked::getSkipIndicesPackedReader() const
  DB::DataPartStorageOnDiskPacked::existsFileImpl(String const&) const
  DB::indexFileExistsInChecksums(...)
  DB::MergeTreeIndexMinMax::getAllSubstreamsInPart(...)
  DB::IMergeTreeDataPart::calculateColumnsAndSecondaryIndicesSizesOnDiskUnlocked() const
  DB::IMergeTreeDataPart::getColumnSize(String const&) const
  DB::MergeTreeData::addPartContributionToColumnAndSecondaryIndexSizesUnlocked(...)
  DB::MergeTreeData::Transaction::commit(DB::DataPartsLock&)
  DB::MutatePlainMergeTreeTask::executeStep()

So committing a mutation of a packed part does lazy on-disk size accounting, which performs a real asynchronous read; under the stress test's thread-pool fault injection the read cannot be scheduled and the exception escapes a noexcept function. It reproduces across many unrelated pull requests and on master over the last month:

SELECT toStartOfDay(check_start_time) AS d, count(), groupUniqArray(pull_request_number)
FROM checks
WHERE check_start_time > now() - INTERVAL 30 DAY AND test_status IN ('FAIL','ERROR')
  AND test_name LIKE 'Received signal 6%' AND test_context_raw LIKE '%MergeTreeData::Transaction::commit%'
GROUP BY d ORDER BY d DESC

12 occurrences over 12 different days, including pull_request_number = 0 (master). I did not find an existing issue for it.

-- The post-build phase ran at all (it is skipped entirely when the wrapper does not
-- report having one), and the join stayed in memory rather than spilling.
SELECT
ProfileEvents['JoinBuildPostProcessingMicroseconds'] > 0 AS post_build_phase_ran,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assertion is weaker than the contract this PR is fixing. A plain HashJoin also gives JoinBuildPostProcessingMicroseconds > 0 and spills = 0, so the test still passes if the planner stops wrapping the query in SpillingHashJoin. That wrapper is only chosen when max_bytes_before_external_join > 0, getTempDataOnDisk() is available, and GraceHashJoin::isSupported() holds. Please add an EXPLAIN PLAN assertion (for example Algorithm: SpillingHashJoin(HashJoin), as in 03915_spilling_hash_join) or another direct check that this query really took the wrapped path.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #112691 "Do not read part sizes while committing under the parts lock". Open, assigned to Avogar, no review yet. Your reading of the mechanism matches mine; the fix invalidates the size aggregates for a part whose sizes are not computed yet instead of reading them, so nothing is read inside the NOEXCEPT_SCOPE at all.

That build predates it: the regression test 04653_packed_part_size_accounting_no_read_in_commit.sql is absent at ab4c8d757 and at the current head 932ff90b1506, and present at the PR head af3a5078. MergeTreeData.cpp resolves at all three refs, so those are real absences and not a wrong path.

One precision on the census: the signature splits over two sub hashes of the same two frames. 3563-2928 covers the PR side (3 hits, 3 PRs, all Stress test (arm_release), this build being the third), and the master hit you saw is under 3563-40df (Stress test (amd_msan), 2026-07-29), which also fired on amd_asan_ubsan, so it is not arm only.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 3cf74b5 Aug 10, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the spilling-hash-join-post-build branch August 10, 2026 22:35
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 11, 2026
Requested in review: 03753 is not the test of the runtime filter built from
the fixed hash table, so the setting belongs in the file's settings section
rather than only in Q4.

Measured that the wider scope costs no coverage. With the setting pinned to 0
for the whole file and with it absent, Q1/Q2/Q3/Q5/Q6/Q7 produce identical
RuntimeFilter counters (Q1 6/98, Q2 9/195, Q3 11/293, Q5 8/197, Q6 5/100,
Q7 104/0, RuntimeFiltersCreated=1 throughout); only Q4 differs, 0/302 with
the pin against 12/290 without it. 04241 remains the dedicated test of the
shared fixed hash table filter.

The onset is ClickHouse#111972, also identified in review. Verified by A/B on one host
with one test file and one server configuration: with the two SpillingHashJoin
post-build overrides removed, the unpinned test passes 8 of 8 runs in one
process; with them present it passes the first run and then fails 7 of 7 with
RuntimeFilterBlocksProcessed=12, byte-identical to CI. max_bytes_ratio_before_external_join
defaults to 0.5, so SpillingHashJoin wraps the join by default and previously
inherited hasPostBuildPhase() = false, which kept publishSharedRuntimeFilters
from displacing the fully disabled bloom filter.

40 of 40 runs pass with the new form (20 randomized, 20 not). Removing the
pin reddens the test 5 of 5.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants