Skip to content

Parallelize read-in-order from a single part with PrefetchingConcatProcessor - #100391

Merged
alexey-milovidov merged 188 commits into
masterfrom
parallel-read-in-order
Nov 22, 2026
Merged

alexey-milovidov merged 188 commits into
masterfrom
parallel-read-in-order

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

When a single MergeTree part is split into multiple streams for read-in-order, use the new PrefetchingConcatProcessor instead of relying on the downstream MergingSortedTransform. The key difference:

  • MergingSortedTransform marks all inputs as needed but only consumes from one stream at a time (for non-overlapping ranges), and each port can only buffer 1 block — so after initial prefetch, reading becomes sequential.

  • PrefetchingConcatProcessor marks all inputs as needed AND pulls data from non-current inputs into internal buffers, keeping upstream sources busy. It outputs data in strict input order (concatenation), which is correct because ranges from a single part are non-overlapping and pre-sorted.

The output consumes the inputs one after another, so sustained parallelism needs the later inputs to read far ahead. The buffers therefore share a byte budget, set by the new setting read_in_order_max_bytes_to_prefetch (128 MiB by default). The budget goes to the inputs nearest the current one first, and every input gets a head start of two chunks. With 0, each input reads ahead only those two chunks.

This avoids both the merge comparison overhead and the sort overhead, while enabling true parallel IO and filtering across range groups.

Benchmark on 100M rows (4 threads, single part, poor PK selectivity):

  • Single-thread read-in-order: 1.57s
  • Parallel + sort (no read-in-order): 1.27s
  • PrefetchingConcat: 0.61s (2.6x faster)

Changelog category (leave one):

  • Performance Improvement

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

Improve the performance of queries that are reading in the order of the primary key.


Note

Medium Risk
Changes read-in-order execution and introduces a new buffering processor in the query pipeline; incorrect gating or backpressure/buffering behavior could impact result ordering or memory usage in some MergeTree reads.

Overview
Adds PrefetchingConcatProcessor: a new concat-like processor that keeps all inputs marked needed and buffers per-input chunks (bounded by max_buffered_chunks) to prefetch non-current streams while still outputting streams strictly in order.

Wires it into MergeTree read-in-order: ReadFromMergeTree now conditionally replaces MergingSortedTransform with PrefetchingConcatProcessor when reading in ascending order from a single part split into multiple streams and only when there is filtering work (PREWHERE or row-level filter); it also adds prefer_multiple_streams/setPreferMultipleStreams() so aggregation-/distinct-in-order paths can opt out to avoid collapsing parallel streams.

Tests/bench coverage updated: adds a new stateless test asserting PrefetchingConcat appears only for single-part reads and preserves sort order, adjusts an existing buffering test to force multi-part behavior, and adds a performance scenario guarding against regressions for filter-less ORDER BY reads.

Reviewed by Cursor Bugbot for commit c0ba40d. Bugbot is set up for automated code reviews on this repo. Configure here.


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

Version info

  • Merged into: 26.12.1.148-master (included in 26.12 and later)

alexey-milovidov and others added 2 commits March 22, 2026 20:18
…ocessor

When a single MergeTree part is split into multiple streams for read-in-order,
use the new `PrefetchingConcatProcessor` instead of relying on the downstream
`MergingSortedTransform`. The key difference:

- `MergingSortedTransform` marks all inputs as needed but only consumes from
  one stream at a time (for non-overlapping ranges), and each port can only
  buffer 1 block — so after initial prefetch, reading becomes sequential.

- `PrefetchingConcatProcessor` marks all inputs as needed AND pulls data from
  non-current inputs into internal buffers, keeping upstream sources busy.
  It outputs data in strict input order (concatenation), which is correct
  because ranges from a single part are non-overlapping and pre-sorted.

This avoids both the merge comparison overhead and the sort overhead,
while enabling true parallel IO and filtering across range groups.

Benchmark on 100M rows (4 threads, single part, poor PK selectivity):
- Single-thread read-in-order: 1.57s
- Parallel + sort (no read-in-order): 1.27s
- PrefetchingConcat: 0.61s (2.6x faster)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Tests `PrefetchingConcatProcessor` throughput on a 50M row single-part
MergeTree table with:
- Poor PK selectivity (LIKE '%...' — all granules read)
- Good PK selectivity (LIKE 'prefix%' — few granules)
- Full scan with ORDER BY
- Aggregation in order

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 [92d22b4]

Summary: ✅


AI Review

Summary

