Skip to content

Add sorted_merge and parallel_sorted_merge join algorithms - #112973

Closed
alexey-milovidov wants to merge 119 commits into
masterfrom
sorted-merge-join
Closed

alexey-milovidov wants to merge 119 commits into
masterfrom
sorted-merge-join

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

Related: #109005
Closes: #117680

Implements the two algorithms planned in this discussion: full_sorting_merge and parallel_full_sorting_merge are always supported, so anything listed after them in join_algorithm is unreachable — listing them is an unconditional choice, not a preference. The new sorted_merge and parallel_sorted_merge algorithms execute the same merge join, but are available only when both join inputs can be efficiently read in the order of the join keys (e.g. MergeTree tables whose primary key starts with the join keys), so the pre-join sorts become cheap FinishSorting or disappear. When the tables' order cannot be exploited, the selection falls through to the next algorithm in the list. That makes them meaningful as a high-priority preference: join_algorithm = 'sorted_merge,parallel_hash' uses the streaming, low-memory merge join exactly when it is certainly beneficial, and a hash join otherwise.

sorted_merge runs a single in-order merge join. parallel_sorted_merge additionally shards the join by ranges of the tables' common primary-key prefix into independent per-shard merge joins running in parallel — the same source-side sharding query_plan_join_shard_by_pk_ranges applies, enabled for this join by the algorithm itself; the in-order reads stay intact (no scatter, no re-sort). When the sharding cannot apply (e.g. an ASOF join), it degrades to a single sorted_merge.

