Skip to content

Replace reseed block with storing spilled keys inside aggregation hashtable w/o states - #129750

Draft
azat wants to merge 5 commits into
ClickHouse:masterfrom
azat:replace-reseed-with-empty-states
Draft

azat wants to merge 5 commits into
ClickHouse:masterfrom
azat:replace-reseed-with-empty-states

Conversation

@azat

@azat azat commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Replace reseed block with storing spilled keys inside aggregation hashtable w/o states

Resolves quadratic spilling of #126249


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

azat added 2 commits November 6, 2026 09:05
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
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [187562f]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
05407_external_aggregation_overflow_any_spill_before_cap FAIL cidb
05407_external_aggregation_overflow_any_spill_before_cap FAIL cidb
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
aggregation_overflow #1 FAIL dashboard
aggregation_overflow #0 FAIL dashboard
aggregation_overflow #2 slower query history
system_clusters_replicated_databases #0 unstable query history

AI Review

Summary

The PR retains admitted aggregation keys across spills and writes only newly accumulated states, avoiding repeated spill output. Block: the current head (187562ff95ab) still breaks ordered aggregation's memory bound, and its latest cache rewrite introduces a measured 2.04× regression in aggregation that never spills. One new inline finding was submitted; existing findings are retained below without duplicate comments.

PR Metadata

Performance Improvement is appropriate. Its required changelog entry is present but needs user-facing wording; the exact replacement is given under Nits.

Findings

❌ Blockers

  • src/Interpreters/Aggregator.cpp:1208: Capped aggregation loses its cache even without spilling. The settings-only keepsKeysAcrossSpills predicate disables both consecutive-key caching and the equal-key single-place update path. Aggregating sum(number) over 100 million rows, grouped by toUInt64(intDiv(number, 1000000)), with a one-million-key cap and spilling disabled, slows from 0.233–0.235 s at 36273da5b85b to 0.477–0.479 s at a245744b6a23; throw remains at 0.226–0.235 s. Preserve safe caching until flushed states actually exist, or support revival through the cache. The affected aggregation sources are unchanged at the current head. New thread.

  • src/Interpreters/Aggregator.h:1770: Ordered aggregation retains keys from already-emitted blocks. keysArena selects persistent storage for ordered aggregation, while AggregatingInOrderTransform::generate releases only state arenas. Variable-length keys therefore accumulate across output blocks. Reproduced on a245744b6a23: the existing 200,000-row example with wide String keys succeeds in throw mode but exceeds the 40,000,000-byte limit in any mode inside AggregatingInOrderTransform. Exclude ordered aggregation from persistent-key allocation or release its key arena after conversion. Existing thread.

  • src/Interpreters/Aggregator.cpp:2809: The scheduler still counts retained keys as reclaimable memory. [dismissed by author -- https://github.com/Replace reseed block with storing spilled keys inside aggregation hashtable w/o states #129750#discussion_r4494937726] The current AggregatingTransform::getMemoryStats still reports all variants.memoryUsage() while hasData remains true for cold keys, so the original idle-query spill loop remains possible. The prior reproduction recorded 13 parts, zero released bytes, and increasing memory without further input. Report only reclaimable state memory, excluding retained keys and cold-only tables. The author-resolved thread was left untouched.

⚠️ Majors

💡 Nits

  • The changelog entry describes internal implementation rather than user impact. Replace it with: “Reduce temporary-disk writes during external GROUP BY aggregation with max_rows_to_group_by and group_by_overflow_mode = 'any', while preserving complete aggregate values for admitted groups.”
Tests
  • ⚠️ Add a committed regression for ordered aggregation with variable-length keys across multiple emitted blocks and a bounded memory limit.
  • ⚠️ Add a performance case for repeated keys with an unreached any cap and spilling disabled; the spill-volume test does not protect this path.
Performance & Safety

Consumer tracing covered executeImplBatch and mergeStreamsImplCase revival, LowCardinality mapped-value caches, nullable-key markers, inline counters, non-final conversion skipping cold states, destroyImpl skipping null states, and final flushing before in-memory merge/finalization or state-size estimation. Ordered arena lifetime and scheduler accounting remain the gaps described above. All 24 additional queries succeeded, with all 12 spill/no-spill comparisons matching across string, nullable, LowCardinality, composite serialized, and array keys, using both inline counters and ordinary aggregate states.

Final Verdict

❌ Block. Preserve ordered aggregation's memory bound and restore performance for capped aggregation that never spills, with focused regression coverage for both.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 6, 2026
The kept-keys spill rework replaced the per-stream rebuild of the trivial
`GROUP BY ... LIMIT` cutoff with a bare `restricted_to_kept_keys` marker, so
the crossing block's overshoot stayed in the table: the query kept aggregating
groups the LIMIT drops, and the hash table statistics recorded a block-rounded
size instead of the exact cap (caught by
`05406_hash_table_stats_key_group_cap`, 550000 vs 589824).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Nov 6, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 806.51 MiB 807.15 MiB +655.14 KiB (+0.08%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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 ⚠️

23 object files changed (+7.85 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.10 MiB 35.95 MiB +7.85 MiB (+27.92%)

719 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.

Compile time of recompiled translation units

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

Translation unit Master PR Δ vs median
src/Interpreters/Aggregator.cpp 101.6 s 129.5 s +32.2 s (+33%)

Slowest changed entities of src/Interpreters/Aggregator.cpp:

  • InstantiateFunction DB::Aggregator::executeImpl<true>: +1.1 s (+55%)
  • InstantiateClass std::unique_ptr<char *[], (lambda at /ClickHouse/src/Interpreters/Aggregator.cpp:1942:27)>: +0.8 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long, bool) const new 189.35 KiB +189.35 KiB
programs/clickhouse DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long, bool) const new 189.32 KiB +189.32 KiB
programs/clickhouse DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 188.89 KiB removed -188.89 KiB (-100.00%)
programs/clickhouse-keeper DB::Aggregator::writeToTemporaryFile(DB::AggregatedDataVariants&, unsigned long) const 188.35 KiB removed -188.35 KiB (-100.00%)

Job report

@nihalzp nihalzp self-assigned this Nov 8, 2026
…ation

Keeping the admitted keys in the table across spills leaves cells with
null states, and the batch loops revived them on the next row with a
`nullptr` check per found key plus a cold call to `createAggregateStates`.
That check ran for every query, and the `aggregation_overflow` perf test
(`max_rows_to_group_by = 10`, `any`, where the first block admits all its
keys so almost every row takes the found path) got 33-43% slower on ARM.

Add a `revivable` template parameter to `executeImpl`, `executeImplBatch`
and `mergeStreamsImplCase`, selected at runtime by `keepsKeysAcrossSpills`,
so the check and the revival exist only in the instantiation that mode
uses; every other query runs the loops unchanged. The kept-keys mode now
always runs without the consecutive-keys cache (before, only under
`no_more_keys`), since the revival must reach the table cell and the cache
hands out copies: this keeps the number of extra instantiations at one per
state kind instead of two.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
/// `keepsKeysAcrossSpills`, the common state pool otherwise.
Arena * keysArena(AggregatedDataVariants & result) const
{
if (!keepsKeysAcrossSpills())

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.

[Blocker] Preserve the memory bound of aggregation over ordered input

keepsKeysAcrossSpills also returns true for params.aggregation_in_order, so executeOnBlockSmall and mergeOnBlockSmall now put variable-length keys into keys_arena. However, AggregatingInOrderTransform::generate releases only aggregates_pools, and invalidate only resets the variant type. Keys from every already-emitted block consequently accumulate until the query ends, although this path never spills. This changes ordered aggregation from bounded memory to memory proportional to the full input's keys.

For example:

CREATE TABLE t (p UInt64, k String, v UInt64) ENGINE = MergeTree ORDER BY p;
INSERT INTO t SELECT intDiv(number, 1000), concat(toString(number), repeat('x', 240)), number FROM numbers(200000);
SELECT p, k, sum(v) FROM t GROUP BY p, k
SETTINGS optimize_aggregation_in_order = 1, max_threads = 1,
         max_rows_to_group_by = 100000000, group_by_overflow_mode = 'any',
         max_memory_usage = 40000000, max_block_size = 4096,
         aggregation_in_order_max_block_bytes = 1048576
FORMAT Null;

On the available PR CI binary (36273da5b85b), this fails with MEMORY_LIMIT_EXCEEDED in AggregatingInOrderTransform; changing only the overflow mode to throw completes at a 19.66 MiB peak. The arena selection and missing release are still present at the current head (a245744b6a23). Exclude ordered aggregation from persistent-key allocation, or release its key arena when each table is converted, and add a focused regression using variable-length keys across multiple output blocks.

log_comment = '05401_external_aggregation_overflow_any_keeps_kept_keys';

SYSTEM FLUSH LOGS query_log;
SELECT max(ProfileEvents['ExternalAggregationWritePart']) > 0

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.

[Major] Keep the two-row block size out of the shared query-log scan

The session-wide max_block_size = 2 is still active for this system.query_log assertion. That table contains the other stateless tests' queries, so the helper can scan a large shared log in two-row blocks even though the fixture itself has only four input rows. The same leakage occurs in the new 05407 and 05408 tests. It makes their verification cost grow with the CI server's log and can turn these small regression tests into expensive scans.

Keep the tiny block size on the queries that exercise spilling, and give the query-log assertions a normal query-local max_block_size (or reset it before reading the log). Preserve the spill assertions and the two-row input blocks.

@azat azat added ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check labels Nov 8, 2026
/// `revivable` batch replaces in place, so its lookups must return table cells, never a
/// per-block copy of the mapped value (see `keepsKeysAcrossSpills`) - the consecutive-keys
/// cache makes such copies. Hence that mode has only the no-cache instantiation.
bool use_cache = !is_simple_count && !keepsKeysAcrossSpills()

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.

[Blocker] Preserve the cached path for aggregations that never spill

keepsKeysAcrossSpills depends only on settings, so this disables the consecutive-key cache even before any spill and when external aggregation is disabled. Besides hashing every repeated key again, StateNoCache always reports false from hasOnlyOneValueSinceLastReset, losing the single-place aggregate update path for blocks of equal keys.

This query never spills or approaches its cap:

SELECT toUInt64(intDiv(number, 1000000)) AS k, sum(number)
FROM numbers(100000000)
GROUP BY k
SETTINGS max_threads = 1, enable_adaptive_aggregator = 0,
         compile_aggregate_expressions = 0,
         max_rows_to_group_by = 1000000, group_by_overflow_mode = 'any',
         max_bytes_before_external_group_by = 0,
         max_bytes_ratio_before_external_group_by = 0
FORMAT Null;

With the ARM CI arm_binary builds, warm query times increase from 0.233–0.235 s at 36273da5b85b to 0.477–0.479 s at a245744b6a23 (2.04×); changing only the overflow mode to throw stays at 0.226–0.235 s. Startup/decompression is excluded, and the aggregation sources are unchanged between a245744b6a23 and this review's head, 187562ff95ab.

Preserve the cached path until a variant actually contains flushed states, or make revival update the backing cell while retaining safe caching. Please add a focused performance case with repeated keys and a cap that is never reached.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants