Skip to content

Keep the hash table statistics of a capped GROUP BY apart from the uncapped aggregation - #126374

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/hash-table-stats-key-group-cap
Oct 17, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/hash-table-stats-key-group-cap

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122608

Changelog category (leave one):

  • Performance Improvement

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

A GROUP BY whose groups are capped, by the trivial GROUP BY ... LIMIT optimization or by max_rows_to_group_by with group_by_overflow_mode 'any' or 'break', now keeps its own hash table size statistics, and so does an aggregation over such a capped one. It no longer preallocates the hash table of the same aggregation without the cap, and the next uncapped run still preallocates for all its groups. Closes #122608.

Description

The trivial GROUP BY ... LIMIT optimization moves the LIMIT into the aggregation as max_rows_to_group_by = LIMIT + OFFSET with group_by_overflow_mode = 'any', but the hash table statistics key of the aggregation did not include that cap. A capped run and the same uncapped aggregation shared one entry: the capped run preallocated the full table, then replaced the entry with its own small sizes (sum_of_sizes=50 for LIMIT 10 over 1M keys), so the next uncapped run preallocated nothing. Results are not affected.

setAggregationHashTableCacheKeys now mixes max_rows_to_group_by, the overflow mode and whether it is the LIMIT cutoff (which keeps exactly the cap, not whole blocks) of the aggregation and of every aggregation below it into the key stamped on the AggregatingStep when any of them can stop admitting keys (any or break); without such a cap the key is unchanged. The node hashes of calculateHashTableCacheKeys, which automatic parallel replicas and join keys use, do not change. A throw cap keeps sharing the uncapped entry: such a run either throws or keeps every group.

Release build, 40M rows over 8M Nullable(UInt64) keys, count(), max_threads = 16, GROUP BY k LIMIT 5000 alternating with GROUP BY k:

  • the LIMIT 5000 run: 159-161 ms and 1.44 GiB peak memory before, 94-108 ms and 30 MiB after;
  • the uncapped run right after it: 355-359 ms with nothing preallocated before, 300-325 ms after, no slower than an uncapped run after an uncapped one.

The new test asserts AggregationPreallocatedElementsInHashTables for the planner cutoff with two LIMIT values, the settings pass of aggregate-free projections, any and break caps, a settings cap equal to a LIMIT, an outer aggregation over a capped subquery, cold and warm, and a throw control. It fails on master and passes 90 randomized runs; 285 related tests show no new failures.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.127-master (included in 26.11 and later)

groeneai and others added 2 commits October 16, 2026 22:30
…capped one

The trivial GROUP BY LIMIT optimization pushes LIMIT into the aggregation as
`max_rows_to_group_by = LIMIT + OFFSET` with `group_by_overflow_mode = 'any'`,
and a user can set the same cap with `any` or `break`. The aggregation's
statistics key did not include that cap, so a capped run and the same uncapped
aggregation shared one entry: the capped run preallocated the uncapped table
size, and its small sizes replaced the entry, so the next uncapped run
preallocated nothing. An aggregation over a capped one (for example a capped
subquery) shares the same problem one level up, since the inner step is hashed
without its cap.

Mix the cap and the overflow mode of every `AggregatingStep` in the
aggregation's subtree, the step itself included, into the key stamped on the
step, whenever any of them can stop admitting keys (mode is not `throw`).
Uncapped steps contribute zeros, so an outer cap over an uncapped inner and an
uncapped outer over a capped inner stay apart, and a plan without any such cap
keeps exactly the previous key. Only the stamped key changes; the node hashes
returned by `calculateHashTableCacheKeys` (used by automatic parallel replicas
and join keys) stay as they are. A `throw` cap either throws or keeps every
group, so it keeps sharing the uncapped entry.