Implementation notes:

  • Eligibility is decided during plan physicalization, where the input subplans are visible: JoinStepLogical::inputsCanBeReadInJoinKeyOrder finds the ReadFromMergeTree below each input (mirroring findReadingStep of optimizeReadInOrder) and probes the actual read-in-order matcher (wouldReadInOrderBeUseful, the same side-effect-free probe topKThroughJoin uses) with the join-key sort description. A nested merge join below an input qualifies as well: it emits its rows sorted by its own join keys (left keys for INNER/LEFT, right keys for RIGHT, both for INNER; a FULL join is not sorted), the keys are traced through the expressions in between (aliases only), and the Sort before JOIN above it is built as a FinishSorting right away - so a multi-way join on a shared key stays a chain of merge joins with no re-sorting, and parallel_sorted_merge shards the whole chain by the common primary-key ranges (fixes sorted_merge/parallel_sorted_merge are selected only for the bottom join of a multi-way join, so the listed fallback runs every join above it #117680, where only the bottom join could be a sorted merge and the upper joins fell through to the hash fallback). With parallel replicas the join below is not yet physical when the runtime-filter pass runs, so the algorithm it will select is predicted by replaying the selection order (predictMergeJoinOutputOrder). Two hazards of the primary-key-range sharding pass this exposed are fixed: the pass no longer carries a sharding through an unsharded merge join (it joins one stream per side, so the join above would have paired arbitrary streams as shards), and a merge join that degraded from its sharding no longer resizes its output; the single-stream fallback of JoinStep now merges any multi-stream sorted input. The predicted decision degrades gracefully in both directions: a false positive runs like full_sorting_merge (with a full sort), a false negative falls through to the next algorithm.
  • The same memoized predicate makes tryAddJoinRuntimeFilter keep its hands off an eligible join listed before the first hash-family algorithm. Without this, planting a runtime filter erases the merge algorithms from the list (a merge join reads both sides concurrently and cannot use a runtime filter), silently overriding the priority order — the defining feature of these algorithms. For non-eligible joins the runtime filter (and the erasure) stays, because those algorithms are not selectable anyway. When applyParallelReplicas later breaks the eligibility (a join input becomes a distributed read), the filter pass is re-run for exactly the joins it had skipped, so the hash fall-through gets its runtime filter back.
  • FullSortingMergeJoin now carries the selected algorithm (getSelectedAlgorithm) instead of an is_parallel flag; the hash-scatter rewrite (optimizeParallelFullSortingMergeJoin) stays exclusive to parallel_full_sorting_merge, and optimizeJoinByShards runs in a restricted mode (only parallel_sorted_merge-selected joins, with a cheap pre-scan bail-out) when query_plan_join_shard_by_pk_ranges is off. When the sharded stream counts diverge at pipeline-building time (e.g. a data-dependent PREWHERE prunes one side to a single empty stream), JoinStep merges each side's per-shard sorted streams back into one sorted stream and runs the single-stream merge join instead of failing (the same approach as Fix LOGICAL_ERROR in full_sorting_merge JOIN when sharding stream counts diverge #109393, applied at the sharding fallback).
  • The CreateSetAndFilterOnTheFlyStep pair (max_rows_in_set_to_optimize_join) is not added for sorted-merge joins: it sits between the read and the sort and would defeat the in-order read the algorithm was selected for.
  • The new values are gated on the query plan serialization version (DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SORTED_MERGE_JOIN, reusing 20 of the current release): a serialized plan towards an older peer drops them from join_algorithm, so that peer falls through to the next listed algorithm instead of rejecting the plan with UNKNOWN_JOIN; a list of only these values is refused.
  • The old analyzer has no query plan at selection time, so there the algorithms are never selected and the list falls through (documented). With only sorted_merge listed and no exploitable order, the query fails with NOT_IMPLEMENTED, like other unsupported single-algorithm configurations.
  • The known lower-priority-fallback side effects of listing merge algorithms (stricter USING key-type inference, topKThroughJoin deferral) extend to the new values and are documented in the join_algorithm setting description.

Tests: 04669_sorted_merge_join_selection pins the selection gating via EXPLAIN PIPELINE (selected on a primary-key join with no re-sort, falls through on non-key joins / disabled read-in-order / old analyzer, priority order respected, error when listed alone without exploitable order) and correctness against hash for INNER/LEFT/RIGHT/FULL/ANY/join_use_nulls. 04670_parallel_sorted_merge_join pins the primary-key-range sharding (Sharding: marker with query_plan_join_shard_by_pk_ranges = 0, no ScatterByPartitionTransform, no MergeSortingTransform), the ASOF degradation, and correctness. 04824_sorted_merge_join_parallel_replicas_fallthrough and 04894_sorted_merge_join_parallel_replicas_runtime_filter pin the parallel-replicas edge (fall-through to hash with the runtime filter restored), 04895_parallel_sorted_merge_join_shard_stream_divergence pins the diverged-shard degradation, 04896_sorted_merge_join_null_safe_equals pins the ineligibility of a nullable null-safe (<=>) join (whose keys are compared wrapped into tuple(...), so they cannot be read in table order), 05047_sorted_merge_join_asof_key_order pins that an ASOF join is probed in the order the merge join actually sorts by (equality keys first, the inequality key last) rather than in the textual order of the ON conjuncts, 04907_sorted_merge_join_cast_fallthrough pins the fall-through when a common-type conversion can reorder a key, 04760/04850 pin the join_use_nulls and query_plan_join_shard_by_pk_ranges contracts, and 05056_sorted_merge_join_multi_way pins the multi-way chains (3 and 4 tables merge-only with no MergeSortingTransform, which nested kinds/keys keep the order and which fall through, the sharded chain, and correctness against hash). The PR #109005 regression tests and the join runtime filter tests pass unchanged.

Changelog category (leave one):

  • New Feature

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

Added new join_algorithm values sorted_merge and parallel_sorted_merge: merge-join algorithms that are available only when both join inputs can be efficiently read in the order of the join keys (so the join benefits from the tables' order instead of sorting), and otherwise fall through to the next algorithm in the list. parallel_sorted_merge additionally shards the join by primary-key ranges into independent per-shard merge joins running in parallel. Listing them first, e.g. join_algorithm = 'sorted_merge,parallel_hash', uses the streaming low-memory merge join exactly when it is certainly beneficial.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Unlike `full_sorting_merge` / `parallel_full_sorting_merge`, which are
always supported (so anything listed after them in `join_algorithm` is
unreachable), the new algorithms are available only when both join inputs
can be efficiently read in the order of the join keys - the pre-join sorts
become cheap `FinishSorting` or disappear. When the tables' order cannot
be exploited, the selection falls through to the next algorithm in the
list, which makes them meaningful as a high-priority preference, e.g.
`join_algorithm = 'sorted_merge,parallel_hash'`.

`sorted_merge` runs a single in-order merge join. `parallel_sorted_merge`
additionally shards the join by ranges of the tables' common primary-key
prefix into independent per-shard merge joins (the same source-side
sharding as `query_plan_join_shard_by_pk_ranges`, enabled for this join by
the algorithm itself), keeping the in-order reads intact.

The eligibility is decided during plan physicalization, where the input
subplans are visible: `JoinStepLogical::inputsCanBeReadInJoinKeyOrder`
finds the `ReadFromMergeTree` below each input and probes the actual
read-in-order matcher (`wouldReadInOrderBeUseful`) with the join-key sort
description. The same memoized predicate makes `tryAddJoinRuntimeFilter`
keep its hands off an eligible join: a runtime filter would erase the
merge algorithms from the list and silently override the priority order
(a merge join cannot use a runtime filter - it reads both sides
concurrently). The old analyzer has no plan at selection time, so there
the algorithms are never selected and the list falls through.

Suggested in
#109005 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 2, 2026 03:03
@mintlify

mintlify Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 9, 2026, 4:14 AM

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bec4b80]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_asan_ubsan, flaky check) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (amd_tsan, s3 storage, targeted) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
05565_sorted_merge_join_nested_planned_full_sorting_merge FAIL cidb
Build profile diff ERROR

