Skip to content

Parallel read in order with multiple parts - #100394

Open
alexey-milovidov wants to merge 231 commits into
masterfrom
parallel-read-in-order-multi-part
Open

alexey-milovidov wants to merge 231 commits into
masterfrom
parallel-read-in-order-multi-part

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

Reading a MergeTree table in the order of the primary key splits every part into as many streams as max_threads allows and hands all of them to one MergingSortedTransform. SortingStep puts a BufferChunksTransform in front of every merge input, so the read-ahead a query holds grows with max_threads rather than with the data: a full ordered scan of a four-part, 50-million-row table peaks at 158 MB with max_threads = 8 and at 425 MB with max_threads = 32.

This pull request concatenates the streams of one part with a new WindowedPrefetchingConcatProcessor placed before the merge. The merge then has one input per part instead of one per stream; the concatenation keeps a window of the part's upcoming streams reading ahead, each with the same read-ahead budget it had as a merge input (max_block_size / prefer_external_sort_block_bytes, switched off by read_in_order_use_buffering = 0). The read-ahead is therefore bounded by the number of parts times the window instead of by the number of streams.

Peak memory_usage of SELECT * FROM t ORDER BY key FORMAT Null, measured on aarch64:

table max_threads before after
4 parts, 50M rows 8 158 MB 159 MB
4 parts, 50M rows 32 425 MB 226 MB
2 parts, 50M rows 32 356 MB 119 MB

The win is in how the figure scales: before, it grows with max_threads; after, it is governed by the number of parts. At max_threads = 8 there is no difference.

Wall-clock time is a second-order effect and is reported as such. On the shapes the dedicated tests cover it is between 0% and −5%, with one index-selective query at −11.6% [−12.7, −10.3]. Narrowing the merge does not make the merge cheaper — going from 24 inputs to 2 moves MergingSortedTransform's own elapsed_us only from 416 ms to 398 ms, because it is dominated by copying rows rather than comparing them — and total query CPU is unchanged. The difference is scheduling overlap, worth a roughly fixed 10–20 ms per query, which is why it looks large only on short ones. The full measurement, including the A/A control that validates it, is in #100394 (comment).

Read-ahead depth matters more than the number of streams kept awake. A stream reads its ranges sequentially, so it only has a read outstanding while it has room for the result; waking every stream of a part instead moved the in-flight read count from 2.03 to 2.20 and cost 65 MB. Giving the two streams in the window a real budget instead of two chunks is what pays: with min_bytes_to_use_direct_io = 1 — reads bound by latency rather than served from the page cache — a two-part table at max_threads = 32 is −35.3% [−45.6, −28.2], and a four-part table −6.0% [−30.2, +0.8]. Warm-cache scans are neutral (+2.3% [+0.5, +4.5] at max_threads = 8, +0.5% [−2.1, +2.2] at 32, −0.6% on a 22-column table).

Known remaining cost. On a table whose rows are expensive to materialize (22 String columns) the per-part concatenation is about 7% slower than reading every stream as its own merge input, with identical CPU: the merge occasionally waits on a part whose next stream has not been started. tests/performance/read_in_order_wide_columns.xml and tests/performance/read_in_order_direct_io.xml are added so both this shape and the latency-bound one are measured in CI; read_in_order_multi_part.xml and read_in_order_single_part.xml cover the merge-bound shape and the single-part path this change leaves alone.

Scope. The new pipeline shape applies to a full ordered scan only. It is disabled when the read carries a LIMIT (pushed down or outer) and when a downstream step wants several streams of its own — aggregation-in-order, distinct-in-order and LIMIT BY. It is also disabled when a step between the read and the merge does per-row work (a WHERE that stays outside PREWHERE, ARRAY JOIN, a computing expression), so that work keeps one instance per read stream; only renames, such as the projection of SELECT *, keep the per-part merge. Every query in the pre-existing order_by_read_in_order and read_in_order_many_parts tests falls into one of those cases and is unaffected, which is why neither of them moves.

Builds on #100391, which is merged: a read of a single part keeps the PrefetchingConcatProcessor path and the conditions introduced there, and this pull request adds the per-part path for a read of several parts next to it. The opt-outs that keep the read streams separate (prefer_multiple_streams) are the ones from #100391.

