Repository navigation
Parallelize read-in-order from a single part with PrefetchingConcatProcessor - #100391
Conversation
…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]>
|
Workflow [PR], commit [92d22b4] Summary: ✅
AI ReviewSummaryThe PR adds 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 VerdictStatus: ✅ Approve |
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]>
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]>
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]>
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]>
|
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. |
|
🕵 CI note for f8c3d74: the only failure, |
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.
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
|
🕵 Merged |
# Conflicts: # src/Processors/QueryPlan/SortingStep.h
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp
|
🕵 Merged |
|
🕵 CI note for abf61c0: the only failure, |
…under 26.12 The `settings_changes_history` style check requires new settings to be recorded under the current version. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100391&sha=87812687cebc230287505107d7f3437f9c66ec9d&name_0=PR&name_1=Style%20check #100391 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
I found all of it good.
…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]>
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]>
When a single MergeTree part is split into multiple streams for read-in-order, use the new
PrefetchingConcatProcessorinstead of relying on the downstreamMergingSortedTransform. The key difference:MergingSortedTransformmarks 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.PrefetchingConcatProcessormarks 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. With0, 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):
Changelog category (leave one):
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 bymax_buffered_chunks) to prefetch non-current streams while still outputting streams strictly in order.Wires it into MergeTree read-in-order:
ReadFromMergeTreenow conditionally replacesMergingSortedTransformwithPrefetchingConcatProcessorwhen reading in ascending order from a single part split into multiple streams and only when there is filtering work (PREWHEREor row-level filter); it also addsprefer_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
PrefetchingConcatappears 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-lessORDER BYreads.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
26.12.1.148-master(included in26.12and later)