Skip to content

Size the adaptive aggregator's pressure valve from the spill threshold - #117880

Merged
alexey-milovidov merged 20 commits into
masterfrom
fix-adaptive-drain-memory
Sep 6, 2026
Merged

alexey-milovidov merged 20 commits into
masterfrom
fix-adaptive-drain-memory

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Closes: #117879
Related: #117326
Caused by: #111459

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):

Fixed an external GROUP BY dying with MEMORY_LIMIT_EXCEEDED inside the adaptive aggregator's own memory valve when enable_adaptive_aggregator is on. The pressure sweeps that shed the staged backlogs to disk sized their working set - the batch a sweep claims, the residue the tails share, and the tables in flight to the writer - from absolute constants that did not know max_bytes_before_external_group_by, so the valve could hold tens of times the budget it was defending. They are now sized from that threshold.

Description

enable_adaptive_aggregator's pressure sweeps are the memory valve of the frozen path: once query memory crosses max_bytes_before_external_group_by they claim a batch of the staged backlogs, drain it into a hash table and write that table out through the ordinary external aggregation. The three things the valve holds while doing that - the batch it claims, the residue its sub-part tails accumulate in the session's shared table, and the tables in flight to the writer - were bounded by adaptive_pressure_spill_min_keys (a million keys) and adaptive_pressure_detached_bytes_budget (256 MiB). Neither knows the threshold, so the valve's own working set could be tens of times the budget it was defending, and the query died on max_memory_usage while it was supposed to be spilling.

A million keys with their aggregate states is hundreds of megabytes whatever max_bytes_before_external_group_by says, and 256 MiB in flight is more than the whole budget of a query that asked to spill at 200 MB.

adaptivePressurePartBytes sizes a part from the threshold - an eighth of it, floored - and the two detach sites now read the built table's real allocatedBytes beside the key count, so a table of wide keys is written before it outgrows the budget instead of after a million of them. The sweep's claim is bounded the same way, by the bytes its drain is expected to take rather than by the record count alone, and the in-flight budget is narrowed to a couple of parts. adaptive_pressure_spill_min_keys and adaptive_pressure_detached_bytes_budget stay as the ceilings, so a query with a large threshold, or none at all, behaves exactly as before.

The part floor is measured rather than picked. The peak is a U in it, because a part too small is padding and a reader: on a 3M-key external GROUP BY spilling at 20 MB the query needs 200 MB of max_memory_usage at an 8 MiB floor (90 parts), 150 MB at 32 MiB (26 parts) and 200 MB again at 64 MiB (15 parts). 32 MiB is where the residue and the merge-time readers balance.

One residual left alone. The remaining pressure with this fix is on the read side, deserializing states from the spilled parts - the site #117326 addresses from the other end, by writing the residue out so a thawed producer stops spilling one part per block. The two are complementary: this one bounds what the valve holds, that one keeps the residue from poisoning a baseline producer's spill decision. Neither subsumes the other.

Validation

New test 05059_adaptive_aggregator_pressure_valve_memory.sh, parallel-safe, 1.2 s. On the base commit it fails with this task's own signature, Code: 241 ... While executing AggregatingTransform, at 286.81 MiB against a 286.10 MiB limit. Beside the result it asserts that the query really went external, that the valve really ran, that the tables really froze, that the drain really carried the stream, and that no producer thawed or stood down - so it cannot pass by taking the baseline path instead of the path the claim is about.

Limit sweep on that query, max_bytes_before_external_group_by = 20000000, same build both arms: base fails at 100, 150, 200, 300 and 400 MB and passes at 600 MB, having spilled 41 MiB in 7 parts; with the fix it passes from 150 MB up, spilling 32 MiB in 26 parts. At max_bytes_before_external_group_by = 200000000 the base needs more than 600 MB and the fix passes at 400 MB.

00084_external_aggregation statement 2 against real test.hits, the test's own settings, max_memory_usage = 600000000 (= 572.20 MiB), the freeze threshold lowered so that the frozen path is taken every run instead of racing the external threshold for it: base 3 failures in 5 - two While executing AggregatingTransform at 570.91 and 568.42 MiB, one While executing SourceFromNativeStream at 570.66 MiB with 820 parts - and its two passing runs sit at 558.06 MiB, 97.5% of the limit. With the fix, 0 failures in 5 at 256.24 to 268.38 MiB, 45 to 47% of the limit, spilling 208.8 to 211.9 MiB in 38 to 54 parts. Results identical on both arms.

