Skip to content

Optimize LIMIT BY by pushing down LIMIT BY into Sort - #104000

Merged
nihalzp merged 22 commits into
ClickHouse:masterfrom
nihalzp:pushdown-limit-by
May 25, 2026
Merged

nihalzp merged 22 commits into
ClickHouse:masterfrom
nihalzp:pushdown-limit-by

Conversation

@nihalzp

@nihalzp nihalzp commented May 4, 2026 •

Copy link
Copy Markdown
Member

ORDER BY ... LIMIT BY queries currently sort and merge all rows from every stream into a single stream before the final LIMIT BY drops the per-key excess rows. This PR adds a per-stream LIMIT BY inside the sort pipeline when LIMIT BY's columns are a prefix of the ORDER BY. Each parallel sort stream applies LIMIT BY to itself in cheap in-order mode (O(1) memory per stream). Then final merge and subsequent steps then sees only (group_length + offset) × num_streams × distinct_keys rows instead of the entire input.

EXPLAIN PIPELINE
SELECT number % 100 AS k, number AS v
FROM numbers_mt(1000000)
ORDER BY k, v LIMIT 2, 3 BY k;
    ┌─explain────────────────────────────────────┐
 1. │ (Expression)                               │
 2. │ ExpressionTransform                        │
 3. │   (LimitBy)                                │
 4. │   LimitByTransform (InOrder)               │
 5. │     (Expression)                           │
 6. │     ExpressionTransform                    │
 7. │       (Sorting)                            │
 8. │       MergingSortedTransform 15 → 1        │
 9. │         LimitByTransform (InOrder) × 15    │ <- newly added
10. │           MergeSortingTransform × 15       │
11. │             LimitsCheckingTransform × 15   │
12. │               PartialSortingTransform × 15 │
13. │                 (Expression)               │
14. │                 ExpressionTransform × 15   │
15. │                   (ReadFromSystemNumbers)  │
16. │                   NumbersRange × 15 0 → 1  │
    └────────────────────────────────────────────┘
image 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 ORDER BY ... LIMIT BY queries by running LIMIT BY inside each parallel sorted stream during Sort when LIMIT BY's columns are a prefix of the ORDER BY. This reduces the number of rows flowing through the final sort merge and any downstream pipeline steps. This optimization is controlled by the new setting query_plan_push_limit_by_into_sort (enabled by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.131

@clickhouse-gh

clickhouse-gh Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e6abe5]

Summary: ✅


AI Review

Summary

This PR introduces query_plan_push_limit_by_into_sort and pushes per-stream in-order LimitByTransform into SortingStep when LIMIT BY keys are a prefix of ORDER BY. I reviewed the current diff and all prior discussion threads; previously raised concerns are addressed in the current code (including preserving zero-row chunks in LimitByTransform), and I did not find remaining correctness, safety, or contract issues.

Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Contributor

This PR adds a per-stream LIMIT BY inside the sort pipeline when LIMIT BY's columns are a prefix of the ORDER BY.

This is only restriction for in order LIMIT BY? and for normal, we could push any LIMIT BY to sorting step. (Yeah, in that case it will need to build hash table, but it will be build in any case for top limit by statement)

@nihalzp

nihalzp commented May 4, 2026

Copy link
Copy Markdown
Member Author

This is only restriction for in order LIMIT BY?

Yes, this optimization will only work if LIMIT BY is prefix of ORDER BY.

and for normal, we could push any LIMIT BY to sorting step. (Yeah, in that case it will need to build hash table, but it will be build in any case for top limit by statement)

The difference is that for normal case (LIMIT BY is not a prefix of ORDER BY), if we push down LIMIT BY, we will have num_streams hash tables instead of only one hash table (top LIMIT BY). In the worst case scenario: uniform and high cardinality scenario, these num_streams hash table can each contain all unique keys causing memory limit exceeded. Once we have external LIMIT BY, we can generalize it.

@alexey-milovidov alexey-milovidov 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.

Perfect!

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp
@nihalzp

nihalzp commented May 16, 2026

Copy link
Copy Markdown
Member Author

