Repository navigation
Support ReadInOrder in distributed plan - #115244
Conversation
|
Workflow [PR], commit [bb8a162] Summary: ✅
AI ReviewSummaryThis PR adds an experimental PR Metadata
Exact replacement: ### Changelog category (leave one):
- Experimental Feature
### Changelog entry:
Experimental: enable `distributed_plan_read_in_order = 1` to let distributed `ORDER BY` queries read in table sorting-key order and stop early instead of always scanning and sorting when no exchange survives between the read and the sort.Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit bb8a162.
Changed lines: Changed C/C++ lines covered: 164/175 (93.71%) · Uncovered code |
Three fixes on top of the previous commit, all found by the PR review bot or while verifying it: `findReadingStep` stopped at the `GatherExchange` that `tryMakeDistributedRead` puts directly over the read it just made distributed, so `buildInputOrderInfo` rejected it and the contract was never installed for a bucketed distributed read - the main large-table case. Look through that transient gather; it is folded into a shuffle by `tryReplaceScatterGatherWithShuffle` later anyway. A gather that maintains a sort description, or one over anything other than the read itself, is still treated as a real boundary. `ReadFromMergeTree::deserialize` reapplied the order contract only when `distributed_read_bucket_count > 0`, so a non-bucketed fragment (a table under `distributed_plan_max_rows_to_broadcast`) parsed the contract and dropped it, feeding scan-order rows into a gather that expects them sorted. The `FinishSorting` `SortingStep` constructor took a bare `max_block_size` and built its `Settings` from that alone, leaving `temporary_files_buffer_size` at 0. `updatePlanSettings` then assigned that 0 to a `NonZeroUInt64` plan setting, so serializing such a step threw `BAD_ARGUMENTS`. Both callers already had real settings to hand; pass them instead. Co-Authored-By: Claude Opus 5 <[email protected]>
|
ReadInOrder can only be activated when - |
The scatter pass-through added earlier was unsound. An exchange hands each partition its rows in arrival order, so a sorting step told "your input is already sorted, just merge it" across a surviving exchange merges unsorted data and returns rows from the wrong part of the table. It reproduced as `SELECT id FROM big ORDER BY id LIMIT 20 OFFSET 24990` returning rows from 49990 or 66798 instead of 24990, intermittently - a single run often passed. The scatter/gather pair that tryMakeDistributedRead and tryMakeDistributedSorting leave behind is only harmless when optimizeExchanges drops the shuffle it fuses into, which happens when the shuffle is keyless and its source and result bucket counts match. That is the one case where the read and the sorting end up in the same fragment. So descend a keyless scatter only after checking the gather below it has the matching bucket count, and reach the gather half only through that verified scatter - a gather found any other way is a real boundary. In practice this means read-in-order applies when `distributed_plan_default_reader_bucket_count` equals `distributed_plan_default_shuffle_join_bucket_count` (both default to 8); a mismatch keeps the full sort. Two tests: a non-bucketed case (table under `distributed_plan_max_rows_to_broadcast`, which the previous commit's deserialize fix was for), and a surviving-exchange case with mismatched bucket counts. Both assert the plan shape so they cannot silently stop covering their path, and the second repeats the query because the wrong results were intermittent. Co-Authored-By: Claude Opus 5 <[email protected]>
Corrects a claim in 5d1d902. That commit widened deserialize to reapply input_order_info whenever it was set, not only for a bucketed read, on the grounds that a non-bucketed fragment could carry the contract and lose it. That shape cannot arise: findReadingStep installs the order only when the scatter and gather collapse, and that happens only when tryMakeDistributedRead bucketed the read. Parallel replicas do not reach it either - deserialize is skipped there unless both serialize_query_plan and the server's process_query_plan_packet are on, and even then the read step was never observed going through it. Nothing could be made to exercise the widened branch, so it goes back to the bucketed condition and the comment records the invariant instead. test_read_in_order_without_distributed_read was named and documented for that branch, so it is renamed to test_distributed_order_by_without_distributed_read and says what it actually covers: with no distributed read the scatter under the sorting survives, this shape keeps its full sort, and the rows must still be right - an ordered read wrongly assumed here returned rows from elsewhere in the table, so the case is still worth having. Co-Authored-By: Claude Opus 5 <[email protected]>
cd61143 removed the check in checkDistributedReadSupported that rejected a distributed plan whose read already carried input_order_info. That check was load-bearing: with enable_analyzer = 0 and query_plan_read_in_order = 0 the old interpreter plans read-in-order before the plan is optimized and builds a FinishSorting up front. optimizeReadInOrder only converts a Type::Full sorting, so the exchange-safety check added in 101dfba never sees that one, and the scatter tryMakeDistributedSorting places under it can survive and feed it rows that are no longer sorted. Measured on the three-node integration cluster with SELECT id FROM big ORDER BY id ASC LIMIT 20 OFFSET 24990: 8 of 16 runs returned rows starting at 16798 instead of 24990. The same query with optimize_read_in_order = 0, or with query_plan_read_in_order = 1, or on the new analyzer, was right every time - so it is that legacy flow specifically. Restoring the rejection is safe for this feature because checkDistributedReadSupported runs before optimizeReadInOrder installs anything, so a read this optimizer asks for in order has no order set at that point. The !query_info.input_order_info term also goes back into supportsBucketedRead, matching master. Note bucketing was not the mechanism: with only the supportsBucketedRead term restored the read stopped being bucketed - the plan changed from ShuffleExchange to ScatterExchange - and the wrong results continued, including with matched bucket counts. Co-Authored-By: Claude Opus 5 <[email protected]>
findGatherOverRead decided a scatter/gather pair would collapse by reusing findReadingStep's passthrough set, which is wider than the rewrite it predicts. optimizeExchanges lifts a plain gather only through Expression, Filter and BuildRuntimeFilter steps, and only when the step's DAG has no non-deterministic function; findGatherOverRead also walked ArrayJoin and checked nothing. ARRAY JOIN is never lifted, so the pair stayed split, the scatter survived between the read and the sorting, and the FinishSorting above it merged chunks the scatter had already interleaved. SELECT id FROM big ARRAY JOIN [1, 2] AS x ORDER BY id ASC LIMIT 20 OFFSET 24990 returned rows from the wrong part of the table on 12 of 12 runs with optimize_read_in_order = 1, and was right every time with it off. Rather than restate the hoist conditions in a second place, they move into canHoistGatherThroughStep in Optimizations/Utils: optimizeExchanges applies it and findGatherOverRead predicts with it, so the two cannot drift. Duplicating that condition is what caused this. The new stateless test takes its reference from the non-distributed result, so it is the ground truth rather than hand-derived arithmetic. Co-Authored-By: Claude Opus 5 <[email protected]>
ede0418 put the !query_info.input_order_info term back into supportsBucketedRead for parity with master. That breaks the stateless worker path: ReadFromMergeTreeAtWorker::canCreateFrom delegates to this, and the worker asks for its order before canCreateFrom is consulted, so an ORDER BY read stopped qualifying, was shipped as a plain fragment, and failed on the worker with "Database ... does not exist" - the worker has no catalog. Both private stateless-worker integration modules failed on it; they pass with the term gone. The term was redundant anyway. What protects the legacy old-analyzer flow is the rejection in checkDistributedReadSupported, which runs before this and throws outright; test_legacy_read_in_order_is_rejected still passes. Co-Authored-By: Claude Opus 5 <[email protected]>
New Bool setting, default false. It gates the only way an ORDER BY in a distributed plan can install a sorted read: the exchange descent in findReadingStep. With it off, optimizeReadInOrder cannot reach a read through an exchange, nothing installs input_order_info, and distributed plans behave exactly as they did before this PR. The reason for the gate is that tryMakeDistributedSorting wraps any SortingStep in a scatter without checking it is Type::Full, so a sort that depends on its input already being ordered can be fed rows through an exchange that does not preserve order. Guarding the carriers of such a sort one at a time does not converge - the old analyzer's FinishSorting and Merge tables both produce one, and there is no reason to think that list is closed. The lasting fix is a Type::Full check at tryMakeDistributedSorting; until then only shapes where no exchange survives between the read and the sort are safe, and those are what this setting enables. Verified by plan shape: with the setting off the read is ReadType: Default under a full sort, with it on it is ReadType: InOrder under a FinishSorting. The tests that are about this path turn the setting on; otherwise they would pass against an ordinary full sort and test nothing. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes55 object files changed (+74.64 KiB total), 0 added.
716 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 units345 translation units recompiled, 3042 s compile time in total, 345 of them have a recent master baseline. |
serialize wrote input_order_info for every serialized ReadFromMergeTree, while deserialize reapplied it only for a bucketed distributed read. Any other serialized plan - a parallel-replicas remote fragment under serialize_query_plan = 1 - therefore carried bytes that the reader ignored. Write the field only when the read is a bucketed distributed read, which is the only case that consumes it, and gate the version-mismatch throw on the same condition so an old peer plus a non-bucketed in-order read is not rejected where master would not have rejected it. master serializes no contract at all, so parallel replicas keeps the behaviour it has there; this PR neither improves nor regresses that path. Also carry distributed_plan_read_in_order into the local plan re-optimization alongside the other read-in-order gates, so a subquery that sets it cannot leave the initiator-local half and the remote replicas disagreeing. Co-Authored-By: Claude Opus 5 <[email protected]>
| Maximum rows to use broadcast join instead of shuffle join in distributed query plan. | ||
| A heuristic for the rule-based distributed planner. When the cost-based optimizer is enabled, the broadcast-vs-shuffle choice is made by estimated cost and this setting has no effect. | ||
| )", EXPERIMENTAL) \ | ||
| DECLARE(Bool, distributed_plan_read_in_order, false, R"( |
There was a problem hiding this comment.
This change ships behind a new experimental setting, distributed_plan_read_in_order, and stays off by default, so the current PR metadata overstates it as a general Improvement. Please switch the changelog category to Experimental Feature and make the changelog entry say explicitly that users have to enable distributed_plan_read_in_order to get the new distributed ORDER BY path.
|
📊 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
|
|
The in-order descent through the exchange pair assumes a rewrite that is separately switchable, and turning that switch off yields silently wrong rows — verified on this PR's CI binary.
The inner gather interleaves the sorted per-bucket streams in arrival order, the any-scatter re-partitions the chunks arbitrarily, and each partition's Reproduced on the PR head build (26.9.1.1, CREATE TABLE t_dro (k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k;
SYSTEM STOP MERGES t_dro;
INSERT INTO t_dro SELECT number * 3, number FROM numbers(20000);
INSERT INTO t_dro SELECT number * 3 + 1, number FROM numbers(20000);
INSERT INTO t_dro SELECT number * 3 + 2, number FROM numbers(20000);
SET make_distributed_plan = 1, distributed_plan_execute_locally = 1,
distributed_plan_default_shuffle_join_bucket_count = 3,
distributed_plan_default_reader_bucket_count = 3,
distributed_plan_max_rows_to_broadcast = 0,
optimize_read_in_order = 1, distributed_plan_read_in_order = 1,
max_block_size = 1000,
distributed_plan_optimize_exchanges = 0; -- the one extra flag
SELECT k FROM t_dro ORDER BY k LIMIT 5 OFFSET 44444; -- expect 44444..44448Across 30 runs, 5 returned wrong rows ( The distinct-in-order and limit-by-in-order legs take the same flag ( One question on the cloud side of the same contract: the serialization/restore of the order contract lives in The rest held up well under scrutiny: the hoist predicate is literally shared between the predictor and the rewriter ( |
| /// An exchange hands each partition its rows in arrival order, so the read may read in order only if | ||
| /// the scatter/gather pair fuses into an identity shuffle and is dropped, leaving read and sorting together. | ||
| if (auto * scatter = typeid_cast<ScatterExchangeStep *>(step); | ||
| scatter && scatter->getKeys().empty() && data.distributed_plan_read_in_order) |
There was a problem hiding this comment.
distributed_plan_read_in_order is not a sufficient safety gate here, because the rewrite this branch is predicting is still separately switchable. findReadingStep will descend through this keyless ScatterExchange whenever distributed_plan_read_in_order = 1, but optimizeExchanges only runs under distributed_plan_optimize_exchanges (optimizeTree.cpp:622-623). With that debug setting turned off, the verified ScatterExchange(any) -> GatherExchange -> Read pair survives between the read and the consumer, and every caller of this helper can then treat unordered input as ordered: SortingStep becomes FinishSorting, and the same helper is reused by DistinctStep, LimitByStep, and in-order aggregation.
That is a silent wrong-results path, not just a missed optimization. The gate here needs to match the rewrite it relies on (e.g. require distributed_plan_optimize_exchanges too, or re-check after exchange optimization), and this needs a focused regression with distributed_plan_optimize_exchanges = 0 plus a small max_block_size so the surviving exchange actually interleaves chunks.
…rder pass `optimizeTreeSecondPass` runs `optimizeReadInOrder` on two traversals. The earlier one was added by #116854, so that read-in-order is applied before projection selection, and #115244 then narrowed its gate to `!make_distributed_plan`. Both landed on master on 2026-09-03 and came in with the last merge. For a non-distributed query that earlier traversal is therefore the one that converts the `SortingStep` to `FinishSorting`, and it runs before `pushLimitByIntoSort` has attached the `LIMIT BY` hint - so `preferMultipleStreamsForPushedDownLimitBy` saw no hint and did nothing. The later traversal does run after the hint is attached (the pre-order traversal visits the parent `LimitByStep` first), but by then the sorting is no longer `Full`, so `optimizeReadInOrder` returned immediately and never reached the request. `setPreferMultipleStreams` was consequently never called, and the per-part `PrefetchingConcat` collapsed the per-stream `LimitBySortedStreamTransform` prefilter to a single stream per part - the exact serialization that request exists to prevent. Handle an already converted `FinishSorting` instead of returning: its `prefix_description` is the read-in-order prefix it was converted with, and the hint the converting pass could not see is attached by the time the other pass visits the step. Whichever traversal converts the sorting, the other one applies the request, so the decision no longer depends on which pass gets there first. `findReadingStep` stops at a `UnionStep`, so the fan-out over union branches that the conversion already did is factored into `preferMultipleStreamsForPushedDownLimitByBelowSorting` and reused here. Caught by `04054_read_in_order_prefetching_concat`, assertion `order_by_limit_by_multi_part_no_prefetching`, which was the only failure in the `Fast test` run on `ceb1047271ad` (1 of 11358 executed tests). Measured on a 3-part table with `max_threads = 6`, before and after, everything else equal: direct table, `ORDER BY grp, key LIMIT 3 BY grp` before: `PrefetchingConcat` x 3, prefilter `LimitBySortedStreamTransform` x 3 after: no `PrefetchingConcat`, prefilter `LimitBySortedStreamTransform` x 6 `Merge` table, same query before: `PrefetchingConcat` 3, `LimitBySortedStreamTransform` 4 after: `PrefetchingConcat` 0, `LimitBySortedStreamTransform` 7 Both controls are unchanged by the fix and keep per-part prefetching, as they should: an `ORDER BY` suffix that is not covered by the read-in-order prefix (no per-stream prefilter runs, so there is nothing to protect), and `query_plan_push_limit_by_into_sort = 0` (no hint at all). The `Merge` route was affected identically but had no coverage - `04318_read_in_order_prefetching_concat_merge` exercised only the bare `LIMIT BY` shape, which reaches the reader through `optimizeLimitByInOrder` and was never broken. It now also covers `ORDER BY ... LIMIT BY` over a `Merge` table, whose `PrefetchingConcat` assertion fails without this fix.
Adds support for
ReadInOrderoptimization forORDER BYqueries in distributed plansThe ReadInOrder Info travels with the serialized
ReadFromMergeTreeand is reapplied on the target, whichre-derives the ordinary in-order read locally.
findReadingSteplooks through the transient scatter/gatherpair that
tryMakeDistributedReadleaves above the read, so a bucketed distributed read installs theinfo too. Also fixes a
FinishSortingstep being unserializable because itstemporary_files_buffer_sizewas left at 0.
Changelog category
Changelog entry
A distributed
ORDER BYquery plan can now read in order if the table's sorting key and query's sorting key are same/similar....
Workflow [PR]
Sync PR [sync-upstream/pr/115244]