The whole adaptive-aggregator and external-aggregation family is green against a local server, 24 of 24 unrandomized, 00084_external_aggregation itself among them: 00084, 00284_external_aggregation, 00284_external_aggregation_2, 01576_if_null_external_aggregation, 02354_distributed_with_external_aggregation_memory_usage, 02703_jit_external_aggregation, 02933_group_by_memory_usage, 02941_projections_external_aggregation, 03560_parallel_replicas_external_aggregation, 04603, 04604, 04605, 04606, 04648, 04649, 04650_adaptive_aggregator_pressure_spill, 04652, 04653, 04654, 04824_quantile_deterministic_external_aggregation, 04910, 05025, 05042 and the new 05059.


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

Version info

  • Merged into: 26.9.1.840 (included in 26.9 and later)
  • Backported to: 26.8.3.51

`enable_adaptive_aggregator`'s pressure sweeps are the memory valve of the
frozen path: once query memory crosses `max_bytes_before_external_group_by`
they claim a batch of the staged backlogs, drain it into a hash table and
write that table out through the ordinary external aggregation. The three
things the valve holds while doing that - the batch it claims, the residue its
sub-part tails accumulate in the session's shared table, and the tables in
flight to the writer - were bounded by `adaptive_pressure_spill_min_keys` (a
million keys) and `adaptive_pressure_detached_bytes_budget` (256 MiB). Neither
knows the threshold, so the valve's own working set could be tens of times the
budget it was defending, and the query died on `max_memory_usage` while it was
supposed to be spilling. A million keys with their aggregate states is hundreds
of megabytes whatever the threshold says.

`adaptivePressurePartBytes` sizes a part from the threshold, an eighth of it
with a floor, and the two detach sites now read the built table's real
`allocatedBytes` beside the key count, so a table of wide keys is written
before it outgrows the budget instead of after a million of them. The sweep's
claim is bounded the same way, by the bytes its drain is expected to take
rather than by the record count alone, and the in-flight budget is narrowed to
a couple of parts. The absolute constants stay as the ceilings, so a query with
a large threshold, or none at all, behaves exactly as before.

The part floor is measured rather than picked: the peak is a U in it, because a
part too small is arena padding plus a reader at merge time. On a 3M-key
external `GROUP BY` spilling at 20 MB the query needs 200 MB of
`max_memory_usage` at an 8 MiB floor (90 parts), 150 MB at 32 MiB (26 parts)
and 200 MB again at 64 MiB (15 parts).

On `00084_external_aggregation` statement 2 against real `test.hits` with the
test's own settings and the frozen path taken every run, the base fails 3 times
in 5 at 568 to 571 MiB against the test's 572.20 MiB limit - twice from the
drain itself and once from the merge reading 820 parts - and its passing runs
sit at 97.5% of the limit. With this change, 0 failures in 5 at 256 to 268 MiB,
45 to 47% of the limit, spilling the same volume.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a79ae6e]

Summary: ✅


AI Review

Summary

This PR reworks the adaptive aggregator's pressure-time spill valve so its claim size, shared residue, and detached spill budget track max_bytes_before_external_group_by instead of fixed constants, and it adds focused coverage around wide payloads, heap-owning states, and oversized chunk splitting. The current head closes most of the earlier gaps, but one pressure-time tail path still lets the shared residue overfill past the new part bound before it detaches, and the new regression tests still do not uniquely prove the early-pressure path they are meant to guard.

Findings

⚠️ Majors

  • [src/Interpreters/AdaptiveAggregationKernels.cpp:1999] The pressure-time tail claim is still sized against a fresh part instead of the remaining room in shared.early_drain_variants. If the shared residue already holds just under one part, another just-under-a-part backlog still comes through the tail path, drainStagedBatch grows the shared table to nearly two parts, and only then does the code detach it. That breaks the new "shared residue is part-bounded" contract and can recreate the same MEMORY_LIMIT_EXCEEDED spike on repeated sub-part sweeps.
    Suggested fix: cap the tail claim against the remaining sharedDrainTableBytes(shared) / size() the same way the finish drain now does, or detach the shared table before draining a tail that would fill it.
Tests
  • ⚠️ [tests/queries/0_stateless/05059_adaptive_aggregator_pressure_valve_memory.sh:45] The new valve tests use AdaptiveAggregationPressureSweeps and AdaptiveAggregationPressureDrainedRecords as proof that the pressure-time path ran, but drainStagedChunksAtFinish increments both counters too. That means the checks still pass if the query survives to EOF with a staged backlog and only the finish drain externalizes it, which is weaker than the PR contract. Please pin a signal unique to drainStagedChunksUnderMemoryPressure, or use a limit/shape that demonstrably fails when only the finish drain runs. The same issue applies to the companion valve tests that copied these assertions.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit a79ae6e.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 287/308 (93.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
@nihalzp nihalzp self-assigned this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a79ae6e46 with master 319bfd73f (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

9 object files changed (+50.47 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AdaptiveAggregationKernels.cpp.o 1.83 MiB 1.87 MiB +37.04 KiB (+1.98%)

716 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

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.19 MiB 12.25 MiB +64.00 KiB (+0.51%)
programs/clickhouse ProfileEvents::global_counters_storage 12.19 MiB 12.25 MiB +64.00 KiB (+0.51%)

Job report

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 3, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 4, 2026
…memory

`Aggregator.h` conflicted where master added `releaseAdaptiveDrainResidue`
next to this branch's `adaptivePressurePartBytes` group; both declarations
are kept.

Master's `releaseAdaptiveDrainResidue` calls `SpillReservation::reserveOrWait`,
which this branch gave a third parameter - the budget, derived from
`max_bytes_before_external_group_by` rather than read from the absolute
constant. Its two calls now pass `adaptivePressureDetachedBytesBudget`, so the
residue release and the quiesce that follows it stand against the same budget
the sweeps do.
…e table's

Two review findings on the pressure valve's byte bound, both of them cases
where a bound derived from the destination table alone lets the working set
outgrow `max_bytes_before_external_group_by` anyway.

The first: `estimateAdaptiveDrainBytes` counted the records' bookkeeping and
aggregate states plus the staged key bytes, but the batch a sweep claims stays
alive until `drainStagedBatch` returns, and a general-aggregate chunk carries
its gathered `argument_columns` beside its keys. A stream of wide variable-width
arguments therefore sat entirely outside the bound: `records * (32 +
total_size_of_aggregate_states) + key_bytes` could stay under
`adaptivePressurePartBytes` while the batch itself was several times that.
`stagedChunkBytes` now reports a chunk's whole staged footprint - the routing
hashes, the key bytes and offsets, and the payload, whether that is a
count-only chunk's run lengths or a general chunk's argument columns - and the
sweep accumulates it in place of the key bytes alone, both for the claim's cut
and for the reservation it then asks the writer budget for.

The second: the finish drain sized its next batch from `part_records` only, a
count derived from the fixed state width that says nothing about a backlog of
wide keys or wide staged arguments. It could therefore recreate at the merge
boundary the over-budget table the sweeps exist to prevent. It now claims the
same way the sweep does, cutting on whichever of the record target and the byte
target the batch reaches first, each measured against the shared table's
remaining room to a part.
…keys

`05059_adaptive_aggregator_pressure_valve_memory` pins the pressure valve on a
stream whose cost is its keys and its aggregate states, which is exactly the
shape the destination-table estimate can see. The two cases it cannot are here.

The first query's aggregate argument is the widest thing in it - a couple of
hundred bytes staged per record against a `uniq` sketch over one distinct value
per group - so the batch a sweep claims is almost entirely
`AggregatePayload::argument_columns`, which the bound counted as nothing before.
The second stages wide keys with a narrow state, which is the shape whose batch
the finish drain used to size from a record count alone.

Both keep every producer frozen with all-distinct keys and encode the claim in
`max_memory_usage`, ten times the threshold they asked to spill at.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was CONFLICTING: Aggregator.h conflicted where master added releaseAdaptiveDrainResidue next to this branch's adaptivePressurePartBytes group, and master's new function calls SpillReservation::reserveOrWait, which this branch gave a third parameter - both of its calls now pass adaptivePressureDetachedBytesBudget).

Addressed both AI-Review Majors and added the tests it asked for - see the replies on the two threads and the new 05076_adaptive_aggregator_wide_payload_valve_memory.

The only red was Stress test (arm_release), on Logical error: Not-ready Set is passed as the second argument for function 'A. That is the known open fuzz blocker #107619, unrelated to the adaptive aggregator - it reproduces across unrelated pull requests and on master.

`05054_adaptive_aggregator_baseline_spill_residue` came from master with the
sweeps writing the shared drain table only at the key floor of a million keys,
so its 400000 wide keys stayed resident until a baseline thread released them.
With the part bound sized in bytes as well, the sweeps detach that table at
32 MiB, which the 400000-key residue exceeds, so whether the release found any
data left was a matter of timing and the residue release counter read 0 in CI.

The parts-versus-sweeps bound was holding on master by an accident of the old
valve: a resident residue kept query memory over the threshold, so master swept
on nearly every block (140 sweeps for 54 parts) and the parts never caught up.
With the sweeps shedding memory the count falls to about 20 for the same parts,
while the post-thaw baseline spills are the same size as on master.

The scenarios that need the residue resident now use 150000 keys at a 30 MB
threshold: about 20 MB of residue, under the part bound, and every sweep in the
tail regime, so the release is deterministic (verified across repeated runs, in
the keys-only and the live-states variant). They read 3M rows, because a low
threshold means many parts and the merge holds a reader per part. The parts are
bounded against the block count instead of the sweeps; the no-spill scenario
asserts the release counter instead of the absence of parts, since the sweeps
may legitimately write at the part bound.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117880&sha=6020df95f251bbd06297e50d2efdfee86e076ef0&name_0=PR&name_1=Fast%20test
PR: #117880
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged `master` again (clean, no conflicts) and fixed the sole CI red, `05054_adaptive_aggregator_baseline_spill_residue` in Fast test (the `Finish Workflow` red was only the Bugfix validation jobs being dropped behind it).

The test came from master assuming the sweeps write the shared drain table only at the million-key floor, so its 400000 wide keys stayed resident until a baseline thread released them. With the part bound also sized in bytes, the sweeps detach that table at 32 MiB, which the 400000-key residue exceeds, so whether the release found any data was timing: `AdaptiveAggregationResidueReleases` read 0 in CI and 1 locally on the same binary.

Its `parts <= sweeps` bound held on master by an accident of the old valve: with the residue resident, query memory stayed over the threshold and master swept on nearly every block (140 sweeps for 54 parts, measured with the master binary). With the sweeps actually shedding memory the count drops to about 20 for the same parts, while the post-thaw baseline spills are the same size as on master (tables of 65k-140k keys), so the branch does not reintroduce the one-part-per-block defect the test guards.

The rewrite in `6d8bbb52333a`: the two scenarios that need the residue resident use 150000 keys at a 30 MB threshold (about 20 MB of residue, under the part bound, every sweep in the tail regime), which made the release deterministic in every one of the repeated local runs, keys-only and with live states. They read 3M rows because the merge holds a reader per part and the lower threshold produces more of them. The parts are bounded against the block count instead of the sweeps, and the no-spill scenario asserts the release counter rather than the absence of parts, since the sweeps may legitimately write at the part bound. `05059` and the new `05076` still pass locally.

…ide its time limit

`05054_adaptive_aggregator_baseline_spill_residue` took 235 s in
`Stateless tests (amd_asan_ubsan, flaky check)`, over the 180 s limit: the check runs
the changed tests on every core of the runner at once, and all four scenarios spill on
every row, which a sanitizer build pays for several times over. The four scenarios now
process half the rows (and the third one takes the first scenario's shape instead of
6M rows at an 80 MB threshold), which halves the ASan CPU time of the test from about
42 s to about 15 s, while every assertion still held in 16 repeated runs on the ASan
and release binaries. The second scenario keeps a threshold well above the residue
scenarios': at 40 MB one thread in five runs froze instead of giving up.

#117880
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117880&sha=6d8bbb52333af0b41ef5009df15797b3dab13427&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
Address review: the batch a pressure sweep claims is sized from the records'
bookkeeping, the fixed width of their states and the staged bytes, and read back
through `allocatedBytes`, which sums arenas and hash-table buffers; states such as
`uniqExact` or `groupBitmap` own memory outside the arenas that neither reading sees.
The producer-local drain runs on one thread, so the growth of that thread's own memory
tracker across `drainStagedBatch` is the built table's full cost, heap included, and
the reservation against the detached-bytes budget is now corrected to the largest of the
estimate, `allocatedBytes` and that growth.

The new `05097_adaptive_aggregator_heap_state_valve_memory` is the focused repro: keys
repeating four times in a row, so every group's `uniqExact`, `groupBitmap` and
`groupArray` states hold several values while the stream stays on the frozen path, at
a 20 MB threshold inside a 200 MB memory cell.

#117880
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (clean) and pushed two commits.

The sole red was 05054_adaptive_aggregator_baseline_spill_residue in Stateless tests (amd_asan_ubsan, flaky check), at 235 s against the 180 s limit. It was not a hang: that check runs the changed tests on every core of the runner at once, and in that run everything was six to seven times slower than in the parallel suites - the pre-existing 05059 took 74 s there against its usual 10 s - so the heaviest test crossed the limit. 05054 was the heaviest because all four scenarios spill on every row, which a sanitizer build pays for several times over. 499b6e75c122 halves the rows of every scenario (the third one takes the first one's shape instead of 6M rows at an 80 MB threshold), which takes the test from about 42 s to about 15 s of ASan CPU time, below the other two; every assertion held in 16 repeated runs on the ASan and release binaries. The second scenario's threshold stays well above the residue scenarios' on purpose: at 40 MB one thread in five runs froze instead of giving up.

b80146facdd5 answers the open review thread on states that own memory outside the arenas - measurements, the bound, a correction of the sweep's spill reservation to the drain's own tracked allocation, and the focused repro 05097_adaptive_aggregator_heap_state_valve_memory; see the reply there.

…hread cannot freeze

The second scenario of `05054_adaptive_aggregator_baseline_spill_residue` asserts that
no thread froze (`AdaptiveAggregationLocalFreezes` = 0) and that the threads gave up on
freezing instead. It fed a hot prefix followed by a unique tail, which assumes every
thread sees enough hot rows before its first tail block: a thread gives up after
sixteen times the freeze threshold in rows while under the threshold in keys, and
freezes as soon as a block leaves it at the threshold. `numbers_mt` hands blocks out on
demand, so on a loaded runner a thread that starts late draws its first block from the
tail and freezes on it. That is what the four flaky checks hit
(`no shared table was created 0`).

Every block now carries the same mix, one unique key in thirty-two rows, so a thread
holds about five hundred keys when it gives up and cannot reach a thousand before
then in any order of the blocks. The threshold is lowered to what the unique keys of
2M rows cross early, so the scenario still goes external.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117880&sha=b80146facdd5f484f981b7b0b41e25c7a132b6ef&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
#117880
Address review: the shared `early_drain_variants`, which the tail drains grow across
many sweeps, was sized and reserved by `allocatedBytes` alone at the finish-drain cap,
the tail detachment and `releaseAdaptiveDrainResidue`, and `allocatedBytes` sums only
arenas and hash-table buffers, so heap that states such as `uniqExact` or `groupBitmap`
own outside the arenas was invisible on that path even after the producer-local drain
started reading its own tracked allocation.

The session now keeps `early_drain_tracked_bytes`, the growth of the sweeping thread's
memory tracker across every `drainStagedBatch` into the shared table since it was last
replaced, and all three places read the larger of `allocatedBytes` and that account. Both
drains into the shared table run under `pressure_sweep_mutex`, which guards the account.
A new profile event, `AdaptiveAggregationSharedTableSpills`, counts the shared table's
writes at the part bound, and `05097_adaptive_aggregator_heap_state_valve_memory`
asserts it, so the heap-state shape is proven to travel the shared-table path as well
as the producer-local one.

#117880
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (clean) and pushed two commits.

The red was 05054_adaptive_aggregator_baseline_spill_residue in the four flaky checks, all on the second scenario: no shared table was created 0, a thread froze instead of giving up. The scenario fed a hot prefix and then a unique tail, which assumes every thread sees enough hot rows before its first tail block - a thread gives up after sixteen times the freeze threshold in rows while under it in keys, and freezes as soon as a block leaves it at the threshold. numbers_mt hands blocks out on demand, so on a loaded runner a thread that starts late draws its first block from the tail and freezes on it. 4602eea8f779 gives every block the same mix, one unique key in thirty-two rows: a thread holds about five hundred keys when it gives up and cannot reach a thousand before then, in any order of the blocks. Passes repeatedly here on the CI release binary and on a fresh local build; the other three scenarios are unchanged.

ce1eed778911 answers the open review thread on the shared drain table (the tail drains' allocatedBytes-only sizing) - see the reply there. The four adaptive tests 05054, 05059, 05076 and 05097 pass on the rebuilt binary.

@mintlify

mintlify Bot commented Sep 5, 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 5, 2026, 4:47 PM

…und on its own

`splitStagedChunkAtPartBound` cut a chunk along bucket boundaries only, so a
chunk whose bytes sat in one two-level bucket - a few records with wide
arguments routed to the same bucket - came out of the cut as a single range
and was published whole; the pressure sweep and the finish drain then claimed
it whole, `reserveOrWait` admitted the oversized request as the only one, and
the drain built a table over the part the bound exists to keep. The ranges are
now record ranges: a bucket that fits is taken whole, and a bucket that is over
the bound on its own is cut inside, record by record, so only a single record
over the bound can still go out as one piece. `sliceStagedChunk` takes a record
range for that, which is a contiguous slice of every staged array like a bucket
range was; a bucket that spans two pieces is drained in two goes.

The new test `05102_adaptive_aggregator_same_bucket_chunk_split` routes
sixty-four one-megabyte arguments to bucket 120 alone and asserts that the
chunk was cut and that no piece came out over the bound. The
`AdaptiveAggregationStagedChunkPiecesOverBound` event description follows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Pushed a114d37 for the AI Review's remaining Major: a staged chunk whose bytes sit in one two-level bucket was published unsplit, because the cut ran along bucket boundaries only. The cut now goes record by record inside a bucket that is over the bound on its own, so only a single record over the bound can still go out whole. New test 05102_adaptive_aggregator_same_bucket_chunk_split covers the same-bucket shape (all sixty-four heavy rows in bucket 120); the thread is replied and resolved. The branch is 291 commits behind master but merge-clean and nothing was red, so it was not re-merged this pass.

…rt bound

Both claims of staged chunks - the pressure sweep's and the finish drain's - appended a
chunk and only then compared the batch against the part bound, so a batch stopped after the
chunk it crossed on and held two chunks each just under the bound. With the cut at publication
that shape is real: a single record over half a part comes out as a piece of its own, and two
such pieces of 24 MiB in one backlog were claimed together and drained into one table of 48 MiB
against a 32 MiB part.

`claimStagedChunksToBound` now runs the claim for both drains and closes it before a chunk whose
addition would reach the record or the byte target, leaving that chunk to the next claim; a
claim closed that way is a full batch, a part of its own. Only a first chunk that is over a
target alone is still taken whole. The new `AdaptiveAggregationStagedClaimsClosedAtBound` event
counts the claims closed this way.

The new `05103_adaptive_aggregator_claim_closed_at_bound` is the requested repro: three records
with a twenty-megabyte argument each, all in two-level bucket 120 so their pieces are published
back to back, at a threshold whose part bound is the 32 MiB floor; it asserts the three pieces
over half a part and a claim closed before one of them. The eight other adaptive valve tests
pass on the rebuilt binary.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed a79ae6e for the AI Review's remaining Major on the claim loops: both drains appended a chunk and only then tested the part bound, so two single-record pieces each just under the bound were claimed together and drained into one table of twice the part. The claim now runs through one helper for both drains and closes before the chunk that would take it to the record or the byte target, leaving it to the next claim; only a first chunk that is over the bound alone is still taken whole. The new AdaptiveAggregationStagedClaimsClosedAtBound event counts such claims and the new 05103_adaptive_aggregator_claim_closed_at_bound is the requested repro with three 20 MB records in one two-level bucket; see the thread reply. The thread is replied and resolved, and the nine adaptive valve tests pass on the rebuilt binary. Nothing was red on the previous head and the branch is merge-clean, so master was not re-merged this pass.

/// the chunk that would have taken it there, is a part of its own, which is what tells
/// the two regimes below apart; a batch that merely ran out of chunks is the tail.
routing_type = shared.early_drain_variants->type;
const auto claim = claimStagedChunksToBound(chunks, 0, routing_type, adaptive_pressure_spill_min_keys, part_bytes);

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.

claimStagedChunksToBound still sizes the pressure-time claim against a fresh part, not the remaining room in shared.early_drain_variants. If the session already carries, say, 0.9 part of residue, another 0.9-part backlog still comes through the !batch_is_full arm because this claim ignores sharedDrainTableBytes(shared), and drainStagedBatch then grows the shared table to roughly 1.8 parts before line 2037 detaches it.

That breaks the new "shared residue is part-bounded" invariant and can recreate the same MEMORY_LIMIT_EXCEEDED spike on repeated sub-part sweeps. I think the tail claim needs the same remaining-room cap the finish drain now uses, or an early detach before draining a tail that would fill the shared table.

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.

🕵 Confirmed, and fixed in 8f8f896 on the branch fix-adaptive-drain-memory-tail-detach: the tail arm of drainStagedChunksBatchUnderMemoryPressure now writes the shared table out before draining a tail into it when the residue it holds and the tail's estimate together would reach the part bound or the key floor, under the same reservation as the other detached tables; the drain then goes into a fresh table. Capping the tail claim against the remaining room instead would have turned the regime decision on its head - a claim capped at a tenth of a part comes out "full" and goes to a producer-local table, one tiny part per sweep - so the claim keeps deciding part-or-tail against a fresh part and the room check is done on the table.

The new event AdaptiveAggregationSharedTableSpillsBeforeTail counts such writes and 05104_adaptive_aggregator_shared_table_spilled_before_tail is the repro: 300-byte keys in blocks of 65536 records are cut into three pieces of half a part, two of them fill a claim and the third is a tail of half a part into a residue of half a part. On the fixed build every one of the 6-7 shared-table writes per run is a pre-emptive one in sequential runs; under 32 concurrent runs the after-drain check still fires occasionally, because the arena's chunk doubling can take a 21 MB table to 43 MB on a 17k-record tail, which no estimate sees - so the test asserts the pre-emptive count is positive, not that it equals the total.

It cannot land on this branch right now: the PR was added to the merge queue at 2026-09-06 11:55 UTC, which locks the branch. It will go up as a follow-up PR against master once this one merges.

-- aggregator, or by leaving the frozen path for the baseline one, which is not the path the
-- claim is about.
SELECT 'went external', (SELECT coalesce(sum(value), 0) FROM system.events WHERE event = 'ExternalAggregationWritePart') > 0;
SELECT 'the valve ran', (SELECT coalesce(sum(value), 0) FROM system.events WHERE event = 'AdaptiveAggregationPressureSweeps') > 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.

These assertions do not actually prove that the production-time valve ran. drainStagedChunksAtFinish also increments AdaptiveAggregationPressureSweeps and AdaptiveAggregationPressureDrainedRecords in src/Interpreters/AdaptiveAggregationKernels.cpp:1886 and src/Interpreters/AdaptiveAggregationKernels.cpp:1942, so this test still goes green if the query reaches EOF with a staged backlog and only the finish drain externalizes it.

That is weaker than the PR contract, which is specifically about the early spill path under max_bytes_before_external_group_by. Please pin a signal unique to drainStagedChunksUnderMemoryPressure, or use a shape/limit that demonstrably fails when only the finish drain runs. The same issue applies to the companion valve tests that copied these checks.

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.

🕵 Agreed, and fixed in 8f8f896 on the branch fix-adaptive-drain-memory-tail-detach: drainStagedChunksAtFinish no longer counts into AdaptiveAggregationPressureSweeps and AdaptiveAggregationPressureDrainedRecords; it has its own AdaptiveAggregationFinishDrains and AdaptiveAggregationFinishDrainedRecords. The two pressure events are now unique to drainStagedChunksUnderMemoryPressure, so the assertions in this test and in the companion valve tests prove the production-time path ran without any change to the tests themselves. All eleven adaptive tests (04650, 04654, 05054, 05059, 05076, 05097, 05099-05103) pass on the rebuilt binary, and none of them runs the finish drain at all (AdaptiveAggregationFinishDrains reads 0 in every one), so the old assertions were in fact met by the pressure path - they just could not prove it.

It cannot land on this branch right now: the PR was added to the merge queue at 2026-09-06 11:55 UTC, which locks the branch. It will go up as a follow-up PR against master once this one merges.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI Review's two remaining findings (the pressure-time tail drained into a shared table that already held nearly a part, and the valve tests' reliance on events the finish drain also increments) are fixed and tested in 8f8f896, on top of a fresh merge of master, but the push to this branch was rejected: the PR was added to the merge queue at 2026-09-06 11:55 UTC and a queued branch cannot be updated. I have not dequeued it. The commit is on the branch fix-adaptive-drain-memory-tail-detach and will be opened as a follow-up PR against master once this one merges; the two threads carry the details.

Merged via the queue into master with commit 79305ee Sep 6, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-adaptive-drain-memory branch September 6, 2026 13:01
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 6, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 6, 2026
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Sep 6, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 6, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 6, 2026
Backport #117880 to 26.8: Size the adaptive aggregator's pressure valve from the spill threshold
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 8, 2026
… about to spill

`00084_external_aggregation` statement 2 still exceeds its `max_memory_usage`
with `Code: 241 ... While executing SourceFromNativeStream` after ClickHouse#117880
merged. The measurement below is from the true-master job on `79305ee7`, which
is that fix's own merge commit, so it was compiled in.

Records staged before the thaw stay published for the merge, by design
(Aggregator.cpp:2374-2380), and a thread the thaw put back on the baseline path
cannot free them by flushing its own table. The baseline spill decision,
however, is read from query-wide memory (Aggregator.cpp:2494-2501), so that
residency keeps the threshold crossed on every following block. In the failing
job 1,351,680 staged records stayed resident from the thaw to the finish drain,
about 131 MiB at the 102 bytes per record the thaw line implies, 69% of the
190.7 MiB threshold, before either producer's table holds anything: 394
post-thaw parts were written for a 17,107-row result, median 399 KiB
compressed, and `initGenerate` then opens one `SourceFromNativeStream` per part
with a `min(compressed_size, DBMS_DEFAULT_BUFFER_SIZE)` buffer each, 170.3 MiB
of read buffers held open at once. That is the frame the limit fires in.

The frozen path already sheds the backlog under the very same trigger
(Aggregator.cpp:2414-2419: `flushPendingChunks` then
`drainStagedChunksUnderMemoryPressure`). The thawed one did not, so the pool
released by ClickHouse#117326 was the smaller of the two: a sub-32-MiB shared-table tail
against a 131 MiB backlog. This adds those same two calls to the baseline hook,
before the residue release, so the backlog becomes about four part-sized files
instead of a resident pool. `drainStagedChunksUnderMemoryPressure` takes only
the session, so a baseline producer may drive it, and no new setting, constant
or counter is introduced; the valve is the one ClickHouse#117880 has just sized from the
threshold and covered with ten tests. Total work is unchanged and moves from
the finish barrier to the first post-thaw block over the threshold.

The `session->initialized` guard is load-bearing rather than defensive:
`drainStagedChunksBatchUnderMemoryPressure` dereferences
`shared.early_drain_variants->type` after its `chunks.empty()` early return,
and until now it was only ever called from the frozen path, where a freeze has
created that table. `initAdaptiveSession` publishes the table and then stores
the flag with release ordering, so the acquire load here makes it visible.
A session in which no thread ever froze has neither table nor backlog.

Measured on one `clickhouse local` stream that reproduces the shape (threshold
56 MB, max_threads 2, 2M rows of 50000 wide repeat-dominated keys, so the whole
532,480-record backlog stays resident): `ExternalAggregationWritePart` is
97-119 against 244 blocks without this change and 5-6 with it, five runs per
arm with no overlap, both arms reporting thaws and pressure sweeps. Peak memory
follows: without the change the query dies at a `max_memory_usage` of twice the
threshold in seven of eight runs, with it the peak is 1.4-1.5x the threshold,
which is spent in the pre-thaw staging phase this change does not touch.
Payload variations, results identical to the unfixed arm in every case and
parts unfixed to fixed: `sum` plus `count` states 25 to 7 with both exact
totals preserved, and `uniqExact`, whose heap lives outside the arena, 176 to
7.

The new test `05104_adaptive_aggregator_thawed_backlog_shed.sh` asserts the
part count against the block count, plus the thaw and sweep counters so it
cannot pass without engaging the aggregator, and it fails on a binary built
from this tree without the two statements. The whole `adaptive_aggregator`
family stays green, 23 of 23, including `05054`, whose scenario 1 part count
falls while its residue-release assertion still holds, and 100 of 100
randomized runs pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release 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.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

External GROUP BY dies on max_memory_usage inside the adaptive aggregator's own memory valve

5 participants