Repository navigation
Add OptimizeTrivialGroupByLimitPass - #104473
Conversation
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.
|
Workflow [PR], commit [5f5cc42] Summary: ✅ AI ReviewSummaryThis PR introduces Findings
Final VerdictStatus: Minimum required action:
|
- 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]>
|
Does it work correctly with multiple threads? I'm concerned, because the set of first keys could be different in different threads. |
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]>
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.
|
@groeneai, fix unit tests for FileCache. |
|
@alexey-milovidov — confirmed: the failing FileCache unit test on PR #104473 head CIDB (14-day cross-PR,
Root cause is a known race: Fix is already filed: #104418 (OPEN since 2026-05-08). It replaces the racy integration-style test with a focused unit-level test on |
|
@groeneai, fix the failure of 04217_array_concat_json_extract_keys_index and send a PR. |
|
@alexey-milovidov filed the test-only fix as #104629. Root cause: CI's Fix: Wrap the |
- 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).
- `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
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]>
| 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> |
There was a problem hiding this comment.
I didn't know we could use tag. Nice
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]>
|
The following CI failures on this PR are unrelated to the changes in this PR (which only touches
@groeneai, please investigate these failures and provide fixes in separate PRs. If fixes are already in progress, link them here. |
|
caseWithExpression is fixed by #104858, but I don't think that one covers |
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) |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: 85.00% (51/60) · Uncovered code |
…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.
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Added
OptimizeTrivialGroupByLimitPass. For trivialSELECT ... FROM t GROUP BY k LIMIT nqueries (noHAVING,ORDER BY, or window functions), the analyzer now setsmax_rows_to_group_by = n + offsetwithgroup_by_overflow_mode = 'any', so aggregation stops oncendistinct keys have been produced instead of grouping the entire input. Controlled by the new settingoptimize_trivial_group_by_limit_query(enabled by default).Documentation entry for user-facing changes
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 ofGROUP BY ... LIMIT, any 5 distinct keys are a valid answer — so we can stop aggregation as soon as 5 distinct keys exist.What changed
OptimizeTrivialGroupByLimitPass.optimize_trivial_group_by_limit_query(default1) to gate the pass.GROUP BYand aLIMIT, and has noHAVING,ORDER BY, or window clauses; it would change observable results for those.max_rows_to_group_by, so it never overrides an explicit overflow contract.Origin
Split out from WIP PR #81944.
Version info
26.5.1.647