Skip to content

Optimize LIMIT BY when BY columns is a prefix of the primary key - #105135

Merged
nihalzp merged 42 commits into
ClickHouse:masterfrom
nihalzp:limit-by-in-pk-order
Jun 11, 2026
Merged

nihalzp merged 42 commits into
ClickHouse:masterfrom
nihalzp:limit-by-in-pk-order

Conversation

@nihalzp

@nihalzp nihalzp commented May 16, 2026 •

Copy link
Copy Markdown
Member

Similar to preliminary DISTINCT, LIMIT BY will ask MergeTree to read in BY order.

CREATE TABLE t (a UInt32, b UInt32, c UInt32) ENGINE = MergeTree ORDER BY (a, b, c);
INSERT INTO t SELECT number % 1000, number % 97, number % 7 FROM numbers(10000);

EXPLAIN PIPELINE SELECT a, b, c FROM t WHERE c > 2 LIMIT 5 BY a, b
SETTINGS optimize_limit_by_in_order = 1;
   ┌─explain───────────────────────────────────────────────────────────────┐
1. │ (Expression)                                                          │
2. │ ExpressionTransform                                                   │
3. │   (LimitBy)                                                           │
4. │   LimitByTransform (InOrder)                                          │ <- streaming, was: LimitByTransform
5. │     (Expression)                                                      │
6. │     ExpressionTransform                                               │
7. │       (Expression)                                                    │
8. │       ExpressionTransform                                             │
9. │         (ReadFromMergeTree)                                           │
10.│         MergeTreeSelect(pool: ReadPoolInOrder, algorithm: InOrder) 0→1│ <- read-in-order pool
   └───────────────────────────────────────────────────────────────────────┘
image image image

Changelog category (leave one):

  • Performance Improvement

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 after WHERE col = const fixes leading columns. With this enabled the MergeTree reads data in primary-key order and LIMIT BY first filters in streaming mode with O(1) memory per sorted stream which filters out most of the data, then finally running normal LIMIT BY on reduced data to get the final result. Controlled by the new setting optimize_limit_by_in_order (enabled by default).

Version info

  • Merged into: 26.6.1.644

@clickhouse-gh

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9ff414]

Summary: ✅


AI Review

Summary

This PR adds optimize_limit_by_in_order so LIMIT BY can request MergeTree reads in sorting-key order when the BY keys form a value-ordered prefix, including compatible permutations and fixed leading key columns. The current head addresses the earlier multi-stream correctness, reverse-key merge direction, stale sort-property, and setting-description issues; I did not find any remaining blocker or major finding in the changed code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 1ad45b5c-ae92-41a6-b543-a88dfe9c6c20
  • MIRAI run: 8043bc1b-f780-4d4c-8d95-e04a6829f984
  • PR check IDs:
    • clickbench_210689_1781127231
    • clickbench_210842_1781127265
    • clickbench_210948_1781127371
    • tpch_adapted_1_official_210968_1781127371
    • tpch_adapted_1_official_211119_1781127403
    • tpch_adapted_1_official_211240_1781127491

Comment thread src/Core/Settings.cpp Resolved
@nihalzp
nihalzp requested a review from thevar1able June 9, 2026 13:34

@thevar1able thevar1able left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

Comment thread src/Core/Settings.cpp
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"(

@thevar1able thevar1able Jun 10, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not sure if such new settings should be enabled by default (see #104859 (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 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.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.30% +0.10%

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

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit 6fbc052 Jun 11, 2026
326 of 328 checks passed
@nihalzp
nihalzp deleted the limit-by-in-pk-order branch June 11, 2026 11:43
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 11, 2026
alexey-milovidov added a commit to amosbird/ClickHouse that referenced this pull request Jun 12, 2026
…-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]>
alexey-milovidov added a commit that referenced this pull request Jun 16, 2026
`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]>
JiaQiTang98 pushed a commit to JiaQiTang98/ClickHouse that referenced this pull request Sep 4, 2026
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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants