Skip to content

Spill the adaptive aggregator's learning-phase tables under memory pressure - #115038

Merged
nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-adaptive-learning-external-spill
Aug 17, 2026
Merged

nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-adaptive-learning-external-spill

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114987

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Requested by @ nihalzp in #114987 (comment).

The problem. Aggregator::executeOnBlock ends in a baseline tail that converts the table to
two-level, checks limits and spills past max_bytes_before_external_group_by. The adaptive block
returns before that tail. Its thaw arm stands down first and its frozen arm runs a drain valve, but
the learning arm returned with no memory response at all. A producer leaves learning only by
freezing at adaptive_aggregator_freeze_threshold keys or by giving up after 16x that many rows, so
with the threshold raised neither bound fires inside one query and the table grows in RAM with no
byte bound.

The change. A learning table has no frozen twin to pair with and nothing staged, so under
pressure it can stand down for good and spill through the branch that already exists below. Gating
it on the pressure trigger matters: the tail can convert the table to two-level, after which
isConvertibleToTwoLevel() is false and the producer could never freeze again, so an unconditional
fall-through would disable the feature rather than fix it.

Reachability is narrower than the report implies. At the default
adaptive_aggregator_freeze_threshold = 16384 the spill still works, so this needs a raised
threshold, not stock settings. The reporter agreed on the issue.

Validation. On the report's query with the threshold raised, ExternalAggregationWritePart goes
from 0 to 46, matching the feature-off arm, and under max_memory_usage = 700000000 the query
changes from MEMORY_LIMIT_EXCEEDED to completing. Each new defect cell fails on the unfixed
binary, the freeze counters are byte-identical on the fast path, and the two files passed 100
randomized runs.

Left alone deliberately: the stand-down reuses Reason::TooFewDistinctKeys rather than adding a
MemoryPressure enumerator, since that field has no readers today; and a frozen local table stays
unbounded in bytes for growing states such as groupArray, which the issue raises separately.

Version info

  • Merged into: 26.8.1.1521 (included in 26.8 and later)

…essure

Aggregator::executeOnBlock ends in a shared baseline tail that converts the
table to two-level, checks limits, and spills past
max_bytes_before_external_group_by. The adaptive block returns before that
tail: the thaw arm stands down first and the frozen arm runs its drain valve
under the same trigger, but the learning arm returned with no memory response
of any kind.

A producer leaves the learning phase only by freezing at
adaptive_aggregator_freeze_threshold keys or by giving up after
adaptive_freeze_give_up_row_multiple times that many rows. Raise the threshold
and neither bound fires inside one query, so every block took the early return
and the local table grew in RAM with no byte bound: the phase is bounded only
in keys, and the single limit the arm did check, max_rows_to_group_by, has to
be 0 for the adaptive path to be admitted at all. A GROUP BY that spills with
the feature off then dies with MEMORY_LIMIT_EXCEEDED with it on.

A learning table is an ordinary table. It has no frozen twin to pair with, no
staged records, and no shared session, so unlike a frozen one it can stand
down for good and spill through the branch that already exists. The stood-down
state is the one the give-up rule already produces, so the merge path needs no
change.

The transition is gated on the pressure trigger rather than unconditional.
The baseline tail can convert the table to two-level, and
isConvertibleToTwoLevel() is false for an already-two-level table, so the
freeze guard would never pass again and an unconditional fall-through would
trade this bug for a silently foreclosed feature. Copying the frozen arm's
valve instead would be a no-op: it drains a backlog that is only ever
populated from the frozen path, through a session that freezeAdaptive has not
initialized yet.

Reachability needs a raised adaptive_aggregator_freeze_threshold. At the
default of 16384 the spill still works, so this is not a default-on
regression.

