Skip to content

Send a subquery with a redundant ORDER BY to parallel replicas as a whole - #125685

Merged
nickitat merged 7 commits into
masterfrom
pr-redundant-subquery-order-by
Nov 12, 2026
Merged

nickitat merged 7 commits into
masterfrom
pr-redundant-subquery-order-by

Conversation

@nickitat

@nickitat nickitat commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Improve parallel replica execution for queries that aggregate over subqueries with redundant ORDER BY clauses by allowing replicas to perform the aggregation. Also enable automatic parallel replica plan matching for these queries.


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

Version info

  • Merged into: 26.11.1.2135-master (included in 26.11 and later)

… whole

`findQueryForParallelReplicas` stopped at any `Sorting` step, so in
`SELECT sum(...) FROM (SELECT ... ORDER BY k)` only the inner subquery
went to the replicas: they sorted their rows (the local one reading in
order), and the initiator merged the sorted streams just to aggregate
them. `query_plan_remove_redundant_sorting` then dropped the merge on the
initiator but not the sorting on the replicas.

Remove the redundant sortings from the plan this decision is made on, the
same way the plan the query runs with has them removed. The whole query
then goes to the replicas and they aggregate, exactly as when the
subquery has no `ORDER BY`.

This also lets automatic parallel replicas match such queries: the
single-node plan had no sorting, the parallel replicas plan did, so the
hash of the replicas' part was never found in the single-node plan
(`Cannot find step with matching hash`).

`02967_parallel_replicas_joins_and_analyzer` covers a subquery with
`ORDER BY` stopping the subquery from going to the replicas; the sortings
there are redundant, so it now keeps them with
`query_plan_remove_redundant_sorting = 0`.

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

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [31bee42]

Summary: ✅


AI Review

Summary

The PR removes redundant sorting before choosing parallel-replica query boundaries, allowing replicas to aggregate sorted subqueries and enabling automatic plan matching for the query-based implementation. No unresolved findings remain at 31bee420d599a6000de8084fea282cfaa0b5c9f7. The earlier coverage concern is addressed, and reported measurements support the performance claim: median execution time decreased from 148 ms to 17 ms, with transferred data reduced from 31.5 MB to 1.8 KB. Current-head CI reports passing cases for 05394 and 02967. The separate plan-based automatic-matching limitation is tracked in #131089.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 13, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Oct 13, 2026
nickitat added a commit that referenced this pull request Oct 14, 2026
…in `05261`

The redundant `ORDER BY` shape of `05395_autopr_nested_query_shapes` needs
#125685, so it is commented out
with a reference to it.

`05261_autopr_transplant_analysis_table_order` reads two of its three tables
whole on every replica, about half of what the query reads, and the
duplicated-read limit merged into master since then declined it. Raise the
limit in the test: what it covers is the pairing of reads.

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

Every case of `05394_parallel_replicas_redundant_subquery_order_by` ran
with `automatic_parallel_replicas_mode = 0`, so none of them went through
`considerEnablingParallelReplicas` and its plan-hash matching. Run the
aggregation over the sorted subquery with
`automatic_parallel_replicas_mode = 2` and check that `query_log` records
nonzero `RuntimeDataflowStatisticsInputBytes` and
`RuntimeDataflowStatisticsOutputBytes` for it. Without the fix both are 0
and the server logs `Cannot find step with matching hash`.

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

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 31bee420d with master f76039cd1 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.68, programs/clickhouse-keeper ×0.74 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 11.1 s +6.8 s (+159%)
Compile time of recompiled translation units

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

Job report

