Repository navigation
Let read-in-order propagate through SpillingHashJoin - #111973
Conversation
`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.
|
Workflow [PR], commit [fda60b4] Summary: ✅
AI ReviewSummaryThis PR teaches read-in-order and the Findings
Final VerdictThe PR is close, but I would not merge it until the legacy LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 197/223 (88.34%) · Uncovered code |
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.
|
📊 Cloud Performance Report 🟢 AI verdict: 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. clickbenchFlagged queries (1 of 43)
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)
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
|
`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.
…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]>
…_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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 99/99 (100.00%) · Uncovered code |
…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
|
🕵 Merged
@groeneai, investigate the two failures below and provide a fix in a separate PR (if a fix is already in progress, link it here):
|
|
Both investigated. 1. AST fuzzer
The Status: approved by @vdimir on 07-28 and Keying on the message plus the 2. Stress 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 ( One thing worth recording now: the master hit ( 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).
|
🕵 Merged All 5 CI reds on 30676ab are unrelated fleet-wide stress failures that started on 2026-08-10:
Neither fix is on |
|
🕵 The sole CI red on 2bb07bb — |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The changes looks correct.
`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]>
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…keep-left-order Revert "Merge pull request #111973 from ClickHouse/spilling-hash-join-keep-left-order"
…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]>
…ouse#111973 from ClickHouse/spilling-hash-join-keep-left-order"
…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
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]>
`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).
SpillingHashJoin::hasDelayedBlockswas hardcoded totrue, even in theIN_MEMORY_JOINstate 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 — andmax_bytes_ratio_before_external_joindefaults to0.5, which wraps every hash join. The in-tree comment intopKThroughJoin.cppalready describes this as the steady state.IJoindocuments that "SpillingHashJoin overrideskeepLeftPipelineInOrderto forbid switching to GraceHashJoin at runtime", but no such override existed, so the escape hatch the comment describes was never implemented.This implements it.
keepLeftPipelineInOrdernow pins the join to its in-memory algorithm, andhasDelayedBlocksreportsfalsefrom 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 toGraceHashJoinwould scatter rows by hash and silently return them in the wrong order.The optimizer asks before it commits (
findReadingStepchecks feasibility, andkeepLeftPipelineInOrderis only called later, if reading in order actually turns out to be possible). So a newIJoin::canKeepLeftPipelineInOrdercarries the question "would you preserve the order if I asked?", defaulting to!hasDelayedBlocks()so every other join keeps its current answer.SpillingHashJoinanswers 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(default1) turns the optimization off again, and it is registered inSettingsChangesHistorywithprevious_value = false, socompatibilityset to a version before 26.8 restores the old behavior.ConcurrentHashJoindoes not spill on its own (its threshold argument only bounds preallocation), soswitchToGraceHashJoinis the single place the invariant has to hold.The same gate applies to the first-pass
topKThroughJoin: anORDER BY left_key LIMIT nover a spill-capableLEFT JOINnow steps aside for the second-pass read-in-order plan instead of materializing a pushed-downSortandLimit, and goes back to pushing them down when the setting is0. The handoff keeps the deferral's pre-existing conditions — most notably,query_plan_join_swap_tablemust be explicitlyfalse, because under the defaultautoa later optimization may swap the join sides and invalidate the read-in-order plan; withauto, such queries keep the pushed-downSortandLimit.Making this the default path exposed a pre-existing problem in read-in-order through a
JOIN, which #110283 pinned down with04516_join_order_estimation_pruned_partsa few hours before this branch entered the merge queue.max_rows_to_readwithread_overflow_mode = 'throw'is not checked against the rows a query reads, but against the rows the reading steps announce up front:ReadProgressCallback::onProgresssubstitutesprogress.total_rows_to_readforprogress.read_rowswhenever the estimate is the larger of the two, andReadFromMergeTreeannouncesmin(part rows, InputOrderInfo::limit).buildSortingDAGdropped the limit at everyJoinStep, so a plan reading in order through aJOINalways announced whole parts, andORDER BY left_key LIMIT 1over aLEFT JOINthat reads 20 rows announced 1010 and failedmax_rows_to_read = 100. Dropping the limit is right for a join that can filter the left stream, but aLEFT ALL/LEFT ANYjoin emits at least one row for every left row, sonoutput rows need at mostnleft rows - duplication only makes fewer left rows necessary. The limit now survives those joins and is dropped everywhere else (INNER,SEMI,ANTI, ...).InputOrderInfo::limitnever truncates a read - it feeds the announcement, the read-pool task size, thetake_full_partheuristic anduse_buffering- so this cannot change results. The behavior was already reachable onmasterwithmax_bytes_ratio_before_external_join = 0, which makestopKThroughJoindefer to the second pass exactly as it now does by default.Related: #111248
Related: #111972
Related: #110283
Changelog category (leave one):
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 = 0to restore the previous behavior, where such joins are not used for read-in-order and remain free to spill. As part of this, anORDER BY ... LIMITover aLEFT JOINread in order no longer reports the whole table as the number of rows it intends to read, so it no longer tripsmax_rows_to_readwithread_overflow_mode = 'throw'for a read that stops early.Version info
26.8.1.1426(included in26.8and later)