Skip to content

Read in order through SpillingHashJoin - #124873

Merged
antaljanosbenjamin merged 19 commits into
masterfrom
read-in-order-through-spilling-join
Nov 2, 2026
Merged

antaljanosbenjamin merged 19 commits into
masterfrom
read-in-order-through-spilling-join

Conversation

@antaljanosbenjamin

@antaljanosbenjamin antaljanosbenjamin commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

The read-in-order optimization now works through joins that can spill to disk: when the query plan needs the left table's row order (e.g. ORDER BY t1.pk LIMIT n), a hash join that crosses the spill threshold spills through a partial merge join, which preserves the order, instead of a grace hash join. join_algorithm = 'partial_merge' got an order-preserving probe and supports the optimization too.


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

Version info

  • Merged into: 26.11.1.1101-master (included in 26.11 and later)

@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 Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [82b5002]

Summary: ✅


AI Review

Summary

The PR enables reading in order through spill-capable hash joins by selecting an order-preserving MergeJoin fallback, and adds the same probe mode to partial_merge. Reviewed head 82b50029ff9efaf49fbd8d6548b45e7b2e0ba4cf. Request changes for the remaining unbounded INNER ANY JOIN claim-state allocation. Two previously dismissed resource-limit concerns also remain in the current code; they are retained below without reopening discussion.

Findings

