Skip to content

Let read-in-order propagate through SpillingHashJoin - #111973

Merged
alexey-milovidov merged 29 commits into
masterfrom
spilling-hash-join-keep-left-order
Aug 14, 2026
Merged

alexey-milovidov merged 29 commits into
masterfrom
spilling-hash-join-keep-left-order

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

SpillingHashJoin::hasDelayedBlocks was hardcoded to true, even in the IN_MEMORY_JOIN state where nothing is ever delayed. That is the flag gating the read-in-order-through-join and top-k-through-join optimizations, so wrapping a hash join for auto-spilling silently disabled both — and max_bytes_ratio_before_external_join defaults to 0.5, which wraps every hash join. The in-tree comment in topKThroughJoin.cpp already describes this as the steady state.

IJoin documents that "SpillingHashJoin overrides keepLeftPipelineInOrder to forbid switching to GraceHashJoin at runtime", but no such override existed, so the escape hatch the comment describes was never implemented.

This implements it. keepLeftPipelineInOrder now pins the join to its in-memory algorithm, and hasDelayedBlocks reports false from that point on. Pinning is required for correctness, not just speed: once the plan drops a sort because the join preserves the left order, a later switch to GraceHashJoin would scatter rows by hash and silently return them in the wrong order.

The optimizer asks before it commits (findReadingStep checks feasibility, and keepLeftPipelineInOrder is only called later, if reading in order actually turns out to be possible). So a new IJoin::canKeepLeftPipelineInOrder carries the question "would you preserve the order if I asked?", defaulting to !hasDelayedBlocks() so every other join keeps its current answer. SpillingHashJoin answers yes while still reporting delayed blocks, and only stops reporting them once actually pinned — if the optimization turns out not to apply, nothing is pinned and the delayed-block transforms are still built.

Trade-off: a pinned join can no longer spill, so it holds the whole right side in memory and the memory tracker enforces the limit, exactly as it would with no auto-spill threshold configured. Since dropping the sort and then spilling would be a wrong-results bug, the only alternative is the conservative status quo of never propagating read-in-order through these joins. Both are now reachable: the new setting query_plan_read_in_order_through_spilling_join (default 1) turns the optimization off again, and it is registered in SettingsChangesHistory with previous_value = false, so compatibility set to a version before 26.8 restores the old behavior. ConcurrentHashJoin does not spill on its own (its threshold argument only bounds preallocation), so switchToGraceHashJoin is the single place the invariant has to hold.

The same gate applies to the first-pass topKThroughJoin: an ORDER BY left_key LIMIT n over a spill-capable LEFT JOIN now steps aside for the second-pass read-in-order plan instead of materializing a pushed-down Sort and Limit, and goes back to pushing them down when the setting is 0. The handoff keeps the deferral's pre-existing conditions — most notably, query_plan_join_swap_table must be explicitly false, because under the default auto a later optimization may swap the join sides and invalidate the read-in-order plan; with auto, such queries keep the pushed-down Sort and Limit.

Making this the default path exposed a pre-existing problem in read-in-order through a JOIN, which #110283 pinned down with 04516_join_order_estimation_pruned_parts a few hours before this branch entered the merge queue. max_rows_to_read with read_overflow_mode = 'throw' is not checked against the rows a query reads, but against the rows the reading steps announce up front: ReadProgressCallback::onProgress substitutes progress.total_rows_to_read for progress.read_rows whenever the estimate is the larger of the two, and ReadFromMergeTree announces min(part rows, InputOrderInfo::limit). buildSortingDAG dropped the limit at every JoinStep, so a plan reading in order through a JOIN always announced whole parts, and ORDER BY left_key LIMIT 1 over a LEFT JOIN that reads 20 rows announced 1010 and failed max_rows_to_read = 100. Dropping the limit is right for a join that can filter the left stream, but a LEFT ALL/LEFT ANY join emits at least one row for every left row, so n output rows need at most n left rows - duplication only makes fewer left rows necessary. The limit now survives those joins and is dropped everywhere else (INNER, SEMI, ANTI, ...). InputOrderInfo::limit never truncates a read - it feeds the announcement, the read-pool task size, the take_full_part heuristic and use_buffering - so this cannot change results. The behavior was already reachable on master with max_bytes_ratio_before_external_join = 0, which makes topKThroughJoin defer to the second pass exactly as it now does by default.

Related: #111248
Related: #111972
Related: #110283

