Skip to content

Push LIMIT into aggregation-in-order for early termination - #104859

Merged
thevar1able merged 37 commits into
masterfrom
aggregation-in-order-limit-pushdown
Jun 29, 2026
Merged

thevar1able merged 37 commits into
masterfrom
aggregation-in-order-limit-pushdown

Conversation

@thevar1able

@thevar1able thevar1able commented May 13, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Push LIMIT into aggregation-in-order to enable early termination when GROUP BY key matches ORDER BY key and table sorting key, significantly reducing the number of rows read.

Resolves #105196

image

Version info

  • Merged into: 26.7.1.267 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5564b30]

Summary: ✅


AI Review

Summary

This PR adds default-on LIMIT push-down for aggregation-in-order via optimize_aggregation_in_order_limit, with guards for the previously unsafe plan shapes and focused stateless/performance coverage. The implementation now looks sound for the reviewed in-order aggregation paths, but one public result-metadata contract is still stale: the setting deliberately weakens rows_before_limit_at_least for affected GROUP BY ... ORDER BY ... LIMIT queries while existing Template format docs still promise exactness.

Findings

⚠️ Majors

  • [src/Core/Settings.cpp:4077] optimize_aggregation_in_order_limit is default-on and its setting text says it may reduce rows_before_limit_at_least, but docs/en/interfaces/formats/Template/Template.md and the copied description in src/Processors/Formats/Impl/TemplateRowInputFormat.cpp still say that when a query contains GROUP BY, rows_before_limit_at_least is exact. That violates the user-facing metadata contract for affected GROUP BY ... ORDER BY ... LIMIT queries: Template users can now observe a lower-bound value while the docs promise an exact pre-limit group count. Existing thread: Push LIMIT into aggregation-in-order for early termination #104859 (comment)
    Suggested fix: update both Template descriptions to describe rows_before_limit_at_least as a lower estimate for GROUP BY when early termination is possible, and point users to exact_rows_before_limit when they need the exact count.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: update the stale Template format documentation and generated/copied TemplateRowInputFormat.cpp description so they match the new rows_before_limit_at_least behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 13, 2026
@thevar1able
thevar1able force-pushed the aggregation-in-order-limit-pushdown branch from 4e8d160 to eb6ba21 Compare May 13, 2026 15:36
@groeneai groeneai mentioned this pull request May 16, 2026
1 task
ExpressionStep with ARRAY JOIN does not preserve row count
(its TransformTraits already expose preserves_number_of_rows = !hasArrayJoin),
so unconditionally treating it as transparent could push LIMIT past row-
multiplying actions and under-read.

ExtremesStep preserves row count and order by traits, but it observes the
stream before LIMIT is applied; crossing it would feed it a truncated prefix
and produce wrong extremes output.
@thevar1able
thevar1able marked this pull request as ready for review May 18, 2026 14:01
@Ergus

Ergus commented Jun 2, 2026

Copy link
Copy Markdown
Member

Hi @thevar1able

Let's merge with master to solve the conflicts and retry CI

Comment thread src/Core/Settings.cpp
- [GROUP BY optimization](/sql-reference/statements/select/group-by#group-by-optimization-depending-on-table-sorting-key)
)", 0) \
DECLARE(Bool, optimize_aggregation_in_order_limit, true, R"(
When enabled and aggregation in order is active, pushes LIMIT into the aggregation step to enable early termination after producing enough groups. This reduces the amount of data read when ORDER BY matches the GROUP BY key prefix. May reduce the value reported by `rows_before_limit_at_least`; use `exact_rows_before_limit` if exact counts are needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This default-on optimization changes the public rows_before_limit_at_least contract for GROUP BY ... ORDER BY ... LIMIT: once aggregation stops early, the counter can report only the prefix read instead of the full number of pre-limit groups. The setting text notes that, but docs/en/interfaces/formats/Template/Template.md and the matching TemplateRowInputFormat.cpp description still say that when a query contains GROUP BY, rows_before_limit_at_least is exact. Please update those docs in this PR, or keep the optimization default-off until the public format documentation no longer promises an exact count.

@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 182/183 (99.45%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@thevar1able
thevar1able added this pull request to the merge queue Jun 29, 2026
Merged via the queue into master with commit 4504984 Jun 29, 2026
174 checks passed
@thevar1able
thevar1able deleted the aggregation-in-order-limit-pushdown branch June 29, 2026 21:56
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @thevar1able @Ergus — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

<query>SELECT CounterID, EventDate, count() FROM hits_100m_single GROUP BY CounterID, EventDate ORDER BY CounterID, EventDate LIMIT 10 FORMAT Null</query>

<!-- ORDER BY is a prefix of GROUP BY (GROUP BY has extra non-PK column) -->
<query>SELECT CounterID, EventDate, RegionID, count() FROM hits_100m_single GROUP BY CounterID, EventDate, RegionID ORDER BY CounterID, EventDate LIMIT 10 FORMAT Null</query>

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.

@thevar1able the optimization should be applied as well when the order by is a subset of group by? Should a performance test be added for that? if the columns are not in the same order in both, it should also be applied. Can you confirm this?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jul 14, 2026
Add queries for the cases raised in review of ClickHouse#104859:
`ORDER BY` as a single-column subset of `GROUP BY`, `GROUP BY` columns
permuted relative to the table sorting key, and a permuted `GROUP BY`
with an extra non-key column combined with a subset `ORDER BY`.

Related: ClickHouse#104859 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 23, 2026
The initial implementation #78553 belongs to a different optimization
(top-K heap pruning during aggregation, #96630, not yet merged), not
to the aggregation-in-order LIMIT push-down in #104859.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…n-order LIMIT push-down

Address review feedback from @Ergus on PR ClickHouse#104859:

- `04339_aggregation_in_order_limit_filter`: a row-count-reducing filter
  (both `HAVING` fused into the aggregation and a `WHERE` in an outer
  subquery, i.e. a real `FilterStep`) between the aggregation and the
  outer `LIMIT`. The optimization must not push the limit past the
  filter; the test asserts the result is identical with
  `optimize_aggregation_in_order_limit` on and off.

- `04340_aggregation_in_order_limit_parallel_replicas`: correctness under
  `enable_parallel_replicas = 1`, comparing results with the setting on
  and off. Under parallel replicas the cross-replica merge is a
  `MergingAggregated` over non-final per-replica `Aggregating` steps, so
  the optimization (which requires a final in-order `AggregatingStep` and
  refuses to cross a row-reducing `MergingAggregated`) does not fire on
  the distributed path. The test pins this down.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rder-limit-pushdown

Push LIMIT into aggregation-in-order for early termination
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The initial implementation ClickHouse#78553 belongs to a different optimization
(top-K heap pruning during aggregation, ClickHouse#96630, not yet merged), not
to the aggregation-in-order LIMIT push-down in ClickHouse#104859.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Add queries for the cases raised in review of ClickHouse#104859:
`ORDER BY` as a single-column subset of `GROUP BY`, `GROUP BY` columns
permuted relative to the table sorting key, and a permuted `GROUP BY`
with an extra non-key column combined with a subset `ORDER BY`.

Related: ClickHouse#104859 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimization of GROUP BY with aggregation by sorting key.

5 participants