AI Review

Summary

Adds conditional sorted_merge and parallel_sorted_merge selection, including nested merge joins, primary-key-range sharding, and runtime-filter restoration after parallel-replica rewrites. Reviewed the current diff and all prior discussions; no actionable findings remain. Four focused stateless tests matched their references on the PR's Fast test binary, and six additional nested-join result comparisons passed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 2, 2026
The style check rejects the phrase "new analyzer" - the analyzer is enabled
by default since ClickHouse 24.3.
…electable

`tryAddJoinRuntimeFilter` skipped the join runtime filter whenever `sorted_merge`
or `parallel_sorted_merge` was listed before the first hash algorithm and the
inputs could be read in join-key order. But the physical selection additionally
requires `FullSortingMergeJoin::isSupported`, so a join shape the merge algorithm
does not implement - `SEMI`, `ANTI`, a one-sided `ON` condition, a disjunction -
fell through to `hash` while having lost its runtime filter, making
`join_algorithm = 'sorted_merge,hash'` slower than plain `hash`.

`JoinStepLogical::inputsCanBeReadInJoinKeyOrder` now mirrors the supportability
checks of `FullSortingMergeJoin::isSupported`: the kind/strictness must be one
`MergeJoinAlgorithm` implements, and every `ON` condition must be a two-sided key
predicate (plus the single `ASOF` inequality). Both callers use the same memoized
predicate, so the runtime-filter pass and the selection still agree.
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds two new opt-in join algorithms, sorted_merge and parallel_sorted_merge, which merge-join tables that are already stored in join-key order. The default join_algorithm does not change, and the pipeline changes only touch merge-join paths. All four flagged improvements are marked not sure because the new code does not run for these queries. ClickBench Q33 (-11.9%) and Q34 (-12.5%) and TPC-H Q1 (-16.9%) have no joins, and TPC-H Q7 (-23.5%, 19 ms) uses the default hash join. All four queries have noisy histories, and the ClickBench medians fall inside master's recent range, so the shifts look like run-to-run variation.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1134 999 -11.9% <0.0001 aggregation: Q33 is a single-table GROUP BY with no join, so the new sorted_merge join algorithms never run here. The -11.9% is also inside master's recent range, and this query's history is noisy.
⚠️ 34 not_sure 1140 998 -12.5% <0.0001 aggregation: Q34 is a single-table GROUP BY with no join, so the PR's join planning and pipeline changes do not run here. The -12.5% is inside master's recent range, and this query's history is noisy.

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 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 54 -16.9% <0.0001 aggregation: TPC-H Q1 is a lineitem-only aggregation with no join, so nothing in this diff runs. The -16.9% is an 11 ms shift on a query whose measurements are very noisy.
⚠️ 7 not_sure 81 62 -23.5% <0.0001 join_operator: Q7 joins with the default hash algorithm. The new sorted_merge paths and the changed resize for merge-join pipelines only apply when a merge join is used, so the -23.5% (19 ms) on this noisy query is not attributable to the PR.

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: 5f775498-09fb-48c1-a5d4-567507b27acd
  • MIRAI run: d7cc8114-0e78-4c98-a33b-cc90b0c78944
  • PR check IDs:
    • clickbench_1072452_1791819910
    • clickbench_1072465_1791819910
    • clickbench_1072471_1791819910
    • tpch_adapted_1_official_1072478_1791819910
    • tpch_adapted_1_official_1072508_1791819910
    • tpch_adapted_1_official_1072522_1791819910

