Repository navigation
Shed the adaptive aggregator's staged backlog when a thawed thread is about to spill - #118474
Conversation
… 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]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex), two full passes over this tree:
Severity: ❌ blocker / The thing I pressed hardest on, because an 8 line change here could quietly break unrelated Session id: cron:clickhouse-review-slot-8:20260906-211000 |
|
Workflow [PR], commit [372875d] Summary: ✅
AI ReviewSummaryThis PR moves the adaptive backlog shed onto the baseline memory-pressure path before Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 372875d.
Changed lines: Changed C/C++ lines covered: 39/39 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260906-194300 |
|
cc @nickitat @nihalzp, could you review this? Records staged before the adaptive aggregator thaws stay published for the merge, so a thawed thread found query memory over |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units79 translation units recompiled, 759 s compile time in total, 79 of them have a recent master baseline. |
…o it The AI review objected that the test's two liveness assertions, `ExternalAggregationWritePart > 0` and `AdaptiveAggregationPressureSweeps > 0`, are both satisfiable by the pre-existing finish-time drain, so a later change that stops taking the new branch in `Aggregator::executeOnBlock` could leave the test green. The part-count bound above them is the actual oracle and does fail when only `drainStagedChunksUnderMemoryPressure` is dropped, but nothing in the test named the new hook directly. Add `AdaptiveAggregationSpillBacklogSheds`, incremented from the new branch and from nowhere else, and assert it in `05104_adaptive_aggregator_thawed_backlog_shed`. It cannot be reached by the finish-time drain or by the finish-time externalization, so it pins the hook itself rather than the query merely going external and sweeping. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…s not a race `05104_adaptive_aggregator_thawed_backlog_shed` was flaky in CI: the `amd_debug` and `amd_binary` flaky checks failed it 5 and 7 times, and the `arm_binary` parallel run once, always on the same single line, `shed the backlog on the thawed spill path 1 -> 0`. Every other assertion held in each failure, including `AdaptiveAggregationThaws > 0`, so the shape reached the thaw and then never took the baseline spill decision again. The cause is the margin the old stream left. Records staged before the thaw are about 42 MB at 524288 records, the earliest the thaw can fire, and the two baseline tables the thaw hands the producers could only add about 12 MB more at 50000 distinct keys of 65 bytes. Against a 56 MB threshold that is a crossing decided by a few megabytes, so a producer running a little ahead of its twin could have the frozen sweeps shed the backlog before the thaw and leave nothing resident to re-cross with. Measured on this tree, the old shape sheds only over a 42-66 MB band of thresholds. Widening the key space to 100000 and the stream to 4M rows makes the post-thaw table growth several times that margin rather than comparable to it. The shedding then fires over the whole 30-80 MB band, with the pinned 56 MB in the middle of it, and the separation the part-count oracle rests on grows rather than shrinks: 5-7 parts with the fix against 365-390 without it, where the old shape gave 5-6 against 97-119. On the unfixed tree the query now also dies with the `Code: 241 ... While executing SourceFromNativeStream` this pull request was opened for, in 5 of 5 runs. Verified on this tree: 20 of 20 runs of the test pass, 24 of 24 pass under the exact randomized settings of the `arm_binary` failure with eight of them running at once, and 12 of 12 pass pinned to one and to two cores. The shed arm peaks under 100 MB, so the unchanged 300 MB `max_memory_usage` keeps its headroom for a sanitizer arm. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118474&sha=36d1b4e7b0afc87c8ec84263897855a126bdf6cb&name_0=PR PR: ClickHouse#118474 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two other tests took `05104` on master while this branch was open, and master now runs up to `05110`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 The first CI run flagged the new test as flaky, not the change: The margin was too narrow. Records staged before the thaw are about 42 MB at 524288 records, the earliest the thaw can fire, and at 50000 distinct keys of 65 bytes the two baseline tables the thaw hands the producers could add only about 12 MB more. Against the 56 MB threshold that made the post-thaw crossing a race: a producer running ahead of its twin let the frozen sweeps shed the backlog before the thaw, leaving nothing resident to re-cross with. Measured on this tree, the old shape sheds only over a 42-66 MB band of thresholds. Widening the key space to 100000 and the stream to 4M rows makes the post-thaw table growth several times that margin instead of comparable to it. The shedding now fires over the whole 30-80 MB band, with the pinned 56 MB in the middle, and the part-count oracle separates further rather than less: 5-7 parts with the fix against 365-390 without it, where the old shape gave 5-6 against 97-119. On the unfixed tree the query now also dies with the Verified here: 20 of 20 runs pass, 24 of 24 under the exact randomized settings of the Also merged |
|
The flaky checks on
Both fast flaky-check jobs finished Trajectory for the same test across the three heads: The fast-versus-sanitizer split survives the widening, so what fails is not the key space. I am measuring where the current fixture sits between its two edges, the backlog that survives to the thaw and the growth of the thawed tables, before touching anything. For reference, on the pre-widening shape the shedding fired over a 43-85 MB band of thresholds with two producers and a 20-150 MB band with eight, same binary. |
…ot a race The `AdaptiveAggregationSpillBacklogSheds` assertion added in 36d1b4e and retuned in d910a11 still fails on the two fast build arms at 33b3122, 4 runs of 50 on `Stateless tests (amd_binary, flaky check)` and 4 of 50 on `(amd_debug, flaky check)`, while all five sanitizer arms pass 50 of 50. Only that line flips to 0. The two assertions in this test want opposite shapes, which is why widening the key space did not close it. Every crossing of the external threshold writes one part, so the part bound needs the shedding to be rare: measured on this tree at 56 MB the resident backlog costs 234-244 parts against 7 with it shed, and the hook is taken 3-4 times, all of them in the first blocks after the thaw. A wider key space raises how far the thawed tables carry the query back over the threshold, but the crossing stays a one-shot event, and the shapes that make it recur put the two arms' part counts on top of each other: at 400000 keys the shed arm writes 33-36 parts against the resident backlog's 42-61, and with eight producers 111-133 against 114-123. So the liveness assertion moves to a second query at a quarter of the threshold, where the crossing recurs on most blocks and the hook is taken 44-52 times per run, while the part bound keeps the shape it separates on. That query bounds nothing, so it runs half the stream and peaks lower than the first one, 70-80 MB against 80-100 MB, and the 300 MB limit keeps its sanitizer headroom unchanged. Measured with a binary carrying the hook, the test passes 60 of 60 unpinned, 40 of 40 pinned to one core and 32 of 32 with eight instances at once on two cores. Without the hook it fails 8 of 8, on the part bound and on the shed line together. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118474&sha=33b3122526d42278808cbf99e6856ee4bf73d752&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 Co-Authored-By: Claude Opus 5 <[email protected]>
|
Pushed The reason the wider key space could not close it is that the two assertions want opposite shapes. Every crossing of the external threshold writes one part, so the part bound needs the crossing to be rare, and at 56 MB it is: measured on this tree the hook is taken 3-4 times, all of them in the first blocks after the thaw, for 7-8 parts against 234-244 with the backlog resident. Every shape that makes the crossing recur collapses that separation instead:
Post-thaw stream length is not the failing edge either: cut to 700000 rows, so that barely twenty blocks follow the thaw, the crossing still fires 6 of 6. So the second query runs at a quarter of the threshold, where the crossing recurs on most blocks and the hook is taken 44-52 times per run. It bounds nothing, so it runs half the stream and peaks at 70-80 MB against the first query's 80-100 MB, and the unchanged 300 MB limit keeps its sanitizer headroom. With the hook the test passes 132 of 132 here: 60 unpinned, 40 pinned to one core, 32 with eight instances at once on two cores. Without it, 8 of 8 fail, on the part bound and the shed line together. Style checks 14 of 15, the exception being One gap stays disclosed and unpinned: a tree with only I also corrected the Validation line in the description, which still said the new test passes 20 of 20. |
The hook sat inside the baseline spill branch, which also requires `result.isTwoLevel() && worth_convert_to_two_level`. The freeze thresholds (`adaptive_aggregator_freeze_threshold[_bytes]`, 16384 / 4 MiB) are far below the two-level ones (`group_by_two_level_threshold[_bytes]`, 100000 / 50000000), so a thawed producer can carry the whole staged backlog while its own table is still single-level and unspillable: the query stays over `max_bytes_before_external_group_by` and `checkLimits` runs before the branch is ever reached. Move `flushPendingChunks` + `drainStagedChunksUnderMemoryPressure` onto the same memory-pressure trigger the frozen branch uses, before `checkLimits` and independent of the two-level state. The spill branch keeps only `releaseAdaptiveDrainResidue`, which sheds the residue below the sweeps' part bound. `05111_adaptive_aggregator_thawed_backlog_shed` gains a stream with the two-level conversion put out of reach, asserting the hook fires there in its own process. Ablation on this tree: with the hook reverted, that stream sheds nothing and dies with `MEMORY_LIMIT_EXCEEDED` at ~99 MiB under a 100 MB limit in 2 runs out of 5; with it, 5/5 pass and the hook is taken 3-4 times. The original streams are unchanged (5-7 parts, 13/13 runs pass, 8/8 concurrent).
`system.events` is cumulative for the whole `clickhouse-local` process, so the `AdaptiveAggregationSpillBacklogSheds` assertion sat behind the first stream of the same invocation, which takes the hook 3-4 times itself. The assertion therefore stayed green whenever the hook fired only in the first stream, and pinned nothing about the low-threshold shape it documents. Give the liveness stream its own `clickhouse-local` invocation, so the counter it reads belongs to that stream alone. The reference is unchanged. Verified here: 17 of 17 runs pass - 3 sequential, 8 with eight instances at once, and 6 pinned to a single core. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ver the mixed state Review pointed out that the hook reads `adaptive->isBaseline()`, which is broader than the thaw the event name, its description and the test comments claimed: once any producer has frozen, `session->initialized` stays true, so a producer that stood down on its own - by the give-up rule, or by the pressure stand-down - falls through the same branch and sheds the frozen one's backlog with no thaw anywhere in the query. The broad gate is intentional. The backlog is session-wide memory, so whichever producer arrives at the spill trigger is the right one to shed it, and narrowing this to `BaselineState::Reason::RepeatedStagedKeys` would only make the query wait for a thaw, or for a frozen producer to reach its own trigger, to free memory that already holds the query over the external threshold. So the wording is what changes: the comment above the hook and the `AdaptiveAggregationSpillBacklogSheds` description now name the baseline path and say why the gate is not the thaw verdict, and the assertion the second stream carries is renamed accordingly. The state the review named is now also covered, in its own `clickhouse-local` process like the other streams, since `system.events` is cumulative per process. The two `UNION ALL` branches give the two producers their own key streams: the first is distinct per row, so the staged sample is never repeat-dominated and the thaw cannot fire, and it stages about 32 MB below the threshold - no sweep of its own sheds them - and then ends; the second holds 10 keys over its first 100000 rows, so it gives up after about 16000 of them, long before any memory pressure, and only then turns key-rich, which is what carries the query over the threshold after the frozen producer is gone. The stream asserts `AdaptiveAggregationThaws = 0` next to `AdaptiveAggregationGiveUps > 0` and `AdaptiveAggregationSpillBacklogSheds > 0`, so the shed it pins can only have come from a producer that never thawed, and the whole backlog leaves with it. Verified on this tree: 14 of 14 runs of the test pass (3 sequential, 8 concurrent, 3 pinned to one core and 3 to two cores), and `check_style.py` is clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Addressed the AI Review's remaining item on the new event/test contract in The hook is gated on So the contract moves to the baseline path: the comment above the hook, the Verified on this tree: the test passes 14 of 14 runs (3 sequential, 8 concurrent, 3 pinned to one core and 3 to two cores), the two touched translation units compile and |
05140 flaky check at
|
|
🕵 Let's go with (a). Pool the (b) is not worth the cost here. Please keep the pooled line's failure message naming which streams were pooled, so a future red For the record on priority: the signature this pull request was opened for is still live on |
`AdaptiveAggregationSpillBacklogSheds` was asserted separately on each of the three streams that reach the hook. Which producer arrives at the baseline spill trigger first is a race, so each stream reads the counter as a coin flip even on a run where the backlog does end up shed, and three independent reads redden three times as often as one read over all three. The read is therefore pooled: each of those streams now ends by handing its own counter out of its own `clickhouse-local` process, and one line at the end of the test asserts that at least one of them saw a shed. Nothing else moves. The part bound stays on the first stream, and each pooled stream keeps the claim only it can make, the thaw with no two-level table on the third and `AdaptiveAggregationThaws = 0` next to `AdaptiveAggregationGiveUps > 0` on the fourth, so the shapes the gate was widened to cover are all still pinned. The counters are still read per process and combined afterwards, never by running the streams together, because `system.events` is cumulative per process and one process would let a shed on one shape satisfy another. The pooled line names the three streams it covers, so a red run does not have to read the test to find out that the line is a disjunction and which shapes went into it. Pooling does not weaken the read, because none of the three shapes can reach a non-zero counter without the hook. Measured on this tree: 104 runs of the test pass, 40 sequential and 64 at eight concurrent, and no stream read 0 in any of them. On a binary with the hook reverted, all three read 0 in 10 runs of 10, so the pooled line reads 0 and the test reddens on it; in 9 of those 10 the first stream also died with MEMORY_LIMIT_EXCEEDED at `SourceFromNativeStream` under its own limit, which is the defect this pull request is about. `check_style.py` is clean. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Implemented in 92448c1.
The pooled line, verbatim from the reference: Verified on this tree (debug):
Two things I measured while doing it, for the record, with no action taken on either:
|
|
|
||
| # Naming the streams the read was pooled over, so that a red run does not have to work out from the | ||
| # source that the line is a disjunction and which shapes it covers. | ||
| printf 'shed the backlog on the baseline pressure path in at least one of the liveness, single-level and mixed streams\t%d\n' \ |
There was a problem hiding this comment.
This pooled shed_total > 0 check no longer proves the two non-liveness contracts this PR added.
The single-level stream is the only case that shows the hook must run before result.isTwoLevel() / worth_convert_to_two_level, and the mixed stream is the only case that shows adaptive->isBaseline() intentionally covers a producer that never thawed. Because line 221 only asks for one of the three streams to report a non-zero AdaptiveAggregationSpillBacklogSheds, either regression can now slip through as long as the liveness stream still fires.
A concrete trace: move the hook back behind the spill branch and line 161 drops to 0 while line 124 stays non-zero; narrow the gate back to RepeatedStagedKeys and line 214 drops to 0 while lines 124 or 161 can still keep this pooled assertion green. This needs a per-shape assertion again, or another observable that lets the single-level and mixed streams fail on their own.
There was a problem hiding this comment.
Both traces reproduce. I built each mutant at 92448c114be5 and ran it against the pooled oracle and
against the per-shape oracle it replaced (e6aa8b0085d0), one binary per row:
| mutant | per-shape oracle | pooled oracle | read that drops to 0 |
|---|---|---|---|
hook moved back behind the spill branch (inverse of c8c2d2bbe870) |
0/5 pass, always on shed the backlog without a two-level table |
10/10 pass | line 161, every run |
gate narrowed to RepeatedStagedKeys |
0/5 pass, always on shed the backlog with no thaw |
8/8 pass | line 214, every run |
The counts are not marginal either. Under the first mutant the single-level read is 0 in 10 runs of 10
while the liveness read stays at 2; under the second the mixed read is 0 in 8 of 8 while liveness and
single-level stay at 2 and 3-4. So the pooled line cannot tell either mutant from a green run.
What I am not doing is restoring the per-shape assertions, because CI has already measured that form.
This test has 30 recorded failures on this pull request. Nine of them come from the two heads where
the hook already sits on the pressure trigger (960b156c927c and e6aa8b0085d0); the other 21 are the
earlier hook site under a differently worded assertion, so they are not comparable. Grouping those
nine by which read returned 0:
| per-shape read | CI failures | arms |
|---|---|---|
single-level, shed the backlog without a two-level table |
8 | amd_binary, amd_debug |
mixed, shed the backlog with no thaw |
1 | amd_msan |
liveness, shed the backlog on the baseline pressure path |
0 | none |
The two reads this asks to go back per-shape are exactly the two CI has caught returning 0 on a tree
with the hook present. That is also why the pooled line survives both mutants: the read carrying it is
the liveness one, the only one never measured at 0.
That leaves the other half of the suggestion, an observable those two shapes can fail on on their own.
It is a real gap, and it is a design call on a form that was directed in
#118474 (comment) two hours before this
review, with the two alternatives priced and refused in the same comment. I am not reverting that on a
measurement which confirms its stated cost rather than contradicting it, so I am leaving the residual
recorded here as the table above states it.
| M(AdaptiveAggregationDrainedRecords, "How many delayed records the adaptive aggregation drained into the shared table at merge time.", ValueType::Number) \ | ||
| M(AdaptiveAggregationPressureSweeps, "How many times the adaptive aggregation drained staged records early because of memory pressure.", ValueType::Number) \ | ||
| M(AdaptiveAggregationPressureDrainedRecords, "How many staged records the adaptive aggregation drained early under memory pressure.", ValueType::Number) \ | ||
| M(AdaptiveAggregationSpillBacklogSheds, "How many times the adaptive aggregation shed the staged backlog because a thread on the baseline algorithm - one the thaw put back there, or one that stood down on its own - was about to spill while staged records were still resident.", ValueType::Number) \ |
There was a problem hiding this comment.
AdaptiveAggregationSpillBacklogSheds no longer implies that the producer was "about to spill".
This hook now runs before the result.isTwoLevel() / worth_convert_to_two_level gate, and 05140's single-level stream intentionally reaches it with two-level conversion disabled, so the query never becomes spillable in that case.
That makes the system.events description misleading for exactly the scenario this PR added to cover. Please drop the "about to spill" wording or rephrase the event so it only promises "baseline memory-pressure path while staged records were still resident".
There was a problem hiding this comment.
Agreed, and it is checkable in the tree. The hook's gate at Aggregator.cpp:2482 carries
isBaseline(), the external threshold and session->initialized, and no result.isTwoLevel() or
worth_convert_to_two_level term; the spill itself at Aggregator.cpp:2523 requires both. The
single-level stream reaches the hook 3 to 5 times per run with group_by_two_level_threshold set out of
reach, so there the producer was over the external threshold and could not spill at all. The sibling
AdaptiveAggregationResidueReleases uses the same phrase and is accurate, because it does sit inside
the two-level-gated branch.
Wording that promises only what the gate checks:
How many times the adaptive aggregation shed the staged backlog because a thread on the baseline
algorithm - one the thaw put back there, or one that stood down on its own - crossed the external
aggregation threshold while staged records were still resident.
I raised the same point in
#118474 (comment) before this review, and the
string is the pull request owner's. The pooled assertion in the other thread is open on this same head,
so I will land this wording in the same push as whatever is decided there rather than sending the branch
a separate commit for one line.
…og when a thawed thread is about to spill
Backport #118474 to 26.8: Shed the adaptive aggregator's staged backlog when a thawed thread is about to spill
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_usagewithenable_adaptive_aggregatoron. Records staged before the aggregator thawed its tables stayed resident until the merge, so a thawed thread found query memory overmax_bytes_before_external_group_byon every block and wrote a temporary file per block, and the merge then held a reader per file. Those records are now written out from such a block onwards, until query memory falls back below the threshold.Description
Related: #117326, #117880
00084_external_aggregationstatement 2 still dies withCode: 241 ... While executing SourceFromNativeStreamon seven consecutive days of master runs, at amax_memory_usagethree times itsmax_bytes_before_external_group_by, i.e. more headroom than the 2x the docs recommend. The job measured below ran on79305ee7, which is #117880's own merge commit, so that fix is present.Records staged before the thaw stay published for the merge, by design, and a thawed thread cannot free them by flushing its own table. The baseline spill decision reads query-wide memory, so in that job 1,351,680 staged records (~131 MiB, 69% of the threshold) kept the threshold crossed on every later block: 394 post-thaw parts for a 17,107-row result, after which
initGenerateopens oneSourceFromNativeStreamper part, 170.3 MiB of read buffers.The frozen path already sheds the backlog under exactly this trigger. This gives the thawed path the same two calls, on the same memory-pressure gate and, like the frozen one, before
checkLimits, guarded on the session having a shared drain table. It is deliberately not nested in the baseline spill branch: the freeze thresholds sit far below the two-level ones, so a thawed table can carry the whole backlog while still being single-level and unspillable, and waiting for the conversion would leave it resident across the limit checks. #117326's residue release stays in the spill branch, where what is left to shed is the residue below the sweeps' part bound. No new setting and no new machinery: the valve is the one #117880 has just sized from the threshold, and the staged records still reach the merge, as about four part-sized files instead of a resident pool. Total work is unchanged; the drain moves from the finish barrier to the over-threshold blocks after the thaw, each shedding until query memory is back under the threshold.Validation: new
05140_adaptive_aggregator_thawed_backlog_shed.sh. On one stream, parts fall from 365-390 to 5-7 against 488 blocks, and the test fails on the unfixed binary, where the query dies with theCode: 241 ... While executing SourceFromNativeStreamthis pull request was opened for. Theadaptive_aggregatorfamily stays green. The assertion that pins the hook itself is checked over a second stream at a quarter of the threshold, where the crossing recurs on most blocks, because every shape that makes it recur inside the first stream collapses the part bound's separation.AdaptiveAggregationSpillBacklogShedscounts the records that hook's sweep took out rather than arrivals at the trigger, so it reads one shed per producer, exactly 2 in 23 runs of 23 there; counted on arrivals it read 44-48, and 421 on a binary whose hook is reached but sheds nothing, where the assertion went green on nothing. It also pins the hook's block-timeflushPendingChunks: deleting only that call fails the test 10 of 10. Each of the three streams runs in its ownclickhouse-localprocess, sincesystem.eventsis cumulative per process and an assertion sharing a process with an earlier stream would be satisfiable by it. With the hook the test passes 132 of 132 runs here, 40 of them pinned to one core and 32 with eight instances at once; without it, 8 of 8 fail on the part bound and the shed line together.A third stream covers the case with no two-level conversion in reach (
group_by_two_level_thresholdandgroup_by_two_level_threshold_bytesput out of reach, threshold still 56 MB), where the hook is the only thing that can shed after the thaw. Ablation there: with the hook reverted the stream sheds nothing and dies at ~99 MiB under a 100 MB limit in 2 runs out of 5; with it, 5 of 5 pass and it sheds 3-4 times per run.The hook is gated on the baseline phase and not on the thaw that motivated it, and a fourth stream covers that: once any producer has frozen,
session->initializedstays true, so a producer that stood down on its own - by the give-up rule, or by the pressure stand-down - sheds the frozen one's backlog with no thaw in the query. The gate is deliberately broad, because the backlog is session-wide memory and whichever producer arrives at the spill trigger is the right one to shed it: in that stream the frozen producer has already finished and stopped sweeping while 32 MB of staged records are still resident, so gating on the thaw verdict would leave them holding the query over the threshold for the rest of the run. The stream gives the two producers their own key streams from twoUNION ALLbranches - the first distinct per row, so the staged sample is never repeat-dominated and the thaw cannot fire; the second 10 keys over its first 100000 rows, so it gives up long before any memory pressure and only then turns key-rich - and assertsAdaptiveAggregationThaws = 0next toAdaptiveAggregationGiveUps > 0and the shed counter, so the shed is attributable to a producer that never thawed.AdaptiveAggregationSpillBacklogShedsand the comments around the hook are worded for that baseline path rather than for the thaw.The first CI run flagged the test itself as flaky: its key space was narrow enough that the post-thaw crossing of the threshold was a race against the frozen sweeps, so the shedding fired only over a 42-66 MB band of thresholds. Widening the key space to 100000 keys and the stream to 4M rows puts the shedding over the whole 30-80 MB band, with the pinned 56 MB in the middle of it.
26.8is affected, with the setting on by default there and the same hook present; please applyv26.8-must-backport(I do not hand-author release-branch PRs).CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=79305ee77d5b450e827ac16ea1126701c3b076f2&name_0=MasterCI
Workflow [PR]
Sync PR [sync-upstream/pr/118474]
Version info
26.9.1.959(included in26.9and later)26.8.3.63