Skip to content

Fix wrong results after external GROUP BY and max_rows_to_group_by>0 - #126249

Merged
azat merged 1 commit into
ClickHouse:masterfrom
azat:fix-kept-keys-explicit-overflow-any
Nov 12, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
azat:fix-kept-keys-explicit-overflow-any

Conversation

@azat

@azat azat commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix wrong results after external GROUP BY and max_rows_to_group_by>0 (can lead to excessive spills with max_rows_to_group_by>0 and group_by_overflow_mode=any, but only in case of spilling limit is small)

With max_rows_to_group_by>0/group_by_overflow_mode=any, a stream stops admitting new keys and keeps aggregating the ones already in its hash table.

But external aggregation empties that table, so every later row of an admitted key found nothing to merge into and was dropped: the key came out of the merge with only the rows that preceded the spill.

The trivial GROUP BY ... LIMIT is not affected, since it introduced the "reseed" concept (in #114690), that was used here to fix it.


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

Version info

  • Merged into: 26.11.1.2006-master (included in 26.11 and later)
  • Backported to: 26.10.12.12

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b91f25c]

Summary: ✅


AI Review

Summary

PR #126249 preserves admitted keys across external GROUP BY spills when an explicit max_rows_to_group_by uses group_by_overflow_mode = 'any'. Reviewed head: b91f25c2edb77fdc025303da4b1d4cd36de87ce0. The previously reported resource regression remains reproducible; changes are requested.

Findings

⚠️ Majors

  • src/Interpreters/Aggregator.cpp:3497–3521,3559–3577: Retaining admitted keys must preserve external aggregation's resource bounds. [dismissed by author -- https://github.com/Fix wrong results after external GROUP BY and max_rows_to_group_by>0 #126249#discussion_r4336293286]

    Every spill recreates every previously admitted group with an empty aggregate state. Later spills write those groups again, including keys absent from the intervening input. While distinct keys accumulate below the cap, spill volume grows quadratically with the number of input blocks, and the repeated states increase external-merge memory.

    Reproduced with the current head's Fast test binary:

    SELECT toUInt64(number) AS k, count()
    FROM numbers(200000)
    GROUP BY k
    SETTINGS max_threads = 1, max_block_size = 4096,
             enable_adaptive_aggregator = 0,
             max_rows_to_group_by = 1000000, group_by_overflow_mode = 'any',
             group_by_two_level_threshold = 1,
             group_by_two_level_threshold_bytes = 0,
             max_bytes_ratio_before_external_group_by = 0,
             max_untracked_memory = 0,
             max_bytes_before_external_group_by = 2000000,
             max_memory_usage = 50000000
    FORMAT Null;

    This raises MEMORY_LIMIT_EXCEEDED during the external merge after writing 22,981,993 compressed bytes. Changing only max_rows_to_group_by to 0 succeeds and writes 920,197 bytes. Neither run reaches the explicit cap. The author's accepted tradeoff remains a concern because it makes a fitting workload fail its memory limit and multiplies spill I/O by approximately 25.

    Keep admitted-key bookkeeping separate from spillable aggregate states, and avoid writing empty states for keys untouched since the preceding flush, or use an equivalent approach that preserves spill bounds while enforcing the cap.

Tests
  • ⚠️ Add a resource regression with several spills before the explicit cap is reached, checking successful completion under a fixed memory limit. The three added regressions exercise tiny key sets and cannot detect the retained-state amplification above.
Final Verdict

⚠️ Request changes. Preserve spill resource bounds while retaining admitted-key identities, and cover that behavior with a focused regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 16, 2026
@azat
azat force-pushed the fix-kept-keys-explicit-overflow-any branch from 472ab5d to 31c458b Compare October 20, 2026 16:58
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b91f25c2e with master 2170ef336 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

7 object files changed (+99.36 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.13 MiB 28.23 MiB +99.20 KiB (+0.34%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.95, programs/clickhouse-keeper ×1.10 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 9.1 s 18.5 s +9.8 s (+114%)
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long, bool) const new 7.5 s +7.5 s
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 4.7 s gone -5.2 s (-100%)
Compile time of recompiled translation units

91 translation units recompiled, 1004 s compile time in total, 91 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +53.8 s (+6%) in total before that adjustment.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long, bool) const new 226.55 KiB +226.55 KiB
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long, bool) const new 225.79 KiB +225.79 KiB
programs/clickhouse DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 186.53 KiB removed -186.53 KiB (-100.00%)
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 185.84 KiB removed -185.84 KiB (-100.00%)

Job report

@nihalzp nihalzp self-assigned this Oct 20, 2026
@azat
azat marked this pull request as draft October 20, 2026 21:51
@azat
azat force-pushed the fix-kept-keys-explicit-overflow-any branch from 31c458b to 9dd53bc Compare October 21, 2026 11:07
@azat
azat marked this pull request as ready for review October 21, 2026 11:07
Comment thread src/Interpreters/Aggregator.cpp Resolved

@nihalzp nihalzp left a comment

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.

Looks good!

Regarding the quadratic memory issue, one idea could be that instead of populating the aggregation table with keys after spill, we can keep the seeded keys separately in some hash set. Then, for every incoming key, we can probe the table first and if it misses then probe the hash set: before the cap, the hash set tells whether the key is new and counts toward max_rows_to_group_by; after the cap, a key found in the hash set goes back into the table and the others are dropped. We can optionally speed this up by having a Bloom filter as well.

The benefit is that our aggregation stays fast because the local table after a spill would stay small most of the time compared to the hash set with all seeded keys. Second, we avoid the quadratic memory issue because each spill empties the aggregation table and writes only the states accumulated since the previous spill, and the seeded keys no longer count toward the spill floor.

@clickhouse-gh clickhouse-gh Bot added the can be tested Allows running workflows for external contributors label Nov 3, 2026
@azat
azat force-pushed the fix-kept-keys-explicit-overflow-any branch from 9dd53bc to a935ccc Compare November 6, 2026 08:28
@azat

azat commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Regarding the quadratic memory issue

You mean spilling right, yes it can be fixed that way, but I decided not to do any optimizations here and only fix the real bug, introducing separate hashtable will need extra handling, while this use case looks very narrow, not sure it worth the complexity

With max_rows_to_group_by>0/group_by_overflow_mode=any, a stream stops
admitting new keys and keeps aggregating the ones already in its hash
table.

But external aggregation empties that table, so every later row of an
admitted key found nothing to merge into and was dropped: the key came
out of the merge with only the rows that preceded the spill.

The trivial `GROUP BY ... LIMIT` is not affected, since it introduced
the "reseed" concept, that was used here to fix it.

v2: Stop capping `GROUP BY` once external aggregation has flushed anything
v3: Keep the keys of every spill so `max_rows_to_group_by` still counts them
@azat
azat force-pushed the fix-kept-keys-explicit-overflow-any branch from a935ccc to b91f25c Compare November 10, 2026 16:39
@azat
azat added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit 4951f24 Nov 12, 2026
187 checks passed
@azat
azat deleted the fix-kept-keys-explicit-overflow-any branch November 12, 2026 01:13
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 19, 2026
robot-clickhouse added a commit that referenced this pull request Nov 24, 2026
Cherry pick #126249 to 26.10: Fix wrong results after external GROUP BY and max_rows_to_group_by>0
robot-clickhouse added a commit that referenced this pull request Nov 24, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 24, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 24, 2026
Backport #126249 to 26.10: Fix wrong results after external GROUP BY and max_rows_to_group_by>0
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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

6 participants