Skip to content

Support ReadInOrder in distributed plan - #115244

Merged
shankar-iyer merged 19 commits into
ClickHouse:masterfrom
shankar-iyer:read_in_order_dist_plan
Sep 3, 2026
Merged

shankar-iyer merged 19 commits into
ClickHouse:masterfrom
shankar-iyer:read_in_order_dist_plan

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Adds support for ReadInOrder optimization for ORDER BY queries in distributed plans

The ReadInOrder Info travels with the serialized ReadFromMergeTree and is reapplied on the target, which
re-derives the ordinary in-order read locally. findReadingStep looks through the transient scatter/gather
pair that tryMakeDistributedRead leaves above the read, so a bucketed distributed read installs the
info too. Also fixes a FinishSorting step being unserializable because its temporary_files_buffer_size
was left at 0.

Changelog category

  • Improvement

Changelog entry

A distributed ORDER BY query 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]

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bb8a162]

Summary: ✅


AI Review

Summary

This PR adds an experimental distributed_plan_read_in_order path that lets distributed ORDER BY queries serialize ReadInOrder on bucketed ReadFromMergeTree reads and reapply it on the worker/replica side, while tightening several earlier wrong-results cases. The main fixes look sound, but one blocker is still open: the new exchange descent assumes optimizeExchanges will run even though that rewrite is separately disabled by distributed_plan_optimize_exchanges, which still leaves a silent wrong-results path. The PR metadata also still describes the change as a general improvement even though the feature is experimental and off by default.

PR Metadata

Changelog category is not correct for the shipped change: the feature is behind the new experimental setting distributed_plan_read_in_order and is disabled by default, so this should be Experimental Feature, not Improvement.

Changelog entry is still required, but it should say the capability is opt-in and name the setting explicitly.

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
  • ⚠️ I could not validate the cloud-only ReadFromObjectStorageStep / ReadFromMergeTreeAtWorker order-contract path end to end from this repository: the distributed worker/object-storage implementations behind the #if CLICKHOUSE_CLOUD branches are not present here. A focused cloud integration test or the hidden implementation would close that gap.
Findings
❌ Blockers
  • [src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:179] The new exchange descent still assumes the matched ScatterExchange(any) -> GatherExchange -> Read pair will be removed, but that rewrite only runs when distributed_plan_optimize_exchanges = 1 (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:629). With distributed_plan_read_in_order = 1 and distributed_plan_optimize_exchanges = 0, findReadingStep still descends through the pair, SortingStep / DistinctStep / LimitByStep / in-order aggregation still treat the input as ordered, and the surviving exchange can interleave chunks in arrival order. That is a silent wrong-results path, not just a missed optimization.
    Suggested fix: make the descent gate match the rewrite it relies on, e.g. require optimization_settings.distributed_plan_optimize_exchanges when populating FindReadingStepContext::distributed_plan_read_in_order, or re-check the shape after exchange optimization instead of predicting it earlier.
Tests
  • ⚠️ Add a focused regression with distributed_plan_read_in_order = 1, distributed_plan_optimize_exchanges = 0, and a small max_block_size so the surviving exchange actually interleaves chunks. The current tests pin distributed_plan_optimize_exchanges = 1, so they cannot catch the blocker above.
  • ⚠️ If this feature is intended to work on the cloud-only distributed object-storage / worker path too, add or point to a focused cloud integration test proving that the worker-side fragment preserves the ReadInOrder contract.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit bb8a162.

Metric Baseline Current Δ
Lines 88.60% 88.70% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 164/175 (93.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 18, 2026
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]>
@shankar-iyer

Copy link
Copy Markdown
Member Author

ReadInOrder can only be activated when -
distributed_plan_default_reader_bucket_count = distributed_plan_default_shuffle_join_bucket_count

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]>
shankar-iyer and others added 2 commits August 18, 2026 13:22
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]>
shankar-iyer and others added 2 commits August 18, 2026 16:37
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]>
@shankar-iyer
shankar-iyer requested a review from davenger August 19, 2026 04:01
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bb8a162a1 with master 41b3bd68a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of fb0b23675; 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

