Repository navigation
Disable read-in-order when primary key selectivity is poor - #100377
alexey-milovidov wants to merge 219 commits into
Conversation
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]>
|
Workflow [PR], commit [44faf57] Summary: ✅
AI ReviewSummaryPR #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 Findings
Tests
Missing context / blind spots
Final Verdict |
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]>
….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]>
# Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp
|
🕵 Merged master (21e5e8f) to resolve a conflict in |
# 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]>
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]>
…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]>
|
🕵 @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) ( |
|
The fix is in progress: #125706. This run is a real memory cgroup OOM kill, not the harness's forced stop: Cause: a fuzzed secondary query of #125706 attaches the dump only to a The same signature (a |
|
🕵 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,
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, The description of this PR also no longer matches If both are merged. The guard runs at planning time, before What #100391 does not cover:
Proposal:
The serialization of the read-in-order soft limit ( |
|
🕵 Closing in favor of #100391 and #100394, see #100377 (comment). |
When the WHERE clause cannot use the primary key effectively (e.g.,
LIKE '%...'), theoptimize_read_in_orderoptimization kills parallelism: each part is read by a single stream instead of many. This can makeORDER BYqueries 4x slower than the same query withoutORDER BY.Example on a 2.5B row table with
ORDER BY pathandWHERE path LIKE '%stderr.log':optimize_read_in_order = 0: ~9.6sThe 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-streamPartialSortingTransform+MergeSortingTransform, so the output is still sorted as theSortingStepabove expects.New setting
read_in_order_max_primary_key_ratiocontrols 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):
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_ratiothat 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 likeSELECT ... 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
New setting
read_in_order_max_primary_key_ratio(Float, default 1.0): maximum ratio of selected to total primary key granules foroptimize_read_in_orderto 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]