Skip to content

Support aggregate functions in the trivial GROUP BY LIMIT optimization - #114690

Merged
alexey-milovidov merged 50 commits into
masterfrom
trivial-group-by-limit-aggregates
Sep 28, 2026
Merged

alexey-milovidov merged 50 commits into
masterfrom
trivial-group-by-limit-aggregates

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Closes: #114637
Related: #81944
Related: #114695

The trivial GROUP BY ... LIMIT n optimization (optimize_trivial_group_by_limit_query, default true) 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 faster GROUP BY top-K heap wherever that applies (see below), so it serves the queries the heap does not cover, e.g. LIMIT above 1000.

Why it was restricted. The settings-based rewrite (max_rows_to_group_by = n + offset with group_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 for LIMIT without ORDER 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 + offset distinct keys (the pre-existing per-block checkLimits). That stream publishes a frozen seed of exactly n + offset kept 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-existing no_more_keys path against a table of n + offset keys. 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 in Aggregator.cpp are 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 OptimizeTrivialGroupByLimitPass remains 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 rejects DISTINCT, QUALIFY, window functions and arrayJoin in 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 3 returned 1 row instead of 3; SELECT count() OVER () FROM t GROUP BY k LIMIT 5 returned ~100 instead of 100000). Test 04837 pins 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 10 with the GROUP BY top-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 set query_plan_max_limit_for_top_k_optimization = 1).

Relation to the GROUP BY top-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 (tryOptimizeGroupByTopK bails out on max_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 #4 vs #5 in the CI comparison is 71.8 ms vs 47.7 ms (amd) and 51.1 ms vs 32.3 ms (arm) on a UInt64 key, and local runs agree for two fixed-width keys, uniq + sum with LIMIT 100, a filtered input, String and LowCardinality(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 + OFFSET above query_plan_max_limit_for_top_k_optimization (1000 by default) or 100000, a user-set max_rows_to_group_by, or a serialized plan. Pinned by 05224_trivial_group_by_limit_aggregates_top_k_arbitration and the default-settings pairs of tests/performance/optimize_trivial_group_by_limit.xml (which must stay neutral).

exact_rows_before_limit. Capping the aggregation at LIMIT + OFFSET groups makes rows_before_limit_at_least report at most that many, so the shared helper bails out under exact_rows_before_limit = 1, which covers both the new aggregate form and the pre-existing settings-based form (it reported 1000 instead of 1000000 in 05256).

The values of the returned keys match the full aggregation exactly (verified by the 04836 join-against-truth tests for UInt64/String/LowCardinality/Nullable/two-key shapes, count/sum/min/max/uniqExact, with OFFSET, under single-stream and 16-stream execution, from aggregate projections, and over remote()).

Changelog category (leave one):

  • Performance Improvement

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

The trivial GROUP BY ... LIMIT n optimization (setting optimize_trivial_group_by_limit_query) now also applies to queries with aggregate functions in the projection when the GROUP BY top-K optimization does not apply (for example, LIMIT above query_plan_max_limit_for_top_k_optimization): once any aggregation thread exceeds n + offset distinct 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 with DISTINCT, QUALIFY, LIMIT AFTER/LIMIT UNTIL, window functions, or arrayJoin in the projection, where it could return wrong results, or with exact_rows_before_limit, where it made rows_before_limit_at_least inexact.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.866-master (included in 26.10 and later)

alexey-milovidov and others added 3 commits August 13, 2026 17:09
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]>
@mintlify

mintlify Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 26, 2026, 2:39 AM

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d59d9a8]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
entropy #2 FAIL dashboard
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
json_to_string #1 FAIL dashboard

AI Review

Summary

This PR extends the trivial GROUP BY ... LIMIT optimization to projections with aggregate functions by freezing a shared kept-key set, rebuilding per-stream hash tables around it, and coordinating that path with spilling, projection reads, and GROUP BY top-K. The overall direction looks sound, but there is still one serialized-plan regression where an explicit user aggregation cap can be silently dropped.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/AggregatingStep.cpp:990] serializeSettings always writes max_rows_to_group_by = 0 whenever shared_kept_keys_for_overflow_any is set. That is correct for the optimization-derived cutoff, but it also erases an explicit user max_rows_to_group_by / group_by_overflow_mode = 'any' that the planner intentionally keeps alive when it matches the trivial-limit cap. On serialize_query_plan = 1 remote() / distributed queries, the deserialized plan then runs exact aggregation instead of honoring the requested cutoff, so the same query changes behavior depending on whether the plan is shipped and can lose the memory bound the user asked for. The serialization path needs to distinguish a derived cap from a user-specified one and only clear the derived case.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit d59d9a8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 331/351 (94.30%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 13, 2026
Comment thread src/Planner/Planner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d59d9a82834d9aaf6c09ab7a4a54a6b84bdbf180 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

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.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1101 906 -17.7% <0.0001 aggregation: Q18 groups by UserID, minute and SearchPhrase with ORDER BY count() DESC LIMIT 10. The new cutoff exits on hasOrderBy(), so this -17.7% is not caused by the PR.
⚠️ 31 not_sure 309 274 -11.3% <0.0001 aggregation: Q31, the filtered WatchID/ClientIP aggregation, ends in ORDER BY c DESC LIMIT 10, so the kept-keys cutoff never arms. The -11.3% comes from a code path this PR does not change.
⚠️ 32 not_sure 1376 723 -47.5% <0.0001 aggregation: Q32, the full WatchID/ClientIP aggregation, has ORDER BY c DESC and is excluded from the cutoff. The PR leaves only two extra flag checks in checkLimits on this path, which cannot explain -47.5%.
⚠️ 33 not_sure 1256 1155 -8.0% <0.0001 aggregation: Q33 groups by URL with ORDER BY c DESC LIMIT 10, so the cutoff is not applied. The -8.0% does not come from this diff.
⚠️ 34 not_sure 1259 1162 -7.7% <0.0001 aggregation: Q34 is Q33 with a constant key added, and it also has ORDER BY. Its -7.7% tracks Q33 almost exactly, which points to a shared cause outside this PR.

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: 041f05ec-100a-49d8-a109-e57d8d6d4915
  • MIRAI run: abc35d29-d283-4dbe-ad4b-244180abcb3b
  • PR check IDs:
    • clickbench_1904223_1790399760
    • clickbench_1904229_1790399760
    • clickbench_1904235_1790399760
    • tpch_adapted_1_official_1904243_1790399760
    • tpch_adapted_1_official_1904257_1790399760
    • tpch_adapted_1_official_1904293_1790399760

Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the automated review in 1001736: disable the aggregate kept-keys cutoff when make_distributed_plan is enabled, because that planner cannot enforce a global aggregation cap after distribution. Added a remote functional regression query with make_distributed_plan = 1.

…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
alexey-milovidov and others added 2 commits September 26, 2026 00:49
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 t_pfl_05079 (AggregateFunction(quantile('0.5'), Float64), created by the previous release while running 05079_parse_aggregate_function_typed_param): Cannot convert String to double (CANNOT_CONVERT_TYPE). It hit about 100 PRs from 2026-09-21 to 2026-09-25 in CIDB; the earlier attempt #121506 was closed without merging.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The upgrade check runs the previous release's own copy of the tests, and this run installed v26.9.2.8-stable (job.log: clone ... --branch=v26.9.2.8-stable). At that tag, 05079_parse_aggregate_function_typed_param still creates t_pfl_05079 with quantile(0.5::Decimal32(1)), which 26.9 persists as quantile('0.5'): a spelling neither 26.9 nor master can parse back (the 26.9 branch's own Stress test failed to restart on it 4 times between 2026-09-17 and 2026-09-21).

The fix is already merged: #121590 (@ azat, into 26.9 on 2026-09-22) stops 05079 from persisting the column, and #121506 was closed in favor of it. It has not reached this check because v26.9.2.8-stable predates it, and no release has been published on any branch since 2026-09-22. The check takes the newest published release below 26.10, so it turns green with the next 26.9 release. No new PR from me.

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 v26.9-must-backport label yet.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (clean merge) and addressed the ⚠️ Request changes verdict and the CI performance regression.

  • exact_rows_before_limit (f591daa): the shared getTrivialGroupByLimit bails out, which also fixes the pre-existing settings-based form. New test 05256.
  • Performance regression optimize_trivial_group_by_limit #4 (+40% amd, +58% arm) (27003a5): measured head to head on the same build, the GROUP BY top-K heap beats the kept-keys cutoff on fixed-width keys too (#4 vs #5: 71.8 vs 47.7 ms amd, 51.1 vs 32.3 ms arm). The earlier "7-9x" figures were measured against a baseline with the heap disabled. Local runs of the CI binary agreed on every key type. So the planner now arms the cutoff only when the heap does not apply: it is disabled, LIMIT + OFFSET is above its cap (1000 by default), max_rows_to_group_by is set, or the plan is serialized. This also makes the LowCardinality(Nullable(T)) finding moot. The tests of the cutoff now disable the heap explicitly instead of relying on the CI profile's max_rows_to_group_by: 10G. The PR description is updated.
  • Upgrade check: unrelated, and already fixed on the 26.9 branch by Fix 26.9 upgrade check #121590; it clears with the next 26.9 release.
  • array_first_last #11: unrelated to aggregation, which this PR changes.

All 13 trivial_group_by_limit tests pass locally, including 5 randomized runs each.

/// 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]

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.

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 alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 28, 2026
Merged via the queue into master with commit e112dc2 Sep 28, 2026
344 of 349 checks passed
@alexey-milovidov
alexey-milovidov deleted the trivial-group-by-limit-aggregates branch September 28, 2026 02:20
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

robinld pushed a commit to robinld/ClickHouse that referenced this pull request Oct 4, 2026
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]>
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 13, 2026
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]>

This branch was successfully deployed

1 active deployment
staging - docs — d59d9a82 Deployed Sep 26, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). 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.

Trivial GROUP BY LIMIT optimization: support aggregate functions in the projection (2x on ClickBench Q17)

4 participants