Changelog category (leave one):

  • Performance Improvement

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

Reading in order through a JOIN now also works when a hash join has an automatic spill-to-disk threshold configured (the default since 26.5). When this optimization applies, the join stays in memory so it preserves the left-side order; set query_plan_read_in_order_through_spilling_join = 0 to restore the previous behavior, where such joins are not used for read-in-order and remain free to spill. As part of this, an ORDER BY ... LIMIT over a LEFT JOIN read in order no longer reports the whole table as the number of rows it intends to read, so it no longer trips max_rows_to_read with read_overflow_mode = 'throw' for a read that stops early.

Version info

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

`SpillingHashJoin::hasDelayedBlocks` was hardcoded to `true`, even in the `IN_MEMORY_JOIN`
state where nothing is ever delayed. That is what gates the read-in-order-through-join and
top-k-through-join optimizations, so wrapping a hash join for auto-spilling silently disabled
both - and `max_bytes_ratio_before_external_join` defaults to `0.5`, which wraps every hash
join.

`IJoin` already documents that "SpillingHashJoin overrides `keepLeftPipelineInOrder` to forbid
switching to GraceHashJoin at runtime", but no such override existed, so the escape hatch the
comment describes was never implemented.

Implement it. `keepLeftPipelineInOrder` now pins the join to its in-memory algorithm and
`hasDelayedBlocks` reports `false` from that point on. Pinning is required for correctness, not
just speed: once the plan drops a sort because the join preserves the left order, a later switch
to `GraceHashJoin` would scatter rows by hash and silently return them in the wrong order.

The optimizer asks before it commits, so a new `IJoin::canKeepLeftPipelineInOrder` carries the
question ("would you preserve the order if I asked?"), defaulting to `!hasDelayedBlocks()` so
every other join keeps its current answer. `SpillingHashJoin` answers yes while still reporting
delayed blocks, and only stops reporting them once actually pinned - if the optimization turns
out not to apply, `keepLeftPipelineInOrder` is never called and the delayed-block transforms are
still built.

Note the trade-off this makes explicit: a pinned join can no longer spill, so it holds the whole
right side in memory and the memory tracker enforces the limit, exactly as it would with no
auto-spill threshold configured.
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fda60b4]

Summary: ✅


AI Review

Summary

This PR teaches read-in-order and the topKThroughJoin handoff to work through SpillingHashJoin by pinning the join in memory when the planner commits to preserving the left-side order, and it also fixes the max_rows_to_read overestimation for the LEFT JOIN ... ORDER BY ... LIMIT path. The core implementation and the follow-up fixes from the earlier review threads look sound, but there is still one compatibility gap in the LEFT ANY handling.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:171] any_join_distinct_right_table_keys = 1 rewrites LEFT ANY JOIN to JoinStrictness::RightAny, but the new left-preserving checks still match only literal Any/All. Under that documented compatibility mode, legacy LEFT ANY queries still miss the new read-in-order / pinned-SpillingHashJoin path, because the same enum test is used here, in joinKeepsLeftSideLimit, and in topKThroughJoin.cpp.
    Suggested fix: treat JoinStrictness::RightAny as the same left-preserving semantics as JoinStrictness::Any in all three places, and add a focused regression test with any_join_distinct_right_table_keys = 1.
Final Verdict

