Skip to content

Stop reading input in aggregate-free GROUP BY ... LIMIT once enough keys are found - #126490

Open
raimannma wants to merge 14 commits into
ClickHouse:masterfrom
raimannma:group-by-limit-no-aggregates-early-stop
Open

raimannma wants to merge 14 commits into
ClickHouse:masterfrom
raimannma:group-by-limit-no-aggregates-early-stop

Conversation

@raimannma

@raimannma raimannma commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #110047

optimize_trivial_group_by_limit_query already caps an aggregate-free GROUP BY ... LIMIT n at n + offset keys, but the aggregation kept reading its whole input after the cap was reached. Now Aggregator::checkLimits stops a stream once it is over the cap when there are no aggregate functions, and for the trivial GROUP BY ... LIMIT shape the first stream over the cap stops all the others, since it alone holds enough keys for the LIMIT. On a 200M-row MergeTree table, SELECT k FROM t GROUP BY k LIMIT 10 reads about 2M rows instead of 200M (5-70x faster depending on the key and WHERE); queries outside this shape are unchanged.

Changelog category (leave one):

  • Performance Improvement

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

A GROUP BY ... LIMIT query without aggregate functions, such as SELECT a, b FROM t GROUP BY a, b LIMIT 10, now stops reading the table as soon as it has found enough distinct keys.


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

… keys are found

`OptimizeTrivialGroupByLimitPass` caps an aggregate-free `GROUP BY ... LIMIT n` at
`max_rows_to_group_by = n + offset` with `group_by_overflow_mode = 'any'`, but
`AggregatingTransform` kept pulling the whole input after the cap was reached,
although every later block was a no-op for the aggregation. So the source, `WHERE`
and the key expressions still ran over all the data.

- `Aggregator::checkLimits` now returns `false` in `ANY` mode when there are no
  aggregate functions, like `BREAK`: the rest of the input cannot change the result.
- With the new `Aggregator::Params::stop_all_streams_on_overflow_any`, set by the
  planner for the trivial `GROUP BY ... LIMIT` shape, the first stream over the cap
  makes all the other streams stop as well, because it alone already holds enough
  keys for the `LIMIT`. A stream waiting for input (e.g. behind a filter that drops
  all its rows) sees the flag only when its next chunk arrives.

Closes: ClickHouse#8777
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 17, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ae1f3f]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
04780_json_subcolumn_index_match_not_quadratic FAIL cidb

AI Review

Summary

PR #126490 stops aggregate-free GROUP BY ... LIMIT queries once a stream holds enough distinct keys, including ordered aggregation, projections, and serialized plans. At head 7ae1f3fd46c3b5a34a10a76b65cc75d30a262253, all four prior findings are addressed and no new actionable findings remain. The focused 05408_trivial_group_by_limit_stops_reading regression passed in Fast test; broader CI is still running.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 18, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Interpreters/Aggregator.h Resolved
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Oct 18, 2026
…lized plans

Two review findings:
- The stop fired only when a stream exceeded `max_rows_to_group_by`, so an input with
  exactly `LIMIT + OFFSET` distinct keys was still read to the end. With the flag, a
  stream now stops as soon as it has `max_rows_to_group_by` keys.
- `AggregatingStep` did not serialize the flag, so under `serialize_query_plan = 1` the
  remote node only stopped the streams over the cap. It is now the plan setting
  `aggregation_stop_all_streams_at_max_rows_to_group_by`, which needs the query-plan
  serialization version 21 (the bump of release 26.11).

The flag is renamed to `stop_all_streams_at_max_rows_to_group_by`.
Review comment: ClickHouse#126490 (comment)

A shared flag did not stop a sibling `AggregatingTransform` waiting in `NeedData`, e.g.
behind a filter that drops all its rows: the executor prepares a processor again only after
a port update, so that stream kept reading until the end of its input.

Now a `StopAllStreamsTransform` passes each stream into its aggregation. When the aggregation
stops reading early, it sends a chunk to a `StopAllStreamsSignal` processor connected to all
the streams, which finishes the signal inputs of every `StopAllStreamsTransform`. Each of them
then finishes its stream, which wakes the waiting aggregation. The data path stays per stream,
so there is no shared processor on it.
…ection pipelines

Found by the local codex review:
- With external aggregation, a block bringing a stream to exactly `max_rows_to_group_by`
  keys could be spilled before the stop was checked, emptying the table, so the stream never
  stopped. The check moves to `Aggregator::checkLimits`, which runs before the spill decision,
  after the overflow check so that `OverflowAny` is still counted.
- `AggregatingProjectionStep` created separate stop groups for the pipelines of the ordinary
  parts and of the projection parts, although both feed one aggregation. They now share one.
…h keys

Found by the local codex review: `StopAllStreamsTransform` finished silently as soon as its
input ended, possibly before the aggregation consumed the last chunk. If that chunk brought the
aggregation to the cap, the other streams were not told to stop. Now at the end of the input it
waits until the consumer either asks for more data (finish silently) or closes the port (stop
all the streams).
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7ae1f3fd4 with master 3f2770fd6 (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.

Object file sizes

53 object files changed (+135.01 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/StopAllStreamsTransform.cpp.o new 129.04 KiB +129.04 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

200 translation units recompiled, 1387 s compile time in total, 199 of them have a recent master baseline.

Job report

raimannma and others added 4 commits October 19, 2026 19:24
Review comment: ClickHouse#126490 (comment)

`AggregatingInOrderTransform` does not check `max_rows_to_group_by`, so with
`optimize_aggregation_in_order` an aggregate-free `GROUP BY ... LIMIT` read the whole input.
For this shape it now gets `max_rows_to_group_by` as its limit hint without an `ORDER BY`
prefix, so it may stop at any group, also inside a run of equal sorting keys, and the streams
stop together through `StopAllStreamsTransform`.
…wn_limit

The test measures the rows read on the shards to check the push down of `LIMIT`, which
`optimize_trivial_group_by_limit_query` now reduces also with aggregation in order.
…-aggregates-early-stop

# Conflicts:
#	src/Core/ProtocolDefines.h
…-aggregates-early-stop

# Conflicts:
#	src/Planner/Planner.cpp
raimannma and others added 2 commits November 22, 2026 16:45
…... LIMIT`

The table with the projection did not fix `index_granularity`, unlike the other
tables of the test. The flaky check randomized it to 12, so the insert of 5M rows
wrote about 416k granules and took 256 s under the thread fuzzer, and the test ran
longer than 180 s.

ClickHouse#126490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stresshouse

stresshouse Bot commented Nov 22, 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 Q28: The measured difference cannot be attributed to this PR from the available source evidence. I checked the tested merge 968fd2dc against its first parent b79c41c2. In src/Planner/PlannerSteps.cpp, addAggregationStep sets stop_all_streams_at_max_rows_to_group_by only when aggregates_size == 0, group_by_overflow_mode is ANY and getTrivialGroupByLimit applies. Q28 has AVG/COUNT/MIN plus HAVING and ORDER BY, so none of those conditions hold and the flag stays false. In src/Processors/QueryPlan/AggregatingStep.cpp, the StopAllStreams transforms …

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1006 1132 +12.5% <0.0001 The measured difference cannot be attributed to this PR from the available source evidence. I checked the tested merge 968fd2dc against its first parent b79c41c2. In src/Planner/PlannerSteps.cpp, addAggregationStep sets stop_all_streams_at_max_rows_to_group_by only when aggregates_size == 0, group_by_overflow_mode is ANY and getTrivialGroupByLimit applies. Q28 has AVG/COUNT/MIN plus HAVING and ORDER BY, so none of those conditions hold and the flag stays false. In src/Processors/QueryPlan/AggregatingStep.cpp, the StopAllStreams transforms …

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: 78d91611-a668-436a-9b56-66d243a629c6
  • MIRAI run: 2cf2e170-11ef-4b82-9dd2-661aa4f2c66c
  • PR check IDs:
    • clickbench_823556_1795368224
    • clickbench_823563_1795368224
    • tpch_adapted_1_official_823577_1795368224
    • tpch_adapted_1_official_823606_1795368224

@rschu1ze

Copy link
Copy Markdown
Member

@raimannma I think the optimize_trivial_group_by_limit_query optimization is conceptually a subset of the enable_group_by_top_k_optimization optimization. What do you think about

  • moving/integrating the first one into the second one (step 1), and
  • implementing early out within enable_group_by_top_k_optimization (step 2, only if it does not already work).

@raimannma

Copy link
Copy Markdown
Contributor Author

@raimannma I think the optimize_trivial_group_by_limit_query optimization is conceptually a subset of the enable_group_by_top_k_optimization optimization. What do you think about

  • moving/integrating the first one into the second one (step 1), and
  • implementing early out within enable_group_by_top_k_optimization (step 2, only if it does not already work).

Thanks, not sure if I understood you right. @rschu1ze
I don't think the trivial cutoff is a subset of top-K. Top-K returns the n smallest groups, so it has to read the whole input while the trivial shape only needs any n groups.

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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GROUP BY … LIMIT N (no aggregates, no ORDER BY) should early-terminate the read like SELECT DISTINCT … LIMIT N

3 participants