Skip to content

Propagate the output order of a full sorting merge join - #117786

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix-merge-join-output-sort-order
Oct 4, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix-merge-join-output-sort-order

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #117679
Related: #109426

A chain of full_sorting_merge joins on one key sorted its input from scratch once per join above the bottom one (N-2 full MergeSortingTransforms for N tables), because JoinStep did not advertise the order of its result. MergeJoinAlgorithm emits its result in the order of the left input for INNER and LEFT joins and of the right input for RIGHT joins, so applyOrder now reports the leading run of join-key columns of that side as the sort property of a FullSortingMergeJoin step (per stream, since the join output is resized to max_streams). The sort above it - the pre-sort of the next merge join, or an ORDER BY - becomes a FinishSorting, a merge of the already sorted streams. parallel_full_sorting_merge keeps its hash-sharded execution at every level of a chain and does not advertise the order.

Two more changes were needed for that to work:

  • applyActionsToSortDescription gave up at the first output of an Expression that was not derived from a sort column, so the order survived the trivial expressions between a join and the sort above it only when the sort column happened to be the first output. Unrelated outputs are skipped now.
  • optimizeJoinByShards (query_plan_join_shard_by_pk_ranges) turned every merge-join FinishSorting on a chain into a PartitionedFinishSorting, assuming it sits on a read in order. Above a join that is not sharded itself this keeps one stream per shard and fails the single merge join with Join is supported only for pipelines with one output port, or, when the join order optimizer places the unsharded merge join below, pairs its arbitrarily resized output streams with the primary-key layers of the other side and returns wrong results. Merge-join sorts are now committed only once the join they feed is sharded, and an unsharded Y-shaped join no longer passes the left subtree through (can_split_left_table only holds for hash joins, whose probe keeps the left streams).

Three 10M-row tables joined on id (join_algorithm = 'full_sorting_merge', 8 threads): 0.72 s -> 0.41 s; four tables: 0.79 s -> 0.47 s. Peak memory did not change - the sort was not its driver.

Changelog category (leave one):

  • Performance Improvement

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

A full_sorting_merge join now advertises that its result is ordered by the join key, so a sort above it - the pre-sort of the next merge join in a chain, or an ORDER BY - merges the already sorted streams instead of sorting from scratch. Joining several tables on the same key with full_sorting_merge no longer performs one full sort per join. Also fixed the interplay with query_plan_join_shard_by_pk_ranges, which could otherwise fail with a logical error or return wrong results for such a chain.


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

Version info

  • Merged into: 26.10.1.1532-master (included in 26.10 and later)

A chain of `full_sorting_merge` joins on one key sorted its input from
scratch once per join above the bottom one, because `JoinStep` did not
advertise the order of its result. `MergeJoinAlgorithm` emits its result
in the order of the left input for INNER and LEFT joins and of the right
input for RIGHT joins, so `applyOrder` now reports the leading run of
join-key columns of that side as the sort property of a
`FullSortingMergeJoin` step (per stream, since the join output is resized
to `max_streams`). The sort above it - the pre-sort of the next merge
join, or an `ORDER BY` - becomes a `FinishSorting`, a merge of the
already sorted streams.

Two more things were needed for that to work:

- `applyActionsToSortDescription` gave up at the first output of an
  `Expression` that was not derived from a sort column, so the order
  survived the trivial expressions between a join and the sort above it
  only when the sort column happened to be the first output. Unrelated
  outputs are skipped now.

- `optimizeJoinByShards` (`query_plan_join_shard_by_pk_ranges`) turned
  every merge-join `FinishSorting` on a chain into a
  `PartitionedFinishSorting`, assuming it sits on a read in order. Above
  a join that is not sharded itself that keeps one stream per shard and
  fails the single merge join with `Join is supported only for pipelines
  with one output port`, or, when the join order optimizer places the
  unsharded merge join below, pairs its arbitrarily resized output
  streams with the primary-key layers of the other side and returns wrong
  results. Merge-join sorts are now committed only once the join they
  feed is sharded, and an unsharded Y-shaped join no longer passes the
  left subtree through (`can_split_left_table` only holds for hash joins,
  whose probe keeps the left streams).

`parallel_full_sorting_merge` keeps its hash-sharded execution at every
level of a chain and does not advertise the order.

Three 10M-row tables joined on `id`: 0.72 s -> 0.41 s, four tables:
0.79 s -> 0.47 s (8 threads); the plan has no `MergeSortingTransform`
left. Peak memory did not change - the sort was not its driver.

Closes: #117679

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [705fc49]

Summary: ✅


AI Review

Summary

