Repository navigation
Release the adaptive aggregation drain residue before spilling on query memory - #117326
Conversation
…ry memory `enable_adaptive_aggregator`'s own setting description states that when draining the backlogs early is not enough to get back under the external threshold, "the shared table spills to disk through the ordinary external aggregation" (`src/Core/Settings.cpp:4394`). It does not, and an external `GROUP BY` can exceed `max_memory_usage` as a result. The baseline spill check in `Aggregator::executeOnBlock` compares `getCurrentQueryMemoryUsage()`, which is query-wide, but flushing can only free the checking thread's own table. The session's shared drain table is detached and written only once it holds `adaptive_pressure_spill_min_keys` distinct keys (`AdaptiveAggregationKernels.cpp:1622`), so below that floor no sweep ever writes it and it stays resident until the merge. For a thread that has returned to the baseline path that residue alone holds the reading over the threshold; `writeToTemporaryFile` re-initializes the thread's table but not the residue, so the condition is still true on the next block. Each block therefore leaves a temporary file holding a single block's keys, and `AggregatingTransform::initGenerate` eagerly builds one `SourceFromNativeStream` per file, each with up to 1 MiB of read buffer. The memory limit is hit there, on the read-back, not during aggregation. Measured on `00084_external_aggregation`'s second statement, which runs at three times its external threshold: 339 temporary parts, 332 of them KiB-scale, and 1 written before the thaw against 338 after it. The failing CI runs show the same shape at a larger scale, 840 parts with 824 KiB-scale. Write the residue out regardless of the part floor, then re-read query memory and decide the spill from that. The sample is taken with `pressure_sweep_mutex` held, so no sweep can refill the table, and with the whole in-flight detached byte budget held, which is granted only when nothing is being serialized and which prevents a new detach from starting; those are the same two exclusions the existing tail branch already takes together, so this adds no synchronization primitive and no new lock order. Nothing subtracts from or otherwise adjusts a memory reading: the code changes the world and then re-reads it. The value is kept in a separate `spill_decision_memory` local. `current_memory_usage` still feeds `result_size_bytes`, the two-level conversion decision and the `min_free_disk_space` disk reservation, so only the spill condition changes. All four ways a thread reaches the baseline path (the thaw between blocks and mid-block, the `TooFewDistinctKeys` give-up, and the pressure stand-down) fall through to this one site in the same `executeOnBlock` invocation, and the guard tests only that the thread is on the baseline path, never the reason it got there. `mergeOnBlock`'s identical-looking check has no adaptive producer in scope and runs after the finish barrier, where `drainStagedChunksAtFinish` already owns the shared table. The shared table is created by the first `freezeAdaptive`, so a session in which no thread ever froze has none while a learning thread can still reach the baseline path by giving up. The helper therefore returns early unless `initialized` is set, using the acquire load the repository already uses for that pointer. Without that guard `04650_adaptive_aggregator_pressure_spill.sh` segfaults. The new test asserts the part count next to a positive pressure-sweep count and a positive thaw count, so it cannot pass by never engaging the adaptive aggregator, and its second scenario drives the session in which no thread freezes. Not addressed here: the read-back is the general defect, since the baseline path alone produced 467 parts on the same test's first statement, and bounding the number of concurrent `SourceFromNativeStream` would hold the documented merge bound whatever the part count. Co-Authored-By: Claude Opus 5 <[email protected]>
… table under the lock Review round on the previous commit found two defects in the release path. The gate that decided whether to release the shared drain table tested only that the thread was on the baseline algorithm, that an external threshold was set, and that query memory was over it. The spill it exists to serve, ten lines below, additionally requires the thread's own table to be two-level and worth converting. On an over-threshold block failing either of those the release therefore wrote the shared table where the unpatched code wrote nothing at all, and because the existence of a temporary file is what makes `initGenerate` choose the external merge over the in-memory bucket-parallel one, an aggregation that used to merge in memory would start merging through temporary files, with `should_produce_results_in_order_of_bucket_number` forced on. The gate now carries the same two conjuncts. Measured on a query in that regime: 6 temporary files and `ExternalAggregationMerge` before, 0 and an in-memory merge after, with the residue and the thaw unchanged. The guard on a session where no thread ever froze read the shared table's `shared_ptr` outside `pressure_sweep_mutex`, while all three sites that assign it hold that mutex. Splitting it leaves the atomic check where it was and moves the pointer test after the lock is taken. `worthConvertToTwoLevel` is an OR whose bytes arm compares the cross-thread aggregator tracker against `group_by_two_level_threshold_bytes`, and a table keeps its type across a flush, so both new conjuncts hold on the blocks the reported failures were spilling on: the fix still takes the same query from 19 to 324 temporary files down to 7 to 14, with the spilled volume unchanged. The test's oracle changes with it. A constant bound on the file count is not scale-invariant, so it is replaced by a liveness counter, `AdaptiveAggregationResidueReleases`, and a relationship: the files written may not outnumber the pressure sweeps. Measured over six runs an arm, that ratio is 3.50 to 3.82 unpatched and 0.343 to 0.482 patched. A second scenario now asserts that it really went external, so it cannot pass having skipped the path it covers, and a third is a negative control for the narrowed gate: a residue exists and memory is over the threshold, but no table is two-level, and nothing is written. Co-Authored-By: Claude Opus 5 <[email protected]>
Review round on the previous commit found that the `uniqExact(number % 5000) AS a` alias in the new test was never executed. `RemoveUnusedProjectionColumnsPass` keeps an unused subquery aggregate only when the subquery has no `GROUP BY`, all three scenarios have one, and nothing outside the subqueries referenced the alias, so the analyzer pruned it. The fixture has always been a keys-only `GROUP BY`, and `EXPLAIN QUERY TREE` shows no `uniqExact` anywhere in the analyzed tree. The comment claiming fat states was wrong twice over: `400000` is a multiple of `5000`, so every row of a group shares one `number % 5000` value and each state would have held exactly one element even had it survived. Consuming the alias in the outer query instead was tried first, and rejected by measurement. Aggregate states then exist in every producer table and in the residue, compressed spill volume rises from about 46 MB to about 57 MB, the external threshold is re-crossed sooner after the release, and the ratio of files written to pressure sweeps moves to 0.517 to 0.589 across six runs. That leaves under a factor of two against the assertion's bound of one file per sweep, where the keys-only fixture leaves 0.310 to 0.562. Deleting the alias is execution-equivalent rather than merely equal in the numbers: for both inner shapes the two forms produce byte-identical `EXPLAIN QUERY TREE` and `EXPLAIN actions = 1` output, and the inner `Aggregating` step carries keys and no aggregates. Twelve interleaved run pairs on one binary confirm it, splitting six to six. The comment now describes the residue as the dominant resident term through the count and the width of its keys, which is what the shape selection established. Co-Authored-By: Claude Opus 5 <[email protected]>
The release samples query memory again and hands that sample to the spill decision, but the reservation for the file the decision then writes was still built from the reading taken before the release. The stale term is exactly the residue, whose bytes at that moment also occupy disk in the temporary file the release just wrote, so the request double counts them. This is a hard rejection rather than a hint: the sum becomes `reserve_size` in `TemporaryFileOnLocalDisk`, where a failing reservation throws `NOT_ENOUGH_SPACE`. It is reachable on default settings, because `min_free_disk_space_for_temporary_data` defaults to 0, which leaves `reserve_size` equal to the stale reading rather than making it zero, so the free space check always runs. The residue is bounded by the part floor of a million keys plus one batch's overshoot, so the over-request is hundreds of megabytes. The local holding the reading is seeded from the pre-release value, so on every path where the release did not run or returned nothing the emitted size is unchanged. The null check on the shared drain table was unreachable. `initAdaptiveSession` assigns the pointer before storing `initialized` with release ordering, so the acquire load above already implies non-null, and all three sites that replace the table install a fresh one under the coordinator lock before releasing it; five sibling reads dereference it unchecked. Its comment documents a real invariant and moves to the first read under the lock. The comment on the quiescing reservation claimed the whole budget is granted only when nothing is in flight. A sweep that has claimed its batch and released the coordinator lock has not reserved yet, so that batch is resident and unreserved inside the sample. The comment now claims only what the budget and the lock actually buy: no detached table or reserved writer is in flight. The new test's first scenario now runs under `max_memory_usage = 300000000`, so it asserts the end-to-end outcome the changelog claims rather than the part count relationship alone. The value is measured, not picked: on a ladder of six runs per rung per arm the base arm exceeds the limit at 200, 300 and 400 MB while the fix stays under it from 200 to 900 MB, so the limit sits at the middle rung of a two-fold window with a rung of clearance on either side, and all eighteen base-arm failures are `MEMORY_LIMIT_EXCEEDED` while executing `SourceFromNativeStream`, which is the signature the CI report carries. The files-to-sweeps bound is untouched, so a regression that inflates the file count without crossing the limit is still caught. Co-Authored-By: Claude Opus 5 <[email protected]>
The three sites that swap the session's shared drain table moved the live pointer out of the session and only then allocated its successor. `std::move` on a `shared_ptr` nulls the source and an assignment evaluates its right-hand side first, so a throw inside `createAdaptiveDrainTable` left `early_drain_variants` null while `initialized` stayed true, and nothing catches it. That helper is a chain of tracked allocations, a two-level table `init` and up to 256 arenas, and the whole path runs only while query memory is over the external threshold with the residue still resident, so `MEMORY_LIMIT_EXCEEDED` is reachable exactly there. Eleven reads dereference the pointer entitled only by the `initialized` release/acquire pairing, so a producer sweeping or releasing in the window before cancellation quiesces the query would dereference null. Each site now constructs the replacement first and installs it with two moves that cannot throw. This corrects a wrong premise in an earlier round of this pull request rather than fixing it silently: that round deleted a null check on this pointer and justified the deletion by asserting the three swap sites install a fresh table under the coordinator lock before releasing it. They did, but only on the non-throwing path. The deletion stands, and is now correct for the reason it claimed, because the invariant holds on the exception path too; guarding one of eleven reads would have left the other ten trusting an invariant the code could still break. The reorder costs nothing. `Arena`'s constructor only records the sizes, so an empty drain table is its control blocks and hash header, and holding both for the length of two moves does not add a second residue. Co-Authored-By: Claude Opus 5 <[email protected]>
The three scenarios in `05054_adaptive_aggregator_baseline_spill_residue` aggregate keys only: each inner query projects the group key alone, so `params.aggregates_size` is zero and no assertion in the file can observe an aggregate state travelling through the release. The reported failure this change exists to prevent is state-carrying, a `uniq` over a second column, so the guard ran on a strictly weaker shape than the defect. The fourth scenario aggregates `count` per key and asserts both exact totals, 400000 groups over 6000000 rows, in place of the file-to-sweep ratio, which stays in the first scenario and is not perturbed. A lost or corrupted state contribution moves the sum. It pins no memory limit, because a live aggregate raises the spilled volume and this scenario checks results rather than the limit. This is a regression guard for a class that has not been observed, not a reproducer. `releaseAdaptiveDrainResidue` writes through the same `spillDetachedAdaptiveTable` as the three pre-existing sweep sites and detaches in the same shape, so nothing here suggests the serialization is wrong for aggregate states, and on the base binary both totals are already correct. What the base binary fails is the liveness assertion, because the counter does not exist there. The round-4 commit 5056fbf states that the over-request it removes is bounded by the part floor and therefore "hundreds of megabytes". That magnitude does not hold. Across five configurations there were 610 spill sites, of which exactly one carried an over-request at all, at 2.0 MB, a factor of 1.02. The mechanism is mutual exclusion: the stale term is bounded by the bytes the release just freed, and a spill follows a release only when that amount was too small to bring the reading back under the threshold, so a large stale term and a following spill cannot coexist. That change itself is correct and stays, because the emitted size is seeded from the pre-release reading and so is provably unchanged on every path where the release did not run; only its stated magnitude was wrong. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review of this change: a cold code review by the publishing reviewer plus an
Two limits, both also in the description: this fixes the post-thaw fragmentation behind the reported Round 6 changed test files only, so the code the final gate pass reviewed is the code that publishes. Session id: cron:clickhouse-review-slot-9:20260831-105900 |
|
Workflow [PR], commit [1854dce] Summary: ✅
AI ReviewSummaryThis PR fixes the adaptive-aggregation case where a thread that has already fallen back to the baseline path keeps spilling its own hash table because query-wide memory still includes unreleased shared drain residue. The current head now releases that residue before the spill decision, refreshes the spill reservation from the refreshed reading, and preserves the Missing context / blind spots
Final Verdict✅ No new findings on the current head. LLVM Coverage Report |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260831-102900 |
|
cc @nihalzp @nickitat, could you review this? The baseline spill check in |
The scenario meant to observe an aggregate state travelling through the residue release aggregated a lone count(), which Aggregator.cpp:765-769 classifies as is_simple_count. Frozen producers then stage a CountPayload of inline multiplicities instead of an AggregatePayload of row references and prepared instructions, so its totals could not see the general aggregate-state release and spill path at all, while the reported failure it stands for aggregates uniq(SearchPhrase). Measured by deleting the state contribution from the staged drain, so that the AggregatePayload drain emplaces its keys and creates its states but skips executeAggregateInstructions: the whole file still matched its reference byte for byte. The same count(), placed next to a second aggregate, reports 4099456 instead of 6000000 against that mutant, and the added sum reports 16162926352704 instead of 17999997000000, identically over three runs. Two aggregates rather than one non-count aggregate make is_simple_count structurally unreachable for this query, instead of resting on sum not being count, and keep the existing row-count total meaningful. Sum over numbers_mt is exact, so the oracle stays a pair of exact totals that the outer query consumes. 112/112 green, 12 with --no-random-settings and 100 randomized, and the release still fires in the scenario. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units78 translation units recompiled, 712 s compile time in total, 78 of them have a recent master baseline. |
CI finish ledger - 87b02d7Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
None of the rows above is caused by this pull request. On the On the Session id: |
|
Fixing PR for the |
CI finish ledger - 0bdab02Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose 170 check runs at this head: 150 success, 18 skipped, 2 failure.
Session id: cron:our-pr-ci-monitor:20260903-080000 |
GROUP BY dies on max_memory_usage inside the adaptive aggregator's own memory valve
#117879
…due before spilling on query memory
Backport #117326 to 26.8: Release the adaptive aggregation drain residue before spilling on query memory
… 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]>
`parts stay far below the block count` failed twice in `Stateless tests (arm_binary, parallel)` (PRs ClickHouse#123144 and ClickHouse#122138) and cannot tell the defect from a thread that was descheduled. The baseline spill decision reads query-wide memory. A frozen thread that gets no CPU while the others thaw and finish the stream keeps its frozen table and staged records resident (20.5-25 MiB measured), so the thawed threads spill one part per block with the residue release in place. Under the SIGPROF half of the CI thread fuzzer (P=0.02, up to 2 s) the fixed engine writes 61-62 parts and prints exactly the CI line. The line is also vacuous. Without the release (master before ClickHouse#117326, or the release block deleted) scenario 1 writes 53-58 parts, under the bound of 60, so the line passes on the defect. It became so when the rows were cut from 3M to 1M (499b6e7, bce9bf4) while the thaw point stayed at 524288 staged records, about 52 blocks before the end of the stream. The release stays covered by `residue released` and by scenario 4's `released with live states`: both read 0 on the two defect binaries in every run and 1 on the fixed engine in every run. Measured with clickhouse-local (amd_binary of master a2e4282 unless noted): - new test: identical to the reference on the debug, ASan and amd_binary builds; clickhouse-test --test-runs 50 -j 50 on debug: 50/50 OK; thread fuzzer P=0.1/100 ms and P=0.02/2 s, 400 runs each: 0 diffs. The current test on the same rig: 1/800 (`parts stay far below the block count 0`). - defect binaries: the new test fails 6/6 on the two counter lines; the current parts line passes 6/6. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an external
GROUP BYexceedingmax_memory_usagewhenenable_adaptive_aggregatoris on. Intermediate data the adaptive aggregator held and could not release kept a thread on the baseline algorithm flushing its own hash table on every block, so each block wrote a temporary file and the merge then allocated a reader per file. That data is now written out first.Description
Related: #111459, #115038
enable_adaptive_aggregatorpromises that when draining is not enough "the shared table spills to disk through the ordinary external aggregation" (Settings.cpp:4394). It does not.executeOnBlock's spill check compares query-wide memory, but flushing frees only the checking thread's own table. While the session's shared drain table stays belowadaptive_pressure_spill_min_keysno sweep writes it, so for a thread back on the baseline path that residue alone holds the reading over the threshold and every following block spills again.initGeneratethen builds oneSourceFromNativeStreamper file, which is where the limit is hit. On00084_external_aggregationstatement 2: 339 parts, 1 before the thaw and 338 after.releaseAdaptiveDrainResiduewrites the residue out regardless of the part floor, then re-reads query memory with the sweep mutex and the whole in-flight budget held, so refills and in-flight writes cannot enter the reading. It runs only where that spill would, so it never adds one. Same query: 7 to 15 parts.One residual left alone: the pre-existing tail sweep destroys its reservation just before the table it stands for, handing that budget on a moment early.
One question for the owner. The reading still counts transient adaptive memory this thread cannot release, as it has always counted every peer's local table. Making it exact means quiescing publication at every over-threshold block, changing this feature's throughput contract; bounding the read-back would bound RAM whatever the part count. Neither is implemented. Which do you prefer?
26.8is affected, with the setting on by default there; please applyv26.8-must-backport(I do not hand-author release-branch PRs).CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117190&sha=c10c2e3eee0d8e912567a15cc694e41b07accfa3&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
Validation
New test
05054_adaptive_aggregator_baseline_spill_residue.sh, parallel-safe, four scenarios, 2.8 to 3.0 s per run: 12/12 unrandomized and 100/100 randomized green, no run differing from the reference. On the base commit it fails 3/3 with this task's own signature,Code: 241 ... While executing SourceFromNativeStream, at 289.4 MiB.Scenario 1 pins
max_memory_usageat 286.1 MiB. Measured peaks, 6 runs per rung from 100 to 900 MB: at most 190.7 MiB with the fix, above 381.5 MiB on base, so the limit sits between the arms with about 1.5x clearance on the fix side. A second channel bounds the temporary files by the sweep count rather than by a constant, beside positive release, sweep and thaw counts, so it cannot pass without engaging the aggregator, and a file-count regression under the limit still reds it. Files-to-sweeps ratio: 3.476 to 4.065 on base, 0.310 to 0.562 with the fix, six runs each.00084_external_aggregationstatement 2, adaptive path forced, 15 runs per arm, thawing runs only: base 11/15 thawing runs at 19 to 324 temporary files, with fix 13/15 at 7 to 15 files, and the spilled volume unchanged on both arms at 213 to 223 MB compressed.Scenario 2 covers a session where no thread ever froze, so there is no shared table to release, and asserts it went external anyway. Scenario 3 is the negative control: a residue exists and memory is over the threshold, but no table is two-level, so nothing is written at all. Scenario 4 carries a live
count()per key and asserts the exact totals, so a lost state contribution moves the sum; both totals are already correct on base, so it is a regression guard, not a reproducer.Also green:
00284_external_aggregation*,01576_if_null_external_aggregation,02933_group_by_memory_usageand the rest of the adaptive family; an in-memory thaw still reports zero temporary files, the lost-row tripwire never fired, and cancellation returnsQUERY_WAS_CANCELLED.Workflow [PR]
Sync PR [sync-upstream/pr/117326]
Version info
26.9.1.653(included in26.9and later)26.8.3.29