Repository navigation
Optimize LIMIT BY when BY columns is a prefix of the primary key - #105135
Conversation
|
Workflow [PR], commit [d9ff414] Summary: ✅
AI ReviewSummaryThis PR adds Final VerdictStatus: ✅ Approve |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
| DECLARE(Bool, optimize_distinct_in_order, true, R"( | ||
| Enable DISTINCT optimization if some columns in DISTINCT form a prefix of sorting. For example, prefix of sorting key in merge tree or ORDER BY statement | ||
| )", 0) \ | ||
| DECLARE(Bool, optimize_limit_by_in_order, true, R"( |
There was a problem hiding this comment.
I'm not sure if such new settings should be enabled by default (see #104859 (comment)).
There was a problem hiding this comment.
I think it's fine to keep it on by default. Because of compatibility, old users will start with this optimization turned off anyway so any potential issue will not impact them.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 170/186 (91.40%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code |
6fbc052
…-in-order Master's ClickHouse#105135 added a new `buildInputOrderInfo` overload for `LimitByStep` that calls `buildSortingDAG` with the old 4-argument signature, while this PR extends it with `has_filter_step`/`has_row_reducing_step` out-parameters. Git merged both changes without a textual conflict, leaving a broken call. The FINAL limit pushdown gate is only checked on the `SortingStep` path, so the flags are genuinely unused on the `LIMIT BY` path, matching the other non-FINAL call sites. Co-Authored-By: Claude Fable 5 <[email protected]>
`LIMIT N BY <pk-prefix>` without an `ORDER BY` is driven into read-in-order mode by the `buildInputOrderInfo` overload for `LimitByStep` (added on master in #105135). Unlike the aggregation-in-order and distinct-in-order branches in the same file, it did not call `setPreferMultipleStreams`, so the per-part `PrefetchingConcat` path collapsed the parallel input streams into one per part and serialized the per-key limiting. `LimitByStep::transformPipeline` already handles multiple sorted input streams correctly: with `input_sorted_by_keys` and more than one stream it runs `LimitBySortedStreamTransform` per stream as a prefilter, then does `resize(1)` and a final `LimitByTransform` to dedup across streams. So keeping multiple streams is safe and restores the parallelism, matching the behavior on master before this PR. The `ORDER BY` (`SortingStep`) path intentionally keeps `PrefetchingConcat`, since it wants a single merged sorted stream. This fixes a performance regression that appeared after merging #105135 into this branch: the `limit_by_in_pk_order` performance test became ~2x slower than master on both amd and arm for queries reading in PK order with `LIMIT N BY` of a single key (queries #0, #4, #5, #6, #7), while multi-column `LIMIT BY` (which falls back to the merge path) was unaffected. Verified locally with the merged tree: `EXPLAIN PIPELINE` for `SELECT ... LIMIT 5 BY a` now shows `LimitBySortedStreamTransform * 8` (parallel) instead of a single collapsed stream, while `ORDER BY` still uses `PrefetchingConcat`. The LIMIT BY in-order correctness tests (`04238_limit_by_in_pk_order`, `04257_multi_stream_limit_by_in_order`, the `04054`/`04318` prefetching-concat tests, `02493`, `01551`) all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
buildInputOrderFromUnorderedKeys, the InputOrder builder used by GROUP BY, DISTINCT and LIMIT BY, never consulted KeyDescription::reverse_flags. It hardcoded current_direction = 1 and emitted that into the sort_description it returns, while the ORDER BY sibling builder in the same file computes a reverse_indicator from reverse_flags and multiplies it in. The read side does honour the flags, so the parts arrive with a reversed key column descending while AggregatingStep is handed a description claiming ascending. AggregatingInOrderTransform then runs a direction-aware less inside std::upper_bound, never finds a new group boundary, and collapses a whole run into a single group with a wrong aggregate value. This affects any reversed column inside the matched key prefix, not just the mixed-direction key from the report, and it affects a Merge table over such tables as well. For a Merge table whose children read the matched prefix in opposite physical directions the direction is not knowable as a single value: ReadFromMerge::requestReadingInOrder pushes one InputOrderInfo into every child, each child applies its own reverse_flags, and AggregatingStep hands the same description to every transform. Aggregation in order is therefore declined for that case only. DISTINCT and LIMIT BY keep the optimization there: their transforms compare compareAt(...) != 0, so they are direction-insensitive and correct today. The same change was written and then reverted inside PR ClickHouse#105135 (ff21d56 added it, d021467 reverted it with no rationale). Reading the commit sequence, it was dropped because that PR removed the sorted merge it protected an hour later (c50a62a), i.e. as no longer needed rather than as incorrect; the GROUP BY consumer still performs a direction-aware merge and was never covered by that PR's tests. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&name_0=MasterCI Closes ClickHouse#111901
`LIMIT N BY <pk-prefix>` without an `ORDER BY` is driven into read-in-order mode by the `buildInputOrderInfo` overload for `LimitByStep` (added on master in ClickHouse#105135). Unlike the aggregation-in-order and distinct-in-order branches in the same file, it did not call `setPreferMultipleStreams`, so the per-part `PrefetchingConcat` path collapsed the parallel input streams into one per part and serialized the per-key limiting. `LimitByStep::transformPipeline` already handles multiple sorted input streams correctly: with `input_sorted_by_keys` and more than one stream it runs `LimitBySortedStreamTransform` per stream as a prefilter, then does `resize(1)` and a final `LimitByTransform` to dedup across streams. So keeping multiple streams is safe and restores the parallelism, matching the behavior on master before this PR. The `ORDER BY` (`SortingStep`) path intentionally keeps `PrefetchingConcat`, since it wants a single merged sorted stream. This fixes a performance regression that appeared after merging ClickHouse#105135 into this branch: the `limit_by_in_pk_order` performance test became ~2x slower than master on both amd and arm for queries reading in PK order with `LIMIT N BY` of a single key (queries #0, #4, #5, #6, #7), while multi-column `LIMIT BY` (which falls back to the merge path) was unaffected. Verified locally with the merged tree: `EXPLAIN PIPELINE` for `SELECT ... LIMIT 5 BY a` now shows `LimitBySortedStreamTransform * 8` (parallel) instead of a single collapsed stream, while `ORDER BY` still uses `PrefetchingConcat`. The LIMIT BY in-order correctness tests (`04238_limit_by_in_pk_order`, `04257_multi_stream_limit_by_in_order`, the `04054`/`04318` prefetching-concat tests, `02493`, `01551`) all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Similar to preliminary
DISTINCT,LIMIT BYwill askMergeTreeto read inBYorder.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up
SELECT ... LIMIT N BY <cols>queries when<cols>are a prefix of the table's sorting key, or become one afterWHERE col = constfixes leading columns. With this enabled theMergeTreereads data in primary-key order andLIMIT BYfirst filters in streaming mode with O(1) memory per sorted stream which filters out most of the data, then finally running normalLIMIT BYon reduced data to get the final result. Controlled by the new settingoptimize_limit_by_in_order(enabled by default).Version info
26.6.1.644