@alexey-milovidov The PR only optimizes the case when LIMIT BY is a prefix of ORDER BY. But same push down can be done for any general case as well (regardless of it's a prefix or not). Is it worth doing for the general case too?

My concern was excessive memory usage during worst case scenario when we have extremely high cardinality data but this case should be quite rare.

@nihalzp

nihalzp commented May 17, 2026

Copy link
Copy Markdown
Member Author

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@nihalzp

nihalzp commented May 18, 2026

Copy link
Copy Markdown
Member Author

@groeneai Why AST fuzzer (amd_debug) (Assertion `px != 0' failed (STID: 2286-2cea)) is failing? Try to produce a reproduction.

@groeneai

Copy link
Copy Markdown
Collaborator

@nihalzp Here is what I found. Short version: the failure is unique to this PR run on commit 66e1bac24c92 (today's master merge), the crashing query does not exercise the new LIMIT BY pushdown optimization at all, and the Assertion 'px != 0' failed signature has hit 7 unrelated PRs / 14 times in the last 60 days with zero master hits — looks like a chronic AST-fuzzer-only flake. I do not see a causal link to the LIMIT BY pushdown changes, but I cannot rule out a subtle interaction with something that landed on master between your two master merges.

CIDB cross-PR analysis

Filtered to last 60 days on default.checks:

Signature Hits PRs Master hits
STID: 2286-2cea (this one) 1 only #104000 0
STID: 2286-* family (broader) 1 only #104000 0
Assertion 'px != 0' (any STID) 14 7 unrelated PRs 0
ExtremesTransform + dumpStructure + AST fuzzer 1 only #104000 0

PR-specific runs on #104000:

Commit Date Result
a468307d (initial) 2026-05-04 PASS
e6cc8f9 (after first master merge) 2026-05-16 PASS
66e1bac24c (after Alexey's master merge) 2026-05-17 FAIL (STID 2286-2cea)

Two prior runs of the same PR passed the AST fuzzer cleanly — only the run on the latest master-merge commit failed.

The actual crashing query

The AST fuzzer log times out (kills clickhouse-client) before recording the offending query, but the server log preserves it. The crashing query (query 12, log line 12416216 in server.log.zst):

SELECT DISTINCT 1025, toFixedString('%', 1048576), 100
UNION ALL
SELECT 9223372036854775807, '\0', materialize(toLowCardinality(1025))

This query has:

  • SELECT DISTINCT over UNION ALL
  • A 1 MB constant FixedString(1048576) in one arm
  • A materialized LowCardinality column in the other arm
  • No LIMIT BY, no ORDER BY, no LIMIT

The pipeline trace from the same log confirms ExtremesTransform was in the pipeline (i.e. extremes = 1 was active for this query), and the abort happened in the planner→execute transition (10-minute gap between the planner trace and the next log line, after clickhouse-server: ... Assertion 'px != 0' failed.).

I grep'd the full 6.9 M-line fuzzer.log for LIMIT.*BY and got zero matches — i.e. the AST fuzzer corpus for this run never produced a LIMIT BY query, so neither pushLimitByIntoSort (gated on LimitByStep) nor addPerStreamLimitByIfNeeded (gated on !limit_by_columns.empty()) fired during the entire run.

Why the stack trace is misleading

The visible stack is the exception-message-formatting path, not the underlying bug:

Chunk::dumpStructure() const                  Chunk.cpp:163   ← `column->dumpStructure()` deref of null intrusive_ptr
Chunk::checkNumRowsIsConsistent()             Chunk.cpp:66    ← throw with dumpStructure() as fmt arg
Chunk::setColumns(MutableColumns, UInt64)     Chunk.cpp:56
ExtremesTransform::work()                     ExtremesTransform.cpp:52

So:

  1. ExtremesTransform::work() calls extremes.setColumns(std::move(extremes_columns), 2).
  2. checkNumRowsIsConsistent() detects column->size() != 2 for at least one column.
  3. It throws LOGICAL_ERROR; constructing the message calls dumpStructure().
  4. dumpStructure() iterates columns and dereferences each via column->dumpStructure().
  5. A different column in the same vector is a null intrusive_ptr<IColumn> → boost::intrusive_ptr::operator->() fires its BOOST_ASSERT(px != 0).

So extremes_columns ended up with at least one entry whose size != 2 and at least one null entry. Looking at ExtremesTransform::transform(), every code path assigns a non-null column with size 2 to every index after the initial resize(num_columns) (either cloneResized(2) for const, or cloneEmpty() + insert(min) + insert(max) for non-const). Under the documented contract this state should be unreachable.

Why I don't think this is your PR

  1. The failing query has no LIMIT BY / ORDER BY → neither pushLimitByIntoSort nor addPerStreamLimitByIfNeeded runs.
  2. No LIMIT BY query appears anywhere in the 6.9 M-line fuzzer log → the new optimization was inert for this entire fuzzer run.
  3. Your PR does not touch ExtremesTransform, LimitByTransform, Chunk, or any code on the failure path.
  4. Assertion 'px != 0' AST-fuzzer hits have been spread across 7 unrelated PRs in the last 60 days with 0 master hits. STID sub-codes differ (0250-3d88, 2286-2cea, 1288-31a1, 1288-3bd5), but all share the same boost intrusive_ptr null-deref pattern.
  5. Two prior runs of this PR (commits a468307d, e6cc8f9) passed the AST fuzzer cleanly.

What I'd suggest

  • Just rebase / merge master again and re-run. Empirically, two of three runs on this PR have been clean, and this signature family doesn't reproduce on master at all.
  • If the assertion comes back on the next run with a similar ExtremesTransform → dumpStructure stack, ping me and I'd suggest treating it as a chronic AST-fuzzer bug separate from this PR. A reasonable hypothesis on the trigger family: extremes = 1 + UNION ALL with very-large-FixedString / LowCardinality(...) shapes producing degenerate chunks in ExtremesTransform::transform. I have not been able to localize this to a deterministic repro yet.

Artifacts I used (for anyone reproducing):

[session: cron:clickhouse-ci-task-worker:20260518-141500]

@nihalzp

nihalzp commented May 18, 2026

Copy link
Copy Markdown
Member Author

@groeneai Create a PR trying to fix the issue.

@groeneai

Copy link
Copy Markdown
Collaborator

Hi @nihalzp — opened a fix PR: #105264.

Root cause for Assertion 'px != 0' failed (STID: 2286-2cea): ExtremesTransform::transform, on the first chunk, resizes extremes_columns to N null entries and fills them column by column. The AST fuzzer triggered MEMORY_LIMIT_EXCEEDED (4 MiB max_memory_usage) inside insert of the 1 MiB FixedString value, leaving extremes_columns half-populated — leading indices held size-2 columns, the failing index held a column with fewer than 2 rows, trailing indices were still null. During pipeline shutdown ExtremesTransform::prepare advanced to Finished, then returned Ready because !extremes && !extremes_columns.empty(). work then called extremes.setColumns(std::move(extremes_columns), 2), the row-count check tripped, and Chunk::dumpStructure (called to format the error) dereferenced one of the null intrusive pointers — boost::intrusive_ptr<IColumn>::operator->, assertion px != 0.

Deterministic reproducer that abort'd master before the fix and now returns a normal MEMORY_LIMIT_EXCEEDED to the client:

SELECT DISTINCT 1025, toFixedString('%', 1048576), 100
UNION ALL
SELECT 9223372036854775807, '\0', materialize(toLowCardinality(1025))
SETTINGS extremes = 1, max_memory_usage = '4Mi'
FORMAT Null;

Fix builds into a local MutableColumns and moves into extremes_columns only on success, so a throw during construction leaves the member in its valid empty state.

The other PRs with Assertion 'px != 0' reports (STID 0250-3d88 in hasPhrase.cpp, STID 1288-3bd5 / 1288-31a1 in SummingSortedAlgorithm::postprocessChunk) are different root causes in unrelated code paths — they share only the boost::intrusive_ptr null-check assertion symptom.

This is independent of the LIMIT BY pushdown work in #104000.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request May 20, 2026
…ation

`ExtremesTransform::transform` resized `extremes_columns` to `N` null entries
on the first chunk and filled them one column at a time. If any step inside the
loop threw — for example `MEMORY_LIMIT_EXCEEDED` raised by `insert` while
copying a large value into the freshly cloned column — the member was left in
a half-populated state: leading indices held size-2 columns, the failing index
held a column with fewer than 2 rows, and trailing indices were still null.

The exception flowed downstream via `ISimpleTransform::work`'s `catch` block,
the input port was closed during pipeline shutdown, and
`ExtremesTransform::prepare` then ran `ISimpleTransform::prepare` to
`Status::Finished`, set `finished_transform = true`, and returned `Ready`
because `!extremes && !extremes_columns.empty()`. `work` then called
`extremes.setColumns(std::move(extremes_columns), 2)`. The row-count check
inside `Chunk::checkNumRowsIsConsistent` spotted the short column, tried to
format the error via `Chunk::dumpStructure`, dereferenced one of the still-null
intrusive pointers, and aborted the server with
`Assertion 'px != 0' failed (STID: 2286-2cea)` on
`boost::intrusive_ptr<IColumn>::operator->`.

The fix builds into a local vector and moves into the member only on success.
A throw during construction destroys the local vector during stack unwinding
and leaves `extremes_columns` empty, which is the documented "no chunk
processed yet" state. `work` no longer materialises a partial chunk and the
client receives a normal `MEMORY_LIMIT_EXCEEDED` (or whatever the original
exception was) instead of a server crash.

Reference CI report:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/104000/66e1bac24c924afddb3c58be48a8174b37f0f2e3/ast_fuzzer_amd_debug/
Reported via PR: ClickHouse#104000

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.20% +0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 89.47% (102/114) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue May 25, 2026
Merged via the queue into ClickHouse:master with commit 825bf32 May 25, 2026
166 checks passed
@nihalzp
nihalzp deleted the pushdown-limit-by branch May 25, 2026 18:10
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 25, 2026
DavidHe-2008 pushed a commit to DavidHe-2008/ClickHouse that referenced this pull request Jun 1, 2026
Optimize `LIMIT BY` by pushing down `LIMIT BY` into `Sort`
@PedroTadim

Copy link
Copy Markdown
Member

Hello! There is an optimization of pushing ORDER BY LIMIT into GROUP BY. Does this optimization also reflect with LIMIT BY?

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.

7 participants