55 object files changed (+74.64 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.18 MiB 1.21 MiB +28.57 KiB (+2.36%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp.o 185.85 KiB 207.47 KiB +21.62 KiB (+11.63%)

716 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

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

Job report

Comment thread src/Core/ProtocolDefines.h Resolved
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]>
Comment thread src/Core/Settings.cpp
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"(

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 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: 45e2862b-6350-4261-9d22-225837a7bdab
  • MIRAI run: c7884bd9-a900-47d6-ad94-46939f559356
  • PR check IDs:
    • clickbench_1063676_1788460287
    • clickbench_1063682_1788460287
    • clickbench_1063688_1788460287
    • tpch_adapted_1_official_1063699_1788460287
    • tpch_adapted_1_official_1063710_1788460287
    • tpch_adapted_1_official_1063746_1788460288

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

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.

findReadingStep descends a keyless ScatterExchange/GatherExchange pair around a bucketed read (scatter branch at src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp:177-187, gather branch at :190-196) on the prediction that optimizeExchanges will later hoist the gather, fuse the pair into a keyless equal-count ShuffleExchange, and drop it as an identity, leaving the in-order read directly under the converted FinishSorting. But that rewrite runs only under if (optimization_settings.make_distributed_plan && optimization_settings.distributed_plan_optimize_exchanges) (optimizeTree.cpp:622-623), and distributed_plan_optimize_exchanges is a user-visible query setting (default true, present since 26.4) that the descent never consults. With it set to 0, the plan keeps

GatherExchange (sorted by (k ASC))
└── Limit (local top-N)
    └── Sorting (prefix: k ASC)          <-- FinishSorting: assumes prefix-sorted input
        └── ScatterExchange (any scatter)
            └── GatherExchange           <-- unsorted: delivers buckets in arrival order
                └── ReadFromMergeTree (InOrder)

The inner gather interleaves the sorted per-bucket streams in arrival order, the any-scatter re-partitions the chunks arbitrarily, and each partition's FinishSortingTransform runs over input that is not sorted by its prefix — so the "sorted" streams the outer gather merges are not sorted, and the result is wrong, nondeterministically, with no error.

Reproduced on the PR head build (26.9.1.1, a4b7873d), single server:

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..44448

Across 30 runs, 5 returned wrong rows (54379, 54380, 54382, 54383, 54385 and similar — a single partition's subsequence passed off as the global order); with distributed_plan_optimize_exchanges = 1 the result is correct on every run. At the default max_block_size the race hides at this scale because each part arrives as one chunk, so partitions happen to receive whole sorted chunks — which is also why a test at defaults can pass while the plan shape is broken.

The distinct-in-order and limit-by-in-order legs take the same flag (optimizeReadInOrder.cpp:1461, :1553) and run under distributed plans (optimizeTree.cpp:543, :546), so DistinctSorted and in-order LIMIT BY over unsorted per-partition streams are exposed the same way. The straightforward fix is to make the descent's gate match the rewrite's gate, e.g. set the context flag to optimization_settings.distributed_plan_read_in_order && optimization_settings.distributed_plan_optimize_exchanges at the four construction sites (optimizeReadInOrder.cpp:1213, :1339, :1461, :1553).

One question on the cloud side of the same contract: the serialization/restore of the order contract lives in ReadFromMergeTree::serialize/deserialize, but with the default distributed_plan_prefer_replicas_over_workers = false a bucketed read is converted at fan-out into the worker-side read step (makeDistributed.cpp:1486-1505). Does that step's serializer preserve input_order_info the same way? If not, the worker path would feed per-bucket unsorted streams into the same order-assuming FinishSorting. The new comment in supportsBucketedRead suggests this is handled, but it isn't visible from this repository.

The rest held up well under scrutiny: the hoist predicate is literally shared between the predictor and the rewriter (canHoistGatherThroughStep), projection substitution can't undo the in-order read (projections run first and decline both bucketed and in-order reads), version skew is fail-loud in both directions (SUPPORT_IS_DISABLED at serialize below v11, NOT_IMPLEMENTED on an old receiver), the worker's requestReadingInOrder refusal throws instead of silently reading unordered, and the worker pins the coordinator's exact bucket marks by part name.

/// 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)

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.

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.

@shankar-iyer
shankar-iyer added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit 865af56 Sep 3, 2026
174 checks passed
@shankar-iyer
shankar-iyer deleted the read_in_order_dist_plan branch September 3, 2026 21:48
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
alexey-milovidov added a commit that referenced this pull request Sep 4, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product 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.

4 participants