Skip to content

Revert "Revert "Unify the spill trigger for hash joins"" - #119335

Merged
alexey-milovidov merged 30 commits into
masterfrom
revert-119334-revert-117356
Sep 20, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
revert-119334-revert-117356

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

Related: #117356
Related: #119334
Closes: #110521

Re-applies #117356, which was reverted in #119334.

One control for when a hash join spills. How it spills is still your choice of algorithm.

grace_hash spilled on max_rows_in_join / max_bytes_in_join and ignored max_bytes_before_external_join; every other hash algorithm did the opposite. Now, for all of them:

  • max_bytes_before_external_join / max_bytes_ratio_before_external_join — the spill threshold.
  • max_rows_in_join / max_bytes_in_join with join_overflow_mode — a hard cap. It never causes spilling, and a join that spills no longer exceeds it (GraceHashJoin ignored the check_limits argument of addBlockToJoin entirely).

Every algorithm stays selectable. grace_hash is external from the first block, so it needs a non-zero spill threshold: without one it is passed over for the next algorithm in join_algorithm, and rejected with a clear error when it is the only one listed.

Also fixed on the way: FillingRightJoinSideTransform detected spillability with typeid_cast<GraceHashJoin *>, so MemorySpillScheduler never reached the adaptive SpillingHashJoin path. It now goes through the IJoin virtuals canSpillToDisk / getSpillableBytes / requestSpill.

legacy_join_size_limits_trigger_spilling (default false, enabled by compatibility with 26.8 and older) restores the earlier meaning: for the part of a join that runs on disk the two limits trigger further spilling instead of stopping the query, and standalone grace_hash accepts a zero threshold again.

New since #117356: mixed-version serialize_query_plan is fail-closed. The setting is added to the join step settings at query-plan serialization version 17; below it the name is omitted (a peer that does not know it would reject the whole blob) and read back as legacy mode, and a join step whose spilling depends on the new contract — a non-zero max_rows_in_join / max_bytes_in_join, or grace_hash with a spill threshold — is refused rather than downgraded, because such a peer would run it with the old contract without saying so. gtest_join_spill_trigger_plan_setting.cpp locks that rule down.

Changelog category (leave one):

  • Backward Incompatible Change

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

max_bytes_before_external_join and max_bytes_ratio_before_external_join are now the spill threshold for every hash-based join_algorithm, including grace_hash, which previously ignored them and spilled on max_rows_in_join / max_bytes_in_join instead. Those two are a hard cap again for every algorithm: they no longer cause spilling, and a join that spills no longer exceeds them. All join algorithms remain available; join_algorithm = 'grace_hash' now needs a non-zero spill threshold, and is skipped in favour of the next algorithm in the list when it has none. Set legacy_join_size_limits_trigger_spilling = 1 (or compatibility to 26.8 or older) to restore the previous behavior.

🤖 Generated with Claude Code


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

@yariks5s yariks5s self-assigned this Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [edce8ed]

Summary: ✅


AI Review

Summary

This PR re-applies the spill-trigger unification for hash joins, adds the mixed-version serialize_query_plan fail-closed gate, and routes MemorySpillScheduler through IJoin spill virtuals. Most of the follow-up fixes are coherent, but GraceHashJoin still has a real join_overflow_mode = 'break' race in its parallel build path, so the change is not ready to merge.

Findings

❌ Blockers

  • [src/Interpreters/GraceHashJoin.cpp:362-385] stop_after_current_bucket only stops calls that observe it before entering addBlockToJoin, but GraceHashJoin is still fed by multiple concurrent FillingRightJoinSideTransforms ([src/QueryPipeline/QueryPipelineBuilder.cpp:549-586]). A thread that already passed line 369 can keep running through addBlockToJoinImpl, flush the non-current part of its block into delayed buckets, or even repartition the current bucket after another thread latched break. getDelayedBlocks then drops those delayed buckets, so join_overflow_mode = 'break' becomes timing-dependent and can lose right-side rows from the bucket that was supposed to be kept.
    Suggested fix: latch break under the same bucket-mutation path (hash_join_mutex / addBlockToJoinImpl) and make in-flight builders bail out before they can write any more rows to delayed buckets or split the current bucket after the latch fires.