The PR is close, but I would not merge it until the legacy LEFT ANY compatibility mode is either covered by the new left-preserving predicates or explicitly scoped out in the user-facing contract.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 197/223 (88.34%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 26, 2026
Returning early from `switchToGraceHashJoin` left `chosen_join` unset while the state stayed
`COLLECTING`, so `onBuildPhaseFinish` dereferenced a null pointer as soon as a pinned join
actually reached the threshold.

Turn the check into `maySwitchToGraceHashJoin`, evaluated at the call sites, so a pinned join
reports the threshold as not reached and always finishes through the in-memory promotion.
`logged_spill_suppressed` becomes atomic because the check runs on every build thread.

Rework the test onto the query shape from `03711_read_in_order_through_join`, which is what
actually triggers the optimisation - the previous one exercised neither the pin nor the
optimisation. It now asserts `ReadType: InOrder` through a join with a 1-byte spill threshold,
and that nothing spilled. Verified to fail on master (`ReadType: Default`) and pass here.
Comment thread src/Interpreters/SpillingHashJoin.h Resolved
Comment thread src/Interpreters/SpillingHashJoin.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 2 query(s) improved out of 35 analysed

This PR enables reading in order to propagate through spill-capable hash joins by pinning them in memory, a query-plan optimization that only affects join queries. The large, consistent speedups on tpch_adapted_1_official Q7 (×8.0 faster) and Q8 (×2.1 faster) line up directly with that change, and both show matching CPU-time drops. ClickBench queries are single-table with no joins, so the flagged Q23 improvement cannot come from this PR (and its runs were noisy) and is downgraded to not_sure; the envelope-suppressed no_change rows Q18 and Q30 are also off-path and look correctly decided.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 167 75 ×2.2 faster <0.0001 aggregation: This PR only changes read-in-order through spill-capable joins; ClickBench Q23 has no join, so a ×2.2 faster result can't come from it. The source runs were also very noisy, so this is run-to-run variance, not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 72 ×8.0 faster <0.0001 plan_change: Q7 is join-heavy with ordering, exactly what this PR helps: reading in order can now propagate through a spill-capable join by pinning it in memory. ×8.0 faster is a large, consistent shift and the CPU time dropped in step (8077 ms to 455 ms).
🟢 8 improvement 175 82 ×2.1 faster <0.0001 plan_change: Q8 is also a multi-join query that benefits from the same read-in-order-through-join plan change. ×2.1 faster is confirmed by both tests with a matching CPU-time drop (1768 ms to 670 ms).

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 7ede712d-d3fa-4f59-9437-91f1a41f04b3
  • MIRAI run: b8cbec38-7af7-4975-ade5-ff27de249a03
  • PR check IDs:
    • clickbench_1139416_1786668903
    • clickbench_1139422_1786668903
    • clickbench_1139434_1786668903
    • tpch_adapted_1_official_1139445_1786668903
    • tpch_adapted_1_official_1139455_1786668903
    • tpch_adapted_1_official_1139488_1786668903

`maySwitchToGraceHashJoin` was called before the byte-threshold check in
`addBlockToJoin`, so once the join was pinned the one-shot `LOG_DEBUG`
fired on the very first build block - claiming the spill threshold was
reached for joins that never came close to it.

Check the threshold first and only then ask whether spilling is still
allowed, matching what `onBuildPhaseFinish` already did.
…ty guard

Pinning an auto-spilling join in memory so it can keep the left order is
a behavior change for queries that previously stayed within the memory
limit only by spilling: they become eligible for reading in order, and
then hold the whole right side in RAM instead.

Add `query_plan_read_in_order_through_spilling_join` (default `1`) to
turn the optimization off again. With `0`, a join that may spill is
never used for reading in order - the conservative pre-existing
behavior - and therefore also keeps its ability to spill. The setting is
registered in `SettingsChangesHistory` with `previous_value = false`, so
`compatibility` set to a version before 26.8 restores that behavior
without naming the setting.

The guard sits in `findReadingStep`, the only place that turns
`canKeepLeftPipelineInOrder` into a commitment. It is also added to the
list of read-in-order gates that a distributed subquery plan re-reads
from its own context in `optimizeTree`.

New test `04649_spilling_hash_join_keep_left_order_opt_out` is the
mirror image of `04648`: same query, setting off, and it asserts both
that the left table is no longer read in order and that the join did
spill.
The new test drove `SpillingHashJoin` into a real spill with a 1-byte
`max_bytes_before_external_join`. `GraceHashJoin` inherits that threshold as its
own `external_join_threshold`, so every bucket with two or more rows overflowed
and it kept doubling the bucket count until it hit
`grace_hash_join_max_buckets` and threw `LIMIT_EXCEEDED`:

  Code: 290. DB::Exception: Too many grace hash join buckets (2048 > 1024)

`04648` is unaffected because there the join is pinned in memory and never
reaches `GraceHashJoin`. Size the opt-out test realistically instead: a 250k-row
right table and a 4 MB threshold, which is crossed by an order of magnitude and
satisfied again after 16-32 splits. `grace_hash_join_initial_buckets` and
`grace_hash_join_max_buckets` are pinned so the randomized-settings jobs cannot
change the bucket arithmetic.

Also address the review finding on the scope of
`query_plan_read_in_order_through_spilling_join`: it gates only the propagation
of reading in order through the join, not the separate `ORDER BY ... LIMIT`
through `JOIN` optimization, which pushes a `Sort` and a `Limit` down to the
preserved side and never relies on the join preserving any order. The setting
description and the `SettingsChangesHistory` entry no longer claim otherwise.
alexey-milovidov and others added 2 commits July 31, 2026 09:31
…shJoin`

The existing tests `04648`/`04649` force `join_algorithm = 'hash'` and disable the
ratio-based threshold, so they only exercise the single-threaded `HashJoin`-backed
`SpillingHashJoin`. The review asked for coverage of the `ConcurrentHashJoin`-backed
path that the default settings use in practice, with ratio-based spilling enabled.

`04661` mirrors `04648` with `join_algorithm = 'parallel_hash'` and
`max_bytes_ratio_before_external_join = 0.5`: the effective threshold is the minimum
of the ratio-derived value and the absolute `max_bytes_before_external_join`, so the
1-byte absolute value keeps it deterministic while the ratio branch runs too. The
pinned join reads in order and never spills (verified in the debug log: 'staying in
memory ... promoting ConcurrentHashJoin').

`04662` mirrors `04649` on the same path: with
`query_plan_read_in_order_through_spilling_join = 0` nothing pins the join and the
concurrent slots really convert to `GraceHashJoin` (verified: 'threshold reached with
ConcurrentHashJoin ... switching to GraceHashJoin').

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
…_ratio_before_external_join`

The `max_bytes_before_external_join` description already mentions that
`query_plan_read_in_order_through_spilling_join` can pin the join in memory
instead of converting it to grace hash join, but the sibling ratio setting
still promised an unconditional conversion once the ratio threshold is
reached. Mirror the caveat there.
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

…gh a spilling join

`query_plan_read_in_order_through_spilling_join` only reached the second-pass
`optimizeReadInOrder`. The first-pass `topKThroughJoin` still treated any
configured auto-spill threshold as an unconditional blocker, so an
`ORDER BY left_key LIMIT n` over a `LEFT JOIN` kept materializing a pushed-down
`Sort` and `Limit` even though the second pass can now pin the join in memory
and stream the rows straight from the primary key - the better plan.

Thread the setting into `Optimization::ExtraSettings` and consult it in
`joinMayHaveDelayedBlocks`: a join that reports delayed blocks only because it
*might* spill (`canKeepLeftPipelineInOrder`) no longer blocks the deferral,
while `GraceHashJoin` and `JoinSwitcher` still do.

New tests `04670_topk_through_spilling_hash_join_left_join` and its opt-out
mirror `04671_...`. `04209_top_k_through_join_read_in_order_gate` pinned the old
contract for the spilling case; its `spilling_on` expectation is updated and a
`spilling_on_opt_out` case keeps the conservative behaviour covered.
…n and of the analyzer

`04670` and `04671` assert on the plan that `topKThroughJoin` produces, but they
did not pin `query_plan_max_limit_for_top_k_optimization`. The stateless test
harness randomizes it over `[0, 1, 10, 100, 1000, 100000]`, and a value below
the tests' `LIMIT 3` makes `topKThroughJoin` bail out before it looks at the
join at all, so `04671` lost the `Sort` it expects below the `Join`. Pin it to
its default.

The `EXPLAIN` filter also let the `Expression` steps through, and the old
analyzer names them differently (`Joined actions + (Rename joined columns +
...)` instead of `Post Join Actions` / `Left Pre Join Actions`), which failed
both tests in the old-analyzer jobs. Those steps carry no information here, so
filter them out; what distinguishes the two plans is the `Sorting` step below
the `Join` and the `ReadType`.

Both tests now pass under the old analyzer and under 5 runs of randomized
settings each, together with their siblings `04648`, `04649`, `04661`, `04662`
and the master test `04209_top_k_through_join_read_in_order_gate`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111973&sha=2b238751da917ddc95bb5ffd551894e661e10a54&name_0=PR
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (27ebeb3) for a fresh CI run. All four reds on f50767c are pre-existing and unrelated to this change (each reproduces across many other PRs in CIDB over the last weeks):

@groeneai, investigate the two failures below and provide a fix in a separate PR (if a fix is already in progress, link it here):

  1. AST fuzzer (amd_debug, targeted, old_compatibility): assertion px != 0 in TreeRewriter::analyzeSelect via ReadFromMerge::createChildrenPlans under WhatIfIndexEstimator (STID: 2982-48f0) — https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111973&sha=f50767c310255c0d5450e580f187b881c59d1d33&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 — 10 occurrences across 8 unrelated PRs since 2026-07-18, no open tracking issue.
  2. Stress test (arm_debug): logical error Shard number is greater than shard count (STID: 5066-457d) — https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111973&sha=f50767c310255c0d5450e580f187b881c59d1d33&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 — the old issues Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-564d) #101325 / Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-457d) #101490 were closed in April, but the failure recurs since 2026-08-03 across at least 7 runs on unrelated PRs and on master, so it needs a fresh look.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Both investigated.

