Skip to content

Disable read-in-order when primary key selectivity is poor - #100377

Closed
alexey-milovidov wants to merge 219 commits into
masterfrom
fix-read-in-order-parallelism
Closed

alexey-milovidov wants to merge 219 commits into
masterfrom
fix-read-in-order-parallelism

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

When the WHERE clause cannot use the primary key effectively (e.g., LIKE '%...'), the optimize_read_in_order optimization kills parallelism: each part is read by a single stream instead of many. This can make ORDER BY queries 4x slower than the same query without ORDER BY.

Example on a 2.5B row table with ORDER BY path and WHERE path LIKE '%stderr.log':

  • Without ORDER BY: ~9.5s
  • With ORDER BY (read-in-order): ~40s
  • With optimize_read_in_order = 0: ~9.6s

The fix adds a runtime check in ReadFromMergeTree::spreadMarkRanges: if the primary key index selected more than a configurable fraction of all granules and there is no LIMIT, we fall back to parallel reading with per-stream PartialSortingTransform + MergeSortingTransform, so the output is still sorted as the SortingStep above expects.

New setting read_in_order_max_primary_key_ratio controls the threshold. The default is 1.0, which preserves the previous behavior (never disable read-in-order based on primary key selectivity): the heuristic is opt-in until the default threshold is tuned against the performance report. Set it below 1.0 (e.g. 0.5) to enable the guard.

Changelog category (leave one):

  • Performance Improvement

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

Add a new setting read_in_order_max_primary_key_ratio that can disable the read-in-order optimization when the primary key selectivity is poor (more than the given fraction of granules selected), falling back to parallel reading with sorting. This avoids severe parallelism loss for queries like SELECT ... WHERE path LIKE '%...' ORDER BY path. The default 1.0 preserves the previous behavior; set a lower value (e.g. 0.5) to enable the heuristic.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

New setting read_in_order_max_primary_key_ratio (Float, default 1.0): maximum ratio of selected to total primary key granules for optimize_read_in_order to stay enabled. When the ratio exceeds this value, read-in-order is disabled in favor of parallel reading with per-stream sorting. The default 1.0 preserves the old behavior.


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

alexey-milovidov and others added 2 commits March 22, 2026 18:48
When the WHERE clause cannot use the primary key effectively
(e.g., `LIKE '%...'`), the read-in-order optimization kills
parallelism: each part is read by a single stream instead of many.
This can make ORDER BY queries 4x slower than the same query
without ORDER BY.

The fix adds a runtime check in `spreadMarkRanges`: if the PK index
selected more than half of all granules and there is no LIMIT
(which could benefit from early termination), we fall back to
parallel reading with per-stream sorting. Each stream gets
`PartialSortingTransform` + `MergeSortingTransform`, so the output
is still sorted as the `SortingStep` above expects.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extract the hardcoded threshold (0.5) into a new setting
`read_in_order_max_primary_key_ratio` (default 0.5). When the ratio
of selected to total primary key granules exceeds this value, the
read-in-order optimization is disabled in favor of parallel reading
with per-stream sorting. Set to 1.0 to never disable read-in-order
based on primary key selectivity.

Also add a test case verifying the setting works (ratio = 1.0
disables the fallback).

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 [44faf57]

Summary: ✅


AI Review

Summary

PR #100377 adds an opt-in primary-key selectivity guard that replaces ordered reads with parallel reads and sorting for poorly pruned queries. Review of head 44faf578a22ca0db4b99e05dfe5e38d13b24ca00 leaves one confirmed performance issue: the guard can add a full sort when the fallback still reads through one stream. ⚠️ Request changes.

Findings