Closes ClickHouse#122608

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the mixGroupByCapsIntoKey comment to one line.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings over 3 rounds) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ An aggregation over an inner aggregation capped by the subquery's own SETTINGS still shared its entry with the uncapped plan (calculateHashTableCacheKeys.cpp, setAggregationHashTableCacheKeys) AGREE, fixed in this PR the caps of every aggregation in the subtree are mixed into the stamped key; nested test group added
2 ⚠️ The test did not show that the cap value is part of the key or that a capped entry is reused AGREE, fixed in this PR LIMIT 1000000 cold and warm, then LIMIT 10 again; a same-cap different-mode pair is not asserted (both keep about the same number of groups)
3 ⚠️ The nested case did not show that the aggregation over a capped one keeps a reusable entry of its own AGREE, fixed in this PR the capped nested query runs cold and warm with an inner cap the data never reaches (deterministic sizes); a mutation that leaves that key unstamped fails the warm line
4 ⚠️ A capped entry warmed at max_threads = 4 is read by the same query at max_threads = 1, which preallocates the sum of four tables DISAGREE not specific to caps, unchanged from master: no aggregation key carries the width (resolved in transformPipeline, AggregatingStep.cpp:489-491, after the key is stamped), and an uncapped entry depends on it the same way (Aggregator.cpp:197-205); master preallocates the same amount
5 💡 A run cut short by a read or time limit in break mode also writes partial sizes under the uncapped key; the same holds for a join over a capped subquery noted, not in scope different settings and key machinery than the group cap of the aggregation itself
6 💡 Every distinct LIMIT + OFFSET gets its own statistics entry noted, not blocking the cache is an LRU bounded by max_entries_for_hash_table_stats; keeping the value is what lets LIMIT 1000000 reuse its own sizes

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261016-223300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's script prints uncapped after capped: 0 on master every run (raw counts 0, 1000000, 1000000, 0); the new test fails on master in every randomized run (13 lines).
b Root cause explained? The stats key of the aggregation omits the group cap that the trivial GROUP BY ... LIMIT optimization (or a user any/break cap) puts into the AggregatingStep, so capped and uncapped runs share one entry; the capped run's small sizes replace it and the next uncapped run preallocates 0, while a capped run after an uncapped one preallocates the full table.
c Fix matches root cause? Yes. The caps of the aggregation and of every aggregation below it are mixed into the key at the one site that stamps it; no write-skip or read-side clamp.
d Test intent preserved / new tests added? New 05406_hash_table_stats_key_group_cap.sql: planner cutoff (two LIMIT values, a reused capped entry), settings pass, any and break caps, an outer aggregation over a capped subquery (cold, and warm with a cap the data never reaches), throw negative control. No existing test changed.
e Both directions demonstrated? Master: 0, 1000000, 1000000, 0 and the test fails on 13 lines; the previous root-only key and a key left unstamped above a capped subquery fail the nested lines; fix: 0, 1000000, 0, 1000000 and 50/50 randomized OK.
f Fix is general across code paths? All cap producers converge on the step's params, so one site covers them, and an aggregation above a capped one is keyed by the caps of its whole subtree. Spilled runs record no statistics; the top-K heap sets no cap; node hashes used by automatic parallel replicas and join keys are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Independent of the key type (measured UInt64 and Nullable(UInt64)); distinct cap values get distinct keys (a constant-cap mutation fails the test); max_rows_to_group_by = 0 and throw keep the old key.
h Backward compatible? (maintainer-approved exception only) Yes. In-memory cache key only; no setting, no format or serialization change.
i Invariants and contracts preserved? Keys are still all computed before any is stamped; the exception path is unchanged; only the stamped key differs.

Session id: cron:clickhouse-impl-slot-6:20261016-222200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai, could you review this? The trivial GROUP BY ... LIMIT cutoff puts a max_rows_to_group_by cap into the AggregatingStep, but the hash table statistics key ignored it, so a capped run overwrote the sizes the uncapped query preallocates from; the caps of the aggregation's subtree are now mixed into the stamped key.

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [844b176]

Summary: ✅


AI Review

Summary

This PR separates hash-table statistics for capped and uncapped GROUP BY operations, including aggregations over capped subqueries. Reviewed revision 844b176f7607fec6c2649c56a94398f0ada85da7 addresses the prior cutoff-identity finding. The focused regression passes in Fast test CI, and the PR provides before/after performance measurements. No remaining actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
The trivial `GROUP BY ... LIMIT` optimization and `max_rows_to_group_by`
with `group_by_overflow_mode = 'any'` can produce the same `(cap, mode)`
pair, but they retain very different tables. The planner cutoff
(`shared_kept_keys_for_overflow_any`) rebuilds the tables to exactly the
kept keys, while the per-stream `any` cap checks the limit after a block
and keeps every key of that block. With one statistics entry for both,
`GROUP BY k LIMIT 10` preallocated the tables of the settings cap and then
overwrote the entry with tiny sizes, so the next settings-capped run
preallocated nothing (measured with 4 streams: 262144 preallocated for the
`LIMIT 10` run, then 0 for the `any` run; after this change 0 and 262144).

Mix the flag into the key with each cap. Reported by the AI review on
the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 17, 2026
Merged via the queue into ClickHouse:master with commit 4c2b5ce Oct 17, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 17, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #126374 to 26.10: Keep the hash table statistics of a capped `GROUP BY` apart from the uncapped aggregation
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… `GROUP BY` apart from the uncapped aggregation
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GROUP BY LIMIT capped run overwrites hash table stats for the uncapped query

5 participants