This PR teaches full_sorting_merge joins to advertise join-key order and fixes the query_plan_join_shard_by_pk_ranges interaction so upper merge joins can reuse that order. The remaining gap is that the new parallel_full_sorting_merge guard is keyed to the setting choice, not to whether the later sharding rewrite actually fires, so realistic fallback plans that still execute as a single merge join lose the optimization entirely.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/applyOrder.cpp:65] The unconditional merge_join->isParallel() bailout suppresses order propagation for every parallel_full_sorting_merge join, but optimizeParallelFullSortingMergeJoin only makes the output unordered when it can actually scatter both pre-join sorts. When one side is already pre-sorted (FinishSorting) or the join keys are not hash-shardable, the later pass keeps a single merge join (src/Processors/QueryPlan/Optimizations/optimizeJoinByShards.cpp:579), so the output order is still real and upper joins or ORDER BY could still reuse it. Today those fallback shapes pay the extra full sort at every upper level even though the join never became unordered.
    Suggested fix: gate this bailout on the actual sharding predicate, or rerun applyOrder after optimizeParallelFullSortingMergeJoin so the unsharded fallback still advertises its order.
Tests
  • ⚠️ Add one focused stateless regression with join_algorithm = 'parallel_full_sorting_merge' where the sharding rewrite is a no-op — for example, a chain fed by pre-sorted inputs so the pre-join sorts are FinishSorting — and assert that the upper merge join or ORDER BY stays on the merge-only path.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Narrow the isParallel() guard so it only suppresses order propagation when parallel_full_sorting_merge will actually be hash-sharded.
    • Add a regression for the unsharded parallel_full_sorting_merge fallback path.

LLVM Coverage Report

⚠️ No coverage measurement for commit 705fc49: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 2, 2026
alexey-milovidov and others added 2 commits September 3, 2026 12:18
…t_explain

The test runs in `-- { echo }` mode, so the comment above the
`full_sorting_merge` query that the previous commit rewrote is part of
the expected output as well.

Co-Authored-By: Claude Code <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 705fc49db with master 2493c465d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