⚠️ Majors

  • Preserve ordered reading when the fallback cannot gain parallelism. src/Processors/QueryPlan/ReadFromMergeTree.cpp:4247 checks requested_num_streams, but spreadMarkRangesAmongStreams subsequently reduces that count using the selected marks, part count, and concurrency thresholds. With one part containing 81,920 rows at fixed granularity 8,192, four requested streams, and merge_tree_min_rows_for_concurrent_read = 163840, the guard sees ten marks and rejects ordered reading, while the fallback reduces to one stream. A local EXPLAIN PIPELINE reproduction shows the same single ReadPoolInOrder source with added PartialSortingTransform and MergeSortingTransform. Setting the ratio to 1.0 removes those sort stages. This adds sorting CPU, buffering, and latency without recovering parallelism. Compute the fallback's effective read parallelism before rejecting ordered reading, using the reader's concurrency rules, and retain ordered reading when that count is one. The existing bot thread was reopened; no duplicate inline comment was posted.

    Reproduction:

    CREATE TABLE small_read (k UInt64) ENGINE = MergeTree ORDER BY k
        SETTINGS index_granularity = 8192, index_granularity_bytes = 0;
    INSERT INTO small_read SELECT number FROM numbers(81920);
    SET max_threads = 4, max_streams_for_merge_tree_reading = 0,
        allow_asynchronous_read_from_io_pool_for_merge_tree = 0,
        enable_parallel_replicas = 0, optimize_read_in_order = 1,
        merge_tree_min_rows_for_concurrent_read = 163840,
        merge_tree_min_bytes_for_concurrent_read = 0,
        merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 0;
    EXPLAIN PIPELINE SELECT k FROM small_read
        WHERE k % 8192 != 8192 ORDER BY k
        SETTINGS read_in_order_max_primary_key_ratio = 0.5;
    EXPLAIN PIPELINE SELECT k FROM small_read
        WHERE k % 8192 != 8192 ORDER BY k
        SETTINGS read_in_order_max_primary_key_ratio = 1.0;
Tests
  • ⚠️ Add a focused stateless pipeline regression with multiple requested streams reduced to one by the concurrency threshold. Assert that ordered reading survives, and use a lower threshold as a control where parallel reading and sorting remain enabled. The existing max_threads = 1 coverage does not exercise this reduction.
Missing context / blind spots
  • ⚠️ Exact-head Praktika CI is still running. The local reproduction completed successfully using the ARM CI binary for parent c5546386c8b6d702268a86fcd56565974b09d312; the guard and stream-reduction code are unchanged in the reviewed head. Current-head stateless and performance results are needed to complete CI validation.
Final Verdict

⚠️ Request changes: account for the fallback's effective stream count and add the focused concurrency-threshold regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 22, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft March 22, 2026 18:04
alexey-milovidov and others added 14 commits March 22, 2026 19:10
Address review: instead of overriding the optimizer's decision at
runtime in `spreadMarkRanges` (patchy), reject read-in-order upfront
in `requestReadingInOrder`. When it returns false, the optimizer
keeps the SortingStep as a full sort — no manual sorting transforms
needed, no TreeRewriter/ExpressionAnalyzer usage.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Three fixes for the read-in-order PK selectivity check:

