Repository navigation
Conversation
… LIMIT BY
`SELECT ... ORDER BY id DESC, ts DESC, seq DESC LIMIT 10` over a 2M-row, 2-part table reads 1,152
rows. Adding `LIMIT 1 BY (id, ts, seq)` makes the identical query read all 2,000,000: nothing below
the `LimitByStep` learns that only a short prefix is wanted, so every reader scans its whole part.
`tryPushDownLimit` cannot move the outer `LimitStep` past `LimitByStep`, and that refusal is correct:
`LIMIT n BY k` consumes an unbounded number of input rows per output row, so a row bound underneath
would drop rows that should have produced output (3 ids of 1000 rows each answer `LIMIT 1 BY (id)
LIMIT 3` with 3 rows, but only 1 with a 3-row bound below). Today the information is simply dropped.
The sound bound is a GROUP count, and the transform that can count groups already sits directly above
the readers: `SortingStep::addPerStreamLimitByIfNeeded` inserts one `LimitBySortedStreamTransform` per
stream, below the `BufferChunksTransform`, and that transform already segments each chunk into
same-key runs. So the outer limit is recorded on `LimitByStep`, forwarded by `pushLimitByIntoSort` to
the sort, and used by the per-stream transform to `stopReading()` once that many groups have been
fully emitted. This mirrors `DistinctStep::limit_hint` and `DistinctSortedStreamTransform`, with
groups substituted for rows. The authoritative single-stream `LimitByStep` above is untouched, so the
per-stream stop only discards rows of groups whose global rank already exceeds the limit.
Three cases must not receive the hint, each measured:
- `always_read_till_end` (e.g. `exact_rows_before_limit`): both LIMIT-BY transforms are registered
as `rows_before_limit` counters, so an early stop would report a truncated count.
- a non-zero `LIMIT BY` offset: a group holding at most `offset` rows yields no output row, so the
number of groups needed is unbounded. Only the new hint is suppressed; the pre-existing per-stream
row pre-cap is offset-correct by widening and keeps working for `LIMIT n OFFSET m BY k`.
- a stateful expression or a `TotalsHavingStep` anywhere in the subtree: a stateful function would
see a different set of rows, and totals are emitted only once the input finishes, so a closed
input yields silently partial totals. `always_read_till_end` does not cover the latter, because
`WITH TOTALS` together with an `ORDER BY` leaves that flag false.
Measured on that fixture: 2,000,000 -> 50,304 read rows for the full key, the same for a strict key
prefix, 2,000,000 -> 327,680 ascending, and 600,000 -> 10,176 through a `Merge` table. Twenty-four
shapes were compared against the unpatched binary and every result is byte-identical, including a
group straddling a chunk boundary, a group spread over three parts, `FINAL`, parallel replicas,
virtual rows, `WITH TIES` and the non-key `LIMIT BY` that must not be optimized.
Reader-layer group-aware early termination remains open; this bounds the read one layer up, inside an
existing transform, without a new upstream-signalling contract.
Related: ClickHouse#113110
Related: ClickHouse#36934
`04238_outer_limit_absent` put `SETTINGS log_comment` on its inner subquery, so the following `read_rows` assertion selected on a comment that no `system.query_log` row carried and returned an empty result instead of a boolean. The committed reference shows it directly: that assertion was one of only two with no value line after it, while every live assertion is followed by `1`. `log_comment` is read from the executing statement's own settings, and only the outer statement produces a `query_log` row, so the fix is to move the clause onto the outer statement. The `count()` result stays `1000000` and the read still covers the whole table, so the assertion now reports `1`. The arm is the regression control for a design that was measured to be wrong: with no outer LIMIT nothing bounds how many groups the read must produce, so no group hint may be recorded. A mutant that forwards a constant non-zero group hint when there is no outer `LimitStep` now fails this assertion, and left it passing before this change. Co-Authored-By: Claude Fable 5 <[email protected]>
The `04238_outer_limit_nonkey` arm placed `SETTINGS log_comment` on its inner subquery, so the `read_rows` assertion that follows selected on a comment that was never recorded and returned zero rows instead of a boolean. It is one of the must-NOT-push controls, so it passed identically whether the pushdown gating worked or was deleted outright. Moving `SETTINGS` onto the outer statement alone is not enough: `uniqExact(z)` equals the row count, so `LIMIT 1 BY (z)` is a pass-through and the plain outer `LimitStep` bounds the read through its own row back-pressure, unrelated to the group hint. Measured 148,032 to 369,216 rows read, so a `> 500000` assertion is deterministically false. Group by `c` instead, which has 7 distinct values. Seven groups cannot satisfy the outer `LIMIT 10`, so the read is unbounded by construction rather than by margin: exactly 1,000,000 rows read at every thread count from 1 to 32. The arm keeps its identity, since `c` is not a sort prefix of `(a, b, c)` and the hash `LimitByTransform` still runs, the same as with `z`. A mechanical audit pairing every `SELECT read_rows` reference line with the line after it now reports ten live assertions and no vacuous one, where it previously reported nine and one.
Internal second-model review (click to expand)Three review rounds, each an independent cold reviewer plus an independent second-model gate. Rounds 1
Round 3 (this round): my own cold review returned 0 findings and Gate B returned 0 findings Test liveness was re-audited mechanically a third time (pair each Session id: cron:clickhouse-review-slot-48:20260805-193900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260805-132500 (implementation); cron:clickhouse-review-slot-48:20260805-193900 (publication) |
|
cc @nihalzp @CurtizJ, could you review this? An outer LIMIT above a sort-prefix LIMIT BY was discarded rather than pushed, since a row bound below LIMIT BY is unsound, so nothing bounded the readers; this carries it as a group count to the per-stream LimitBySortedStreamTransform, which stops once that many groups are fully emitted. |
|
Workflow [PR], commit [2e0a08b] Summary: ✅
AI ReviewSummaryThis PR bounds each sorted stream by the outer Missing context / blind spots
Final VerdictStatus: ✅ Approve |
|
📊 Cloud Performance Report
Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR adds an early stop to the per-stream LIMIT BY that runs inside sorting. It only applies to clickbench🟢 1 improved · Flagged queries (7 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (3 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
The outer-LIMIT fixtures were inserted as a single part. ReadFromMergeTree then derives num_streams from the part count, so the read ran on one stream, and a single stream serves the outer LIMIT from the first granules whether or not a group bound was recorded: read_rows collapsed to 576 for every arm, optimized and not. The `read_rows > 500000` lower bounds on the deliberately not-optimized arms therefore read 0, which is what made the test flaky in the flaky check (7 failures over three build flavours on 213fd07, always a single `-1/+0` assertion flip, never a wrong data row). Splitting the same one million rows over eight parts fixes the stream count at the part count. Measured on the fix binary, every assertion now reads the same value at max_streams_for_merge_tree_reading 1, 2, 4 and 16: outer_limit_full/prefix 82496 (bound < 100000) outer_limit_asc 458752 (bound < 500000) nonkey/offset/absent/exact 1000000 (bound > 500000) stateful_expr/prewhere/filter 1000000 (bound > 500000) The row set and every emitted data row are unchanged, so only the echoed statements move in the reference. The four collapse configurations that reproduce the CI value deterministically (max_streams_for_merge_tree_reading=1, max_threads=1, and a large merge_tree_min_rows/bytes_for_concurrent_read) now all pass; three of the four fail on the previous single-part fixture. On the pristine merge-base binary the test still fails on exactly the three witness assertions it exists to prove (outer_limit_full, _prefix, _asc), so the fixture change does not weaken it.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units195 translation units recompiled, 1366 s compile time in total, 195 of them have a recent master baseline. |
CI finish ledger - 41e0e26Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only 175 check-runs, all completed, 0 queued or in progress,
Neither is caused by this PR. The diff is confined to On the first row: merged #111689 is present at this commit (verified by comparing its merge commit against this head: Session id: cron:our-pr-ci-monitor:20260806-060000 |
|
cc @nihalzp can you review this when you return? It should be quick 🙏 |
|
@nihalzp 🙏 |
CI finish ledger - 1ab4d06Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260908-120121 |
`subtreeBlocksLimitByGroupHint` walked only `node->children`, so a step owning whole plans - `ReadFromMerge` builds one per member table - hid its executable steps from the guard. A `LIMIT n BY <sort prefix>` with an outer `LIMIT` over a `Merge` table then armed the group hint even when a member's stateful expression sat inside a child plan, and `LimitBySortedStreamTransform::stopReading()` truncated that child pipeline. Measured on a `Merge` over two members declaring `s UInt64 ALIAS rowNumberInAllBlocks()`: 82,496 rows read instead of the full 1,000,000, while the same query against a member table directly read all of them; a stateful row policy on one member behaved the same way. The walk now descends into `step->getChildPlans()`, as `PreparedSets.cpp` does for correlated expressions. Nested plans are scanned only from `pushLimitByIntoSort`, where the hint is used. `getChildPlans()` materializes `ReadFromMerge`'s per-table plans and `filterTablesAndCreateChildrenPlans` memoizes them, so scanning them from `tryPushDownLimit` freezes those plans before `applyFilters` prunes the member tables: that way round, `WHERE _table = 'm1'` planned both members and read 541,248 rows instead of 41,248. The plain subtree scan stays in `tryPushDownLimit` as well, because passes between the two sites move steps into fragments they own, where no walk reaches them. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger - cc75c21Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260909-063041 |
|
Fixing PR for the one line in the ledger above ( |
Master's 28fe607 ("Guard LIMIT BY early stop when full input is required") landed on the same five files this branch changes, so five conflicts were semantic rather than textual. Both features are kept: * `LimitByStep::always_read_till_end` (master) marks a `LIMIT BY` whose input must be drained: `GROUP BY ... WITH TOTALS`, `WITH TOTALS` in a subquery of the join tree, or `exact_rows_before_limit` with an outer LIMIT. It suppresses the const-key `stopReading()` and is serialized at plan version 16. * `limit_by_groups_hint` (this branch) is the group bound an outer LIMIT puts on the per-stream sorted `LIMIT BY`, which arms the early stop this branch adds. Resolution: * `SortingStep::updateLimitByHint` takes both the group hint and the flag. * `LimitBySortedStreamTransform` keeps master's `always_read_till_end_` in parameter position 5, so master's three construction sites in LimitByStep.cpp are untouched, and takes `groups_limit_hint_` as a defaulted 6th. * `pushLimitByIntoSort` refuses the group hint when `alwaysReadTillEnd()` is set. The flag is the authoritative signal for "this input must be drained", so it is read directly rather than inferred from plan shape. On the three arms that are observable on a single node the two guards coincide: `GROUP BY a WITH TOTALS ORDER BY a LIMIT 10 BY a LIMIT 10` and the same query with the TOTALS in a subquery both put `TotalsHaving` below the `Sorting`, where the existing stateful-subtree scan already sees it, and `exact_rows_before_limit` makes `LimitStep::alwaysReadTillEnd()` true so no hint is recorded in the first place. With the hint at 0 the transform's own `groups_limit_hint` stop cannot arm, so no second guard is added there. * The group-limit gtest now passes `always_read_till_end_` explicitly: its hint used to be the 5th positional argument and would otherwise have bound to the new flag. Measured on the merged tree: `LIMIT 10 BY a` under `ORDER BY a, b, c LIMIT 10` over a 1M-row, 5-part table reads 286,720 rows with the optimization on and 1,000,000 with it off, so the early stop still fires; the three arms above read 1,000,000. `04238_limit_by_in_pk_order`, master's `05153_limit_by_const_with_totals` and master's `03779_distinct_order_by_limit_by_const_column` all pass, as do the six `LimitBySortedStreamTransform` gtests. The merged index differs from master 015b310 only in the nine files of this PR, and no `contrib/` gitlink moved.
CI finish ledger - 2e585e9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Why #121249 owns it, and why this is not caused by this diff:
Session id: cron:our-pr-ci-monitor:20260923-233131 |
|
Fixing PR for the |
|
Correction for the |
nihalzp
left a comment
There was a problem hiding this comment.
-
Let's gate this optimization behind a new setting.
-
SortingStep::clonecopies the other per-streamLIMIT BYfields but notlimit_by_groups_hint, so a cloned plan silently loses the early stop. -
Let's decide whether the hint applies in one place,
pushLimitByIntoSort. Now the conditions are split between two passes, anddescend_into_child_plansexists only becauseReadFromMerge::getChildPlansbuilds and memoizes its per-table plans before pruning, which is an internal detail of one step. -
LimitByStepnever usesouter_limit_hint; it only carries a value from one pass to the next. With the decision inpushLimitByIntoSort, it can match from the parentLimitand the field goes away. If it stays,updateOuterLimitHintshould keep the smaller value likeDistinctStep::updateLimitHintandSortingStep::updateLimitdo, or be calledsetOuterLimitHint. The comparison withsorted_columns_descrdoes not hold: that field drives the step's own pipeline. -
Let's remove the
TotalsHavingStepbranch fromsubtreeBlocksLimitByGroupHint.limitByAlwaysReadsTillEndalready setsalways_read_till_endonLimitByforWITH TOTALSanywhere in the join tree, including subqueries andUNION, andpushLimitByIntoSortzeroes the hint on that flag.EXPLAINshowsReads all dataonLimitByin all these shapes. -
The new stop in
LimitBySortedStreamTransformignoresalways_read_till_end, unlike the existing stop above it; only the caller keeps the two apart. Let's state it in the constructor withchassert(!groups_limit_hint || !always_read_till_end). -
Let's print the group limit in
SortingStep::describeActions(text and JSON) next toPer-stream LIMIT BY columnsandPer-stream LIMIT BY length. Then the test can check where the hint applies and where it does not withEXPLAIN. -
The
DistinctSteplimit hint in the same function arms the same kind of early stop without a stateful-function guard. If the guard is needed, it is needed for both, so let's make it one helper used by both branches. A good place is a step-level method likeIQueryPlanStep::hasStatefulFunctions, overridden byExpressionStep,FilterStepandSourceStepWithFilterBase:removeRedundantSortingandconvertOuterJoinToInnerJoinTransitivelyrepeat the same per-step checks, and a hard-codedtypeid_castlist misses new steps. -
Let's rename
subtreeBlocksLimitByGroupHint: "blocks" reads as data blocks here, and the function covers two unrelated reasons. Something likesubtreeNeedsCompleteInput. The same value also goes by four names (outer_limit_hint,limit_by_groups_hint,groups_limit_hint,groups_hint); let's use one, e.g.max_groups. -
current_group_rows_seen = 0; ++completed_groups;is repeated at both group boundaries. A smallfinishGroupmakes it explicit that starting a group completes the previous one.
- `pushLimitByIntoSort` reads the `LIMIT` right above the `LIMIT BY` from the traversal stack and decides the group limit there. The `tryPushDownLimit` branch, `LimitByStep::outer_limit_hint` and `descend_into_child_plans` are gone. - New setting `query_plan_limit_by_use_outer_limit`, default 1. - No stateful-function or `TotalsHavingStep` check anymore. `WITH TOTALS` in the query or in its join tree (subquery, `UNION`, `JOIN`) sets `always_read_till_end` on the `LIMIT BY`, which disables the limit. The `DISTINCT` limit hint is seeded from the query's own `LIMIT` in `addDistinctStep` without any stateful-function check, and a plain `LIMIT` stops the read early the same way, so a stateful function under any of them already sees an input cut at an arbitrary point. - `SortingStep::clone` copies the limit, and `describeActions` prints it as `Per-stream LIMIT BY max groups` (JSON `Per-stream LIMIT BY Max Groups`). The test checks with `EXPLAIN` where it applies and where not. - `chassert(!max_groups || !always_read_till_end)` in the `LimitBySortedStreamTransform` constructor, `finishGroup` for both group boundaries, and one name, `max_groups`, for the value. Also merges master, whose per-setting history format the new setting needs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. Addressed in 3f4df73, on top of a master merge (the new setting needs master's per-setting history format):
|
CI finish ledger - 3f4df73Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 152 check runs completed, Session id: cron:our-pr-ci-monitor:20261009-000013 |
|
Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…ance test Master is 26.11 now, so the settings-history check requires the new setting's record under the current version; the 26.10 record would fail the Style check on the next run. The performance test is the query from ClickHouse#131267: 16 overlapping parts, `ORDER BY c2 LIMIT 1 BY c2 LIMIT 200`. Measured with perf.py --runs 15 --stop-merges against master: 0.135 s -> 0.022 s, read_rows 17,472,651 -> 235,520. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's 05020_top_k_through_array_join_explain, added after this branch's last merge, prints the plan of `ORDER BY x LIMIT 1 BY x LIMIT 10`, which now carries the per-stream max groups line; its reference can only be updated on a tree that has the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ORDER BY x LIMIT 1 BY x LIMIT 10` has `Limit` directly above `LimitBy`, so `pushLimitByIntoSort` now arms the per-stream group bound and `SortingStep::describeActions` prints `Per-stream LIMIT BY max groups 10`. The Sorting step stays above `ArrayJoin` in this case, and the results are identical with `query_plan_limit_by_use_outer_limit` 0 and 1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master was bumped to 26.12.1.1 on 2026-11-20 and the 26.11 branch does not have this setting, so `compatibility = '26.11'` must keep it off.
Checks the rows of `ORDER BY ... LIMIT BY ... LIMIT` where each sorted stream stops early: outer `OFFSET`, both sort directions, `LIMIT n BY` with n > 1 and above the outer limit, buffered and unbuffered read in order, `FINAL`, parallel replicas and `remote`. The reference was produced by a master binary with `query_plan_push_limit_by_into_sort = 0`, so it does not depend on the optimization.
|
Took this over on behalf of
Validation with CI binaries, PR head
Results are byte-identical between master, the PR, and the PR with Review: I found no correctness issue. Negative and fractional |
|
📊 Cloud Performance Report
PR verdict: not_sure. 1 measured difference(s) not attributable to this PR. clickbench Q31: The measured difference cannot be attributed to this PR from the available source evidence. Q31 groups by WatchID, ClientIP, then does ORDER BY c DESC LIMIT 10. It has no LIMIT BY clause. In the tested merge c5ee54e7 (PR head 2e0a08b), the only runtime changes are in pushLimitByIntoSort/getLimitByMaxGroups (src/Processors/QueryPlan/Optimizations/limitPushDown.cpp, called from src/Processors/QueryPlan/Optimizations/optimizeTree.cpp), SortingStep::updateLimitByHint/addPerStreamLimitByIfNeeded (src/Processors/QueryPlan/SortingStep.cpp), and LimitBySortedStreamTransform::transform/finishGroup … clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@groeneai Could this also be supported conveniently for negative LIMIT BY? If so, do it in this PR. |
|
Not conveniently in this PR. The group limit stops the per-stream The gain would be real. On an 8-part table with Supporting it means pushing negative
That is a separate optimization, so I would keep it out of this PR, which @ fm4v has already validated. Should I send it as a separate PR once this one is merged? |
Closes: #131267
Related: #113110
Related: #36934
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
An outer
LIMITabove aLIMIT n BYwhose keys are a prefix of the sorting key now bounds how mucheach stream reads, instead of scanning the whole table. On a 1M-row table in 8 parts,
SELECT a, b, c, z FROM t ORDER BY a DESC, b DESC, c DESC LIMIT 1 BY (a, b, c) LIMIT 10reads 82,496rows instead of 1,000,000. Controlled by the new setting
query_plan_limit_by_use_outer_limit.Description
LIMIT n BY kcan consume any number of input rows per output row, so the outerLIMITis not pushedbelow it, and nothing bounds the readers: each stream reads its whole part.
When the
LIMIT BYkeys are a sort prefix,pushLimitByIntoSortalready adds a per-streamLimitBySortedStreamTransformright above each reader. With aLIMIT m OFFSET odirectly above theLIMIT BY, it now also passesmax_groups = m + o: the result has rows from at most that many groups,and every later group of a stream sorts after that stream's first
max_groups, so the transform callsstopReading()once it has completed that many. The single-streamLimitByStepabove still applies thereal
LIMIT BY.max_groupsstays 0 when the input must be read to the end (always_read_till_endon either step, e.g.exact_rows_before_limitorWITH TOTALS), withWITH TIES, and with aLIMIT BYoffset (a group ofat most
offsetrows yields no row).EXPLAIN actions = 1shows it asPer-stream LIMIT BY max groups.Validated by
04238_limit_by_in_pk_order(EXPLAINfor each case above, plusread_rowsfor thereported shape) and a gtest for groups that span chunks.
The performance test
limit_by_into_sort_outer_limitruns the query from #131267 on 16 parts: againstmaster,
perf.pymeasured 0.135 s -> 0.022 s and 17,472,651 -> 235,520 rows read. The second workloadreported there reads 931,840 rows instead of 19,054,296. Queries without an outer
LIMITread the same rows.Reader-layer group-aware early termination (#36934) remains open, hence
Relatedfor it.Measured read rows, setting on vs off (1M rows, 8 parts,
ORDER BY (a, b, c))ORDER BY a DESC, b DESC, c DESC LIMIT 1 BY (a, b, c) LIMIT 10LIMIT 1 BY (a)(strict key prefix)LIMIT 10 OFFSET 5LIMIT 2 OFFSET 1 BY (a),WITH TIES, no outerLIMITexact_rows_before_limit = 1,WITH TOTALSResults are byte-identical with the setting on, off, and with
query_plan_push_limit_by_into_sort = 0for ten shapes at
max_threads1, 4 and 16 (30 of 30).Workflow [PR]
Sync PR [sync-upstream/pr/113565]