nickitat and others added 2 commits October 21, 2026 11:19
…ER BY` test

The plan-based implementation decides on the optimized plan, where the
redundant sorting is already gone, so it never had this problem. Its
`EXPLAIN` shows `ReadFromParallelReplicas` instead of
`ReadFromRemoteParallelReplicas`, and automatic parallel replicas does not
match its plan even without an `ORDER BY`, so the test's checks print 0
under `parallel_replicas_plan_based = 1` while the results agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat marked this pull request as ready for review November 2, 2026 14:34
@nickitat
nickitat requested a review from devcrafter November 2, 2026 14:34
@devcrafter devcrafter self-assigned this Nov 3, 2026
@devcrafter
devcrafter requested a review from groeneai November 3, 2026 21:53

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed it and the change looks correct to me. The decision now uses the optimizer's own redundancy check (tryRemoveRedundantSorting behind the same query_plan_enable_optimizations && query_plan_remove_redundant_sorting gate as QueryPlanOptimizationSettings.cpp:255), so a sorting stops blocking only when the initiator's real plan drops it anyway. The removal only relinks parent->children and the node stays in QueryPlan::nodes, so the QueryNode -> Node mapping cannot dangle.

What I ran (the PR applied to current master f03969e1, which has #119350 and #128556; debug build, 3 localhost replicas, parallel_replicas_plan_based = 0, 3M-row MergeTree):

  • 28 sorted-subquery shapes return the same result as enable_parallel_replicas = 0, also with parallel_replicas_local_plan = 0 and with parallel_replicas_prefer_local_join = 1. The order-dependent ones keep the old decision: float sum, any/anyLast, groupArray, rowNumberInAllBlocks, window functions, LIMIT BY, WITH FILL.
  • 05394 passes 5/5 with randomized settings, 02967 passes. On master e6c0a8e3 both new assertions read 0 0, so they are not vacuous.
  • Perf, for the open bot question: SELECT key % 13 AS g, count(), sum(value) FROM (SELECT key, value FROM t ORDER BY value DESC) GROUP BY g ships 1,626,001 rows / 31.5 MB from the replicas to the initiator on master vs 26 rows / 1.8 KB with the PR; median 148 ms vs 17 ms over 5 runs (debug build, so only the ratio means anything).

One coverage note, not blocking. The effect is wider than the changelog entry: a sorting made redundant by an outer ORDER BY ... LIMIT, or one under a JOIN, also stops blocking, so those queries now go to the replicas whole. The JOIN case is exactly what the new SET in 02967 pins to the old path. With that line removed, every 02967 result row still matches the reference and only the four "ORDER BY in sub1/sub3" EXPLAIN blocks change, so nothing checks the JOIN case at default settings. One JOIN query in 05394, compared against enable_parallel_replicas = 0, would cover it.

SET optimize_move_to_prewhere = 1;
SET enable_join_runtime_filters = 1, join_runtime_filter_min_probe_rows = 0; -- Changes the plan (BuildRuntimeFilter node)
SET use_statistics = 0; -- auto_statistics_types changes the plan
SET query_plan_remove_redundant_sorting = 0; -- the ORDER BY in a subquery below is redundant, and a removed one does not stop the subquery from going to the replicas

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not clear why we do it here. Could you explain intention? Also, this way we are losing default behavior coverage with enabled query_plan_remove_redundant_sorting

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.

It kept the "ORDER BY in sub3/sub1" cases testing the WithMergeableState boundary at the sorting, which this PR removes when the sorting is redundant. You are right that it dropped the default for the whole test: it is back to the default now, and the plans for those two cases show the query going to the replicas whole. 05394_parallel_replicas_redundant_subquery_order_by covers the case with query_plan_remove_redundant_sorting = 0.

@devcrafter

Copy link
Copy Markdown
Member

@nickitat Would it be possible to make the test pass with plan-based parallel replicas? Related to #128413

…d parallel replicas in the tests

`02967_parallel_replicas_joins_and_analyzer` turned `query_plan_remove_redundant_sorting` off for every
query, so the default behaviour was not covered. Keep the default, where the redundant `ORDER BY` in
sub3/sub1 no longer stops the query from going to the replicas whole, and add an `EXPLAIN` with the
setting off for each of the two cases to keep the `WithMergeableState` boundary at the sorting covered.

`05394_parallel_replicas_redundant_subquery_order_by` no longer pins `parallel_replicas_plan_based = 0`:
it checks for `MergingAggregated` on the initiator, which both implementations show when the replicas
aggregate. Only the automatic mode case stays on the query-tree implementation, because the plan-based
one does not match that plan yet (`Cannot find step with matching hash`, independent of this change).

#125685 (comment)
#125685 (comment)
Related: #128413

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nickitat and others added 2 commits November 12, 2026 17:07
…ndant_subquery_order_by`

Related: #131089

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

`05394_parallel_replicas_redundant_subquery_order_by` already covers the sorting that is not removed.

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

Copy link
Copy Markdown
Member Author

05394_parallel_replicas_redundant_subquery_order_by now passes with both implementations: it checks for MergingAggregated on the initiator, which both show when the replicas aggregate. Only the automatic-mode case stays pinned to parallel_replicas_plan_based = 0, because plan-based automatic parallel replicas do not match this plan, also on master: #131089

@nickitat
nickitat enabled auto-merge November 12, 2026 19:02
@nickitat
nickitat added this pull request to the merge queue Nov 12, 2026
Merged via the queue into master with commit a5578f1 Nov 12, 2026
203 checks passed
@nickitat
nickitat deleted the pr-redundant-subquery-order-by branch November 12, 2026 21:26
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 12, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 12, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
nickitat added a commit that referenced this pull request Nov 12, 2026
#125685 is merged, so the
redundant `ORDER BY` shape of `05395_autopr_nested_query_shapes` is back.

`05261_autopr_transplant_analysis_table_order` compared only the selected
marks, which a read handed another read's analysis can leave unchanged:
the filter selects as many marks of `t_order_mid` as of `t_order_big`.
Print the result of every run too, so such a read shows as wrong rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Nov 13, 2026
Backport #125685 to 26.10: Send a subquery with a redundant `ORDER BY` to parallel replicas as a whole
leshikus pushed a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants