Skip to content

Bound the MergeTree read when an outer LIMIT sits above a sort-prefix LIMIT BY - #113565

Open
groeneai wants to merge 16 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-by-group-limit-hint-113110
Open

groeneai wants to merge 16 commits into
ClickHouse:masterfrom
groeneai:groeneai/limit-by-group-limit-hint-113110

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131267
Related: #113110
Related: #36934

Changelog category (leave one):

  • Performance Improvement

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

An outer LIMIT above a LIMIT n BY whose keys are a prefix of the sorting key now bounds how much
each 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 10 reads 82,496
rows instead of 1,000,000. Controlled by the new setting query_plan_limit_by_use_outer_limit.

Description

LIMIT n BY k can consume any number of input rows per output row, so the outer LIMIT is not pushed
below it, and nothing bounds the readers: each stream reads its whole part.

When the LIMIT BY keys are a sort prefix, pushLimitByIntoSort already adds a per-stream
LimitBySortedStreamTransform right above each reader. With a LIMIT m OFFSET o directly above the
LIMIT BY, it now also passes max_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 calls
stopReading() once it has completed that many. The single-stream LimitByStep above still applies the
real LIMIT BY.

max_groups stays 0 when the input must be read to the end (always_read_till_end on either step, e.g.
exact_rows_before_limit or WITH TOTALS), with WITH TIES, and with a LIMIT BY offset (a group of
at most offset rows yields no row). EXPLAIN actions = 1 shows it as Per-stream LIMIT BY max groups.

Validated by 04238_limit_by_in_pk_order (EXPLAIN for each case above, plus read_rows for the
reported shape) and a gtest for groups that span chunks.

The performance test limit_by_into_sort_outer_limit runs the query from #131267 on 16 parts: against
master, perf.py measured 0.135 s -> 0.022 s and 17,472,651 -> 235,520 rows read. The second workload
reported there reads 931,840 rows instead of 19,054,296. Queries without an outer LIMIT read the same rows.

Reader-layer group-aware early termination (#36934) remains open, hence Related for it.

Measured read rows, setting on vs off (1M rows, 8 parts, ORDER BY (a, b, c))
shape off on
ORDER BY a DESC, b DESC, c DESC LIMIT 1 BY (a, b, c) LIMIT 10 1,000,000 82,496
+ LIMIT 1 BY (a) (strict key prefix) 1,000,000 82,496
ascending 1,000,000 458,752
LIMIT 10 OFFSET 5 1,000,000 82,496
LIMIT 2 OFFSET 1 BY (a), WITH TIES, no outer LIMIT 1,000,000 1,000,000
exact_rows_before_limit = 1, WITH TOTALS 1,000,000 1,000,000

Results are byte-identical with the setting on, off, and with query_plan_push_limit_by_into_sort = 0
for ten shapes at max_threads 1, 4 and 16 (30 of 30).


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

groeneai and others added 3 commits August 5, 2026 14:51
… 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.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Three review rounds, each an independent cold reviewer plus an independent second-model gate. Rounds 1
and 2 found and fixed test defects; this round found nothing in either channel.

# Round Finding Verdict
⚠️ r1 Two must-NOT-push controls put SETTINGS log_comment on an inner subquery, so their read_rows assertions selected on a comment that was never recorded and returned zero rows instead of a boolean. Both would pass whether the producer's gating worked or was deleted outright. Agreed, fixed. SETTINGS moved onto the outer statement.
⚠️ r2 The prescribed repair for one of those two arms made the test fail: uniqExact(z) = 1000000 makes LIMIT 1 BY (z) a pass-through, so the plain outer LIMIT bounds the read on both binaries. Agreed, fixed. Re-keyed on a 7-distinct-value column, which cannot satisfy LIMIT 10 and so reads the whole table at every thread count 1..32.
⚠️ r2 A claim in this gate comment said "50 randomized runs of 04238 … 210/210". 04238 and 04257 carry the long tag, so the runner capped them at int(50 x 0.1) = 5. Agreed, corrected. Re-run at --long-test-runs-ratio 1.0: a true 50 invocations of each of the six tests, 300/300 here and 50 of 50 04238 invocations failing on the unpatched binary.
💡 r2 "13 cases" in row (d) was not reproducible against any predicate. Agreed, replaced with three measured counts (10 new log_comment arms, 10 read_rows assertions, 56 added executable statements).
❌ r1 gate Asked to pass the group hint at LimitByStep::transformPipeline's three construction sites so single-stream plans get it too. Declined with measurement. That is mutant M8: 576 rows where 1,000,000 are correct, because there the transform is the authoritative LIMIT BY, not a pre-filter. Its premise also fails: optimizePrimaryKeyConditionAndLimit already calls setLimit on the reading step from the outer LimitStep, and LimitTransform::preparePair closes every input at rows_read >= offset + limit, which reaches the reader in a single-stream plan with no buffer interposed. The multi-stream case was the defect precisely because BufferChunksTransform absorbs that back-pressure.
❌ r1 gate Asked to extend the subtree guard to SourceStepWithFilterBase::filter_actions_dag and ObjectFilterStep. Declined with measurement. Dead code twice over: that field is populated only by applyFilters(), whose sole plan-optimization caller runs in the second pass while this guard runs in the first, so it is null when the guard walks; and it is the index-analysis DAG, where KeyCondition already refuses stateful DAGs. ObjectFilterStep::updatePipeline is return std::move(pipelines.front()): it inserts no transform and evaluates nothing.
❌ r2 gate Asked for a read-count assertion on the WITH TOTALS arm. Declined with measurement. Not constructible: under the guard-removal mutant that arm reads 200,000/200,000 and returns correct totals, because a blocking AggregatingTransform sits between the transform and the readers. Positive control on the same mutant binary: the plain LIMIT BY shape over the same table reads 11,584/200,000. The requested assertion would be a vacuous arm added to satisfy a finding about vacuity.
❌ r2 gate Asked for read-count assertions on the chunk-straddling and multi-part arms. Declined with measurement. The straddling arm reads 4,464 on both binaries by design: it proves the stop does not truncate a group, so a read-count assertion there would assert a non-event. The multi-part arm already is a both-directions pair (90,000 base vs 57,232 here, byte-identical results). The completion predicate itself is pinned by five gtest arms, with a measured reason why SQL cannot pin it: a server-reachable chunk holds far more groups than the hint, so the stopping chunk is the first one either way.
❌ r1 own A reviewer's own finding that the hint setter is not monotone (the sibling DistinctStep::updateLimitHint takes the min). Withdrawn on re-derivation, and re-derived independently in r3: apply_prelimit requires !hasLimitBy(), so no preliminary LimitStep ever coexists with a LIMIT BY; the arm reads only its own directly adjacent parent, so a re-visit writes the identical value. A larger hint could only delay the stop.

Round 3 (this round): my own cold review returned 0 findings and Gate B returned 0 findings
(diffstats matched exactly; prior review state was injected, so there was nothing left to echo).
Independently enumerated carriers beyond the plan's own list, all resolving to no change:
a bare OFFSET cannot reach the new arm (addLimitStep is called only under hasLimit(), and the old
analyzer's executeLimit opens if (query.limitLength()), so a bare OFFSET is an OffsetStep);
NegativeLimitByStep is a sibling class with its own transform, so typeid_cast<LimitByStep *> cannot
match it; arrayJoin above the sort is inherited for free because the existing hasArrayJoin() bail
returns before the new hint transfer; the new SortingStep field is deliberately absent from both
describeActions overloads, so the three existing tests asserting Per-stream LIMIT BY in EXPLAIN
see byte-identical output.

Test liveness was re-audited mechanically a third time (pair each read_rows reference echo with the
line following it, require a bare 0/1): 10 live, 0 vacuous.

Session id: cron:clickhouse-review-slot-48:20260805-193900

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 2M-row, 2-part table with ORDER BY (id, ts, seq), SELECT seq FROM t ORDER BY id DESC, ts DESC, seq DESC LIMIT 1 BY (id, ts, seq) LIMIT 10 reads 2,000,000 rows on unpatched master and 50,304 here, 5 runs of 5 identical on each binary. Oracle: system.query_log.read_rows keyed by query_id.
b Root cause explained? tryPushDownLimit cannot move the outer LimitStep past LimitByStep, which is correct because LIMIT n BY k consumes an unbounded number of input rows per output row. The information was then discarded, so nothing bounded the readers. The sound bound is a group count, and LimitBySortedStreamTransform already counts group boundaries directly above the readers.
c Fix matches root cause? Yes: the outer limit is recorded on LimitByStep, forwarded to the sort, and used by the per-stream transform to stopReading() after that many groups complete. No widened bound, no no-random-* tag, no dataset reduction, no guard at a crash site.
d Test intent preserved / new tests added? 04238_limit_by_in_pk_order gains 10 new read_rows-asserting arms (10 distinct new log_comment values) over 5 new fixture tables, 56 added executable statements in total; no existing case was changed or weakened. New gtest_limit_by_sorted_stream_group_limit.cpp with 5 arms. 03701_limit_by_in_order deliberately untouched.
e Both directions demonstrated? Yes. 04238 passes 3/3 on this branch and fails 3/3 on the unpatched binary, differing on exactly the three optimized-shape assertions. 50 randomized runs of 04238 plus the five sibling limit_by_in_order tests (--test-runs 50 --long-test-runs-ratio 1.0 --order random, a true 50 invocations of each of the six): 300/300 pass here; on the unpatched binary 50 of 50 04238 invocations fail and the other 250 pass, every failure being the same three optimized-shape assertions.
f Fix is general across code paths? The hint reaches the transform only at the one site where it is a pre-cap (SortingStep.cpp:301). The three sites where the same transform is the authoritative LIMIT BY (LimitByStep.cpp:64/:85/:128) keep the default 0; arming them returns 576 rows where 1,000,000 are correct, so the scoping is measured, not assumed. The hash variant LimitByTransform has no contiguity guarantee and is untouched; NegativeLimitByStep is a sibling class, so typeid_cast<LimitByStep *> cannot match it.
g Fix generalizes across inputs (params/datatypes/wrappers)? 24 shapes measured on both binaries: full key vs strict prefix, DESC vs ASC, non-key LIMIT BY, with and without an outer LIMIT, with and without an outer ORDER BY, OFFSET, WITH TIES, exact_rows_before_limit, WITH TOTALS with and without an ORDER BY, FINAL, parallel replicas, virtual rows, ReadFromMerge, a group straddling a chunk boundary, a group spread over three parts, many tiny groups, and one group of 3,000 rows. Every result is byte-identical.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, the new LimitByStep field is not serialized, and the new ctor parameter defaults to 0 at the three untouched sites, so no SettingsChangesHistory.cpp entry is owed. pushLimitByIntoSort's existing length + offset computation and its updateLimitByHint call are unchanged apart from one new argument, so the pre-existing per-stream row pre-cap behaves exactly as today, LIMIT n OFFSET m BY k included.
i Invariants and contracts preserved? A group counts as complete only once a strictly different key follows it, so a group split across chunks is counted once and the trailing rows of the last in-limit group are never cut off; two gtest arms pin exactly that, and counting on entry instead reddens three of them. rows_before_limit_at_least is protected by the always_read_till_end bail (dropping it reddens the exact_rows_before_limit arm). Totals are protected by the TotalsHavingStep arm of the subtree predicate. The stop is evaluated after the runs loop and before the existing empty-output early return, so a chunk that reaches the hint is still emitted whole.

Session id: cron:clickhouse-impl-slot-4:20260805-132500 (implementation); cron:clickhouse-review-slot-48:20260805-193900 (publication)

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e0a08b]

Summary: ✅


AI Review

Summary

This PR bounds each sorted stream by the outer LIMIT when the LIMIT BY keys form a sorting-key prefix, controlled by query_plan_limit_by_use_outer_limit. It preserves the final LIMIT BY and excludes cases requiring more groups or complete input. No actionable findings remain after reviewing the current diff, surrounding execution code, all prior threads and replies, and the regression coverage. The existing performance artifacts confirm the intended benefit: 0.1132 s → 0.0208 s on amd and 0.1253 s → 0.0205 s on arm.

Missing context / blind spots
  • ⚠️ Full CI for head 2e0a08bafce86a8584c59071869c0c0b803cf895 is still pending. The completed CI report and performance artifacts cover d79ad7d0e8333e71e8404cf7807af71c3610a448; they do not establish current-head test success. No tests were executed locally because this checkout has no ClickHouse binary or build directory. Let current-head CI complete before merging.
Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) improved out of 32 analysed

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 ORDER BY ... LIMIT BY ... LIMIT queries, and no flagged ClickBench or TPC-H query uses LIMIT BY. All ten flagged improvements are on code paths the diff does not touch. Nine are downgraded to not sure. ClickBench Q32 (-45.3%) stays an improvement only because the change is too large to override, but it is not attributable to this PR either. The improvements are broad, CPU-backed and centered on aggregation, which suggests the older base build (26.9 vs 26.10) rather than this change. The benchmark set has no LIMIT BY query, so the intended speedup was not measured here.

clickbench

🟢 1 improved · ⚠️ 6 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 32 improvement 1342 734 -45.3% <0.0001 aggregation: The -45.3% change is large enough to lock the verdict. This query has no LIMIT BY and never reaches the changed code, so the gain most likely comes from the base build being older, not from this PR.
⚠️ 16 not_sure 616 508 -17.6% <0.0001 aggregation: This GROUP BY ... ORDER BY ... LIMIT query has no LIMIT BY, so the new per-stream group stop never runs. The -17.6% is not attributable to this PR.
⚠️ 18 not_sure 1064 813 -23.6% <0.0001 aggregation: A heavy GROUP BY with no LIMIT BY clause, so the changed sort/LIMIT BY path is not executed. The -23.6% does not come from this diff.
⚠️ 30 not_sure 235 207 -11.9% <0.0001 aggregation: This query does not use LIMIT BY, so the outer-limit group stop cannot apply. The -11.9% is off-path for this PR.
⚠️ 31 not_sure 308 256 -16.9% <0.0001 aggregation: A GROUP BY with ORDER BY and LIMIT but no LIMIT BY, so pushLimitByIntoSort never sets a hint. The -16.9% is not caused by this change.
⚠️ 33 not_sure 1236 1056 -14.6% <0.0001 aggregation: A high-cardinality GROUP BY with no LIMIT BY, so the changed transform is never built. The -14.6% is not attributable to this diff.
⚠️ 34 not_sure 1244 1045 -16.0% <0.0001 aggregation: Same shape as Q33, a GROUP BY with no LIMIT BY, so the change does not apply. The -16.0% is off-path.

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

⚠️ 3 inconclusive

Flagged queries (3 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 66 53 -19.7% <0.0001 aggregation: TPC-H Q1 is a plain aggregation with no LIMIT BY, and the query is historically noisy. The -19.7% is not from this PR.
⚠️ 7 not_sure 82 61 -25.6% <0.0001 join_operator: Q7 is a join-plus-aggregation query with no LIMIT BY, so the changed path is not executed. The query is historically noisy.
⚠️ 17 not_sure 100 60 -40.0% <0.0001 join_operator: Q17 uses a correlated subquery with joins and no LIMIT BY, so the change cannot reach it. The base measurements were also very noisy.

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
  • StressHouse run: b417c686-5aa5-42e8-acea-c11f55e15fd8
  • MIRAI run: d440d2f7-487d-4594-819a-f2fb4f2c74fb
  • PR check IDs:
    • clickbench_408145_1791484128
    • clickbench_408151_1791484128
    • clickbench_408157_1791484128
    • tpch_adapted_1_official_408164_1791484128
    • tpch_adapted_1_official_408179_1791484128
    • tpch_adapted_1_official_408215_1791484128

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2e0a08baf with master 4aa16c68a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

195 translation units recompiled, 1366 s compile time in total, 195 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 41e0e26

Every 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 CH Inc sync is exempt, and there is no such row on this head.

175 check-runs, all completed, 0 queued or in progress, Finish Workflow = success, 159 success / 14 skipped / 2 failures.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: 'Got read request from replica 1 for unknown stream <db>.aj_big' (STID 5217-5b3d) trunk parallel-replicas coordinator failure, 220 rows over 183 distinct pull requests plus 17 on master in 30 days a fix task is in progress (fixing PR link to follow on this PR)
Stress test (amd_msan) / Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID 2508-30f6) trunk column-type assertion in the join additional-filter path, 115 rows over 97 distinct pull requests plus 10 on master in 30 days #113534 (external, open)

Neither is caused by this PR. The diff is confined to LimitByStep, limitPushDown, SortingStep, LimitByTransform, one gtest and one stateless test; it contains no parallel-replicas or join code, and no frame of it appears in either stack.

On the first row: merged #111689 is present at this commit (verified by comparing its merge commit against this head: behind_by = 0), and the failure still occurs, so that PR does not cover this occurrence and is deliberately not linked as the owner here.

Session id: cron:our-pr-ci-monitor:20260806-060000

@PedroTadim

Copy link
Copy Markdown
Member

cc @nihalzp can you review this when you return? It should be quick 🙏

@nihalzp nihalzp self-assigned this Aug 11, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@egorvas

egorvas commented Sep 3, 2026

Copy link
Copy Markdown

@nihalzp 🙏

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@groeneai

groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1ab4d06

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Hung check failed, possible deadlock found Code-241 memory-accounting drift, not caused by this branch: 62 of 62 hung-check probes were refused with (total) memory limit exceeded: would use 65.44 GiB, attempt to allocate chunk of 0.00 B, current RSS: 2.60 GiB, maximum: 47.43 GiB, so the rejection is on the tracked figure while real RSS sits ~45 GiB below the cap. Zero stacks and zero hung queries were collected, so the leaf never reached system.processlist and it evidences no deadlock in either direction. Discriminator measured on this head: 62 zero-byte refusals, 0 Found hung queries blocks, 0 query_kind rows. Breadth for this test name on this check: 133 rows / 113 pull requests / 10 master runs in 30 days; family-wide across all 12 stress flavours: 1,057 rows and 101 master runs. This branch touches only LimitByStep, limitPushDown, SortingStep, LimitByTransform and two test files a fix task is created (fixing-PR link to follow on this PR)

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]>
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cc75c21

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: Method A not implemented for B (STID 3897-3dc9) Server abort on an ordinary SET statement, on a path this branch cannot reach. FieldFromASTImpl::throwNotImplemented fires from Field::operator== inside SettingsConstraints::checkImpl, called from InterpreterSetQuery::execute under the HTTP handler, so the whole stack is settings-constraint checking and never enters the query pipeline. The comparison site in getNewValueToCheck (src/Access/SettingsConstraints.cpp) predates this branch by about five months, while this branch touches only LimitByStep, limitPushDown, SortingStep, LimitByTransform and two test files. Breadth for this assertion text: 1 row, 1 pull request, 0 master runs in 90 days, so it is the first CIDB observation of the shape and not a recurring one. The aggregators Mergeable Check and PR are red only because they report this leaf (Failed: Stress test (arm_release)) a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260909-063041

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the one line in the ledger above (Stress test (arm_release), Method == not implemented for AST, STID 3897-3dc9): #118993. It implements FieldFromASTImpl::operator ==, which the unchanged-value test in SettingsConstraints::getNewValueToCheck reached without an implementation. This branch is unaffected by it.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2e585e9

Every 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 CH Inc sync is exempt, and it is green here.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) the log scan reddens on a single MutateFromLogEntryTask line: Code: 40 CHECKSUM_DOESNT_MATCH ... Part all_0_0_0_2 from 2 has different columns hash (it may rarely happen on race condition with KILL MUTATION) ... Data after mutation is not byte-identical to data on another replicas. We will download merged part from replica to force byte-identical result. The recovery is handled by the server; the log ENTRY alone is what fails the job. The job's other 13 legs are OK, including The mutation submitted before the upgrade was finished by the new server #121249 (mine, open)
Mergeable Check, PR praktika rollups, red only because they report the leaf above #121249 (mine, open)

Why #121249 owns it, and why this is not caused by this diff:

Session id: cron:our-pr-ci-monitor:20260923-233131

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_release) / Hung check failed, possible deadlock found row in the CI finish ledger for 1ab4d065: #122154 (mine, open). In that run the AST fuzzer called mergeTreeAnalyzeIndexesUUID with a vector search limit of 2147483648 at 11:57:03.96 (server time), 0.8 s before the first (total) memory limit exceeded. The mechanism is in #117681 (comment). #118094 (external, merged) additionally makes the global tracker re-baseline from measured memory on every tick.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Correction for the Upgrade check (amd_release) row in the CI finish ledger: #121249 does not fix it, since the columns hash does not depend on the codec. Fixing PR: #123376.

@nihalzp nihalzp 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.

  • Let's gate this optimization behind a new setting.

  • SortingStep::clone copies the other per-stream LIMIT BY fields but not limit_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, and descend_into_child_plans exists only because ReadFromMerge::getChildPlans builds and memoizes its per-table plans before pruning, which is an internal detail of one step.

  • LimitByStep never uses outer_limit_hint; it only carries a value from one pass to the next. With the decision in pushLimitByIntoSort, it can match from the parent Limit and the field goes away. If it stays, updateOuterLimitHint should keep the smaller value like DistinctStep::updateLimitHint and SortingStep::updateLimit do, or be called setOuterLimitHint. The comparison with sorted_columns_descr does not hold: that field drives the step's own pipeline.

  • Let's remove the TotalsHavingStep branch from subtreeBlocksLimitByGroupHint. limitByAlwaysReadsTillEnd already sets always_read_till_end on LimitBy for WITH TOTALS anywhere in the join tree, including subqueries and UNION, and pushLimitByIntoSort zeroes the hint on that flag. EXPLAIN shows Reads all data on LimitBy in all these shapes.

  • The new stop in LimitBySortedStreamTransform ignores always_read_till_end, unlike the existing stop above it; only the caller keeps the two apart. Let's state it in the constructor with chassert(!groups_limit_hint || !always_read_till_end).

  • Let's print the group limit in SortingStep::describeActions (text and JSON) next to Per-stream LIMIT BY columns and Per-stream LIMIT BY length. Then the test can check where the hint applies and where it does not with EXPLAIN.

  • The DistinctStep limit 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 like IQueryPlanStep::hasStatefulFunctions, overridden by ExpressionStep, FilterStep and SourceStepWithFilterBase: removeRedundantSorting and convertOuterJoinToInnerJoinTransitively repeat the same per-step checks, and a hard-coded typeid_cast list misses new steps.

  • Let's rename subtreeBlocksLimitByGroupHint: "blocks" reads as data blocks here, and the function covers two unrelated reasons. Something like subtreeNeedsCompleteInput. 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 small finishGroup makes it explicit that starting a group completes the previous one.

