Repository navigation
Propagate the output order of a full sorting merge join - #117786
Conversation
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]>
|
Workflow [PR], commit [705fc49] Summary: ✅
AI ReviewSummaryThis PR teaches Findings
Tests
Final Verdict
LLVM Coverage Report |
…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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+31.25 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9 translation units recompiled, 30 s compile time in total, 9 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
…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.
… 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]>
|
🕵 Merged master (7211 commits behind) and addressed the open review thread in 8c84981. That commit also drops the The only red on the previous head, |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The code is good.
…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]>
… 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]>
|
🕵 @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 ( |
|
All of these are already fixed in
In CIDB since 2026-09-25, none of the 11 has failed in any |
…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]>
|
🕵 Addressed the open review thread in 705fc49 (skip non-monotonic outputs in The only failure on the previous head, 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()) |
There was a problem hiding this comment.
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?
Closes: #117679
Related: #109426
A chain of
full_sorting_mergejoins on one key sorted its input from scratch once per join above the bottom one (N-2fullMergeSortingTransforms forNtables), becauseJoinStepdid not advertise the order of its result.MergeJoinAlgorithmemits its result in the order of the left input for INNER and LEFT joins and of the right input for RIGHT joins, soapplyOrdernow reports the leading run of join-key columns of that side as the sort property of aFullSortingMergeJoinstep (per stream, since the join output is resized tomax_streams). The sort above it - the pre-sort of the next merge join, or anORDER BY- becomes aFinishSorting, a merge of the already sorted streams.parallel_full_sorting_mergekeeps 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:
applyActionsToSortDescriptiongave up at the first output of anExpressionthat 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-joinFinishSortingon a chain into aPartitionedFinishSorting, 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 withJoin 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_tableonly 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
full_sorting_mergejoin 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 anORDER BY- merges the already sorted streams instead of sorting from scratch. Joining several tables on the same key withfull_sorting_mergeno longer performs one full sort per join. Also fixed the interplay withquery_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
26.10.1.1532-master(included in26.10and later)