Closes: ClickHouse#114987
Every other adaptive control transition has a ProfileEvent (freeze, give-up,
thaw, probe bypass, the frozen arm's pressure sweep); the pressure stand-down
added by the previous commit had none, so the one path that repairs the
learning-phase spill hole was the only one an operator could not observe.

It also makes the regression test pin the branch directly. Before this, 04650
asserted only that a spill happened with the feature enabled, which implies the
new branch only through a three-step inference over two private constants
(adaptive_aggregator_freeze_threshold, so freeze cannot fire, and
adaptive_thaw_min_staged_records, which pure learning never reaches). A later
change to either bound would have quietly turned that cell into a plain
baseline-aggregation assertion that still passed.

The isLearning() test keeps the counter honest rather than gating the
transition: a producer that already stood down on the give-up rule earlier in
the same block would otherwise be counted as a pressure stand-down too. The
standDown call itself stays unconditional, because it is idempotent and takes
the same reason either way. Measured on the give-up regime (50 keys, 400k rows,
max_bytes_before_external_group_by = 1): without the test the counter reports 3
stand-downs that never happened; with it, 0, while the genuine pressure regime
still reports 4.

The counter is deliberately not added to 04654, which enumerates one row per
control path: none of its four queries raises the freeze threshold, so a row
there would assert a counter its own queries cannot advance.

Negative direction covered by a third clickhouse-local block, in its own
process because system.events is cumulative within one: with both external
thresholds at 0 the trigger cannot fire and the counter must stay at 0.
@groeneai

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

Two review rounds ran on this change: a cold code review plus an independent second-model gate on
each. Round 1 raised one major and bounced it back for a fix; round 2 came back clean.

Round 2 (this revision, 687d548): 0 findings. The re-review was scoped to the delta
(4 files, +30 lines) and covered Aggregator.cpp in full, all changed tests and references, every
executeOnBlock caller, the adaptive state/drain/finish paths, the admission and type matrix, and
the ProfileEvents plumbing.

Round 1 (4e8d89f): 1 major, fixed here.

Finding Verdict
❌ The new stand-down was the only adaptive control path with no ProfileEvent. Freeze, give-up, thaw, probe-bypass and the frozen valve all have one. Without it the test could only pin the branch by elimination over two private constants, so a change to either bound would silently turn the assertion into a baseline-aggregation check that still passes. Agreed, fixed. AdaptiveAggregationPressureStandDowns, incremented at the transition, asserted in both directions in 04650.
⚠️ Same finding also asked to remove or strengthen 04649's equality cell. Disagreed. That cell is the only coverage of a stood-down producer's two-level table merging beside never-engaged producers in prepareVariantsToMerge, which converts every non-two-level variant when at least one is two-level. All six pre-existing cells in that file are arm-vs-arm equality comparisons, so it follows the file's pattern. The strengthening landed in 04650 instead, where the defect oracle and a dedicated clickhouse-local process already live.
⚠️ The finding claimed both new 04650 cells pass on the unfixed binary. Refuted. They redden: 1 to 0, and 3000000 to Code: 241. The gate had run them with enable_adaptive_aggregator = 0, which is not the oracle's arm; the file pins = 1.

Noted, not blocking:

  • 💡 The stand-down reuses Reason::TooFewDistinctKeys rather than a MemoryPressure enumerator.
    That is the wrong label, but the field has no readers anywhere in src/ today, so a new
    enumerator would be dead code. Happy to add it if you want the introspection.
  • 💡 The new ProfileEvent description is longer than its neighbours in that block. Trimmed to
    taste on request.
  • 💡 The 04650 cell asserting the counter stays at 0 with no external threshold does not itself
    assert the adaptive path engaged in that arm, so in principle a future admission-gate rejection
    could make it pass vacuously. The three cells directly above it run the same query shape and
    assert the engaged direction, so that regression would redden those first.
  • 💡 Both test files grew by a 3M-row aggregation. Both already carry Tags: long; the slowest
    CI cells over the last 7 days were 25.0 s and 22.1 s with no failures, against a 600 s per-test
    timeout, and the dataset size is what separates the two memory floors.

The guard on the new counter was verified with a mutation build rather than by inspection: with
the isLearning() test deleted, the give-up regime reports 3 stand-downs that never happened;
with it, 0, while both binaries report 4 on the genuine pressure regime.

Session id: cron:clickhouse-review-slot-11:20260816-193800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on one command. clickhouse local with max_bytes_before_external_group_by=20000000, adaptive_aggregator_freeze_threshold=4000000, group_by_two_level_threshold=1000 over SELECT concat(toString(number), repeat('x', number % 40)) AS k, count() FROM numbers_mt(3000000) GROUP BY k: ExternalAggregationWritePart is 0 with enable_adaptive_aggregator=1 and 46 with 0. Not a low-rate flake.
b Root cause explained? The learning arm of Aggregator::executeOnBlock returned before the shared baseline tail with no memory check, while the thaw arm stands down and the frozen arm runs a drain valve. A producer leaves learning only by freezing at adaptive_aggregator_freeze_threshold keys or by giving up after 16x that many rows, so a raised threshold means neither bound fires inside a query. The phase is bounded only in keys, and the one limit that arm checked, max_rows_to_group_by, must be 0 for the adaptive path to be admitted at all.
c Fix matches root cause? Yes. It adds the missing state transition in the arm that lacked it, under the same trigger expression the frozen arm and the baseline already use, so control reaches the existing spill branch. Not a widened bound, a size reduction, a no-random tag, or a guard at the failure site.
d Test intent preserved / new tests added? No existing cell, setting or tag was weakened; Tags: long was removed only for the randomized sweep and restored (md5 of both files verified byte-identical afterwards). Added to 04650: a spill counter cell, a memory-limit cell, a stand-down counter cell, and a third clickhouse-local block asserting the counter stays 0 with no external threshold. Added a correctness cell to 04649.
e Both directions demonstrated? Yes. ExternalAggregationWritePart 0 to 46. Under max_memory_usage=700000000 the query goes from Code: 241 MEMORY_LIMIT_EXCEEDED to completing. AdaptiveAggregationPressureStandDowns 4 with the fix, absent on base. Each defect cell was re-run against a binary with the transition reverted and reddens there (1 becomes 0; the memory cell raises Code: 241). The negative cell yields 0 on the fixed binary.
f Fix is general across code paths? All arms of executeOnBlock audited. Fixed: learning. Already correct: baseline tail, both thaw sites, frozen arm (has its own valve; its local table is key-bounded and cannot pair a spilled two-level twin). Verified non-carriers: mergeOnBlock and executeOnBlockSmall take no adaptive parameter; the TTLAggregationAlgorithm and AggregatingTransform::initGenerate call sites pass a null adaptive.
g Fix generalizes across inputs (params/datatypes/wrappers)? The gate reads params.max_bytes_before_external_group_by, which Params::getMaxBytesBeforeExternalGroupBy already resolves from both the absolute setting and max_bytes_ratio_before_external_group_by, so one check covers both spellings. Threshold values 0, the default 16384, and 4000000 all measured. Key and state shapes covered by the family: numeric keys, short and long strings, string arguments, fat uniqExact states, few and many groups.
h Backward compatible? Yes. No setting added, no default changed, no serialization or on-disk format touched, no replication path, so no SettingsChangesHistory.cpp entry is due. With no external threshold configured every adaptive profile event is byte-identical to before.
i Invariants and contracts preserved? standDown is the existing terminal transition to BaselineState, so the resulting state is the one the give-up rule already produces and the merge already handles. No lock is taken or released, nothing is staged or drained, the shared session is untouched, and checkLimits still runs on every path including when the new branch does not fire. Merge-side type agreement is asserted by the new equality cell rather than argued.

Session id: cron:clickhouse-impl-slot-7:20260816-182200

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [687d548]

Summary: ✅


AI Review

Summary

This PR fixes a real gap in adaptive GROUP BY spilling: a producer that is still in the learning phase can now stand down under memory pressure and fall through the existing baseline external-aggregation path, and the added tests cover both the result correctness and the new observability counter. I did not find a correctness or safety issue in the code changes themselves; the only review concern is that the PR is currently classified as Not for changelog even though it fixes user-visible query behavior.

PR Metadata

Changelog category is not semantically correct. This change fixes user-visible misbehavior in a stable query path, so it should use Bug Fix, not Not for changelog.

With Bug Fix, a real Changelog entry is required, and the current ... placeholder does not satisfy that requirement.

Exact replacement:

### Changelog category (leave one):
- Bug Fix (user-visible misbehavior in an official stable release)

### Changelog entry (a [user-readable short description](https://github.com/ClickHouse/ClickHouse/blob/master/docs/changelog_entry_guidelines.md) of the changes that goes into CHANGELOG.md):
Fixes adaptive `GROUP BY` spilling when `adaptive_aggregator_freeze_threshold` is raised, so queries in the learning phase can still honor `max_bytes_before_external_group_by` instead of failing with `MEMORY_LIMIT_EXCEEDED`.
Final Verdict

✅ Code looks correct. Update the changelog category and entry before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 11/14 (78.57%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @KochetovNicolai, could you review this? The adaptive aggregator's learning arm returned from executeOnBlock before the baseline tail, so max_bytes_before_external_group_by was a no-op for the whole learning window; it now stands down under the same pressure trigger the frozen arm uses and reaches the existing two-level conversion and writeToTemporaryFile. Gated on the trigger rather than falling through unconditionally, because a converted table can never satisfy isConvertibleToTwoLevel() again and would foreclose freezing.

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 687d54873 with master ce6df4653 (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
Binary Master PR Δ
programs/clickhouse-stripped 694.64 MiB 691.63 MiB -3.01 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Job report

@nihalzp nihalzp self-assigned this Aug 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 687d548

CI is fully finished on this head and it is clean: 177 check-runs, 157 success / 20 skipped,
0 failed, 0 cancelled, 0 still running. Config Workflow and Finish Workflow both succeeded,
and the praktika report is top-level OK with 0 dropped jobs, so the filtered matrix is a real
run rather than a void one. CIDB has 336766 rows across 159 checks for this commit.

Check / test Reason Owner / fixing PR
Config Workflow / Pre Hooks (20:27:45Z, 20:51:53Z) superseded: can be tested label was not yet applied when the workflow first dispatched not applicable, the same job re-ran green at 21:19:42Z on this identical commit

Those two CIDB rows are historical, not open. Both predate the label being applied; the same
Config Workflow job then completed success at 21:19:42Z on the same commit_sha, and the
praktika report for this head reports 0 dropped jobs at every depth.

All five AST fuzzer (*) variants, including both targeted flavours, are green on this head, as
are the Stress test (*) jobs. Counts come from an aggregate CIDB query over this commit, not from
a tally of the job list.

Session id: cron:our-pr-ci-monitor:20260817-020000

@nihalzp
nihalzp added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit cb012d3 Aug 17, 2026
531 of 535 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog 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.

Adaptive learning phase returns before the external-spill branch, ignoring max_bytes_before_external_group_by

4 participants