The PR adds PrefetchingConcatProcessor to overlap filtered, ascending reads from a single MergeTree part while preserving range order, with a shared byte budget and guards that preserve downstream parallel work. Reviewed head 92d22b4403787fbc320c6956b3b73be630fc1bd0, the current diff, related execution paths, and all prior review threads and replies. No remaining actionable findings; the earlier findings are addressed in the current code.

The latest Praktika report reports 15,167 passed tests and zero failures. Validation relies on CI, the committed regression coverage, and the recorded before/after measurements; no local build or test run was performed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 22, 2026
The splitting algorithm takes parts from the back of `parts_with_ranges`,
producing streams in reverse part order: stream 0 gets the last part
(highest keys), stream N the first (lowest). A single stream can also
span parts in reverse order (e.g., `{P2_tail, P1_head}`).

The previous check only compared adjacent stream boundaries (which are
always within the same part due to how splitting works), missing the
within-stream part transitions that break ascending order.

The new check walks through ALL part entries across ALL streams and
verifies ascending PK order at every data_part transition, correctly
rejecting the multi-part case where the split order is reversed.

PrefetchingConcat still applies for the common single-part case
(large table after `OPTIMIZE FINAL`), where ranges are guaranteed to
be contiguous and in ascending order.

Also fix test to use `OPTIMIZE FINAL` (to get a single part) and
5M rows (to exceed `min_marks_for_concurrent_read` threshold).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits March 22, 2026 21:34
1. Fix clang-tidy `modernize-min-max-use-initializer-list`: replace
   nested `std::min` with initializer list form.

2. Update `03168_read_in_order_buffering_1` reference: with
   `PrefetchingConcatProcessor`, a single-part table produces one
   sorted output stream instead of multiple, so the downstream
   `SortingStep` no longer adds `MergingSortedTransform` or
   `BufferChunks`. The buffering is handled internally by
   `PrefetchingConcatProcessor`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`can_use_prefetching_concat` validated stream boundaries only on
PRIMARY KEY index columns. But read-in-order correctness is defined
by `used_prefix_of_sorting_key_size`, which can extend beyond PK.

When the sorting key prefix is wider than PK, two adjacent parts can
be equal on PK columns but out of order on the remaining sorting key
columns. `PrefetchingConcatProcessor` would concatenate instead of
merging, producing misordered output.

Now fall back to `MergingSortedTransform` when there are cross-part
transitions and `used_prefix_of_sorting_key_size > num_pk_columns`.
Single-part streams remain unaffected since within-part ranges are
always non-overlapping and pre-sorted.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. `04054_read_in_order_prefetching_concat`: explicitly set
   `optimize_read_in_order = 1` in all EXPLAIN queries to prevent
   randomized settings from disabling the optimization. Also set
   `index_granularity` and `index_granularity_bytes` on tables to
   prevent randomized MergeTree settings from reducing mark count
   below the split threshold.

2. `03168_read_in_order_buffering_1`: restore original reference
   (from master) and use multiple parts to prevent
   `PrefetchingConcatProcessor` from collapsing multiple streams into
   one, which would eliminate `BufferChunks` from the pipeline. This
   test is about `BufferChunks` behavior, not `PrefetchingConcat`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 7 commits March 29, 2026 00:40
Use `neighbor` to check that no adjacent pair violates the sort order,
so the test catches ordering regressions from the `PrefetchingConcat`
optimization path.

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

The test was producing stderr warnings about non-adaptive granularity
being incompatible with non-zero `min_bytes_for_wide_part`, causing the
Fast test to fail. Fixed-size granules are not essential for this test.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The `neighbor` function is now deprecated and causes test failure.
Use `lagInFrame` with `rowNumberInAllBlocks` to preserve row ordering
and detect ordering violations.

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

Two issues fixed:

1. `PrefetchingConcatProcessor` was collapsing multiple read streams into
   one, breaking aggregation-in-order which needs parallel streams for
   `AggregatingInOrderTransform`. Added `prefer_multiple_streams` flag
   to `ReadFromMergeTree` that is set by the aggregation-in-order
   optimizer in `optimizeReadInOrder`, preventing `PrefetchingConcat`
   from being used when downstream needs multiple streams. This fixes
   the `02404_memory_bound_merging` test failure.

2. Test `04054_read_in_order_prefetching_concat` was flaky because
   randomized `index_granularity_bytes` MergeTree settings could reduce
   the number of streams below threshold. Fixed by explicitly setting
   `index_granularity_bytes = 0` in table creation.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100391&sha=8fa49328a8a67b618468b2a8adadd47e31ae6016&name_0=PR

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits March 30, 2026 16:17
The cross-part mark comparison was unsound: PK index marks store the
first row of each granule, not an upper bound for all rows. Comparing
mark keys across parts cannot prove that all rows of the previous range
precede all rows of the next range, so concatenation could produce
misordered output.

Replace the cross-part comparison logic with a simple single-part check.
`PrefetchingConcat` was designed for the single-part case anyway (ranges
from one part are non-overlapping and pre-sorted), so this restriction
has no impact on the primary use case.

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

The setting causes a warning in stderr which makes the test fail in CI.
Adaptive granularity is the default and works fine for this test.

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

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 21, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI note for f8c3d74: the only failure, Some queries hung in Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel), is unrelated to this PR. The query left running was the replica-side SELECT count() ... WHERE x + sleepEachRow(3) >= 0 from 04117_detach_database_kill_query. It has no ORDER BY, so it does not go through read-in-order. That test was recently moved into the parallel pool, and under parallel replicas the remote query keeps sleeping after the initial query is killed. The fix, #127149 (keeps the test off parallel replicas), is still open. I merged the latest master (857cfee); the merged tree builds, and this PR's read-in-order stateless tests pass locally.

Resolve the conflict in `optimizeReadInOrder.cpp`: master replaced the join flags with
`traversed_joins` (with a strictness-aware virtual-row check); the PR's
`passed_order_preserving_join` is now expressed as `!traversed_joins.empty()`, and
`setPreferMultipleStreams` is kept next to the master's in-order join pinning.
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 13, 2026
The tree hash of a ColumnNode includes its column source, so W GROUP BY keys
over a W-column subquery cost O(W^2) in every pass that puts the keys into a
hash container (GroupingFunctionsResolvePass, AggregateFunctionOfGroupByKeysPass,
removeKeysThatAreFunctionsOfOtherKeys). Nothing in the analyzer checked for
cancellation, so KILL QUERY and max_execution_time were observed only when the
pipeline started. A Stress test (amd_tsan) hung check on ClickHouse#100391 found an AST
fuzzer GROUP BY ALL over merge(REGEXP('^'), '.+') still being analyzed after
2304 s; every trace_log sample of those passes was inside getTreeHash.

getTreeHash already adds the number of visited nodes to a thread-local counter
(the AND-chain work budget reads it). Call CurrentThread::checkIfNotCancelled()
each time that counter crosses a multiple of 65536. The hash is computed before
the check and is unchanged, as is the counter. The check throws only for a
killed query or a throw-mode deadline; with timeout_overflow_mode = 'break'
the query is not killed, so planning-time callers that return partial results
for break mode keep doing so.

Debug build, 8000 columns, max_execution_time = 1: TIMEOUT_EXCEEDED after
31.8 s before, 1.6 s after; KILL QUERY SYNC returns after 31.7 s before,
0.17 s after. Analysis time without a limit is unchanged (2.129 s vs 2.135 s).

The new test asserts that the timed-out query never reached planning
(QueryPlanBuildMicroseconds = 0): before the fix the query is logged as
ExceptionBeforeStart too, but only after it was fully planned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/SortingStep.h
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #130369 (the switch to the -WithMemoryTracking containers). This update was made automatically.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI note for abf61c0: the only failure, 05293_autopr_statistics_plan_based in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2), is unrelated to this PR. It is caused by the randomized enable_adaptive_codec_selection setting, it fails across many PRs and on master, and it was fixed by #133069. I merged the latest master (6349b3b) to pick up the fix, with no conflicts. The merged tree builds.

@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=27 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 81db5eeb-a73f-4982-a59b-f61be110694d
  • MIRAI run: 4b73f69f-7903-4c96-a9ab-9caadd35ce0f
  • PR check IDs:
    • clickbench_738446_1795315673
    • clickbench_738452_1795315673
    • tpch_adapted_1_official_738465_1795315673
    • tpch_adapted_1_official_738496_1795315673

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I found all of it good.

@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 22, 2026
Merged via the queue into master with commit 8174272 Nov 22, 2026
195 checks passed
@alexey-milovidov
alexey-milovidov deleted the parallel-read-in-order branch November 22, 2026 01:50
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 2026
alexey-milovidov added a commit that referenced this pull request Nov 22, 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 added a commit that referenced this pull request Nov 23, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance 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.

5 participants