Repository navigation
Parallel read in order with multiple parts - #100394
alexey-milovidov wants to merge 231 commits into
Conversation
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]>
|
Workflow [PR], commit [45b4a58] Summary: ❌
AI ReviewSummaryThe PR reduces read-ahead memory for ordered multi-part Findings
Tests
Missing context / blind spots
Final VerdictStatus: Preserve parallelism for nontrivial expressions in |
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]>
…el-read-in-order-multi-part
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]>
08500ac to
fd50474
Compare
…` 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]>
…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]>
…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]>
|
🕵 Status for HEAD
|
|
🕵 Status for HEAD The only red check is |
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp # src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp # src/Processors/QueryPlan/ReadFromObjectStorageStep.h
|
🕵 Merged |
# Conflicts: # src/Processors/QueryPlan/BufferChunksTransform.cpp # src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp # src/Processors/QueryPlan/SortingStep.h # src/Storages/StorageMerge.h
|
🕵 Merged master (conflicts in @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 |
|
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 |
|
The fix is in #132631.
#132631 makes the run-trend check skip queries that only read, using the write rule |
…d]]` Fixes the `modernize-use-nodiscard` clang-tidy error in `Build (arm_tidy, 2/4)` and `Build (arm_tidy, 4/4)`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100394&sha=359a44761741f71b2390bd073a55e664cb18e0c2&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29 PR: #100394 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Thanks @groeneai, the Pushed |
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]>
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]>
|
🕵 Pushed The four failures in the new The All changed |
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]>
|
🕵 Pushed The run-trend failure of This change only touches the test; #132631 (the check skipping read-only queries) remains the general fix. There are no unresolved review threads. |
…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]>
|
🕵 Merged The conflicts came from #100391, which this branch was based on: it was merged into
Checked locally on the merged tree: the build passes, and the 35 stateless tests that mention
|
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]>
|
🕵 Pushed
There are no unresolved review threads. |
| && !output_each_partition_through_separate_port | ||
| && input_order_info->limit == 0 | ||
| && !has_outer_limit | ||
| && !prefer_multiple_streams |
There was a problem hiding this comment.
[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.
Reading a
MergeTreetable in the order of the primary key splits every part into as many streams asmax_threadsallows and hands all of them to oneMergingSortedTransform.SortingStepputs aBufferChunksTransformin front of every merge input, so the read-ahead a query holds grows withmax_threadsrather than with the data: a full ordered scan of a four-part, 50-million-row table peaks at 158 MB withmax_threads = 8and at 425 MB withmax_threads = 32.This pull request concatenates the streams of one part with a new
WindowedPrefetchingConcatProcessorplaced 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 byread_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_usageofSELECT * FROM t ORDER BY key FORMAT Null, measured onaarch64:max_threadsThe win is in how the figure scales: before, it grows with
max_threads; after, it is governed by the number of parts. Atmax_threads = 8there 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 ownelapsed_usonly 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 atmax_threads = 32is −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] atmax_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
Stringcolumns) 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.xmlandtests/performance/read_in_order_direct_io.xmlare added so both this shape and the latency-bound one are measured in CI;read_in_order_multi_part.xmlandread_in_order_single_part.xmlcover 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 andLIMIT BY. It is also disabled when a step between the read and the merge does per-row work (aWHEREthat stays outsidePREWHERE,ARRAY JOIN, a computing expression), so that work keeps one instance per read stream; only renames, such as the projection ofSELECT *, keep the per-part merge. Every query in the pre-existingorder_by_read_in_orderandread_in_order_many_partstests 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
PrefetchingConcatProcessorpath 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduce the memory usage of queries that read a
MergeTreetable 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 bymax_threads: a full ordered scan of a four-part table withmax_threads = 32peaks at 226 MB instead of 425 MB.Workflow [PR]
Sync PR [sync-upstream/pr/100394]