Repository navigation
Support aggregate functions in the trivial GROUP BY LIMIT optimization - #114690
Conversation
For the trivial `GROUP BY ... LIMIT n` shape with aggregate functions in the projection, cap the aggregation at `n + offset` keys while keeping the aggregate values of the returned keys exact: once any aggregation stream exceeds the cap, it freezes a shared set of exactly `n + offset` kept keys, and every stream rebuilds its hash table to that set (keeping its accumulated states for the kept keys, dropping the rest) and continues on the regular `no_more_keys` path. A per-stream cutoff (what plain `max_rows_to_group_by` with `group_by_overflow_mode = 'any'` does) would undercount the values: a key kept by one stream and rejected by another loses the other stream's rows in the merge. The rebuild reuses the existing two-stage machinery: `convertToChunks` (final = false) moves the stream's states into chunks, a seed block of kept keys with empty aggregate states pre-seeds a fresh table via `mergeOnBlock`, and re-merging the stream's own chunks with `no_more_keys` drops everything else. The hot aggregation loops are untouched: before the freeze the streams aggregate completely normally, and after the rebuild they run the pre-existing `no_more_keys` path against a table of exactly `n + offset` keys. The cutoff is detected in the planner (not the analyzer pass) and only when the node performs the complete aggregation itself (first and second stage): partial states sent to a remote initiator would be merged with other nodes' states, whose kept keys differ, and the values would be undercounted again across nodes. On the shards of distributed queries and on the replicas of parallel-replicas reading the cutoff stays off. The settings-based rewrite of `OptimizeTrivialGroupByLimitPass` remains for aggregate-free projections (it is sound cross-shard). The shape check is shared between the pass and the planner (`getTrivialGroupByLimit`) and now also rejects DISTINCT, QUALIFY, window functions and `arrayJoin` in the projection, which consume the groups after the aggregation and made the aggregate-free rewrite return wrong results. Closes: #114637 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
All four guard cases were verified to return wrong results on master when placed at the top level (where `OptimizeTrivialGroupByLimitPass` fires): DISTINCT returned 1 row instead of 3, `count() OVER ()` saw ~100 groups instead of 100000, sparse `arrayJoin` returned 1 row instead of 10, and QUALIFY with a window function returned 0 rows instead of 10. A QUALIFY on plain group keys alone is pushed down below the aggregation and was not affected. The test now runs each case both as `INSERT ... SELECT` (the pass path) and as a subquery (the planner path), asserting on deterministic aggregates of the captured result. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The 8/16-bit key methods (`key8`, `key16`, `keys16` and their nullable and low-cardinality variants) aggregate into fixed hash maps bounded by the key space (at most 65536 cells), where the cutoff buys nothing. The implicit-zero fixed maps also cannot represent a kept key with a zero inline `count()` state: such a cell reads as absent, so seeding the rebuilt tables with empty count states lost the kept keys and every subsequent row of them was dropped, producing an empty result (found by the `04214` test shape - a single `count()` over a `number % 100` key). `checkLimits` now ignores `max_rows_to_group_by` when `shared_kept_keys_for_overflow_any` is set and the chosen method uses a fixed hash map, so such aggregations stay complete and exact. The tests cast their keys to `UInt64` where the cutoff is expected to engage, and `04836` pins the fixed-map exemption with an 8/16-bit key case. Also make the profile-events test read from `numbers_mt` with enough blocks for a parallel read: a small MergeTree table can collapse into a single-stream read, where the per-stream cutoff is already exact, no rebuild is needed, and `AggregationSharedKeptKeysRebuilds` legitimately stays zero. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [d59d9a8] Summary: ❌
AI ReviewSummaryThis PR extends the trivial Findings
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit d59d9a8.
Changed lines: Changed C/C++ lines covered: 331/351 (94.30%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR extends the trivial GROUP BY ... LIMIT optimization to queries with aggregate functions, using a shared set of kept keys, but only for queries with no ORDER BY. All five flagged ClickBench improvements (Q18 -17.7%, Q31 -11.3%, Q32 -47.5%, Q33 -8.0%, Q34 -7.7%) are GROUP BY ... ORDER BY count() DESC LIMIT 10 queries. The new code rejects that shape before doing anything, so on these queries the only remaining change is two cheap flag checks in checkLimits. All five are downgraded to not sure. The shared drop in CPU time across unrelated high-cardinality aggregations more likely reflects the gap between the source build and the older 26.9 baseline than this change. clickbenchFlagged queries (5 of 43)
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
|
|
🕵 Addressed the automated review in 1001736: disable the aggregate kept-keys cutoff when |
…mit-aggregates # Conflicts: # src/Interpreters/AggregatedDataVariants.h # src/Planner/Planner.cpp # src/Processors/Transforms/AggregatingTransform.cpp # src/Processors/Transforms/AggregatingTransform.h
# Conflicts: # src/Analyzer/Passes/OptimizeTrivialGroupByLimitPass.cpp # src/Analyzer/Passes/OptimizeTrivialGroupByLimitPass.h # src/Core/Settings.cpp
The CI performance comparison measured the kept-keys cutoff against the heap head to head on the same build (`optimize_trivial_group_by_limit` queries 4 and 5): on `GROUP BY number % 100000000 LIMIT 10` the heap is 1.4-1.6x faster (amd 71.8 ms vs 47.7 ms, arm 51.1 ms vs 32.3 ms), so arming the cutoff for fixed-width keys was a regression against master. The earlier "7-9x faster" figures compared the cutoff against a baseline with the heap disabled (`query_plan_max_limit_for_top_k_optimization = 1` in the test). Local runs of the PR build agree on every shape tried: `UInt64`, two fixed-width keys, `uniq` + `sum` with `LIMIT 100`, a filtered input, `String` and `LowCardinality(Nullable(UInt64))` keys; the heap is as fast or up to 1.3x faster. `preferGroupByTopKOverKeptKeysCutoff` no longer looks at the key types: the cutoff is armed only when the heap does not apply (disabled, the limit above its cap, `max_rows_to_group_by` set, a serialized plan). This also makes the review finding about `LowCardinality(Nullable(T))` keys moot, since the key classification is gone; test `05224` pins such a key to the heap. The tests of the cutoff itself now disable the heap explicitly; before, they relied on the CI profile's `max_rows_to_group_by: 10G`, which keeps the cutoff armed. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114690&sha=b930adcad431b5413319d90763b11915d35e7b82&name_0=PR #114690 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114690&sha=b930adcad431b5413319d90763b11915d35e7b82&name_0=PR&name_1=Upgrade%20check%20(amd_release) and provide a fix in a separate PR. If the fix is already in progress, link it here. The upgraded server cannot attach |
|
Investigated. The upgrade check runs the previous release's own copy of the tests, and this run installed The fix is already merged: #121590 (@ azat, into Separately, 26.9 still writes that spelling for users, so such a table cannot be reattached after a restart there: the writer fix #119810 has no |
|
🕵 Merged
All 13 |
| /// the plan without the derived `max_rows_to_group_by` so that a deserialized plan falls back | ||
| /// to the exact, unoptimized aggregation instead of the per-stream cutoff, which would be | ||
| /// unsound with aggregate functions in the projection. | ||
| settings[QueryPlanSerializationSetting::max_rows_to_group_by] |
There was a problem hiding this comment.
When shared_kept_keys_for_overflow_any is true because the query already had an explicit max_rows_to_group_by / group_by_overflow_mode = 'any' (the planner keeps that case alive at Planner.cpp:2957-2963), this unconditionally serializes max_rows_to_group_by = 0.
On a serialize_query_plan = 1 remote() / distributed query, the deserialized plan then ignores the user's cap and runs exact aggregation instead of honoring the requested cutoff, so the same query changes behavior depending on plan shipping and can lose the memory bound the user asked for. We need to distinguish "derived cap from the trivial GROUP BY ... LIMIT optimization" from "user-specified cap that happens to coincide with it", and only clear the former here.
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
A nested SETTINGS clause is applied to the query node's own context after `clampToSettingsConstraints` and `doSettingsSanityCheckClamp`, and the Planner of that node runs on that context. The aggregation block of `Planner::buildPlanForQueryNode` re-applied `query_node.getSettingsChanges()` as written on top of a copy of those settings, which undid both: a subquery with `SETTINGS max_threads = 1000000000, max_threads_min_free_memory_per_thread = 0` made `AggregatingStep` resize the pipeline to 1e9 ports and OOM-killed the server (found by the targeted AST fuzzer on ClickHouse#123125), and a `MAX` or `readonly` constraint on `max_threads` did not bound the aggregation. The re-application came with ClickHouse#114690 for a Fast test failure of 04836 that a later test change fixed; the node context already carries the nested `make_distributed_plan`, so the values are taken from it as they are. The only thing the raw clause still contributed is the `changed` flag of a nested `group_by_overflow_mode` whose value equals the inherited one: `SettingsConstraints::checkOrClamp` drops such a change, and `getTrivialGroupByLimit` reads the flag to keep a user's explicit `throw`. So that flag is set when the node's clause names the setting; nothing else on this path reads a `changed` flag. Test: the nested `max_threads` still reaches the aggregation, a clause dropped under `readonly` no longer does (fails without the fix), and an explicit nested `group_by_overflow_mode = 'throw'` equal to the default still throws (fails without the flag). Co-Authored-By: Claude Opus 5.5 <[email protected]>
SipHash kept the current partial 8-byte word as a union of a UInt64 and UInt8[8]. `update` wrote a short tail byte by byte into the byte array (the remainder of a previous update too, which clang emits as a `memcpy`), and `finalize` stored the `cnt` byte into the last position and then read the whole word with one 8-byte load. An 8-byte load that overlaps several narrower in-flight stores cannot be store-forwarded on x86: it waits until the stores commit (`ld_blocks.store_forward`). When the hash state lives in memory across a call, e.g. `UniqVariadicHash::apply` -> virtual `IColumn::updateHashWithValue` -> `get128`, every row pays this. How often the blocked load is replayed depends on code placement, so the same machine code is fast in one build and ~55% slower in another: this is why `entropy #2` of the performance comparison flips between ~0.33 s and ~0.52 s per build on amd (master builds 4f8c9f2..a0b6517, and PR builds of ClickHouse#117704, ClickHouse#114690, ClickHouse#119760). Now `current_word` is a plain UInt64 holding the received bytes of the current word in little-endian order, the bytes not received yet being zero (the same numeric value the union had on both endiannesses, so CURRENT_BYTES_IDX is gone). `loadTail` assembles up to 7 bytes in a register with overlapping 4/1-byte loads, the remainder path ORs it in at the right shift, the main loop keeps the word in a local, and `finalize` folds `cnt` into the top byte in a register. Every access to `current_word` is now a whole-word store followed by a whole-word load. Hash values are unchanged. Validation (release build, CMAKE_BUILD_TYPE=None without ThinLTO, Xeon 6975P, `SELECT entropy(MobilePhoneModel)` over 100M rows of a 92%-empty sparse String column, max_threads=16, medians of 18 runs): - base 0.218 s, fix 0.150 s; official master builds 562bdc1 0.204 s (fast layout) and 4f8c9f2 0.285 s (slow layout). - 15 queries: ld_blocks.store_forward base 1.54e9, fix 2.7e7 (slow official 6.07e9); cycles 1.44e11 -> 8.98e10; instructions 5.27e11 -> 4.71e11. - `uniqExact(toString(number % 1000), toString(number % 7))` over 2e8 rows 5.23 s -> 2.98 s; sipHash64/sipHash128 of 1..5-byte strings -6.4%/-4.8%; sipHash64 of 10..50-byte strings +1.1% (instructions +1.8%); GROUP BY two String keys unchanged. - Hash identity: a throwaway differential gtest against the verbatim previous class (every length 0..80 x every 3-way split, 3 key pairs, get64/get128/get128Reference, double get, update after get, the ColumnString row shape, 300k random streams of raw and typed updates): 2,038,362 cases, 0 mismatches; a planted mutation (wrong value for 4-byte tails only) gives 808,592 mismatches. 02534_keyed_siphash and 02552_siphash128_reference (official vectors) pass, and SQL sums of sipHash64/128, keyed and reference variants over 2e7 strings are equal on both binaries. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #114637
Related: #81944
Related: #114695
The trivial
GROUP BY ... LIMIT noptimization (optimize_trivial_group_by_limit_query, defaulttrue) now also fires for projections with aggregate functions — the ClickBench Q17 shape (SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase LIMIT 10) — while keeping the aggregate values of the returned keys exact. Under default settings it yields to the fasterGROUP BYtop-K heap wherever that applies (see below), so it serves the queries the heap does not cover, e.g.LIMITabove 1000.Why it was restricted. The settings-based rewrite (
max_rows_to_group_by = n + offsetwithgroup_by_overflow_mode = 'any') enforces the cutoff per aggregation stream: a key kept by one stream and rejected by another loses the other stream's rows and comes out of the merge with an undercounted value. Returning an unspecified subset of the groups is fine forLIMITwithoutORDER BY; returning wrong values is not.How it works now (shared kept keys, zero hot-path cost). The streams aggregate completely normally until the first one exceeds
n + offsetdistinct keys (the pre-existing per-blockcheckLimits). That stream publishes a frozen seed of exactlyn + offsetkept keys with empty aggregate states (ManyAggregatedData::SharedKeptKeys); every stream then rebuilds its hash table to exactly that key set — keeping the states it accumulated for the kept keys, dropping the rest — and continues on the pre-existingno_more_keyspath against a table ofn + offsetkeys. Streams that finished consuming before the freeze are rebuilt by the last stream before the merge. Every row before the freeze is aggregated normally and every later row of a kept key finds its key in the rebuilt table, so the merged values are exact; the dropped keys are absent from every rebuilt table and never reach the result. The rebuild reuses the existing two-stage machinery (convertToChunks(final = false)+mergeOnBlock), so the hot aggregation loops inAggregator.cppare untouched.Where it fires. The cutoff is detected in the planner and enabled only when the node performs the complete aggregation itself (first and second stage): partial states sent to a remote initiator would be merged with other nodes' states, whose kept keys differ, and the values would be undercounted again — across nodes instead of across threads. On the shards of distributed queries and on the replicas of parallel-replicas reading it stays off. The settings-based rewrite of
OptimizeTrivialGroupByLimitPassremains for aggregate-free projections (it is sound cross-shard). For the 8/16-bit key methods (fixed hash maps bounded by the key space) the cutoff stays inert and the aggregation is complete and exact. External aggregation stays configured and stays available (Aggregator::Params::SharedKeptKeysControl). Before the kept keys are frozen, a stream that needs to spill permanently abandons the cutoff and the aggregation completes exactly, spilling as it would without the optimization. After the freeze, capping the number of keys is not by itself a memory bound — the kept keys are bounded, but their aggregate states are not (uniqExact,groupArray,topK, the exact quantiles) — so a table that has already been rebuilt to the kept keys is still flushed to a temporary file and re-seeded with those keys right afterwards, keeping the values exact; a table that has not been rebuilt yet does not spill, so nothing but kept keys ever reaches the temporary files. On the branches that do not share one kept key set — a single aggregating stream,skip_merging, where the streams hold disjoint keys — every stream caps itself, so its table already holds only its own exact kept keys; such a stream captures them as its own seed (AggregatingTransform::capturePerStreamKeptKeysSeed) and spills and re-seeds through the very same path.Guards for wrong results of the existing optimization. The shape check (shared between the pass and the planner,
getTrivialGroupByLimit) now also rejectsDISTINCT,QUALIFY, window functions andarrayJoinin the projection. These consume or filter the groups after the aggregation, and all four cases were verified to return wrong results on master with the default settings (e.g.SELECT DISTINCT intDiv(k, 25000) FROM t GROUP BY k LIMIT 3returned 1 row instead of 3;SELECT count() OVER () FROM t GROUP BY k LIMIT 5returned ~100 instead of 100000). Test04837pins all four in both the top-level (pass) and subquery (planner) forms. The guards are also submitted separately as the minimal backportable bug fix #114695 (issue #114693); whichever merges second needs a trivial conflict resolution.Measured on a 96-core aarch64 box,
SELECT number % 100000000 AS k, count() FROM numbers_mt(200000000) GROUP BY k LIMIT 10with theGROUP BYtop-K heap unavailable: 0.06–0.13 s with the optimization vs 0.37–0.94 s without (interleaved hot runs on a shared machine); the CI performance comparison confirms it (optimize_trivial_group_by_limit #2−89%,destroy_aggregate_states #1−87%; both tests setquery_plan_max_limit_for_top_k_optimization = 1).Relation to the
GROUP BYtop-K heap. Master has since gained the heap (enable_group_by_top_k_optimization), which covers the same shape and is mutually exclusive with this cutoff (tryOptimizeGroupByTopKbails out onmax_rows_to_group_by > 0). Measured head to head on the same build, the heap is as fast or faster on every key type:optimize_trivial_group_by_limit #4vs#5in the CI comparison is 71.8 ms vs 47.7 ms (amd) and 51.1 ms vs 32.3 ms (arm) on aUInt64key, and local runs agree for two fixed-width keys,uniq+sumwithLIMIT 100, a filtered input,StringandLowCardinality(Nullable(UInt64))keys (the heap up to 1.3x faster). So the planner leaves the heap in charge wherever it applies and arms the cutoff only when it does not: the heap disabled,LIMIT + OFFSETabovequery_plan_max_limit_for_top_k_optimization(1000 by default) or100000, a user-setmax_rows_to_group_by, or a serialized plan. Pinned by05224_trivial_group_by_limit_aggregates_top_k_arbitrationand the default-settings pairs oftests/performance/optimize_trivial_group_by_limit.xml(which must stay neutral).exact_rows_before_limit. Capping the aggregation atLIMIT + OFFSETgroups makesrows_before_limit_at_leastreport at most that many, so the shared helper bails out underexact_rows_before_limit = 1, which covers both the new aggregate form and the pre-existing settings-based form (it reported 1000 instead of 1000000 in05256).The values of the returned keys match the full aggregation exactly (verified by the
04836join-against-truth tests forUInt64/String/LowCardinality/Nullable/two-key shapes,count/sum/min/max/uniqExact, withOFFSET, under single-stream and 16-stream execution, from aggregate projections, and overremote()).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The trivial
GROUP BY ... LIMIT noptimization (settingoptimize_trivial_group_by_limit_query) now also applies to queries with aggregate functions in the projection when theGROUP BYtop-K optimization does not apply (for example,LIMITabovequery_plan_max_limit_for_top_k_optimization): once any aggregation thread exceedsn + offsetdistinct keys, all threads are restricted to a single shared set of kept keys, so the hash tables stay small while the aggregate values of the returned keys remain exact (up to 7–9x faster for such queries). Additionally, the optimization no longer fires for queries withDISTINCT,QUALIFY,LIMIT AFTER/LIMIT UNTIL, window functions, orarrayJoinin the projection, where it could return wrong results, or withexact_rows_before_limit, where it maderows_before_limit_at_leastinexact.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/114690]
Version info
26.10.1.866-master(included in26.10and later)