Repository navigation
Add sorted_merge and parallel_sorted_merge join algorithms - #112973
alexey-milovidov wants to merge 119 commits into
Conversation
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [bec4b80] Summary: ❌
AI ReviewSummaryAdds conditional Final VerdictStatus: ✅ Approve |
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 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_officialFlagged 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
|
# Conflicts: # docs/en/sql-reference/statements/select/join.md
|
🕵 The three stress-test failures on
Merged |
…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`.
|
🕵 The three CI failures on
Pushed |
|
🕵 Merged
All four stateless tests of this PR ( |
# Conflicts: # src/Core/SettingsEnums.cpp
…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]>
|
🕵 Status update on
|
|
🕵 Status update on
|
|
The fix is in progress in #107127. On its CI build at |
|
🕵 @groeneai, thanks for confirming. The |
# 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]>
|
🕵 Status update on
|
|
There is a better idea suggested here #128519 |
# 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]>
|
🕵 Status update on
|
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]>
|
🕵 Status update on
|
# 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]>
|
🕵 Status update on
|
|
Obsoleted by #128519 |
Related: #109005
Closes: #117680
Implements the two algorithms planned in this discussion:
full_sorting_mergeandparallel_full_sorting_mergeare always supported, so anything listed after them injoin_algorithmis unreachable — listing them is an unconditional choice, not a preference. The newsorted_mergeandparallel_sorted_mergealgorithms 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 cheapFinishSortingor 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_mergeruns a single in-order merge join.parallel_sorted_mergeadditionally 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 shardingquery_plan_join_shard_by_pk_rangesapplies, 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. anASOFjoin), it degrades to a singlesorted_merge.Implementation notes:
JoinStepLogical::inputsCanBeReadInJoinKeyOrderfinds theReadFromMergeTreebelow each input (mirroringfindReadingStepofoptimizeReadInOrder) and probes the actual read-in-order matcher (wouldReadInOrderBeUseful, the same side-effect-free probetopKThroughJoinuses) 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 forINNER/LEFT, right keys forRIGHT, both forINNER; aFULLjoin is not sorted), the keys are traced through the expressions in between (aliases only), and theSort before JOINabove it is built as aFinishSortingright away - so a multi-way join on a shared key stays a chain of merge joins with no re-sorting, andparallel_sorted_mergeshards the whole chain by the common primary-key ranges (fixessorted_merge/parallel_sorted_mergeare 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 ofJoinStepnow merges any multi-stream sorted input. The predicted decision degrades gracefully in both directions: a false positive runs likefull_sorting_merge(with a full sort), a false negative falls through to the next algorithm.tryAddJoinRuntimeFilterkeep 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. WhenapplyParallelReplicaslater breaks the eligibility (a join input becomes a distributed read), the filter pass is re-run for exactly the joins it had skipped, so thehashfall-through gets its runtime filter back.FullSortingMergeJoinnow carries the selected algorithm (getSelectedAlgorithm) instead of anis_parallelflag; the hash-scatter rewrite (optimizeParallelFullSortingMergeJoin) stays exclusive toparallel_full_sorting_merge, andoptimizeJoinByShardsruns in a restricted mode (onlyparallel_sorted_merge-selected joins, with a cheap pre-scan bail-out) whenquery_plan_join_shard_by_pk_rangesis off. When the sharded stream counts diverge at pipeline-building time (e.g. a data-dependentPREWHEREprunes one side to a single empty stream),JoinStepmerges 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).CreateSetAndFilterOnTheFlySteppair (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.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 fromjoin_algorithm, so that peer falls through to the next listed algorithm instead of rejecting the plan withUNKNOWN_JOIN; a list of only these values is refused.sorted_mergelisted and no exploitable order, the query fails withNOT_IMPLEMENTED, like other unsupported single-algorithm configurations.USINGkey-type inference,topKThroughJoindeferral) extend to the new values and are documented in thejoin_algorithmsetting description.Tests:
04669_sorted_merge_join_selectionpins the selection gating viaEXPLAIN 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 againsthashforINNER/LEFT/RIGHT/FULL/ANY/join_use_nulls.04670_parallel_sorted_merge_joinpins the primary-key-range sharding (Sharding:marker withquery_plan_join_shard_by_pk_ranges = 0, noScatterByPartitionTransform, noMergeSortingTransform), theASOFdegradation, and correctness.04824_sorted_merge_join_parallel_replicas_fallthroughand04894_sorted_merge_join_parallel_replicas_runtime_filterpin the parallel-replicas edge (fall-through tohashwith the runtime filter restored),04895_parallel_sorted_merge_join_shard_stream_divergencepins the diverged-shard degradation,04896_sorted_merge_join_null_safe_equalspins the ineligibility of a nullable null-safe (<=>) join (whose keys are compared wrapped intotuple(...), so they cannot be read in table order),05047_sorted_merge_join_asof_key_orderpins that anASOFjoin 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 theONconjuncts,04907_sorted_merge_join_cast_fallthroughpins the fall-through when a common-type conversion can reorder a key,04760/04850pin thejoin_use_nullsandquery_plan_join_shard_by_pk_rangescontracts, and05056_sorted_merge_join_multi_waypins the multi-way chains (3 and 4 tables merge-only with noMergeSortingTransform, which nested kinds/keys keep the order and which fall through, the sharded chain, and correctness againsthash). The PR #109005 regression tests and the join runtime filter tests pass unchanged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added new
join_algorithmvaluessorted_mergeandparallel_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_mergeadditionally 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
Workflow [PR]
Sync PR [sync-upstream/pr/112973]