6 object files changed (+31.25 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/applyOrder.cpp.o 101.47 KiB 132.80 KiB +31.34 KiB (+30.88%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 42ffd5b2-334c-45c6-8995-97a9b5d0bb7c
  • MIRAI run: 652480d6-aa9c-4408-899f-6fdc2d9f0b60
  • PR check IDs:
    • clickbench_3206372_1791127911
    • clickbench_3206385_1791127911
    • clickbench_3206397_1791127911
    • tpch_adapted_1_official_3206404_1791127911
    • tpch_adapted_1_official_3206430_1791127911
    • tpch_adapted_1_official_3206444_1791127911

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
alexey-milovidov and others added 3 commits September 10, 2026 12:39
…ut-sort-order

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/applyOrder.cpp
…the join

The output-order guard dropped every key column whose name is also carried by the
other input header. `TableJoin::addJoinedColumn` renames the copy of the right
side when it clashes with a column of the left table, so a name carried by both
inputs denotes the column of the left side in the output: that is the ordered
column itself when the left side is the ordered one, and only the right-ordered
case (a `RIGHT` join) can have the ordered key reach the output under a renamed
name. Reject only that case, and keep rejecting a name that the right side
carries unrenamed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The plan-shape assertions of the test describe a local plan, and the parallel
replicas reader replaces the reading steps with its own, so the test failed in
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`
with a full sort for `order by plan` and no `Sharding:` for
`pk range sharding mixed plan`. Pin the setting like the other randomized ones.

Also cover `JOIN ... USING`, both with and without the analyzer, as asked in the
review: the merged key column is the one of the left side and stays the ordered
one, so the chain keeps merging instead of sorting from scratch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…y column

`applyOrderToJoin` trims the advertised prefix at the first join key that does not reach the join
output under its own name. For a RIGHT join the keys are `clause.key_names_right`, and
`TableJoin::addUsingKey` stores those under the *renamed* name of the right side (`b.id`), which is
absent from the output in exactly the case where the order does survive:
`TableJoin::leftToRightKeyRemap` is populated when the renamed copy is not required, and
`MergeJoinAlgorithm` then fills the single merged output column of the left side from the right key
for every row that has no match on the left. The left key column of a `RIGHT JOIN ... USING` therefore
holds the value of the ordered right key on every row - the order reaches the output, only under the
name of the left key - and it was dropped, so the `ORDER BY` above it stayed a full sort on the legacy
planner.

Follow that mapping for right-ordered joins: a key whose renamed right copy was merged away is
advertised under the name of the left key, and the guard against a key shadowed by the other side does
not apply to it, since the output carries a single column of that name and it is the merged one.

Selecting the renamed copy keeps the two columns apart instead - the remap is then empty and the left
key column carries the default for every right row without a match - so that shape still advertises
`b.id` alone and a sort by the merged name has to stay a full sort.

`05059_full_sorting_merge_join_output_order` pins both, which differ only in the projection: the
merged shape now reports no full sort and three merges, while the shape that selects the renamed copy
and sorts by the merged name keeps its full sort. The results are checked against the hash join, the
`ORDER BY` output is checked to be sorted, and both are covered with and without
`query_plan_join_shard_by_pk_ranges`.

This is legacy-planner only: `TableJoin::hasUsing` is false once a `join_operator` is set, so the
analyzer never populates the remap.
alexey-milovidov and others added 2 commits September 23, 2026 11:06
… the other side

Every row of an `INNER` join has equal keys on both sides, so when the ordered key is not
needed above the join and only the equal key of the other side is kept, that key carries the
order - `a JOIN b ON a.id = b.id JOIN c ON b.id = c.id` no longer inserts a full sort before
the second join. The last key of an `ASOF` join is not an equality and is excluded.

Also drop the `enable_analyzer = 0` part of `05059_full_sorting_merge_join_output_order`:
the analyzer is mandatory since v26.9 and the test failed with `SETTING_CONSTRAINT_VIOLATION`
after merging master.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7211 commits behind) and addressed the open review thread in 8c84981. That commit also drops the enable_analyzer = 0 part of 05059, since the analyzer is mandatory now.

The only red on the previous head, Stress test (arm_debug) with Logical error: Shard number is greater than shard count (STID 5066-457d), is unrelated to this PR: it is parallel replicas shard scoping, tracked in #101325, with the fix in progress in #113589.

@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 code is good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 24, 2026
alexey-milovidov and others added 2 commits September 24, 2026 01:14
…derToJoin`

Master added a `header` parameter to `getCollationAwareSortPrefixInColumns` (it now also stops
the prefix at a float key, where comparison merges `-0.0` with `0.0`). The merge queue rejected
the PR because the new call in `applyOrderToJoin` still used the two-argument form:
https://github.com/ClickHouse/ClickHouse/actions/runs/35939711397

Pass the header of the ordered input, whose columns the sort description refers to. A float
join key is no longer advertised, which only costs a missed optimization.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits October 2, 2026 12:39
… 05059

The swap is applied by the join order optimizer, which swaps the plan
children and the kind before the merge join is built, so the cases enable
`query_plan_optimize_join_order_limit` for them. The legacy planner never
swaps a merge join (`optimizeJoinLegacy` only swaps `FillRightFirst` joins).

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/PRs/117786/dd8eb75d6b3ef9a2f5fd5f0d7d68150003dac6d3/pr/integration_tests_arm_binary_distributed_plan_3_4/job.log (test_replicated_database_active_node_taken/test.py::test_active_node_owned_by_another_server, REPLICA_ALREADY_EXISTS; the earlier fix #121866 was closed without merging) and https://s3.amazonaws.com/clickhouse-test-reports/PRs/117786/dd8eb75d6b3ef9a2f5fd5f0d7d68150003dac6d3/pr/stateless_tests_amd_llvm_coverage_s3_storage_dbreplicated_parallel_3_3/job.log (11 unrelated tests in Stateless tests (amd_llvm_coverage, s3 storage, DBReplicated, parallel, 3/3), e.g. 03971_rename_tables_race_read_consistency, 04498_database_max_tables). Provide a fix in a separate PR. If the fix is already in progress, link it here. The branch was merged with the latest master.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

All of these are already fixed in master. The failing run on dd8eb75d was on 2026-09-24 between 05:17 and 06:21 UTC, before any of the fixes below merged, and the merge with master (f0b9e9a1) contains all of them, so no new PR is needed:

In CIDB since 2026-09-25, none of the 11 has failed in any DBReplicated job.

…ription`

An output that is a non-monotonic function of a sort column (e.g. `toMonth(k)`),
or a worse carrier of a sort column already found, stopped the scan of the
`ActionsDAG` outputs, so a later plain carrier of the column was never seen and
the sort above a full sorting merge join fell back to a full sort. Skip such
outputs instead, and cover a chain of merge joins with such a projection in `05059`.

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

Copy link
Copy Markdown
Member Author

🕵 Addressed the open review thread in 705fc49 (skip non-monotonic outputs in applyActionsToSortDescription, with a regression case in 05059).

The only failure on the previous head, 05029_url_function_schema_inference_hard_timeout_during_backoff in Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) (FAIL: the time limit waited 15 seconds for the retry backoff), is unrelated to this PR: it tests the retry backoff of the url table function, and in the last 30 days it failed once in CIDB (this run) against 30374 passes.

Thanks @groeneai for checking the earlier failures.

/// order would turn the merge-join sort above into `FinishSorting` and leave the next join in a chain
/// unsharded, trading its parallelism for a saved sort. Keep the parallel variant hash-sharded at every
/// level; its output is unordered by design.
if (merge_join->isParallel())

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.

merge_join->isParallel() is too coarse here. applyOrder runs before optimizeParallelFullSortingMergeJoin, and that later pass only turns the join into hash-sharded lanes when both pre-join sorts are still plain SortingStep::Type::Full and the key types are shard-safe. In the documented fallback cases there — a pre-sorted side (FinishSorting) or a key type that cannot be hash-sharded — the pipeline stays a single merge join "exactly like full_sorting_merge", so the output order is still real.

With this unconditional early return, a chain that explicitly uses parallel_full_sorting_merge on already sorted inputs still pays the extra full sort at every upper level even though the join never became unordered. Could this gate follow the actual sharding predicate instead of the setting choice, or rerun the order pass after optimizeParallelFullSortingMergeJoin so the unsharded fallback still advertises its order?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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.

A chain of joins on the same key sorts once per join: a merge join does not propagate its output sort order

3 participants