⚠️ Majors

  • src/Interpreters/MergeJoin.cpp:762: Spilling does not bound INNER ANY JOIN claim-state memory. reinitPerRowFlags allocates one atomic_bool for every right input row after the external merge, including duplicate rows that can never be claim targets. A duplicate-heavy right side therefore needs memory proportional to its full row count before probing, independently of the spill threshold and cache budget, and can fail with a memory-limit exception. Store claims only for distinct keys, or provide bounded/spillable claim storage. Existing finding remains unresolved.

  • src/Interpreters/SpillingHashJoin.cpp:277: The ordered fallback drops the configured join hard caps. [dismissed by author -- https://github.com/Read in order through SpillingHashJoin #124873#discussion_r4230999416] The override still replaces max_rows_in_join, max_bytes_in_join, and join_overflow_mode with the spill threshold; MergeJoin then uses that threshold for spilling rather than enforcing the original caps. Queries that cross a hard cap after switching can continue instead of throwing or stopping. Preserve hard-limit accounting independently of spill/cache sizing. The author explicitly deferred this in the conversation.

  • src/Interpreters/MergeJoin.cpp:862: The spill fallback multiplies its gather budget by probe concurrency. [dismissed by author -- https://github.com/Read in order through SpillingHashJoin #124873#discussion_r4324643311] Each probe stream can retain half of memory_limit in gathered columns while the shared cache retains another full memory_limit; with 16 active streams these buffers alone can approach nine times the threshold, before temporary growth and output. This can exhaust memory on the path selected to relieve memory pressure. Share the gather budget across streams or divide it by probe concurrency. The current comment acknowledges the overshoot, and the author accepted it as a tradeoff.

Tests
  • ⚠️ Add a focused external INNER ANY JOIN regression with a duplicate-heavy right side, a small spill threshold, and a memory limit. The existing cardinality/parity tests do not demonstrate bounded claim-state memory.
Missing context / blind spots
  • ⚠️ No compiled PR binary was available locally, so runtime memory behavior was traced from the allocation paths rather than reproduced. A bounded-memory regression run on the PR binary would close this gap.
Final Verdict

⚠️ Request changes. Minimum required action: bound the external INNER ANY JOIN claim-state allocation and add the focused memory regression above. No new inline findings were posted; the existing claim-state thread remains open. The bot-authored all-filtered-build thread was resolved because its key-count guards have been removed and regression coverage is present.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 9, 2026
@antaljanosbenjamin antaljanosbenjamin changed the title Read in order through `SpillingHashJoin1 Read in order through SpillingHashJoin Oct 9, 2026
Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
Comment thread src/Interpreters/MergeJoin.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 82b50029f with master ca9786f6b (stripped binary size, per-symbol sizes and ThinLTO time; 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

30 object files changed (+88.68 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/MergeJoin.cpp.o 502.97 KiB 566.38 KiB +63.41 KiB (+12.61%)

719 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

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

Job report

@antaljanosbenjamin

Copy link
Copy Markdown
Member Author

The added performance tests shows it works nicely, query one and two

@antaljanosbenjamin

antaljanosbenjamin commented Oct 13, 2026 •

Copy link
Copy Markdown
Member Author

[src/Interpreters/SpillingHashJoin.cpp:225] The new ordered spill path constructs MergeJoin with SizeLimits(0, max_bytes_before_external_join, THROW), so once SpillingHashJoin falls back to MergeJoin it stops honoring the caller’s real max_rows_in_join / max_bytes_in_join / join_overflow_mode contract. A query that should still fail or truncate after spilling can now keep building until the threshold-sized MergeJoin decides otherwise. Suggested fix: keep table_join->sizeLimits() as the hard-cap contract and thread the spill threshold into MergeJoin separately for its own spill/cache budgeting.

I will address this in a different PR. It is not super important, we are already spilling, the max rows in join shouldn't be a problem.

[src/Interpreters/MergeJoin.cpp:1147] The gather path checks gather_max_bytes only once per right block, before copying any of that block’s runs. One wide spilled block can therefore copy far past the budget into gathered_right_columns, and this happens independently in every probe stream. That defeats the memory budget exactly on the path chosen to stay within it. Suggested fix: enforce the byte cap incrementally while copying runs, or byte-bound the spilled right blocks before enabling gather mode.

Addressed by ba674f0. It doesn't enforce the exact memory cap, but we can improve it in the future. Probably more memory is consumed on producing the result than the gathered bytes.

[src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:199] FilledJoinStep now participates in read-in-order traversal, but only JoinStep instances are recorded in joins_to_keep_in_order. The later join-specific guards use that list as their “went through a join” signal, so filled joins now bypass both the parallel-replica bailouts and the inner-join virtual-row requirement. Suggested fix: track join traversal separately from “needs keepLeftPipelineInOrder”, or otherwise make FilledJoinStep visible to those guards too.

Addressed by b61d93e.

@alexey-milovidov alexey-milovidov mentioned this pull request Oct 14, 2026
1 task done
@diegomestre2 diegomestre2 self-assigned this Oct 16, 2026

@diegomestre2 diegomestre2 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.

Great work on enabling this optimization! I left a few comments and can give another read after you address them. If I understand correctly, the biggest change is in the default plans: hash joins are basically SpillingHashJoin by default, and that used to block read-in-order through join. With this PR, queries like ... JOIN ... ORDER BY t1.pk will read in order by default even when nothing spills.

Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
Comment thread src/Interpreters/MergeJoin.cpp Resolved
Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
if (is_inner && is_any_join)
{
inner_any_used_flags = std::make_shared<JoinStuff::JoinUsedFlags>();
inner_any_used_flags->reinitPerRowFlags(right_blocks_row_counts);

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.

[P2] Bound claim-state memory for spilled inner-any joins

This also runs after the right side has been spilled, but reinitPerRowFlags allocates an atomic_bool for every right input row across all sorted blocks. That makes the external algorithm retain memory proportional to the entire right table again, independently of the spill threshold/cache budget. Duplicate-heavy right sides are especially problematic: hundreds of millions of copies of one key require hundreds of millions of flags even though all probes claim only that key's first right row. Previously the external partial merge probe did not have this allocation, so such queries can now fail with a memory-limit exception during post-build processing before producing any result.

Please avoid allocating claim flags for duplicate right rows, or use claim state that can remain bounded/spill. Add a focused duplicate-heavy INNER ANY test with a low spill threshold and memory limit; this allocation is separate from the already-discussed per-stream gather buffers.

@diegomestre2 diegomestre2 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.

Thanks for addressing the comments, once it is green you can merge it. Great work!

Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
SpillingHashJoin disable read-in-order-through-join optimization before, therefore the the two plans of parallel replicas and local didn't differ. Now it differs, because locally we enabled it. Disable read-in-order-through-join to keep it
@@ -792,6 +854,12 @@ void MergeJoin::mergeFlushedRightBlocks()
if (!memory_limit && rows_limit)

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.

Suggested change
if (!memory_limit && rows_limit)
if (!memory_limit && rows_limit && right_blocks.row_count)

so we make sure the division does not fail with 0 as divisor.

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.

That is covered by if (flushed_right_blocks.empty()): SortedBlocksWriter::finishMerge (and flushToManyFiles) returns an empty result in case there are no right blocks or only empty right blocks.

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.

I will a debug check in an upcoming PR, but I really would like to merge this ASAP.

@diegomestre2 diegomestre2 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.

I left one comment only. Feel free to consider it or not, I am not sure if it would break but it is nice to have the check. Good work!

@antaljanosbenjamin
antaljanosbenjamin added this pull request to the merge queue Nov 2, 2026
Merged via the queue into master with commit b0bf237 Nov 2, 2026
180 checks passed
@antaljanosbenjamin
antaljanosbenjamin deleted the read-in-order-through-spilling-join branch November 2, 2026 15:30
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 2, 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-improvement Pull request with some product improvements 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.

3 participants