# Conflicts:
#	docs/en/sql-reference/statements/select/join.md
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three stress-test failures on da5421b are unrelated to this PR:

Merged master (resolved a docs conflict: docs/en/sql-reference/statements/select/join.md was deleted with the legacy docs tree, the ASOF JOIN note update is ported to docs/reference/statements/select/join.mdx) and pushed to retrigger CI.

…join_use_nulls

The AI review raised two findings around `join_use_nulls`:
* `USING` + `join_use_nulls = 1` would allegedly pass the
  `inputsCanBeReadInJoinKeyOrder` gate but fail
  `FullSortingMergeJoin::isSupported`, suppressing the `hash` runtime
  filter and then falling through to `hash` anyway;
* `parallel_sorted_merge` would allegedly lose its primary-key-range
  sharding under `join_use_nulls` because of the `toNullable` wrapping.

Neither happens on the analyzer path (the only one where the new
algorithms exist): `USING` is desugared into an `ON` equality with
explicit casts before physicalization, so the `hasUsing` rejection in
`isSupported` never fires and the merge join really is selected; and
the sharding matcher keeps matching the primary key for the OUTER kinds
and for `USING` alike, because the nullability conversion of the
visible outputs does not obscure the source-side key DAGs. Pin both
contracts with a test and replace the stale 'join_use_nulls is not
supported' comment in `optimizeJoinByShards`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three CI failures on 149a6b9 are all pre-existing master issues, unrelated to this PR:

Pushed c50e443: merged the latest master and added 04760_sorted_merge_join_use_nulls, addressing the two AI-review findings (both refuted empirically — see the thread replies).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (bf23d71347f). Triage of the five CI failures on c50e4435ea1:

All four stateless tests of this PR (04669, 04670, 04696, 04760) pass locally on the merged head. AI review on the previous head: no new findings; no unresolved review threads.

…in with converted keys

`collectMergeJoinKeys` rejected unequal key types, which is right for the
`sorted_merge` eligibility, but `predictMergeJoinOutputOrder` also used it for
`full_sorting_merge`, which sorts the converted keys itself. A nested
`full_sorting_merge` join over `UInt32` and `UInt64` keys was then predicted as
unordered, and the runtime-filter pass turned the `sorted_merge` join above it
into a hash join. Now the prediction accepts converted keys and keeps only the
sides whose type already is the least supertype, mirroring
`predicateOperandsToCommonType`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on b2191014c7e:

  • Fixed the clickhouse-gh[bot] finding. A nested full_sorting_merge join with converted keys (for example UInt32 = UInt64) is no longer predicted as unordered, so the runtime-filter pass keeps the sorted_merge join above it. New test: 05447_sorted_merge_join_nested_full_sorting_merge_converted_keys. It fails without the fix. The related sorted_merge tests pass locally.
  • About the naming (@rschu1ze, @ayakovlev-clickhouse): I have not renamed anything yet, because the two proposals do not agree and a human has to decide. Some facts that may help:
    • parallel_sorted_merge already runs as a single sorted_merge whenever sharding by primary-key ranges does not apply (ASOF, no common primary-key prefix). So one value that picks the implementation internally is easy to build. It would shard whenever possible, for example when max_threads > 1. The single-stream value would then only serve to turn sharding off on purpose, and max_threads = 1 already does that.
    • So one option is a single value, sorted_merge_if_sorted, that behaves like today's parallel_sorted_merge. Then join_algorithm = 'direct,sorted_merge_if_sorted,parallel_hash,hash,ie_join' could be the follow-up default. The other option is the two renamed values that @rschu1ze proposed.
    • Both renames are mechanical (the enum, SettingsEnums, docs, tests). Once the choice is made, they can be done in this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on 209ef748027 (merge of master, no conflicts; all translation units changed by this PR compile):

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress in #107127. On its CI build at 5d3f977 (amd_release), the wrapped query returns 1 x y, same as the unwrapped one, also with join_algorithm = 'hash'; master returns 1 x x.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks for confirming. The AST fuzzer (amd_release, oracle) failure is tracked by #107127, so this PR needs no change for it. CI on 209ef748027 is green and no review threads are unresolved. The one open item is the naming of the new join_algorithm values (two renamed values, sorted_merge_if_sorted and parallel_sorted_merge_if_sorted, or one sorted_merge_if_sorted value that picks the implementation itself). A human needs to decide that. The rename is mechanical, and I will do it in this PR once the choice is made.