Tests
  • ⚠️ tests/queries/0_stateless/05218_grace_hash_break_stops_delayed_buckets.sql proves the delayed-bucket truncation in a single-threaded build, but it does not exercise the parallel right-build path above. The fix needs a regression that forces at least two concurrent right-side builders and shows that the bucket which crosses the cap is kept intact under join_overflow_mode = 'break'.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit edce8ed.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 695/732 (94.95%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing edce8ed43 with master 930ccf281 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 01b8f1c9f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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

69 object files changed (+50.93 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Core/Settings.cpp.o 3.53 MiB 3.55 MiB +16.97 KiB (+0.47%)

716 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

404 translation units recompiled, 3821 s compile time in total, 404 of them have a recent master baseline.

Job report

Comment thread src/Core/ProtocolDefines.h Resolved
alexey-milovidov and others added 4 commits September 12, 2026 04:43
… an older peer

Skipping the `legacy_join_size_limits_trigger_spilling` name below query-plan
serialization version `17` keeps the settings blob parseable, but it does not
make the downgraded plan safe: the older peer knows `max_rows_in_join` /
`max_bytes_in_join` and still treats them as the spill trigger, and its
standalone `GraceHashJoin` ignores `max_bytes_before_external_join`. Such a plan
would silently run with the old contract.

Fail closed instead: `JoinSettings::updatePlanSettings` throws below version `17`
whenever the two contracts can diverge - a non-zero `max_rows_in_join` /
`max_bytes_in_join`, or `grace_hash` with a spill threshold - and stays quiet
when they agree, including when the query explicitly asks for the legacy mode.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…dy` red

`gtest_join_step_logical_decisions.cpp` still built `JoinSettings` from
`QueryPlanSerializationSettings` with the one-argument constructor, which this
branch replaced with the version-taking one, so `Build (arm_tidy)` failed to
compile it.

The new `gtest_join_spill_trigger_plan_setting.cpp` locks down what may be
downgraded below query-plan serialization version `17`: the name is on the wire
towards a current peer and read back as sent; below `17` it is omitted and read
back as legacy mode; serialization is refused when the size limits or a
`grace_hash` spill threshold make the contracts diverge, and allowed when the
query asks for the legacy contract or nothing depends on it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`legacy_join_size_limits_trigger_spilling` is also the way out of the
`serialize_query_plan` refusal towards a server that predates it, so say so where
the setting is declared.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 12, 2026
`spillBehaviorDiffersFromLegacy` treated `join_algorithm = 'grace_hash'` with both
spill thresholds cleared as compatible with a peer that predates
`legacy_join_size_limits_trigger_spilling`, but it is not: here such a join is not
runnable at all - `ExpressionAnalyzer::tryCreateJoin` / `PlannerJoins::tryCreateJoin`
demote `grace_hash` to the next entry of the preference list, and `GraceHashJoin`
refuses the query when it is listed alone - while a pre-`17` peer still builds a
standalone `GraceHashJoin` with `external_join_threshold = 0` and runs it.

So `grace_hash` now diverges from the legacy contract whatever the thresholds are,
and the gate no longer looks at them. The gtest covers both new cases, listed alone
and inside a preference list, and keeps a positive case that still passes the gate:
`grace_hash` with `legacy_join_size_limits_trigger_spilling = 1`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Interpreters/JoinOperator.cpp Resolved
alexey-milovidov and others added 2 commits September 12, 2026 15:35
`spillBehaviorDiffersFromLegacy` treated any appearance of `grace_hash` in
`join_algorithm` as a mixed-version incompatibility, which is broader than the
behavior it guards. `join_algorithm` is an ordered preference list, and the
`hash` / `parallel_hash` / `prefer_partial_merge` / `default` / `auto` branch of
`chooseJoinAlgorithm` ends in an unconditional `HashJoin` / `ConcurrentHashJoin`
/ `SpillingHashJoin`, so nothing behind such an entry is ever consulted - here or
on an older peer, which walks the same list in the same order. A list like
`hash,grace_hash` therefore builds the very same join on both sides, and there is
nothing to fail closed on.

Only a `grace_hash` that is the first entry able to run now counts. The size
limits keep failing closed whatever the list looks like, and the gtest covers the
unreachable-`grace_hash` lists with and without a spill threshold.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits September 14, 2026 18:32
… on a constant

`JoinSettings::spillBehaviorDiffersFromLegacy` exempted only an empty
`ON` clause (`ON 1`) as a join on a constant. `JoinStepLogical::buildPhysicalJoinImpl`
also turns a single predicate of type `Nullable(Nothing)` that is not a binary
condition (`ON NULL`) into an always-false `ConstantJoin`, on both sides of a
serialized plan, so such a step never consults `join_algorithm` and its size
limits are hard caps on both peers. The gate refused it towards a pre-`19`
peer as soon as `max_rows_in_join` / `max_bytes_in_join` were set or `grace_hash`
was listed. Both constant shapes are now recognized by one predicate,
`isJoinOnConstant`, that mirrors the physical build (ASOF excluded, like there).

The gtest builds an `ON NULL` operator and covers it for `grace_hash` and for
the size limits, and checks that an ASOF join with such a clause is not
treated as a join on a constant.

Addresses the review thread on `src/Interpreters/JoinOperator.cpp`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`JoinSettings::spillBehaviorDiffersFromLegacy` refused a downgraded plan for
steps that never reach the new spill contract on either side. The only join
that treats `max_rows_in_join` / `max_bytes_in_join` as a spill trigger on an
old peer is `GraceHashJoin`, standalone or inside the `SpillingHashJoin` of
the hash family, and `GraceHashJoin::isSupported` also requires a single join
clause (`TableJoin::oneDisjunct`). A step has one exactly when its `ON` clause
carries a cross-side equality at the top level: a single `OR` is split into one
clause per disjunct, an inequality-only join becomes an `IEJoinStep` (or a
CROSS join with a residual filter), and all of those check the limits as hard
caps on both sides.

`graceHashSupports` now includes that requirement (`hasEqualityKeys`), and the
gate returns early for any step it declines, before the preference list is
walked, so `join_algorithm = 'ie_join'` or `direct` on such a step is not
refused either. A step with an equality next to inequalities stays refused
when `ie_join` is listed first: an old peer may not honor that preference.

gtest `StepsWithoutASingleEqualityClause` covers a disjunctive `ON` clause and
inequality-only steps with the default, hash-family, `ie_join` and `grace_hash`
lists, and the contrast cases with a top-level equality.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red, Stress test (arm_debug) on ec59ebbd, is unrelated to this PR: the server restart failed to load test_3.t_pfl_05079, a table with an AggregateFunction(quantile('0.5'), Float64) column whose level was persisted as a quoted string and reparses as String (Cannot convert String to double). That is the startup failure fixed by #119810, which is still open; master will be remerged here once it lands.

alexey-milovidov and others added 2 commits September 15, 2026 06:46
… gate

`isPlainEquiJoin` accepted only `JoinConditionOperator::Equals`, so for a step
joined `ON l.a <=> r.a` the merge algorithms were treated as "unknown" and a
spill-capable entry behind `full_sorting_merge` / `partial_merge` made
`JoinSettings::spillBehaviorDiffersFromLegacy` refuse the plan towards an old
peer. But `JoinStepLogical::addJoinPredicatesToTableJoin` extracts a
`NullSafeEquals` predicate as an ordinary key of the same single clause (nullable
keys are wrapped into `tuple(...)` on both sides first), and neither
`FullSortingMergeJoin::isSupported` nor `MergeJoin::isSupported` tells it apart
from `=`, so both sides run the merge join and never consult the later entry.

Both `isPlainEquiJoin` and `hasEqualityKeys` now share one `isCrossSideEquality`
predicate accepting `Equals` and `NullSafeEquals`. New gtest
`NullSafeEqualityIsAKeyForTheMergeAlgorithmsToo` covers the trailing spill-capable
fallback behind a merge algorithm on a null-safe key, the kind/strictness split
and the still-refused hash-family lists.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Interpreters/JoinOperator.cpp Resolved
`spillBehaviorDiffersFromLegacy` treated every entry that stops the
`join_algorithm` walk as the hash-family case, where the size limits stop
being hard caps once a spill threshold is present. That is too broad for
`prefer_partial_merge`: both `chooseJoinAlgorithm` paths try `MergeJoin`
first and fall back to the hash branch only where `MergeJoin::isSupported`
declines the step. A plain equi-join with
`join_algorithm = 'prefer_partial_merge,grace_hash'` never reaches
`grace_hash` and keeps `max_rows_in_join` / `max_bytes_in_join` as hard
caps on both sides, so refusing the mixed-version downgrade was a false
positive.

New `runsStepWithHashFamily` separates "stops the walk" from "uses the
hash-family spill semantics": `prefer_partial_merge` counts as the hash
family only where `MergeJoin` declines the step (a kind / strictness it
does not run, or an `ON` clause that is more than plain equalities, which
stays fail-closed). The gtest no longer bakes in the false positive and
gets a dedicated test for both outcomes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Interpreters/GraceHashJoin.cpp Resolved
…lockToJoin`

When the bucket being built crosses `max_rows_in_join` / `max_bytes_in_join` under
`join_overflow_mode = 'break'`, `checkSizeLimits` returning `false` only stopped the
`FillingRightJoinSideTransform` that saw it. The buckets already spilled to disk were
still loaded and joined in `getDelayedBlocks`, because `stop_after_current_bucket` was
only set in the delayed phase, so the join returned rows well past the configured cap.

Set the latch in `addBlockToJoin` as well, so the join ends with the bucket in memory,
the way `HashJoin` ends with the block that crossed the cap. The flag becomes atomic
because the build phase is concurrent.

Test: `05218_grace_hash_break_stops_delayed_buckets`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red on 39e46581, Build profile diff, is not from this change: the job could not reach the CI logs cluster (ERROR: No connection to LogCluster, eight retries over 2.5 minutes on 2026-09-15 14:04-14:07Z) and failed closed on its has_pr_data read before comparing anything. The same error hit dozens of other PRs since 2026-09-14 19:00Z (checks in the CI database, check_name = 'Build profile diff'). The fix that makes the job skip instead of fail on a transient cluster-read failure is already in flight: #120121. All other completed checks are green; the review threads are all resolved and the AI review verdict is clean.

/// `join_overflow_mode = 'break'`: the caller stops feeding this side, but the buckets already on disk
/// would still be joined in `getDelayedBlocks` - well past the cap. Latch the stop here as well, so
/// the join ends with the bucket in memory, the way `HashJoin` ends with the block that crossed the cap.
stop_after_current_bucket = true;

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.

stop_after_current_bucket only changes what getDelayedBlocks does later; it does not stop concurrent build threads from touching the current bucket. GraceHashJoin still supports parallel build, and addBlockToJoinImpl can keep reaching repartitionCurrentBucket afterwards on both the zero-row spill path and the ordinary overflow path.

That makes join_overflow_mode = 'break' timing-dependent. If thread A trips the cap here and thread B already has another right-side chunk, thread B can still split the "kept" bucket and flush part of it into newly created delayed buckets. The later getDelayedBlocks call then drops those buckets because this flag is set, so the query can lose rows from the very bucket it is supposed to keep. This needs a build-phase latch too: once break has fired, later addBlockToJoinImpl calls must stop repartitioning/spilling the current bucket.

@yariks5s
yariks5s added this pull request to the merge queue Sep 18, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

no significant changes detected. K_source=6 K_base=27 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: eb329233-e1c9-4cfc-aa11-d2c9c4f8e2e2
  • MIRAI run: 38d93a54-b831-4191-97dc-6d0d2a662be6
  • PR check IDs:
    • clickbench_793291_1789769958
    • clickbench_793303_1789769959
    • clickbench_793311_1789769958
    • tpch_adapted_1_official_793322_1789769959
    • tpch_adapted_1_official_793347_1789769958
    • tpch_adapted_1_official_793361_1789769959

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 505d978 Sep 20, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-119334-revert-117356 branch September 20, 2026 04:01
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-backward-incompatible Pull request with backwards incompatible changes 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.

Unify the two disk-spilling hash-join paths: make SpillingHashJoin the single implementation

3 participants