Changelog category (leave one):

  • Performance Improvement

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

Reduce the memory usage of queries that read a MergeTree table in the order of the primary key from several parts. The read-ahead buffering in front of the sorted merge is now bounded by the number of parts instead of by max_threads: a full ordered scan of a four-part table with max_threads = 32 peaks at 226 MB instead of 425 MB.


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

Instead of splitting all parts into streams in a single loop (which
reverses part order and creates cross-part streams), split each part
independently:

1. For each part, allocate streams proportional to its mark count
2. Split the part's ranges evenly across those streams
3. Add PrefetchingConcatProcessor to parallelize within the part
4. MergingSortedTransform merges the sorted per-part outputs

This enables PrefetchingConcat for multi-part tables. Previously it
only worked for a single merged part because the old splitting
algorithm reversed part order.

Pipeline for 3 parts with 6 threads:
  MergingSortedTransform 3 → 1
    PrefetchingConcat 2 → 1  (part 0: 2 parallel streams)
    PrefetchingConcat 2 → 1  (part 1: 2 parallel streams)
    PrefetchingConcat 2 → 1  (part 2: 2 parallel streams)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45b4a58]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 7/8) FAIL Performance dashboard
Query read_in_order_direct_io #0 time keeps growing with each run FAIL
Query read_in_order_direct_io #1 time keeps growing with each run FAIL
adaptive_aggregation_never_frozen_string_tables #1 unstable query history
aggregate_with_serialized_method #2 unstable query history
prefetch_in_aggregation #16 unstable query history

AI Review

Summary

The PR reduces read-ahead memory for ordered multi-part MergeTree scans by concatenating each part's split streams before the sorted merge. Reviewed the current diff and all 58 existing review threads. One remaining performance safeguard gap needs attention: computation of child ALIAS columns through Merge can lose its parallelism.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/ReadFromMergeTree.cpp:2406: The new concatenation can reduce expensive child expressions to one stream per part. ReadFromMerge::convertAndFilterSourceStream evaluates arbitrary child ALIAS expressions in ExpressionStep nodes, whereas preferMultipleStreamsForResidualCPUWork ignores all such nodes. For a two-part child exposing extracted String ALIAS JSONExtractString(payload, 'x'), SELECT key, extracted FROM merged ORDER BY key with max_threads = 32 leaves the opt-out unset and runs extraction on only two streams. Classify actual child expression DAGs in the shared safeguard, retaining exemptions for trivial header handling, or concatenate after the computation.
Tests
  • ⚠️ Add a focused Merge regression with a computed child ALIAS and several split streams per part, verifying that the expensive expression keeps the original parallelism. A before/after measurement with a costly expression would establish its timing impact; existing residual-filter tests do not exercise this path.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory is available, so the finding is based on source tracing, without a local timing measurement. The description's memory measurements predate the latest merge of master; current-head CI is still running. GitHub reports current-head build and workflow checks as pending or in progress.
Final Verdict

Status: ⚠️ Request changes

Preserve parallelism for nontrivial expressions in Merge child plans and add the focused alias regression.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 22, 2026
alexey-milovidov and others added 2 commits March 22, 2026 21:37
With `PrefetchingConcatProcessor`, a single-part table produces one
sorted output stream, so `SortingStep` no longer adds `BufferChunks`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The per-part splitting loop could create more total streams than
num_streams because each part gets at least 1 stream, and rounding
in proportional allocation could overshoot.

Add a streams_remaining budget that decrements as streams are
allocated to parts. Each part's allocation is computed as a fraction
of the remaining budget proportional to its share of remaining marks,
and capped at the budget.

This ensures the total number of MergeTreeSource processors never
exceeds the requested num_streams (typically max_threads).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…h JOIN

When a query like `SELECT ... FROM t JOIN ... ORDER BY ... LIMIT N` goes
through the read-in-order-through-join optimization, `buildSortingDAG`
zeros out `input_order_info->limit` because a JOIN can change the number
of rows. This caused `can_use_per_part_prefetching` to be true, enabling
`PrefetchingConcatProcessor` which eagerly reads all sub-streams of a
part in parallel -- defeating the early termination that LIMIT relies on.