1. AST fuzzer px != 0 (STID 2982-48f0) - fix in progress, #109139.

removeJoin (src/Interpreters/getHeaderForProcessingStage.cpp:59 and :100) clears the child query's GROUP BY and ORDER BY expressions but leaves ASTSelectQuery::group_by_all / order_by_all set. That breaks the invariant order_by_all implies a non-null orderBy(), so TreeRewriter::analyzeSelect enters expandOrderByAll (TreeRewriter.cpp:1429) and dereferences the null orderBy() at TreeRewriter.cpp:850. #109139 resets both flags where the expressions are dropped, which covers all three removeJoin callers (StorageMerge, StorageDistributed, StorageWindowView).

The WhatIfIndexEstimator frame in this report is a new way to reach the same defect rather than a second bug: it plans an EXPLAIN through ReadFromMerge::createChildrenPlans, and the old_compatibility profile is what puts that plan on the old analyzer.

Status: approved by @vdimir on 07-28 and MERGEABLE, but Config Workflow fails on can_be_tested, so the fork run needs the can be tested label, which I cannot apply myself.

Keying on the message plus the expandOrderByAll / createChildrenPlans frames rather than one STID (the same defect also reports as a UBSan member access within null pointer of type 'DB::IAST' and as a segfault on amd_tsan), CIDB gives 12 hits / 11 distinct PRs / 0 on master over 30 days, consistent with your count.