alexey-milovidov and others added 2 commits November 2, 2026 23:33
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/topKThroughJoin.cpp
`master` replaced the `keep_left_read_in_order` flag of `JoinStep` with the
`LeftPipelineOrder` enum, made `keepLeftPipelineInOrder` throw a logical error
for joins that cannot preserve the left block order, and switched the
sharded `full_sorting_merge` joins to `keepLeftPipelineLayout`.

- A `YShaped` join keeps its single output stream unresized whenever any
  left-pipeline requirement is set (`LeftPipelineOrder::None` check), which
  is what the old flag did for both callers.
- The nested merge join below a `sorted_merge` join is now marked with
  `keepLeftPipelineLayout`: `FullSortingMergeJoin` cannot be pinned to the
  left block order, so `keepLeftPipelineInOrder` would throw there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on f83096a7c87 (merge of master):

  • Conflict in topKThroughJoin.cpp (comment only): kept both the SORTED_MERGE / PARALLEL_SORTED_MERGE note and the new PartialMergeJoin note from master.
  • Semantic conflict: master replaced JoinStep's keep_left_read_in_order flag with LeftPipelineOrder. Now keepLeftPipelineInOrder throws a logical error for joins that cannot preserve the left block order, and FullSortingMergeJoin is one of them. So the nested merge join below a sorted_merge join is now marked with keepLeftPipelineLayout. A YShaped join leaves its output stream unresized whenever any left-pipeline requirement is set.
  • Test results: all 21 sorted_merge tests of this PR pass locally, and so do 45 existing full_sorting_merge, read-in-order-through-join and join-by-shards tests.
  • No review threads are unresolved. @groeneai's comment was answered earlier: the oracle failure is tracked in Fix wrong result for duplicate-named subquery columns wrapped in SELECT * #107127. The naming of the new join_algorithm values still needs a human decision, as described above.

@ayakovlev-clickhouse

Copy link
Copy Markdown
Contributor

There is a better idea suggested here #128519
I suggest closing this PR in favor of the other one.

alexey-milovidov and others added 2 commits November 4, 2026 17:01
# Conflicts:
#	src/Interpreters/QueryLog.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeJoinByShards.cpp
…rted-merge algorithm

The loop that suppresses the join runtime filter when a merge algorithm wins the
selection also returned early for `partial_merge` in lists such as
`partial_merge,hash`, which do not contain `sorted_merge` or
`parallel_sorted_merge`. Such queries lost the runtime filter that they had
before. Run the suppression only when one of the sorted-merge variants is
listed, and add an `EXPLAIN` regression test for `partial_merge,hash`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on eac9e08765a9:

@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

alexey-milovidov and others added 3 commits November 6, 2026 01:37
Conflicts: master (#128519) added the planned `full_sorting_merge` bit 4 of the
`JoinStepLogical` optimizer flags; the runtime-filter suppression for sorted-merge
joins moves to bit 8 (still gated by the sorted-merge serialization version). The
runtime-filter eligibility keeps both master's planned-algorithm check and the PR's
runnable-algorithm check.
…_hash` deterministic

`ANY RIGHT JOIN` keeps an arbitrary one of the `psg_a` rows with the same `id`,
which one depends on the stream order, so `sum(s.v)` differed between the merge
and the hash join with some randomized MergeTree settings, while `sum(s.id)`,
`count()` and the number of matched rows were equal. Compare only those.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112973&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20flaky%20check)
#112973

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed_merge` is not selectable

The `ASOF` guard in `tryAddJoinRuntimeFilter` took `sorted_merge` / `parallel_sorted_merge`
as the selected algorithm regardless of the input order, so `join_algorithm = 'sorted_merge,hash'`
lost the runtime filter of the `HashJoin` it fell through to. Use the same eligibility
predicate there, and record the suppression when the merge join really wins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on afc4ff4c9ecd:

  • Merged master. The conflict came from Sort-order-aware join ordering in DPsub (interesting orders) #128519: it uses bit 4 of the JoinStepLogical optimizer flags for the planned full_sorting_merge. This PR used the same bit for the sorted-merge runtime-filter suppression, so that flag moves to bit 8 and stays gated by DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SORTED_MERGE_JOIN. The runtime-filter eligibility now has both checks: master's planned-algorithm check and this PR's runnable-algorithm check.
  • Addressed the clickhouse-gh review on ASOF fallbacks. New test 05556_sorted_merge_join_runtime_filter_asof_fallthrough.
  • The CI failure 05397_sorted_merge_join_predicted_order_skips_unsupported_grace_hash was nondeterminism in the test itself. I reproduced it on a local server with the CI-randomized MergeTree settings. ANY RIGHT JOIN keeps an arbitrary one of the rows with the same id, so sum(s.v) differed between the hash and merge joins, while sum(s.id), count() and the matched-row count were equal. The test now compares only the deterministic columns.
  • The question of closing this in favor of Sort-order-aware join ordering in DPsub (interesting orders) #128519 (now merged) is still open for a human decision.

alexey-milovidov and others added 4 commits November 7, 2026 09:37
# Conflicts:
#	src/Parsers/ParserTablesInSelectQuery.cpp
…d join's order

`buildPhysicalJoin` puts `planned_algorithm` first in the selection list, but
`predictMergeJoinOutputOrder` replayed only the user's `join_algorithms`. A child
join that `DPsub` planned as `full_sorting_merge` (with
`query_plan_join_order_use_interesting_orders`) was then predicted unordered, so
the runtime-filter pass planted a filter on the parent and erased its eligible
`sorted_merge`, forcing a hash join.

Share the effective list through `JoinStepLogical::getEffectiveJoinAlgorithms`
between physicalization, the order prediction and `isGraceHashJoinSkipped`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in `JoinOperator.cpp`: keep the PR's version-gated `join_algorithm`
write and master's comment about the step settings reader.

Master moved the plan serialization version to 21 (release 26.11) and refuses
plans below it, and 26.10 was released with version 20 without the sorted-merge
algorithms, so `DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SORTED_MERGE_JOIN`
moves to 21.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ested_planned_full_sorting_merge`

`query_plan_join_order_use_interesting_orders` requires transitive predicates,
but `clickhouse-test` randomizes `enable_join_transitive_predicates` (false
in 30% of runs). Without them, the nested join is not planned as
`full_sorting_merge`, and the test printed `0 2 4` (hash joins with runtime
filters) instead of `2 0 0`. The CI randomized-settings diagnosis named this
setting as the culprit. All the other tests that set
`query_plan_join_order_use_interesting_orders` pin it already.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112973&sha=0e47b322c1b543ed5a997b5c39922b4dffa2bf14&name_0=PR
PR: #112973

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on bec4b80d07de:

  • CI failure: 05565_sorted_merge_join_nested_planned_full_sorting_merge failed whenever clickhouse-test randomized enable_join_transitive_predicates = 0 (the randomized-settings diagnosis named it as the culprit). query_plan_join_order_use_interesting_orders requires transitive predicates, so the test now pins the setting, as the other interesting-orders tests already do. Confirmed locally: without the pin it prints 0 2 4, with it 2 0 0 for both values of the setting.
  • Merged master. Conflict in JoinOperator.cpp: kept the version-gated join_algorithm write and master's comment. master moved the plan serialization version to 21 (release 26.11) and no longer reads or writes plans below 21, and 26.10 shipped version 20 without the sorted-merge algorithms, so DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_SORTED_MERGE_JOIN is now 21.
  • Build profile diff failed in CI infrastructure (LogClusterNotReady), not because of this PR.
  • Open design question for a human: the suggestion to close this PR in favor of Sort-order-aware join ordering in DPsub (interesting orders) #128519.

@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

Obsoleted by #128519

This branch was successfully deployed

1 active deployment
staging - docs — bec4b80d Deployed Nov 9, 2026 by mintlify[bot]
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-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sorted_merge/parallel_sorted_merge are selected only for the bottom join of a multi-way join, so the listed fallback runs every join above it

5 participants