The fix propagates the outer limit info from `SortingStep` to
`ReadFromMergeTree` via `setHasOuterLimit`, so per-part prefetching is
disabled when early termination matters.

Also fixes two review issues:
- Stream budget: only compute `part_streams > 1` when prefetching is
  enabled, avoiding incorrect budget consumption.
- Backpressure: `PrefetchingConcatProcessor` now calls `setNotNeeded`
  when a non-current input's buffer is full, providing proper
  backpressure instead of unbounded growth.

Update reference files for tests 01551 and 03031 to reflect the new
`PrefetchingConcat`-based pipeline topology.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits March 23, 2026 00:58
The previous implementation restricted `PrefetchingConcat` to forward
direction only (direction == 1), leaving reverse-order queries with a
single stream per part. This was a performance regression compared to
the old algorithm which split parts across multiple streams for both
directions.

Fix by removing the direction restriction and reversing the pipe order
for reverse direction so that `PrefetchingConcat` outputs the highest
ranges first, maintaining correct descending order.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@ClickHouse ClickHouse deleted a comment from CLAassistant Mar 23, 2026
@alexey-milovidov
alexey-milovidov force-pushed the parallel-read-in-order-multi-part branch from 08500ac to fd50474 Compare March 23, 2026 11:14
alexey-milovidov and others added 3 commits March 23, 2026 12:12
…` double-push

`PrefetchingConcatProcessor::prepare` used to check only `output.isNeeded()`
before pulling from all inputs. When the output port already had data
(`canPush` false but `isNeeded` true), the processor would still pull from
inputs, trigger edge updates, and get re-prepared in a tight loop without
making progress. Replace the `isNeeded` guard with `canPush` and remove
the redundant second `canPush` check, so we only pull when we can actually
push downstream.

Also fix a pre-existing bug in `BufferChunksTransform` where a virtual row
could be pushed to the output port that already had data from an earlier
push in the same `prepare` call. Add a `canPush` guard before the virtual
row push; if the output is full, buffer the virtual row chunk instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`PrefetchingConcat` collapses multiple reading streams into one, which
defeats parallel aggregation-in-order and memory-bound merging. Add
`prefer_multiple_streams` flag set by the aggregation-in-order optimizer
to keep per-part streams separate when the downstream step benefits from
parallelism.

Fix `04054_read_in_order_prefetching_concat` test: add `no-random-settings`
and `no-random-merge-tree-settings` tags to prevent randomized settings
from disabling `PrefetchingConcat`; reduce data sizes to avoid timeouts
in sanitizer builds; explicitly set `optimize_read_in_order = 1`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits March 24, 2026 12:00
…on-in-order

Update `01551_mergetree_read_in_order_spread` reference to match the new
pipeline topology where per-part streams are kept separate (no
`PrefetchingConcat`) when `prefer_multiple_streams` is set by the
aggregation-in-order optimizer.

Improve `04054_read_in_order_prefetching_concat` correctness check to
verify sort ordering via `lagInFrame` instead of just checking row count,
addressing the review concern that a count-only check cannot detect
ordering regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Three fixes for the performance test regressions:

1. Disable `PrefetchingConcat` for single-part tables. For a single part,
   `PrefetchingConcat` collapses all N streams into 1 before downstream
   transforms (distinct, sort, expression), destroying parallelism. The old
   code kept N separate streams merged by `MergingSortedTransform`, allowing
   parallel processing throughout the pipeline.

2. Restore the original mark-distribution logic for queries where per-part
   splitting is not beneficial (LIMIT queries, etc.). The new per-part loop
   created one pipe per part, giving `MergingSortedTransform` up to num_parts
   inputs instead of num_streams, which is much more expensive for tables
   with many parts.

3. Limit `PrefetchingConcat` to prefetch only the next few inputs ahead
   (not all), reducing overhead from running many upstream sources in parallel
   when their data won't be consumed until much later.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… rows

When a virtual row is buffered because the output port is full,
`num_buffered_rows` and `num_buffered_bytes` were not incremented.
When the chunk is later dequeued, both counters are decremented
unconditionally, causing unsigned integer underflow and corrupting
flow-control decisions.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@nickitat nickitat self-assigned this Mar 26, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

Publishing pending bot review to unblock new inline comments from this run.

alexey-milovidov and others added 5 commits March 28, 2026 22:30
…mark comments

- Change `count() > 0` to `count() = 0` in the `no_prefetching_with_limit` test
  section so the assertion semantically matches its intent (verifying that
  `PrefetchingConcat` is absent).
- Update benchmark comments in `read_in_order_single_part.xml` to reflect that
  `PrefetchingConcat` is not used for single-part tables.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…allel read-in-order

With `max_streams_to_max_threads_ratio=8`, the read-in-order pipeline now
produces multiple streams directly (parallel read-in-order), so the
`Resize 1 → 4` is no longer present in the pipeline.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…d-in-order without `max_streams_to_max_threads_ratio`

With parallel read-in-order, the pipeline no longer produces a
`Resize 1 → 4` for the basic read-in-order case either (not just the
`max_streams_to_max_threads_ratio=8` case fixed in the previous commit).
The single part is now split into multiple streams directly.

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

Copy link
Copy Markdown
Member Author

🕵 Status for HEAD 10bbc1bf010 (a master merge with no conflicts; the PR is MERGEABLE again): there are no unresolved review threads, and the earlier key_condition_multi_atom_wide_or perf report was explained by @groeneai in #129381, so nothing is left to do there.

CH Inc sync failed again because the bot could not merge the new head into the private sync PR. The conflict was the same as before, in ReadFromObjectStorageStep.h (the private-only totalRows next to requestReadingInOrder(int direction)). I overlaid the PR files onto private master, kept both, and recorded the public head as a parent. The per-file numstat matches the public PR diff exactly. The sync PR is MERGEABLE, and private CI is running. Public CI on this head is still in progress.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status for HEAD 10bbc1bf010: public CI is green (132 passed, 0 failed), and there are no unresolved review threads.

The only red check is CH Inc sync (tests failed). In the private sync PR, one job failed: Stateless tests (amd_debug, meta in keeper, distributed plan, s3 storage, parallel). The failing test is 05345_hash_join_row_store_strings, which hit TOO_MANY_ROWS (max rows: 20.00 million, current rows: 21.21 million) when it scanned system.text_log filtered only by event_date. This PR does not cause it: none of its tests read system.text_log, and the test fails the same way regardless of the PR (119 of 119 reruns). The fix is in progress in #130490, which adds an event_time filter to every system.text_log query in the tests. Once it is merged, a master merge here will clear the sync check. No code change is needed in this PR.

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (1bf7105f6b2) to resolve conflicts in ReadFromObjectStorageStep and optimizeReadInOrder.cpp. On master, ReadFromObjectStorageStep::requestReadingInOrder now takes (direction, optimization_settings) and already rejects direction != 1. I took the master version of it, which makes this PR's own direction check redundant, so the PR no longer touches ReadFromObjectStorageStep.{h,cpp}. The only red check, Build (arm_tidy, 4/4) in gtest_s3_object_storage_explicit_settings.cpp, is unrelated and was fixed on master by 0f632849aac8, which this merge brings in. All PR-touched translation units compile locally.

# Conflicts:
#	src/Processors/QueryPlan/BufferChunksTransform.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
#	src/Processors/QueryPlan/SortingStep.h
#	src/Storages/StorageMerge.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (conflicts in BufferChunksTransform.cpp, SortingStep.h, StorageMerge.h, optimizeReadInOrder.cpp resolved: the PR's virtual-row ordering in BufferChunksTransform is kept together with master's ReadInOrderReadAheadTracker pausing). The merged build passes the PR's stateless tests locally.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=1bf7105f6b27817ec072e61dcd4ff4f49872d783&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%201%2F8) and provide a fix in a separate PR. The run-trend gate flagged read_in_order_direct_io query #1 for time growing with each run. That query is a read-only SELECT ... ORDER BY key DESC FORMAT Null. The reference (master) server shows the same step-up (0.617 → 0.82 s), and the job is labeled disk-almost-full / io-bound, so this looks like environment noise under min_bytes_to_use_direct_io rather than a regression. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix is in progress right now: the run-trend check comes from my #129330, and my earlier fix for its false positives under host contention (#131251, rerun the flagged query before failing) was closed unmerged. I'm investigating this read_in_order_direct_io #1 case; I'll follow up here with a PR (or my findings) shortly.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #132631.

read_in_order_direct_io #1 read the same rows, bytes and marks in every run with flat CPU time. The extra time is disk read latency under O_DIRECT that stepped up on both servers at the same second, so it comes from the host, not from this PR. The same step shows in 23 of the 27 arm jobs of this PR since 2026-10-02.

#132631 makes the run-trend check skip queries that only read, using the write rule perf.py already applies for stop-merges. All 6 failures of the check since #129330 merged are such queries. Reverting #129330 is the alternative, if you prefer it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, the read_in_order_direct_io run-trend fix is tracked in #132631.

Pushed 44d6294df70, which marks Buffer::hasRoom in PrefetchingConcatProcessor.h as [[nodiscard]]. That fixes the modernize-use-nodiscard clang-tidy error that failed Build (arm_tidy, 2/4) and Build (arm_tidy, 4/4) on the previous head. Running clang-tidy locally on PrefetchingConcatProcessor.cpp and BufferChunksTransform.cpp now reports no errors. There are no unresolved review threads.

alexey-milovidov and others added 2 commits November 20, 2026 06:11
The merge of `canOutputEachPartitionThroughSeparatePortForWindow` (now returning `bool`) with this
branch's `distributed_read_bucket_count` check left a bare `return;`. Also use
`VectorWithMemoryTracking` for `fallback_split_parts_and_ranges` to satisfy the style check.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=latest&name_0=PR&name_1=Fast%20test
PR: #100394

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
alexey-milovidov and others added 2 commits November 20, 2026 09:49
The tests check the initiator-local fragment built by `ReadFromLocalParallelReplicaStep`,
which exists only in the query-based implementation of parallel replicas. The new
`Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel)` job
enables `parallel_replicas_plan_based` for every query, so the `EXPLAIN` and coordinator
log anchors of these tests do not apply there. Set `parallel_replicas_plan_based = 0`,
as the other local-plan tests on master do.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=latest&name_0=PR
#100394

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 27e34cd734a + merge of master (e0bf56ffe49).

The four failures in the new Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) job (04650_limit_by_push_down_parallel_replicas_local_plan, 05045_top_k_through_join_scope_parallel_replicas_local_plan, 04697_read_in_order_virtual_row_scope_union_view_parallel_replicas, 04826_read_in_order_concurrent_read_scope_union_view_parallel_replicas) come from the job enabling parallel_replicas_plan_based globally (added on master in #128413). These tests pin the query-based ReadFromLocalParallelReplicaStep fragment, so they now set parallel_replicas_plan_based = 0, as other local-plan tests on master do.

The read_in_order_direct_io #1 run-trend failure in the performance comparison is the host-side O_DIRECT latency step that was already analyzed. The fix is still open in #132631.

All changed .cpp files of the PR pass a syntax check after the merge.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
The run-trend check of the performance comparison failed on query #1
(`ORDER BY key DESC`) on ARM in two consecutive runs. Rows, bytes and
CPU time are the same in every run. After about four seconds of
continuous `O_DIRECT` reading, the time steps from ~0.61 s to ~0.80 s on
both the tested and the reference server. The AMD runners measure
~0.82 s from the first run. So the first measured runs were faster
than the steady state, not later ones slower. Read the table a few
times in `fill_query` statements so that the measured runs start at
the steady state.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=e0bf56ffe49a895ddaff980122a57197002efab1&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%208%2F8%29
#100394
Related: #132631

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 7a6e00124b3, which adds warm-up fill_query reads to tests/performance/read_in_order_direct_io.xml.

The run-trend failure of read_in_order_direct_io #1 (ORDER BY key DESC) on Performance Comparison (arm_release, master_head, 8/8) is the same in both of the last two runs (2f443ece32a and e0bf56ffe49). Both servers run fast for the first ~4 s of continuous O_DIRECT reading (prewarm plus two or three runs, ~0.61 s each), then step to ~0.80 s and stay there. On amd_release (shard 5/6), the same query takes a flat ~0.82 s from the first run. So the ARM step is the end of a short fast phase at the start, not time that keeps growing. The test now reads the table seven times in fill_query statements so that the measured runs start at the steady state. No other test in that shard trips the check.

This change only touches the test; #132631 (the check skipping read-only queries) remains the general fix. There are no unresolved review threads.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 20, 2026
…der-multi-part

#100391, which this branch was based on,
has been merged into master in a form that diverged from the early copy carried here,
so both sides changed the same code. The conflicts are resolved as follows.

- The single-part path stays exactly as in master: `PrefetchingConcatProcessor` with the shared
  byte budget of `read_in_order_max_bytes_to_prefetch`, its conditions in
  `can_use_prefetching_concat`, and its tests.
- The per-part path of this branch (a read of several parts: the streams of one part are
  concatenated, `MergingSortedTransform` merges one stream per part) is kept next to it. Its
  processor, which limits the read-ahead to a window of upcoming inputs and keeps the virtual row
  contract, is moved to a separate class `WindowedPrefetchingConcatProcessor`, because the processor
  in master has different semantics (every input reads ahead, no virtual rows) that are pinned by
  `gtest_prefetching_concat_budget`. The two paths are mutually exclusive: per-part splitting needs
  more than one part, and the distribute-by-streams split of master is used otherwise.
- The opt-outs that both sides implemented independently are taken from master, and the duplicates
  of this branch are removed: `preferMultipleStreamsForPushedDownLimitBy*` (master does it in
  `pushLimitByIntoSort`), `preferMultipleStreamsForComputationAboveRead*` and `stepComputesPerStream`
  (master has `passed_residual_cpu_step` in `findReadingStep`),
  `ReadFromMerge::preferMultipleStreamsForComputationAboveReads` (master has
  `preferMultipleStreamsForResidualCPUWork`, which now also forwards the opt-out to a nested `Merge`
  table, as this branch did), and `disablePerPartPrefetching` (master calls `setPreferMultipleStreams`
  on a deserialized read, which disables the per-part path too).
- The per-part path additionally requires `read_in_order_requested_by_plan_optimizer`, like the
  single-part path in master: the legacy read-in-order path does not run the analysis that sets
  `prefer_multiple_streams`.
- `copyReadInOrderContractFrom` of this branch is kept for the rebuilt reads (`clone`, lazy `FINAL`,
  the local parallel replicas plan) and also carries `read_in_order_requested_by_plan_optimizer`.
- `04054_read_in_order_prefetching_concat` is taken from master (it tests a read of a single part,
  where the expectations of this branch no longer hold), and the multi-part cases of this branch are
  moved to the new test `05857_read_in_order_prefetching_concat_per_part`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and resolved the conflicts (b70cf2eb4ff).

The conflicts came from #100391, which this branch was based on: it was merged into master in a form that had diverged from the early copy carried here, so both sides changed the same code. How they are resolved:

  • The single-part path is exactly as in master: PrefetchingConcatProcessor with the shared byte budget of read_in_order_max_bytes_to_prefetch, its conditions in can_use_prefetching_concat, and its tests.
  • The per-part path of this PR is kept next to it for a read of several parts. Its processor (a window of upcoming inputs, the virtual row contract) is now a separate class, WindowedPrefetchingConcatProcessor, because the processor in master has different semantics that are pinned by gtest_prefetching_concat_budget. It still shows as PrefetchingConcat in EXPLAIN PIPELINE. The two paths are mutually exclusive: per-part splitting needs more than one part, otherwise the split from master is used.
  • Opt-outs implemented independently on both sides are taken from master, and the duplicates of this branch are removed: the LIMIT BY hint handling (pushLimitByIntoSort in master), the residual per-row work check (passed_residual_cpu_step in findReadingStep), its Merge table counterpart (preferMultipleStreamsForResidualCPUWork, which now also forwards the opt-out to a nested Merge table), and disablePerPartPrefetching (master calls setPreferMultipleStreams on a deserialized read).
  • The per-part path now also requires read_in_order_requested_by_plan_optimizer, as the single-part path does.
  • 04054_read_in_order_prefetching_concat is taken from master; the multi-part cases of this branch moved to the new 05857_read_in_order_prefetching_concat_per_part.

Checked locally on the merged tree: the build passes, and the 35 stateless tests that mention PrefetchingConcat or are added or changed by this PR pass, except 04870_read_in_order_remote_task_size_scope_parallel_replicas, which could not run because it needs the s3_cache storage policy that my local server does not have. A wider run of 530 read-in-order, LIMIT BY, lazy FINAL, Merge table and top-K tests had 515 passing; the other 15 could not run for lack of test environment (S3, the test.hits dataset, a few server configs), so they are left to CI. The performance figures in the description were measured before this merge and are not re-measured.

CH Inc sync was the only red check on the previous head (the Praktika report was green); it will rerun on the new head.

alexey-milovidov and others added 2 commits November 23, 2026 04:43
The merge of `master` left two `extern` declarations of the setting
`read_in_order_use_buffering` in `ReadFromMergeTree.cpp`: the one that came
with #100391 and the one this
branch had added. The style check rejects it:
`Found duplicated setting declaration in: src/Processors/QueryPlan/ReadFromMergeTree.cpp -> read_in_order_use_buffering`

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=b70cf2eb4fff621f15bfc3ce2e6ce6999841ddc3&name_0=PR&name_1=Style%20check
#100394

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 45b4a58a46b on top of a merge of master (aee5a7904cc).

  • Style check: ReadFromMergeTree.cpp declared the setting read_in_order_use_buffering twice (Found duplicated setting declaration): once from Parallelize read-in-order from a single part with PrefetchingConcatProcessor #100391 as merged into master, and once from this branch. The second declaration is removed; ReadFromMergeTree.cpp and optimizeReadInOrder.cpp compile on the merged tree.
  • CH Inc sync: the sync branch still held the state of 2026-11-12 and conflicted with the private master in the same files as the public branch did. It now takes master plus the diff of this head (no conflicts, the diff against master is identical to the public one), and the sync PR is MERGEABLE again.

There are no unresolved review threads.

&& !output_each_partition_through_separate_port
&& input_order_info->limit == 0
&& !has_outer_limit
&& !prefer_multiple_streams

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.

[Major] Preserve parallelism for computed child ALIAS columns

The new per-part path also collapses computation inside a Merge child's plan. preferMultipleStreamsForResidualCPUWork in StorageMerge.cpp:1062-1072 deliberately ignores every ExpressionStep, but convertAndFilterSourceStream constructs those steps from arbitrary child ALIAS expressions at StorageMerge.cpp:2836-2858.

For example, use a child with two large parts and this schema:

CREATE TABLE src
(
    key UInt64,
    payload String,
    extracted String ALIAS JSONExtractString(payload, 'x')
)
ENGINE = MergeTree PARTITION BY key % 2 ORDER BY key;

CREATE TABLE merged (key UInt64, extracted String)
ENGINE = Merge(currentDatabase(), '^src$');

SELECT key, extracted FROM merged ORDER BY key
SETTINGS enable_parallel_replicas = 0, max_threads = 32;

Once the parts are large enough to split, the outer plan sees only column renames and the child-plan guard skips the alias computation. Thus prefer_multiple_streams remains false, and this path gives the JSON extraction only two input streams instead of the original split streams. The same gap covers expensive child type conversions. This violates the safeguard for per-row work between the read and sorted merge and can serialize CPU-heavy queries.

Please make the child-plan safeguard inspect actual expression DAGs, exempting only trivial header plumbing, or concatenate after the per-stream computation. Add a focused computed-child-alias regression alongside the filter test; the existing filter and sampling cases do not cover it. The reduced parallelism follows from the current source; I have not measured its wall-clock impact.

This branch was successfully deployed

1 active deployment
staging - docs — 45b4a58a Deployed Nov 23, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. memory When memory usage is higher than expected pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants