Skip to content

Add OptimizeTrivialGroupByLimitPass - #104473

Merged
alexey-milovidov merged 26 commits into
masterfrom
trivial-group-by-limit
May 14, 2026
Merged

alexey-milovidov merged 26 commits into
masterfrom
trivial-group-by-limit

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 9, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Added OptimizeTrivialGroupByLimitPass. For trivial SELECT ... FROM t GROUP BY k LIMIT n queries (no HAVING, ORDER BY, or window functions), the analyzer now sets max_rows_to_group_by = n + offset with group_by_overflow_mode = 'any', so aggregation stops once n distinct keys have been produced instead of grouping the entire input. Controlled by the new setting optimize_trivial_group_by_limit_query (enabled by default).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Why

For SELECT k FROM t GROUP BY k LIMIT 5, ClickHouse currently aggregates the entire input before applying the LIMIT, even though the user clearly only wants 5 distinct keys. By the semantics of GROUP BY ... LIMIT, any 5 distinct keys are a valid answer — so we can stop aggregation as soon as 5 distinct keys exist.

What changed

  • New analyzer pass OptimizeTrivialGroupByLimitPass.
  • New setting optimize_trivial_group_by_limit_query (default 1) to gate the pass.
  • The pass fires only when the query has GROUP BY and a LIMIT, and has no HAVING, ORDER BY, or window clauses; it would change observable results for those.
  • The pass is suppressed when the user has already set a non-zero max_rows_to_group_by, so it never overrides an explicit overflow contract.

Origin

Split out from WIP PR #81944.

Version info

  • Merged into: 26.5.1.647

For `SELECT col FROM t GROUP BY col LIMIT n` queries with no `HAVING`,
`ORDER BY`, or window clauses, set `max_rows_to_group_by = n + offset`
and `group_by_overflow_mode = 'any'` so the aggregation stops once `n`
distinct keys have been produced, instead of grouping the entire input.

Saves I/O and aggregation work for trivial top-N enumerations.

Setting: `optimize_trivial_group_by_limit_query` (default: enabled).

The optimization is suppressed when the user already provides a
non-zero `max_rows_to_group_by`, so this analyzer pass never overrides
an explicit overflow contract.

Originally part of WIP PR #81944.
@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5f5cc42]

Summary: ✅


AI Review

Summary

This PR introduces OptimizeTrivialGroupByLimitPass and related tests/settings to stop aggregation early for trivial GROUP BY ... LIMIT shapes. Most previously raised correctness issues are addressed in the current code, but one contract violation remains: explicit max_rows_to_group_by can still be silently overridden in a way that changes exception behavior.

Findings
  • ❌ Major: [src/Analyzer/Passes/OptimizeTrivialGroupByLimitPass.cpp:88] user_max_rows > max_rows is currently treated as safe, but with default group_by_overflow_mode = 'throw' this pass can still suppress a user-expected TOO_MANY_ROWS exception by forcing group_by_overflow_mode = 'any' and lowering max_rows_to_group_by to LIMIT + OFFSET. This violates explicit overflow contracts when users set non-zero max_rows_to_group_by.
  • Suggested fix: preserve explicit max_rows_to_group_by contracts as well (for example, skip optimization when settings[Setting::max_rows_to_group_by].changed && settings[Setting::max_rows_to_group_by] != 0, or at minimum when mode is not explicitly any).
Final Verdict

Status: ⚠️ Request changes

Minimum required action:

  1. Preserve explicit max_rows_to_group_by overflow contracts so the optimization cannot suppress TOO_MANY_ROWS for users who intentionally configured non-zero max_rows_to_group_by.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 9, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
- Guard `limit + offset` against `UInt64` overflow with `common::addOverflow`;
  on overflow the optimization is skipped so query results are not silently
  truncated (e.g. `LIMIT 18446744073709551615 OFFSET 100` would otherwise wrap
  to `99` and bound aggregation to the wrong number of distinct keys).
- Set `previous_value` to `false` for the new default-on
  `optimize_trivial_group_by_limit_query` setting in `SettingsChangesHistory`,
  per the file-level convention, so the `compatibility` setting can disable
  the new optimization for older versions.
- Add a regression test for the overflow case.
Number `04212` was taken by `04212_input_no_create_temp_grant` after
merging master, so renumber to the next free prefix.
`WITH ROLLUP`, `WITH CUBE`, `WITH GROUPING SETS`, and `WITH TOTALS`
emit additional subtotal/total rows; forcing `max_rows_to_group_by`
with `group_by_overflow_mode = 'any'` would silently drop groups and
corrupt those rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Does it work correctly with multiple threads? I'm concerned, because the set of first keys could be different in different threads.

alexey-milovidov and others added 2 commits May 10, 2026 22:04
The optimization sets `max_rows_to_group_by = LIMIT + OFFSET` with
`group_by_overflow_mode = 'any'`. That check is enforced per-thread,
so when the projection contains an aggregate function, threads can
drop rows for keys not in their own first-N set and the kept keys
end up with undercounted aggregate states.

This test exhibits the bug: with the optimization enabled, kept keys
get count values around 2500 instead of the true 10000.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…functions

The per-thread `max_rows_to_group_by` check is enforced independently
in each aggregating thread. With `group_by_overflow_mode = 'any'`,
threads keep only the first `LIMIT + OFFSET` distinct keys they see
and drop rows for any other key. If two threads end up with
intersecting-but-different key sets, the aggregate states for a kept
key receive only contributions from the threads that kept it.

For `GROUP BY ... LIMIT n` without aggregate functions in the
projection the optimization is still safe: any `n` distinct keys is
a valid answer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 2 commits May 10, 2026 23:03
The pass now skips queries whose projection contains aggregate functions,
so the description was misleading. Reword it to describe the actual
shape of queries the optimization fires for: a trivial `GROUP BY key
LIMIT n` with no aggregate functions in the projection, no `HAVING`,
`ORDER BY`, or window clauses, and no `GROUP BY` modifiers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test uses `max_block_size = 1` to force the per-thread
`no_more_keys` flag to fire after only a few distinct keys, which is
what surfaces the multi-threaded bug. But `max_block_size = 1` also
has very heavy per-block overhead, and with 1M rows the query
exceeded `max_estimated_execution_time` (600 s) on debug and
sanitized builds, so the test failed with `TOO_SLOW` in the flaky
checks:

  https://github.com/ClickHouse/ClickHouse/actions/runs/25638480623/job/75255918411
  https://github.com/ClickHouse/ClickHouse/actions/runs/25638480623/job/75255933330

10K rows is enough to make the bug reliably observable (each of the
4 aggregation threads still sees a different "first 5 keys" set, so
kept keys end up with count != 100 when the optimization is buggy),
while keeping the test fast.

Verified locally:

  - With the fix in `OptimizeTrivialGroupByLimitPass`: output `0 5`.
  - With the fix removed: output `1 5` (bug detected).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The analyzer keeps negative `LIMIT`/`OFFSET` values as `Int64` (and
fractional ones as `Float64`), so reading them with `safeGet<UInt64>`
threw an exception during the pass and turned previously valid queries
like `... GROUP BY k LIMIT -5` into errors.

Read the values via `convertFieldToType` to `UInt64`: if the result is
null (negative or fractional), the pass returns without touching
`max_rows_to_group_by` and the planner handles the query normally.

Adds regression tests with negative `LIMIT`, negative `OFFSET`, and the
combination.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix unit tests for FileCache.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — confirmed: the failing FileCache unit test on PR #104473 head 5e9d827c6968 is the chronic flake FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly on Unit tests (amd_llvm_coverage) (gtest_filecache.cpp:1629, getFileSegmentsNum() == 3 vs expected 0). Not caused by this PR.

CIDB (14-day cross-PR, FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly only):

Total hits 55
Distinct PRs hit 43
Master hits 3 (last 2026-05-10)
Concentrated on Unit tests (amd_llvm_coverage) (52/55)
PR #104473 2 hits — matches the chronic pattern

Root cause is a known race: keep_free_space_elements_ratio = 1.0 makes FileCache::initialize() schedule the async background eviction task, which races with the test's assertProtected / assertProbationary calls — surfaces under slow coverage builds.

Fix is already filed: #104418 (OPEN since 2026-05-08). It replaces the racy integration-style test with a focused unit-level test on SLRUFileCachePriority::collectEvictionInfo that bypasses FileCache::initialize's async eviction race entirely. Verified locally: 30/30 deterministic passes; reintroducing the chassert aborts cleanly. Could you or @kssenii take a look so we can land it?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix the failure of 04217_array_concat_json_extract_keys_index and send a PR.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov filed the test-only fix as #104629.

Root cause: CI's --diagnose-random-settings identifies map_serialization_version_for_zero_level_parts = 'with_buckets' + map_buckets_strategy = 'constant' + small map_buckets_min_avg_size as the culprit on both this PR and PR #103016. Under bucketed serialization, Map entries are stored grouped by hash bucket, so the test's final SELECT * over the three Map(LowCardinality(String), String) columns renders resource as {'job':'g','d':'e'} instead of {'d':'e','job':'g'}.

Fix: Wrap the Map columns in mapSort in the SELECT only — same pattern as the existing 04060_coalescing_merge_tree_array_tuple_with_column_param.sql. The WHERE clause and the arrayConcat(mapKeys(...)) index path (the actual subject of the test, issue #88558 / PR #94515) are untouched, so all randomized serialization configurations are still exercised. 50/50 passes under the test runner with full randomization.

@Algunenano Algunenano self-assigned this May 11, 2026
- Skip the optimization when `LIMIT BY` is present: outer `LIMIT n` selects
  rows after `LIMIT BY` limits per-`expr` rows, so stopping aggregation at `n`
  distinct keys can starve `LIMIT BY` of groups.
- Allow the optimization when the user has set `max_rows_to_group_by` to a
  value larger than `LIMIT + OFFSET`: our derived value is strictly tighter
  and the user has already accepted truncation by using `'any'` overflow mode.
- Preserve the user's explicit `group_by_overflow_mode`: if the user has
  changed it to a non-`ANY` value (`'throw'` or `'break'`), applying the
  optimization would silently override their explicit contract; skip instead.
- Add a regression test for the new conditions and a test verifying via
  the `OverflowAny` `ProfileEvent` that the optimization actually fires
  (the aggregator drops keys after `max_rows_to_group_by` is reached).
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
- `04229_trivial_group_by_limit_profile_events`: this test verifies the
  optimization fires via the `OverflowAny` `ProfileEvent`, which is only
  set with the new analyzer. With `enable_analyzer = 0` (CI "old analyzer"
  config) the pass does not run, so `OverflowAny` stays at zero. Add an
  `.oldanalyzer.reference` so the same test source is reused with a
  matching reference under the old analyzer.

- `02151_hash_table_sizes_stats` and `02151_hash_table_sizes_stats_distributed`:
  these tests measure `AggregationPreallocatedElementsInHashTables` for
  `GROUP BY ... LIMIT N` and expect a size hint based on the full table
  size, but the new optimization caps the aggregation at LIMIT distinct
  keys (with `group_by_overflow_mode = 'any'`), shrinking the recorded
  hash table stat and breaking the preallocation contract this test was
  written to verify. Disable `optimize_trivial_group_by_limit_query` in
  the `run_query` helper so the test continues to exercise the
  full-aggregation preallocation path it was designed for.

CI: #104473
alexey-milovidov and others added 2 commits May 13, 2026 07:54
Compares elapsed time with `optimize_trivial_group_by_limit_query = 1`
vs `0` on `SELECT number FROM numbers_mt(100000000) GROUP BY number LIMIT 5`
to demonstrate the end-user win on the target query shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Algunenano
Algunenano self-requested a review May 13, 2026 07:59
Compare the optimized path vs the disabled setting on a large input
with many distinct keys but a small `LIMIT`. -->

<query tag="optimized">SELECT number FROM numbers_mt(100000000) GROUP BY number LIMIT 5 FORMAT Null SETTINGS optimize_trivial_group_by_limit_query = 1</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.

I didn't know we could use tag. Nice

alexey-milovidov and others added 2 commits May 13, 2026 16:35
In ClickHouse `max_rows_to_group_by = 0` means "no cap", so applying the
optimization for `LIMIT 0` (or `LIMIT + OFFSET == 0`) would silently remove
the user's explicit cap. The query also returns no rows regardless of the
optimization, so the pass buys nothing — skip in that case.

Found in code review on PR #104473.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The following CI failures on this PR are unrelated to the changes in this PR (which only touches OptimizeTrivialGroupByLimitPass and related tests):

  • Unit tests (asan_ubsan, function_prop_fuzzer) / FunctionsStress.stress — broken_determinism in countEqual with FixedString. Also failing on recent master runs.
  • Unit tests (msan, function_prop_fuzzer) / FunctionsStress.stress — broken_determinism in caseWithExpression with Enum16. Also failing on recent master runs.
  • Stress test (arm_ubsan) / Cannot start clickhouse-server — UndefinedBehaviorSanitizer: undefined-behavior /ClickHouse/src/Storages/StorageTimeSeries.cpp:171:36, looks like a null-deref in StorageTimeSeries::StorageTimeSeries from DatabaseCatalog::instance().tryGetTable(...). No open issue or PR found tracking this exact failure.

@groeneai, please investigate these failures and provide fixes in separate PRs. If fixes are already in progress, link them here.

@Algunenano

Copy link
Copy Markdown
Member

caseWithExpression is fixed by #104858, but I don't think that one covers countEqual

alexey-milovidov and others added 2 commits May 14, 2026 00:17
The test was failing with "Test runs too long" on the
`s3 storage, meta in keeper` flaky check (runs the test many
times in sequence). Inserting 1M rows on slow storage exceeds the
time budget. The test asserts behavior, not data size — every
query either uses `LIMIT` independently of input or just needs at
least a handful of distinct keys, so 10000 rows is plenty.

Failure seen on the `clickhouse-private` sync of PR #104473.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
/// and ours would be a no-op. When the user has a tighter throw/break contract, we'd
/// also break their semantics (already guarded by the `mode_is_changed` check above).
const UInt64 user_max_rows = settings[Setting::max_rows_to_group_by];
if (user_max_rows != 0 && user_max_rows <= max_rows)

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.

user_max_rows > max_rows is treated as safe to optimize here, but this can still break an explicit overflow contract.

If a user sets max_rows_to_group_by to a non-zero value and keeps default group_by_overflow_mode = 'throw', this pass rewrites the query to group_by_overflow_mode = 'any' + max_rows_to_group_by = LIMIT + OFFSET and can suppress a TOO_MANY_ROWS exception that would otherwise be raised.

Concrete case: many distinct keys, LIMIT 5, SETTINGS max_rows_to_group_by = 100. Without optimization: exception after 100 keys. With this optimization: returns 5 rows.

Please preserve explicit max_rows_to_group_by contracts too (e.g. skip when settings[Setting::max_rows_to_group_by].changed && settings[Setting::max_rows_to_group_by] != 0, or at least when the mode is not explicitly any).

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.

This is entirely ok.

Why: The meaning of the number of rows in GROUP BY is also affected by the optimization. The setting max_rows_to_group_by should control the actual number of rows - not the number of rows that would have been without the optimization. Changing the behavior (for better) in this case is correct.

@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 85.00% (51/60) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 14, 2026
Merged via the queue into master with commit a6ca99b May 14, 2026
167 checks passed
@alexey-milovidov
alexey-milovidov deleted the trivial-group-by-limit branch May 14, 2026 11:28
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 14, 2026
alexey-milovidov pushed a commit that referenced this pull request May 17, 2026
…replicas

`OptimizeTrivialGroupByLimitPass` runs in the analyzer on the initiator
and lowers `max_rows_to_group_by` on the query's local context. That
mutation is not propagated to remote replicas, so once CI's
`automatic_parallel_replicas_mode=2` randomization is sampled the
aggregator on the remotes never applies the cap and `OverflowAny` stays
at zero. The test then sees `04229_on   0` instead of
`04229_on   1` and fails 3/3 reruns (every PR run hits the same diff).

Pin `enable_parallel_replicas = 0` at the query level in both `SETTINGS`
clauses so the optimization is exercised on the local-coordinator path
it is designed for. Query-level `SETTINGS` takes priority over the
runner's session-level injection, so the pin is robust against
randomization. No `no-*` tag is added (per
`.claude/CLAUDE.md` guidance) and no other randomization is disabled —
`max_threads = 1` was already pinned, the rest stays randomized.

Locally reproduced with a 3-replica `default_parallel_replicas` cluster
on loopback: 5/5 fails without the pin (`04229_on   0`), 20/20 passes
with the pin under the same parallel-replicas session settings.

Cross-PR scope (CIDB, 30d): seen on PRs #104473, #100146, #101033,
#104694, #104966 — all unrelated to the test or its source PR.

Reported by @alexey-milovidov on
#100146.
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jun 7, 2026
The test was occasionally returning two rows from the per-iteration
SELECT against `system.query_log` instead of one, observed as a
spurious extra `1` in the diff before the expected `7` for
`max_threads = 7` iterations across multiple unrelated PRs (ClickHouse#101143,
ClickHouse#105406, ClickHouse#102308, ClickHouse#100752, ClickHouse#104473, ClickHouse#98779, ClickHouse#97302) and on master.

The original filter accepted any `type != 'QueryStart'` row matching
the iteration's `query_id`. Under randomized CI settings a second
`query_log` entry can match the same `query_id` (subquery, distributed
sub-fragment, or non-`Insert` follow-up), giving the test two rows.

Tighten the filter to require the successful initial INSERT only:
`type = 'QueryFinish' AND is_initial_query = 1 AND query_kind = 'Insert'`.
This matches the well-known sibling test `02871_peak_threads_usage`,
which already filters on `type = 'QueryFinish'`.

Verified locally that the new filter correctly suppresses a duplicate
log row sharing the same `query_id` while still returning exactly one
row for the real INSERT.

CI report (one of the recent failures):
https://s3.amazonaws.com/clickhouse-test-reports/101143/

Co-Authored-By: Claude Opus 4.8 <[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.

4 participants