2. Stress Shard number is greater than shard count (STID 5066-457d) - no fixing PR exists yet.

Your reading matches mine. 30 days: 7 hits over 6 PRs plus 1 master hit, first 2026-08-03 15:19Z, last 2026-08-04 09:25Z, across 5 stress variants (arm_release, arm_debug, arm_asan_ubsan, amd_msan, amd_debug). Daily counts over 150 days are 2026-03-29..04-01, then nothing until 2026-08-03, so it is a fresh onset and not a long tail. No open issue tracks it (#81738, #101325 and #101490 all closed in April).

One thing worth recording now: the master hit (ed5bb83c34e9, amd_msan) does not go through ReadFromRemote::addLazyPipe, which is the only site the April fix #101154 patched. It reaches prepareClusterForParallelReplicas (ClusterProxy/executeQuery.cpp:597) from StorageView::readImpl into a nested Planner, then buildQueryPlanForTableExpression (PlannerJoinTree.cpp:2049) and executeQueryWithParallelReplicas (:862). The April override is still present on master and simply does not cover this path: a _shard_num=2 scalar survives into a view's inner plan whose parallel-replicas cluster has one shard. Neither ClusterProxy/executeQuery.cpp nor ReadFromRemote.cpp changed since April, so whatever made the path reachable is upstream of both.

A fix task owns this at full effort and I will post the fixing-PR link here.

…in the deferral probe

`wouldReadInOrderBeUseful` returned `true` for `ReadFromMerge` and
`ReadFromObjectStorageStep` as soon as the sort keys matched, but pass 2
can still reject the actual request: `ReadFromMerge::requestReadingInOrder`
refuses reverse order with `FINAL`, and
`ReadFromObjectStorageStep::requestReadingInOrder` refuses configurations
that do not guarantee data sorted by the declared key. In those cases
`topKThroughJoin` stepped aside for nothing and the query lost both
optimizations.

The probe now mirrors each reader's commit-path rejection: the reverse
order with `FINAL` check for `MergeTree` and `Merge` (the `Merge` children
inherit `FINAL` from the same query), and the non-mutating
`requestReadingInOrder` itself for object storage. The caller-side
`FINAL`-and-any-descending-column heuristic in `topKThroughJoin` is
superseded by the exact check and removed.

New test `04847_topk_through_spilling_hash_join_merge_final_desc` covers a
`Merge` table over `ReplacingMergeTree` on the preserved side of a
spill-capable `LEFT JOIN` with `FINAL` and descending `ORDER BY ... LIMIT`;
it fails on the previous probe (the injected `Sort + Limit` disappears).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (57e076e) and addressed the AI Review major in 2bb07bb (the deferral probe now mirrors each reader's requestReadingInOrder rejections; new test 04847_topk_through_spilling_hash_join_merge_final_desc).

All 5 CI reds on 30676ab are unrelated fleet-wide stress failures that started on 2026-08-10:

Neither fix is on master yet, so these may recur on the fresh run.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole CI red on 2bb07bb — Stress test (arm_tsan) hung check — was the known fleet-wide storm (DROP TABLE prometheus stuck; #114291), exactly as predicted in the previous comment. The fix #114326 merged on 2026-08-12, so I merged master (02c5408) to pull it in and get a clean run. AI Review on the previous head was ✅ with zero unresolved threads.

@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 changes looks correct.

@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 12, 2026
alexey-milovidov and others added 2 commits August 13, 2026 00:54
`max_rows_to_read` with `read_overflow_mode = 'throw'` is not checked against
the rows a query reads, but against the rows the reading steps announce up
front: `ReadProgressCallback::onProgress` substitutes
`progress.total_rows_to_read` for `progress.read_rows` whenever the estimate is
the larger of the two. `ReadFromMergeTree` announces
`min(part rows, InputOrderInfo::limit)`, so the announcement is only as tight
as the limit that reached the reading step.

`buildSortingDAG` dropped the limit at every `JoinStep`, so read-in-order
propagated through a `JOIN` always announced whole parts. A query that stops
after one granule then looked like a full scan to the row limits: in
`04516_join_order_estimation_pruned_parts`, `ORDER BY l.id LIMIT 1` over a
`LEFT JOIN` reads 20 rows but announced 1010, and failed
`max_rows_to_read = 100`.

Dropping the limit is right for a join that can filter the left stream, but a
`LEFT ALL`/`LEFT ANY` join emits at least one row for every left row, so `n`
output rows need at most `n` left rows - duplication only makes fewer left rows
necessary. Keep the limit for those, and keep dropping it everywhere else.

This was reachable on `master` before this branch (with
`max_bytes_ratio_before_external_join = 0`, which makes `topKThroughJoin` defer
to the second pass exactly as it now does by default), but letting read-in-order
through `SpillingHashJoin` makes it the default path, so it is fixed here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Aug 13, 2026
The four queries of 04869_read_in_order_through_join_row_estimate rely on
the total-rows announcement reaching the row limits: the announcement is
delivered per source, and only when the source runs. When in-order reading
splits a part into several sources - which happens when reading from object
storage - a query that stops after the first granule never runs the later
sources, their announcements are never delivered, and the accumulated
estimate stays below \`max_rows_to_read\`. The two queries that expect
\`TOO_MANY_ROWS\` from the conservative announcement then succeed, which
failed the test on every s3/azure configuration:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111973&sha=26ec99825e2dd742f2d73873f4ed280c22bf5692&name_0=PR

\`max_threads = 1\` keeps the whole part in a single source whose
announcement is delivered on the first read on every storage (verified
against a \`local_blob_storage\` disk: multi-source announcements of ~80
rows each vs a single 1000-row announcement). \`enable_parallel_replicas =
0\` is pinned as well, because parallel replicas skip the announcement
altogether and the expected exception can never fire there.

#111973
/// condition changes nothing.
const bool keeps_left_order = join_ptr->canKeepLeftPipelineInOrder()
&& (data.read_in_order_through_spilling_join || !join_ptr->hasDelayedBlocks());
if ((strictness == JoinStrictness::Any || strictness == JoinStrictness::All) && isInnerOrLeft(kind)

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.

any_join_distinct_right_table_keys = 1 rewrites a user-written LEFT ANY JOIN to JoinStrictness::RightAny (QueryTreeBuilder.cpp:1146-1156, TreeRewriter.cpp:605-615), but this branch still treats only literal Any/All as left-order-preserving. That means the legacy LEFT ANY compatibility mode still falls out of the through-JOIN path even though its left-side semantics are identical to JoinStrictness::Any.

The same enum test is repeated in joinKeepsLeftSideLimit below and in topKThroughJoin.cpp:442, so under that documented compatibility setting these queries still miss the new read-in-order / pinned-SpillingHashJoin plan. Please fold RightAny into the left-preserving predicate everywhere this PR keys off LEFT ANY, and add a focused regression with any_join_distinct_right_table_keys = 1.

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 means the legacy LEFT ANY compatibility mode still falls out of the through-JOIN path even though its left-side semantics are identical to JoinStrictness::Any.

This is less important.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 14, 2026
Merged via the queue into master with commit 1fa79a4 Aug 14, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the spilling-hash-join-keep-left-order branch August 14, 2026 15:52
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
maxknv added a commit that referenced this pull request Aug 25, 2026
…keep-left-order

Revert "Merge pull request #111973 from ClickHouse/spilling-hash-join-keep-left-order"
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Aug 25, 2026
…-hash-join-keep-left-order"

This reverts commit 1fa79a4, reversing
changes made to f53f79d.
clickhouse-gh Bot added a commit that referenced this pull request Aug 26, 2026
Backport #116286 to 26.8: Revert "Merge pull request #111973 from ClickHouse/spilling-hash-join-keep-left-order"
alexey-milovidov added a commit to amosbird/ClickHouse that referenced this pull request Aug 28, 2026
…over

Master bumped the development version to 26.9, so the three entries of
this PR (`enable_named_columns_in_function_tuple`,
`allow_named_tuple_conversion_with_extra_source_fields`,
`allow_named_tuple_conversion_with_extra_source_fields_on_insert`)
must move from the now-released 26.8 section to the 26.9 section,
otherwise `02995_new_settings_history` fails. Also updated the
compatibility note accordingly.

Additionally the merge had kept a stale
`query_plan_read_in_order_through_spilling_join` entry that master
removed in 5f8dc5a (revert of ClickHouse#111973); the setting no longer
exists, so the entry is dropped.

Co-Authored-By: Claude Fable 5 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…ouse#111973 from ClickHouse/spilling-hash-join-keep-left-order"
raimannma added a commit to raimannma/ClickHouse that referenced this pull request Aug 29, 2026
…rs` and drop a reverted settings-history entry

Master added `topKThroughJoin` to `getOptimizations` while this branch added
`useRowWrappers`, so the `std::array<Optimization, 22>` had 23 initializers
("excess elements in array initializer"). Also remove the
`query_plan_read_in_order_through_spilling_join` entry from
`SettingsChangesHistory`, which no longer exists on master after
5f8dc5a reverted ClickHouse#111973.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=95071&sha=c227785b06461bfedd17394a98ff90b04b4fbe78&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016JPwa32AWPN8Fczp2cigG8
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 30, 2026
Derived from the manual edits the maintainers applied to the 26.8
changelog after the skill-assisted editing passes (git diff
26f0376
09e0e51 -- CHANGELOG.md):

- Maintainer-prepended `TODO:` flags as a release-workflow device
  (unexplained backward incompatibility, pending revert-of-revert,
  policy-violating setting names), distinct from author-left TODO junk.
- A `Backward Incompatible Change` entry must say what breaks.
- Full significance sort of every category on the final pass by default.
- Scan the whole release section for cross-category duplicate entries
  (`gini`, `use_query_condition_cache_for_top_k`, lazy materialization,
  adaptive codec selection) and describe the net shipped state.
- Check for reverts that postdate the generated range (ClickHouse#111973/ClickHouse#116504).
- Cut accurate-but-internal root-cause stories from entries.
- Formatting: bold-wrapped entries with doubled periods, `ClickHouse`
  spelling (style check), spaces inside parentheses, em-dash pairs to
  commas, redundant `Experimental:` prefix, backticking conversion
  expressions and tool names, automatic LTS marker for X.3/X.8.

Co-Authored-By: Claude Fable 5 <[email protected]>
antaljanosbenjamin added a commit that referenced this pull request Aug 31, 2026
`max_rows_to_read` with `read_overflow_mode = 'throw'` is checked against the row estimate the reading step announces, and `buildSortingDAG` dropped the LIMIT at every join, so read-in-order through a `LEFT JOIN` announced whole parts and failed the check despite reading only a few rows. A `LEFT ALL`/`LEFT ANY` join emits at least one row per left row, so the limit may be kept (`joinKeepsLeftSideLimit`). Restores the part of #111973 that the #116286 revert removed; resurfaced by this PR's `max_bytes_ratio_before_external_join = 0`, which unwraps `SpillingHashJoin` and makes the through-join pass the default path (caught by `04516_join_order_estimation_pruned_parts` in Fast test).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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