groeneai and others added 2 commits October 8, 2026 13:44
- `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]>
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Addressed in 3f4df73, on top of a master merge (the new setting needs master's per-setting history format):

  • New setting query_plan_limit_by_use_outer_limit, default 1.
  • SortingStep::clone now copies the group limit.
  • The decision is made only in pushLimitByIntoSort, which reads the LIMIT right above the LIMIT BY from the traversal stack. outer_limit_hint, the tryPushDownLimit branch and descend_into_child_plans are gone.
  • The TotalsHavingStep branch is removed. EXPLAIN shows Reads all data on LimitBy for WITH TOTALS in the query, in a subquery, a UNION and a JOIN. A view or view() with WITH TOTALS does not set the flag, but there the sort above the aggregation is a full sort that drains its input first, and the totals stay exact.
  • chassert(!max_groups || !always_read_till_end) in the constructor.
  • describeActions prints Per-stream LIMIT BY max groups (JSON Per-stream LIMIT BY Max Groups). The test now checks with EXPLAIN where it applies and where it does not, plus one read_rows check for the reported shape.
  • Stateful functions: I dropped the guard instead of extending it. addDistinctStep seeds the DISTINCT hint from the query's own LIMIT with no such check, so a guard in tryPushDownLimit would only cover a hint coming from an outer query, and a plain LIMIT also stops the read at an arbitrary point under a stateful function. None of the existing early stops guard it, and this one now matches them. If you prefer to keep a guard, I can add IQueryPlanStep::hasStatefulFunctions as you described.
  • The walk you asked to rename went away with the guard. The value is max_groups everywhere (limit_by_max_groups as a SortingStep member, next to limit_by_group_length).
  • Added finishGroup.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3f4df73

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Duplicate announcement received for replica number A (STID 8765-6e14) not from this PR, which changes only the LIMIT BY plan steps: the parallel replicas coordinator aborts in handleInitialAllRangesAnnouncement, reached from createLocalPlanForParallelReplicas inside a nested read built by MergeTreeAnalyzeIndexSource / buildOrderedSetInplace. The same STID fired on 25 other PRs and 1 master run in 30 days #115916 (mine, open)
Mergeable Check, PR rollups of the row above #115916 (mine, open)

All 152 check runs completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261009-000013

@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

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.

groeneai and others added 6 commits November 14, 2026 04:54
…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.
@fm4v

fm4v commented Nov 20, 2026

Copy link
Copy Markdown
Member

Took this over on behalf of fm4v (maintainer edits). Pushed on top of a master merge (6f18bb6c692):

  • c9e1aaa2f3f: the history entry of query_plan_limit_by_use_outer_limit is now 26.12. Master was bumped to 26.12.1.1 on 2026-11-20 and the 26.11 branch does not have the setting, so compatibility = '26.11' must keep it off.
  • 2e0a08bafce: new test 05839_limit_by_outer_limit_results checks the rows (not only EXPLAIN) where the group limit stops a stream early: outer OFFSET, ascending and descending order, LIMIT n BY with n > 1 and above the outer limit, read_in_order_use_buffering on and off, FINAL, parallel replicas and remote. The reference was produced by a master binary with query_plan_push_limit_by_into_sort = 0, so it is independent of the optimization. EXPLAIN on the PR binary shows Per-stream LIMIT BY max groups in all these shapes, including the remote and parallel replicas plans.

Validation with CI binaries, PR head d79ad7d0 vs master 253dc40d (its merge base), amd_release, 5 runs each, max_threads = 8:

Query master read_rows master median PR read_rows PR median
2 parts, ORDER BY id DESC, ts DESC, seq DESC LIMIT 1 BY (id, ts, seq) LIMIT 10 967,808 to 1,696,896 94 ms 50,304 32 ms
4 parts, ORDER BY k LIMIT 1 BY k LIMIT 100, read_in_order_use_buffering = 1 8,813,108 to 12,000,000 579 ms 1,242,771 144 ms
same, read_in_order_use_buffering = 0 1,962,270 240 ms 1,242,771 192 ms

Results are byte-identical between master, the PR, and the PR with query_plan_limit_by_use_outer_limit = 0. 04238_limit_by_in_pk_order passes on the PR binary and fails its new read_rows and EXPLAIN checks on master. The CI performance test limit_by_into_sort_outer_limit was 5.4x faster on amd and 6.1x on arm with no slower or unstable queries.

Review: I found no correctness issue. Negative and fractional LIMIT are separate steps and are not matched, WITH TIES, a LIMIT BY offset and read-till-end are excluded, an outer OFFSET is covered by getLimitForSorting (limit + offset, 0 on overflow), and clone copies the field. All review threads are resolved; the only open question from the 2026-10-08 review is whether to keep a stateful-function guard, which the author answered above.

@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 29 queries analysed

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 …

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 226 201 -11.1% <0.0001 aggregation: 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 …

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
  • StressHouse run: f2965f78-c7f9-4f63-9e35-a6cc87dcba24
  • MIRAI run: 52ba98b8-5525-4276-9345-42fa64843988
  • PR check IDs:
    • clickbench_552609_1795211362
    • clickbench_552615_1795211362
    • tpch_adapted_1_official_552654_1795211362
    • tpch_adapted_1_official_552675_1795211362

@nihalzp

nihalzp commented Nov 21, 2026

Copy link
Copy Markdown
Member

@groeneai Could this also be supported conveniently for negative LIMIT BY? If so, do it in this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Not conveniently in this PR. The group limit stops the per-stream LIMIT BY that pushLimitByIntoSort puts into the sort, and negative LIMIT BY never gets one: pushLimitByIntoSort matches only LimitByStep, and NegativeLimitByStep resizes to one stream and runs after the merge. So there is no per-stream transform for the limit to stop.

The gain would be real. On an 8-part table with ORDER BY (id, ts, seq) (2M rows, master e627fea5), ORDER BY id DESC, ts DESC, seq DESC LIMIT -1 BY id LIMIT 10 reads all 2,000,000 rows, as LIMIT 1 BY id LIMIT 10 does without this PR, against 33,920 rows without LIMIT BY. EXPLAIN PIPELINE has no per-stream transform under BufferChunks, where the positive query has one LimitBySortedStreamTransform per stream.

Supporting it means pushing negative LIMIT BY into the sort first:

  • a per-stream NegativeLimitBySortedStreamTransform in SortingStep. This is sound because the merge keeps each stream's order, so every row among the last n rows of a group is among the last n rows of that group in its own stream. On that table, a per-part LIMIT -n BY (_part, id) before the final LIMIT -n BY id returns the same rows for n = 1, 2, 3;
  • an early stop in that transform, which is an IInflatingTransform and has no stopReading;
  • always_read_till_end on NegativeLimitByStep, with a new plan serialization version, like the one LimitByStep uses to keep WITH TOTALS exact.

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?

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

query_plan_push_limit_by_into_sort=1: ORDER BY k LIMIT 1 BY k LIMIT N reads 3x more rows (2.6x slower)

6 participants