1. Only reject read-in-order when `total_marks_pk > requested_num_streams`,
   so small tables (which don't benefit from parallelism) are not affected.
   This fixes all ~34 test failures where tiny test tables had ratio 1.0.

2. Skip the check when parallel replicas are enabled to avoid
   LOGICAL_ERROR from coordination mismatches (replicas expecting
   WithOrder mode but getting Default).

3. Add `read_in_order_max_primary_key_ratio` to `SettingsChangesHistory.cpp`.

The test now uses `index_granularity = 64` to produce enough marks for
the check to trigger, and explicitly sets the threshold setting.

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

These tests validate specific read-in-order optimization behavior and need
the PK selectivity check disabled to preserve the optimization path they test.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key`: add
  `read_in_order_max_primary_key_ratio = 1.0` to SETTINGS since the test selects all
  granules and the new default (0.5) disables read-in-order
- `02862_sorted_distinct_sparse_fix`: update reference to include the echoed
  `set read_in_order_max_primary_key_ratio=1.0;` line
- `02493_max_streams_for_merge_tree_reading`: update reference to include
  `read_in_order_max_primary_key_ratio=1.0` in echoed queries

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

# Conflicts:
#	src/Core/Settings.cpp
…ying on read-in-order

Tests that check for `InOrder`/`InReverseOrder` in EXPLAIN output, or that
depend on the in-order aggregation pipeline for a fixed memory budget, must
opt out of the new PK selectivity heuristic so the optimization path they
exercise stays in effect regardless of table size or `max_threads`.

Affected tests:
- `00940_order_by_read_in_order_query_plan`, `02911_analyzer_order_by_read_in_order_query_plan`:
  small tables where `total_marks_pk > max_threads` can trigger rejection.
- `01513_optimize_aggregation_in_order_memory_long`, `03168_read_in_order_buffering_2`:
  fixed `max_memory_usage` budgeted for the in-order path; the fallback needs more memory.
- `01655_plan_optimizations_optimize_read_in_window_order[_long]`: window-order plan tests.
- `01814_distributed_push_down_limit`: pushdown plan relies on in-order reads.
- `02377_optimize_sorting_by_input_stream_properties_2`, `02481_aggregation_in_order_plan`,
  `02521_aggregation_by_partitions`: EXPLAIN sorting/pipeline references.
- `03231_pr_reverse_in_order`, `04024_pr_read_in_order_through_join`: read-in-order plan
  under parallel replicas.
- `03275_subcolumns_in_primary_key`, `03277_json_subcolumns_in_primary_key`: tiny tables
  testing EXPLAIN sorting annotation for subcolumn PK.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test was flaky under `Stateless tests ... flaky check` because the random
MergeTree settings fuzzer could change `index_granularity`, `min_bytes_for_wide_part`,
and `max_threads`, shifting the number of marks or streams so the PK selectivity
heuristic triggered on the "good" path too (or did not trigger when it should).

Add `no-random-settings, no-random-merge-tree-settings, no-parallel-replicas` tags,
pin `index_granularity_bytes = 0` and `min_bytes_for_wide_part = 0` so the `CREATE AS`
table is always wide with 64-row granules, and pin `max_threads = 4` so
`requested_num_streams` is stable.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 6 commits April 25, 2026 11:09
….cpp`

The `02995_new_settings_history` test compares against a baseline taken
from v26.4.1, so any new setting must appear in a section with version
greater than 26.4. The new `read_in_order_max_primary_key_ratio` was
mistakenly placed in the 26.4 section, causing the test to report it as
missing from the history.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=527f04f457a4a5b5377d85bdb9f382e5d68456f7&name_0=PR&name_1=Fast%20test
PR: #100377

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The PR's PK selectivity check disables read-in-order when the primary
key index doesn't reduce the number of granules and there is no LIMIT
to push down. The existing condition uses `read_limit == 0` to detect
"no LIMIT", but `read_limit` is also zeroed by `buildSortingDAG` when a
filter, GROUP BY, or ARRAY JOIN sits between the read step and sorting
(the limit cannot be pushed past those). As a result, queries like
`WHERE filter ORDER BY pk LIMIT N` lost read-in-order even though the
LIMIT (combined with virtual row optimization) lets the engine skip
parts entirely - exactly what `04049_virtual_row_overlap` exercises.

Pass an additional `query_has_limit` flag from the optimizer (captured
from `SortingStep::getLimit` before `buildSortingDAG` zeroes the local
copy) so the PK selectivity check fires only when the query truly has
no upper bound on the result.

Also addresses review feedback by comparing `total_marks_pk` against
the effective stream count used by in-order reading (`output_streams_limit`
when set) instead of the pre-adjustment `requested_num_streams`, which
can be inflated by `max_streams_for_merge_tree_reading` for async reads.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=527f04f457a4a5b5377d85bdb9f382e5d68456f7&name_0=PR&name_1=Fast%20test
PR: #100377

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

Four tests use small synthetic tables and assert specific read-in-order
EXPLAIN output (`algorithm: InOrder`, `ReadType: InOrder`,
`AggregatingInOrderTransform`, ORDER BY-derived sorting descriptions).
Their tables select all granules, which trips the new
`read_in_order_max_primary_key_ratio` heuristic and disables exactly the
optimization the tests are written to validate. Pin the setting to `1.0`
in each of these tests so they continue to exercise the in-order path.

- `02317_distinct_in_order_optimization_explain` — reads all granules of
  a 20-row test table.
- `02404_memory_bound_merging` — small 1e6-row in-order aggregation test.
- `03928_deferred_filters_after_final_in_explain` — 3-row table; asserts
  `ReadType: InOrder`.
- `04063_read_in_order_through_creating_sets` — added in this PR; tests
  read-in-order through `CreatingSetsStep`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=5337d80e21689ca154927ce0890d5060d5a13379&name_0=PR
PR: #100377

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test `04104_read_in_order_aggregation_parallelism` asserts that the
read-in-order pipeline expands past 1 stream after aggregation
(`Resize 1 → N` with `N > 1`). The synthetic table reads all granules,
which trips the new `read_in_order_max_primary_key_ratio` heuristic added
in this PR and disables read-in-order entirely - exactly the optimization
the test is written to validate. Pin the setting to `1.0` so the test
continues to exercise the in-order path.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100377&sha=f5e80dc90326f72cba2d2f7d55022ba68bc4c83f&name_0=PR
PR: #100377

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks. Public CI on bebcf38beda is now fully green, so nothing is blocked here. The 05237_with_expression_alias_scope_descendant fix will be tracked in #123790, and the TimeSeries fix in #123763 / #118518. No change to this PR is needed; only CH Inc sync is still pending.

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (21e5e8f) to resolve a conflict in ReadFromMergeTree::clone. Master now copies the deferred FINAL filters itself, and it deep-copies deferred_row_level_filter. This branch had its own shallow copy of the same fields, so I kept the master version and removed the duplicate. It builds, and the PR's read-in-order PK-selectivity and deferred-filter stateless tests pass locally. The one exception is 04891_read_in_order_pk_selectivity_clone_runtime_filter, which needs the test_cluster_one_shard_three_replicas_localhost cluster config that my local server did not have.

alexey-milovidov and others added 3 commits October 7, 2026 12:39
# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
#	src/Storages/StorageMerge.cpp
#	src/Storages/StorageMerge.h
`NegativeLimitByTransform` cannot emit any group's last rows before the
end of its input, so a `LIMIT` above a `NegativeLimitByStep` never lets a
read-in-order scan stop early. `limitPushDown` does not push the `LIMIT`
through it today, so the sort below has no bound and the
`read_in_order_max_primary_key_ratio` guard already fires; make
`limitReadsTillEnd` handle it explicitly so the guard does not depend on
that, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The primary-key selectivity guard in `optimizeReadInOrder` was suppressed when
a `LIMIT` sat above the sort, unless that `LIMIT` (or a `LIMIT BY`) had
`always_read_till_end`. But an ordinary `LIMIT BY` can discard an arbitrarily
long prefix of the sorted stream before letting `N` rows through, and the tie
group of the last row of `LIMIT ... WITH TIES` is unbounded, so neither bounds
the read. `limitReadsTillEnd` now returns true for any `LimitByStep` on the path
and for a `LimitStep` with `withTies`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ee` plan serialization

`requestReadingInOrder` stores the SQL `LIMIT` in `query_task_size_limit` to size the
first read task, but a bucketed distributed read only shipped
`input_order_info->limit`, so the worker replayed `requestReadingInOrder` with
`query_limit = 0` and started with a full first task. Add `ReadFromMergeTree` step
version 2 (at global plan version 20) that carries `query_task_size_limit` and feed it
back on deserialize. Towards an older peer it is omitted, which only reads more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 13, 2026 11:24
…FromMergeTree` steps

`query_task_size_limit` is set by `requestReadingInOrder` and is not derived by the
constructor from `query_info.input_order_info`. Steps built from another step's
`query_info` - the non-`FINAL` branch of `optimizeLazyFinal`, `clone`, and
`createLocalParallelReplicasReadingStep` - inherited the read-in-order request but
left the soft limit at zero, so their first task over-read again. Copy it explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ty guard rejects

`requestReadingInOrder` cleared `query_info.input_order_info` to `nullptr` on a real
PK-selectivity rejection. If the step had already been switched to an in-order read by
`optimizeAggregationInOrder` or `optimizeDistinctInOrder` before the later
`optimizeReadInOrder` pass, that dropped the committed order and left an in-order
`AggregatingStep` / `DistinctStep` above a read that no longer advertised ordered input.
Roll back only the tentative order established by this call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MergeTreeDataSelectExecutor::getRowLimits` skips only the estimate-based
`max_rows_to_read` / `max_rows_to_read_leaf` check during index analysis for
ordered reads. The runtime check on rows actually read (applied through
`setStorageLimits`) must stay in effect, as it does on master. Stop clearing
the row limits from the storage limits in `ReadFromMergeTree::initializePipeline`,
and restore the `TOO_MANY_ROWS` assertions in
`02155_read_in_order_max_rows_to_read` and
`01801_approx_total_rows_mergetree_reverse` to their master versions.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100377&sha=c5546386c8b6d702268a86fcd56565974b09d312&name_0=PR&name_1=Stress%20test%20(amd_debug) (Child process was terminated by signal 9 (KILL), likely the OOM killer. In the last 14 days it failed in 38 other PRs and on master) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #125706.

This run is a real memory cgroup OOM kill, not the harness's forced stop: dmesg.log has oom-kill:constraint=CONSTRAINT_MEMCG and Killed process 6844 (clickhouse-serv) ... anon-rss:46998652kB at 05:45:44.

Cause: a fuzzed secondary query of 04035_url_cluster_callback_cancel_race (urlCluster with 3697 streams, 25,902 processors) got an injected MEMORY_LIMIT_EXCEEDED while its ExecutingGraph was being built (05:44:49). PipelineExecutor appended the whole pipeline dump to that exception (2,132,896 bytes in query_log), and since #121503 logProcessorProfile copies the exception text into the processors_profile_log row of every processor. Tracked memory went from 11.3 GiB to 31.2 GiB in the next 14 seconds, the next processors_profile_log flush of 3,011 rows reserved 4.68 GiB, and the server was killed 55 seconds after the exception.

#125706 attaches the dump only to a LOGICAL_ERROR from building the graph, so this error no longer carries it.

The same signature (a processors_profile_log flush reserving 1.1 to 9.6 GiB) is in 11 of the 17 Stress test (*) runs with the signal 9 row since 2026-10-11, including master 9e058f8454f1 (amd_debug) and c7e8cafa0032 (amd_tsan).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

How does it stand regarding to #100394 #100391?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 These PRs come at the same problem from opposite directions. #100391 covers the main case of this PR, and covers it better.

Overlap. This PR's own measurement in the comment on the projection exemption (60M rows, max_threads = 32, path LIKE '%...') shows where the guard helps:

  • 1 part: in-order 1.59 s, fallback 0.88 s.
  • 2 parts: about equal.
  • 4 and 10 parts: in-order is faster.

So the guard only helps with one or very few parts. That is exactly #100391's target, and on the same kind of query (single part, poor primary-key selectivity) it measured: in-order 1.57 s, parallel read + sort 1.27 s, PrefetchingConcat 0.61 s. It also avoids the memory of a full sort.

The description of this PR also no longer matches master. It says "each part is read by a single stream", but spreadMarkRangesAmongStreamsWithOrder already splits parts across up to num_streams streams and puts BufferChunksTransform in front of the merge. The 4x example (9.5 s vs 40 s) needs to be measured again on current master.

If both are merged. The guard runs at planning time, before spreadMarkRangesAmongStreamsWithOrder. When it fires, read-in-order is never requested, so the PrefetchingConcat path cannot apply. Setting the ratio to e.g. 0.5 would replace the 0.61 s plan with the roughly 1.27 s one in #100391's measurement. The PRs would also conflict in the code: requestReadingInOrder, clone / createLocalParallelReplicasReadingStep (both copy query_task_size_limit), optimizeReadInOrder, SortingStep.h and StorageMerge.

What #100391 does not cover:

  • reads in reverse order;
  • filters that stay above the read instead of moving to PREWHERE (they set prefer_multiple_streams);
  • reads with a LIMIT. This PR also skips those.

Proposal:

  1. Merge Parallelize read-in-order from a single part with PrefetchingConcatProcessor #100391, then Parallel read in order with multiple parts #100394.
  2. Measure the original 2.5B-row query again on top of them.
  3. If there is still a gap, narrow this PR to what remains, probably reverse order or the remaining-filter case. Otherwise close it.

The serialization of the read-in-order soft limit (query_task_size_limit, ReadFromMergeTree step version 2, 45e504c) does not depend on the rest of this PR. It can go into its own PR if it is still needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Closing in favor of #100391 and #100394, see #100377 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants