Skip to content

Shed the adaptive aggregator's staged backlog when a thawed thread is about to spill - #118474

Merged
nihalzp merged 14 commits into
ClickHouse:masterfrom
groeneai:thaw-drains-the-staged-backlog
Sep 8, 2026
Merged

nihalzp merged 14 commits into
ClickHouse:masterfrom
groeneai:thaw-drains-the-staged-backlog

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

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 exceeding max_memory_usage with enable_adaptive_aggregator on. Records staged before the aggregator thawed its tables stayed resident until the merge, so a thawed thread found query memory over max_bytes_before_external_group_by on 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_aggregation statement 2 still dies with Code: 241 ... While executing SourceFromNativeStream on seven consecutive days of master runs, at a max_memory_usage three times its max_bytes_before_external_group_by, i.e. more headroom than the 2x the docs recommend. The job measured below ran on 79305ee7, 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 initGenerate opens one SourceFromNativeStream per 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 the Code: 241 ... While executing SourceFromNativeStream this pull request was opened for. The adaptive_aggregator family 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. AdaptiveAggregationSpillBacklogSheds counts 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-time flushPendingChunks: deleting only that call fails the test 10 of 10. Each of the three streams runs in its own clickhouse-local process, since system.events is 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_threshold and group_by_two_level_threshold_bytes put 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->initialized stays 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 two UNION ALL branches - 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 asserts AdaptiveAggregationThaws = 0 next to AdaptiveAggregationGiveUps > 0 and the shed counter, so the shed is attributable to a producer that never thawed. AdaptiveAggregationSpillBacklogSheds and 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.8 is affected, with the setting on by default there and the same hook present; please apply v26.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

  • Merged into: 26.9.1.959 (included in 26.9 and later)
  • Backported to: 26.8.3.63

… 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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

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

Pre-publication review by an independent model (engine: codex), two full passes over this tree:
3 findings, then 0 after the two contract corrections below. Plus my own cold read of the
resulting code, done before I read the implementation evidence.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test does not independently prove the per-block flushPendingChunks call is live: deleting only that call leaves at most adaptive_seal_target_bytes (4 MiB, AdaptiveAggregationImpl.h:81) pending per producer, which the finish flush collects anyway, so the part-count oracle can stay green AGREE, not fixed Correct, and I would rather disclose it than paper over it. My mutation arm is the whole commit, so it reds the two statements as a pair. No correctness exposure: AggregatingTransform.cpp:1336 flushes unconditionally at finish and the initGenerate leftovers backstop writes whatever is left, so this statement's only effect is shedding up to 4 MiB per producer at the block instead of at the barrier. The load-bearing second call, which sheds the 131 MiB backlog, is covered: parts fall 97-119 to 5-6. Not re-raised on the second pass
2 💡 The contract overclaimed that all pre-thaw records are written at the first spilling block; the drain stops once query memory is back under the threshold and requeues the rest AGREE, fixed Confirmed at AdaptiveAggregationKernels.cpp:1980-1981 (stop condition) and :2004-2006 (requeue), and the residue release touches only early_drain_variants, never the backlog. Changelog entry and description now say the records are written out from such a block onwards, until query memory falls back below the threshold
3 💡 The test prologue restates the defect narrative, calibration ranges and sanitizer reasoning rather than only the invariants needed to maintain the test DISAGREE The sibling this scenario extends, 05054_adaptive_aggregator_baseline_spill_residue.sh, carries a 28 line prologue with the same content classes: calibration measurements ("measured with this binary a table of these 70-byte keys crossed 32 MiB at about 74000 keys"), the same sanitizer cost reasoning ("a sanitizer build pays several times over for each part written and read back"), and the same process isolation sentence. The new prologue is 19 lines, shorter than the file it follows, so this is the family's convention rather than a departure from it
4 💡 From my own review: the description said this test dies at the 2x max_memory_usage ratio the docs recommend, but it runs at 3x AGREE, fixed 00084_external_aggregation.sql:4 sets the threshold to 200000000 and :18 the limit to 600000000, against "about twice as high" in group-by.mdx:377. Corrected before publication: it misdescribed a test the maintainers know and understated the defect, since dying with more headroom than recommended is the worse reading

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

The thing I pressed hardest on, because an 8 line change here could quietly break unrelated
tests: whether shedding earlier can create a temporary part where none existed, flipping
initGenerate from the in-memory bucket-parallel merge to the external one and so exposing
existing .reference ordering. It cannot. The new calls sit inside a guard that already requires
query memory over the threshold, and there are only two cases. Either the shared drain table holds
data, and then the pre-existing residue release already spilled it, so a part existed at this site
before this change; or it is empty, and then that release frees nothing and returns a reading still
over the threshold, so writeToTemporaryFile fires anyway. A part exists at this site with or
without the change. The sweep of 70 aggregation tests differing by exactly the new test is the
empirical half of the same answer.

Session id: cron:clickhouse-review-slot-8:20260906-211000

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [372875d]

Summary: ✅


AI Review

Summary

This PR moves the adaptive backlog shed onto the baseline memory-pressure path before checkLimits, which matches the original failure mode and looks correct in the touched execution path. I still cannot approve the current head because two previously raised issues remain real in the current code: the new test no longer proves the two non-liveness contracts it claims to cover, and the new AdaptiveAggregationSpillBacklogSheds system.events description is still false for the single-level shape this PR intentionally added.

Findings
  • ⚠️ Major [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118474#discussion_r3954066808] [tests/queries/0_stateless/05140_adaptive_aggregator_thawed_backlog_shed.sh:161,214,221] The pooled shed_total > 0 assertion only proves that at least one of the liveness, single-level, or mixed streams hit the hook. It no longer proves the two unique contracts this PR added beyond the liveness stream: that the hook still fires before two-level conversion on the single-level stream, and that the widened adaptive->isBaseline() gate still sheds backlog for a producer that never thawed on the mixed stream. The current top-level discussion already records a concrete mutant where narrowing the gate back to RepeatedStagedKeys makes the mixed stream's own shed counter drop to 0 while line 221 stays green because the other streams satisfy it, so the fourth stream no longer regression-proofs the broader baseline-path contract the PR description claims. Suggested fix: restore a per-shape assertion for the single-level and mixed streams, or add another non-racy observable that each of those shapes can fail on independently.
  • 💡 Nit [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118474#discussion_r3954066814] [src/Common/ProfileEvents.cpp:1010] AdaptiveAggregationSpillBacklogSheds no longer means a producer was "about to spill". The hook runs before the result.isTwoLevel() / worth_convert_to_two_level spill gate, and the single-level stream in tests/queries/0_stateless/05140_adaptive_aggregator_thawed_backlog_shed.sh:140-161 is designed so this counter increments on a query that never becomes spillable at all. That makes the system.events description inaccurate for exactly the scenario this PR added. Suggested fix: rephrase the event around the baseline memory-pressure path while staged records were still resident, without implying imminent spilling.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make the single-level and mixed streams fail independently when their promised hook coverage regresses, and correct the AdaptiveAggregationSpillBacklogSheds description so it matches the hook's actual trigger.

LLVM Coverage Report

Measured on commit 372875d.

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

Changed lines: Changed C/C++ lines covered: 39/39 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local command (threshold 56 MB, max_threads = 2, 2M rows, 50000 wide keys, the 05054 stream): ExternalAggregationWritePart is 97-119 on the unfixed binary and 5-6 with the fix, five runs per arm, no overlap. Both arms report AdaptiveAggregationThaws > 0 and AdaptiveAggregationPressureSweeps > 0, so both reach the code under test.
b Root cause explained? Yes, measured from the failing job's own server log at 79305ee7. Records staged before the thaw stay published for the merge, and a thawed thread cannot free them by flushing its own table; the baseline spill decision reads query-wide memory, so 1,351,680 resident staged records (~131 MiB, 69% of the 190.7 MiB threshold) held the threshold crossed on every later block: 394 post-thaw parts for a 17,107-row result, then one SourceFromNativeStream per part with a min(compressed_size, 1 MiB) buffer each, 170.3 MiB of read buffers, which is the Code: 241 frame.
c Fix matches root cause? Yes. It removes the residency that drives the decision, at the block where the decision is taken, by calling the valve the frozen path already calls under the same trigger. Not a widened bound, not a no-random-* tag, not a data reduction, and deliberately not a guard at the read-back, which would have left the 394 tiny parts and their write amplification in place.
d Test intent preserved / new tests added? Yes. No existing assertion was weakened: 05054 is untouched and green, and its scenario 1's part count only falls further below its own bound. New regression test 05104_adaptive_aggregator_thawed_backlog_shed.sh, parallel-safe, ~0.8 s.
e Both directions demonstrated? Yes, twice. The shipped test file: [ OK ] with the fix, [ FAIL ] against the binary built from the same tree without the two statements, the diff being exactly parts stay far below the block count 1 -> 0. And an A/B suite sweep of 70 aggregation tests against a fixed server and an unfixed one: the failing sets differ by exactly this one test.
f Fix is general across code paths? Yes. The frozen path already carried the invariant and is untouched; a learning thread standing down under pressure falls through to this same hook on the same block; the shared drain table stays covered by releaseAdaptiveDrainResidue, still called and still called after the new drain, so its sub-bound tail is released in the same pass. mergeOnBlock's spill site is not a carrier: its signature takes no AdaptiveAggregationProducer (Aggregator.h:433), so no adaptive session exists there.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured on the same stream with the payload varied; results identical in both arms, parts unfixed to fixed: keys only 98 to 6; sum + count states 25 to 7 with both exact totals preserved; uniqExact, whose heap lives outside the arena, 176 to 7, exact total preserved; LowCardinality key, Nullable key with NULLs, and a composite key with groupArray return identical results and never engage the adaptive aggregator in this shape, so they execute unchanged code.
h Backward compatible? Yes, trivially. No new setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry. Behaviour changes only for a query with enable_adaptive_aggregator = 1 whose thread has thawed and whose query memory is over max_bytes_before_external_group_by, and there it strictly lowers peak memory and part count. Staged records still reach the merge, as parts rather than as resident memory.
i Invariants and contracts preserved? Yes. The invariant restored: a thread's spill decision must not be driven by memory that thread cannot shed. drainStagedChunksUnderMemoryPressure takes only the session, claims work under the sweep mutex, and returns early once the query is back under the threshold or the backlog is empty. Its one unchecked precondition is that the shared drain table exists, since the batch helper dereferences early_drain_variants->type after its chunks.empty() early return; the session->initialized acquire load covers exactly that, paired with the release store that publishes the table in initAdaptiveSession. flushPendingChunks first preserves the publish-before-drain ordering the frozen path uses, and row conservation is unchanged: every result above matches the unfixed arm.

Session id: cron:clickhouse-impl-slot-41:20260906-194300

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

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 max_bytes_before_external_group_by on every block and wrote a temporary file per block, and the merge then held a reader per file; this gives the thawed path the same two shedding calls the frozen path already makes under that same trigger. @nihalzp, it lands in the hook your #115480 moves, so one of the two will need a resolution depending on which goes first.

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

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 372875d62 with master 55c256363 (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.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 4 commits September 7, 2026 01:02
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The first CI run flagged the new test as flaky, not the change: amd_debug and amd_binary flaky checks failed it 5 and 7 times and arm_binary parallel once, always on the same single line, shed the backlog on the thawed spill path 1 -> 0, with every other assertion holding including AdaptiveAggregationThaws > 0.

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 Code: 241 ... While executing SourceFromNativeStream this pull request was opened for, in 5 of 5 runs.

Verified here: 20 of 20 runs pass, 24 of 24 under the exact randomized settings of the arm_binary failure with eight running at once, and 12 of 12 pinned to one and to two cores. The shed arm peaks under 100 MB, so the unchanged 300 MB max_memory_usage keeps its sanitizer headroom.

Also merged master and renumbered the test to 05111, since master took 05104 twice while this was open.

@nihalzp nihalzp self-assigned this Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

The flaky checks on 33b3122526d4 came back red, so the widening improved the rate without closing it. Per-run census from CIDB at that head:

check FAIL OK
Stateless tests (amd_binary, flaky check) 4 46
Stateless tests (amd_debug, flaky check) 4 46
amd_asan_ubsan, amd_msan, amd_tsan (flaky check) 0 50 each
arm_asan_ubsan (targeted) 0 50
amd_debug parallel, arm_binary parallel, Fast test 0 all

Both fast flaky-check jobs finished failure, at 05:22:39Z and 05:23:40Z. The signature is the same single line, shed the backlog on the thawed spill path flipping 1 to 0, with went external, the part bound, thawed onto the baseline path and swept under pressure all still 1.

Trajectory for the same test across the three heads: 6632d17e 50/50 and 50/50 green, before the assertion existed; 36d1b4e7 5 of 40 and 7 of 39 red with an early bail; 33b31225 4 of 50 and 4 of 50 red with no bail.

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]>
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed bf67c1e57f36, test file only: the AdaptiveAggregationSpillBacklogSheds assertion now sits on a second query, and the first one keeps the part bound.

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:

shape parts with the hook parts without it
100000 keys, 2 producers, 56 MB (current) 7-8 234-244
400000 keys 33-36 42-61
8 producers 111-133 114-123
200000 keys, 4 producers 47-74 47-69
current shape at 24 MB 69-72 70-113

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 settings_changes_history, which needs the workflow hook a local run does not have.

One gap stays disclosed and unpinned: a tree with only flushPendingChunks removed still passes, because the pending chunks a producer holds at the hook are capped by adaptive_seal_target_bytes, 4 MiB, inside a backlog that stands at the 524288-record thaw floor, about 42 MB. No part-count oracle separates that, and tuning the fixture until it reddens would rebuild the knife-edge this commit removes.

I also corrected the Validation line in the description, which still said the new test passes 20 of 20.

Comment thread src/Interpreters/Aggregator.cpp Resolved
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]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
Comment thread src/Interpreters/Aggregator.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the AI Review's remaining item on the new event/test contract in e6aa8b0085d0 (thread replied here).

The hook is gated on adaptive->isBaseline(), which is broader than the thaw the event description and the test comments named: once any producer has frozen, session->initialized stays true, so a producer that stood down on its own — the give-up rule, or the pressure stand-down — sheds the frozen one's backlog with no thaw in the query. That is intentional, and narrowing the gate to RepeatedStagedKeys would be the wrong fix: the backlog is session-wide memory, and in the shape now covered the frozen producer has already finished and stopped sweeping while 32 MB of staged records are still resident, so a narrowed gate would leave them holding the query over the external threshold for the rest of the run — the same defect this pull request is about, reached without a thaw.

So the contract moves to the baseline path: the comment above the hook, the AdaptiveAggregationSpillBacklogSheds description, and the second stream's assertion (shed the backlog on the baseline pressure path). The mixed state is a new fourth stream, in its own clickhouse-local process like the others, asserting AdaptiveAggregationThaws = 0 next to AdaptiveAggregationGiveUps > 0 and the shed counter, so the shed can only be attributed to a producer that never thawed.

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 clickhouse links, and check_style.py is clean, including the test-number check (05140 is still free, the highest on master is 05135). No behavior change — the diff to master is the same six files, with the hook's condition untouched.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

05140 flaky check at e6aa8b0085d0: the shed assertions pin which site won a race

At this head 05140_adaptive_aggregator_thawed_backlog_shed fails the 50x flaky check on the three
fastest arms and passes on the two slowest: amd_binary 3/50, amd_debug 1/50, amd_msan 1/50,
amd_tsan and amd_asan_ubsan 50/50. Two different lines flip, shed the backlog without a two-level table on binary and shed the backlog with no thaw on msan, both 1 -> 0.

Not the settings randomizer: shell_config.sh:47-50 builds CLICKHOUSE_LOCAL without
CLICKHOUSE_CLIENT_OPT (only CLICKHOUSE_CLIENT on line 46 gets it), so the runner's randomized
settings never reach these queries.

Mechanism. AdaptiveAggregationSpillBacklogSheds counts a drain only when the baseline hook is
the site that takes the records out. Three sites can take them and two of the three are silent: the
frozen branch in Aggregator::executeOnBlock (Aggregator.cpp:2419) and the finish-barrier
re-check (AggregatingTransform.cpp:1379). All three fire on current_memory_usage > max_bytes_before_external_group_by, and whichever arrives first takes the whole backlog. So each
shed the backlog ... line asserts which site won, not that the shedding happened.

Reproduced locally without 50x. Stream 4's shape with max_bytes_before_external_group_by = 16000000 gives the byte-identical CI signature in 2/2 runs: AdaptiveAggregationThaws 0,
AdaptiveAggregationGiveUps 1, AdaptiveAggregationPressureDrainedRecords 495904 (the whole
backlog did leave memory under pressure) and AdaptiveAggregationSpillBacklogSheds 0. It returns to
1 at 20 MB. Lowering the threshold moves the crossing earlier, so a producer that is still frozen
reaches the trigger first.

The counter has no replacement. With the hook removed (build IDs b69e9a21 vs a23fb0c1, three
runs per arm on streams 2 and 3 and nine on stream 4), AdaptiveAggregationPressureDrainedRecords
is still the whole backlog
(495904 and 532480) and AdaptiveAggregationDrainedRecords is still 0 everywhere, so pdrained > 0,
fdrained = 0 and their conjunction all stay green with the hook gone: vacuous.
AdaptiveAggregationResidueReleases (3 vs 0) and AdaptiveAggregationPressureSweeps (30 vs 3) do
separate on stream 4, but both are downstream of the same hook entry and so carry the same race, and
sweeps is the arrival counting removed in round 4. The hook counter is the only sound discriminator
I could construct.

Why the rate compounds. Streams 2, 3 and 4 assert this same counter independently, so a run
reddens if any one of them loses. Margins at the configured thresholds, head vs no-hook: stream 2
2 vs 0, stream 3 3-4 vs 0, stream 4 exactly 1 vs 0 in 9/9. Stream 4 is a single-claim margin,
one coin flip. Threshold sensitivity: stream 3 reads 2 at 12-40 MB, 3-4 at 56 MB, 2 at 70-80 MB, and
0 at 100 MB because the query then never reaches the threshold at all (pdrained 0, parts 0);
stream 4 reads 0 at 12-16 MB, 1 at 20-56 MB, 1-2 at 70 MB, 3 at 80 MB.

Options, since this is your call on your streams. (a) Pool the attribution: keep all three
streams and every claim unique to them, including the part bound, but assert the hook counter once
across the three so the test reddens only if all three lose. That is p^3 rather than 3p and stays
non-vacuous, since all three read 0 with the hook removed. (b) Close the race where it closes:
shared.thaw_all is session-wide, so on stream 3 no producer is frozen once it has fired and only
the ordering of the thaw against the crossing matters. adaptive_thaw_min_staged_records is a
constexpr (524288, about 42 MB at these key widths), so only the threshold side of that ordering
is tunable from the test, and its window is bounded above by the peak, as the 100 MB row shows.
Stream 4 has no thaw, so its frozen producer competes until its branch ends, which making that
branch a small fraction of the other would fix at the cost of a heavier stream. (c) Drop the two
racy lines and keep the counter where the margin is widest.

I would take (a). Happy to implement whichever you prefer, and I will default to (a) if you have no
preference.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Let's go with (a).

Pool the AdaptiveAggregationSpillBacklogSheds assertion once across the three streams, and keep
every other claim where it is — the part bound on stream 1, the no-two-level-table and no-thaw
shapes on streams 3 and 4 — so each stream still pins a distinct state, only the "which site won"
question is asked once. Your own no-hook census is what makes this sound rather than a weakening:
all three streams read 0 with the hook removed, so the pooled assertion is still non-vacuous, and
AdaptiveAggregationPressureDrainedRecords, AdaptiveAggregationDrainedRecords and their
conjunction stay unusable for the reason you measured.

(b) is not worth the cost here. adaptive_thaw_min_staged_records is a constexpr, so the only
tunable side of the ordering is the threshold, and its window is bounded above by the peak — the
100 MB row is that ceiling. Stream 4 would need its frozen branch made a small fraction of the
other, which buys a heavier stream to close one of three coin flips. (c) throws away the two
shapes the hook's gate was widened to cover, which is exactly the state e6aa8b0085d0 added.

Please keep the pooled line's failure message naming which streams were pooled, so a future red
run does not have to re-derive that the assertion is a disjunction.

For the record on priority: the signature this pull request was opened for is still live on
master. 00084_external_aggregation statement 2 has failed on 8 of the last 9 days, 4-13 times a
day against ~4500 runs, first seen 2026-08-30 and zero on every day from 2026-08-09 to 2026-08-29.
The rate is unchanged after #117880 landed on 2026-09-06 — 11 failures on 09-06 and 13 on 09-07 —
so nothing merged so far touches it, and this is the only open fix.

`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]>
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Implemented in 92448c1.

AdaptiveAggregationSpillBacklogSheds is now read once per stream, out of each stream's own
clickhouse-local process, and asserted once at the end of the test. Everything else stayed where it
was: the part bound on the first stream, thawed onto the baseline path with two-level conversion out
of reach on the third, AdaptiveAggregationThaws = 0 next to AdaptiveAggregationGiveUps > 0 on the
fourth. The three counters are combined after the processes exit, never by running the streams
together.

The pooled line, verbatim from the reference:

shed the backlog on the baseline pressure path in at least one of the liveness, single-level and mixed streams	1

Verified on this tree (debug):

  • 104 runs of the test pass, 40 sequential and 64 at eight concurrent, and no stream read 0 in any of
    them.
  • With the hook reverted, all three read 0 in 10 runs of 10, so the pooled line reads 0 and the test
    reddens on that line. In 9 of those 10 the first stream also died with MEMORY_LIMIT_EXCEEDED at
    SourceFromNativeStream under its own limit.
  • check_style.py clean, various_checks.sh and check_cpp.sh silent.

Two things I measured while doing it, for the record, with no action taken on either:

  • The pooled read no longer distinguishes which state reached the hook. On a binary whose gate I
    narrowed to BaselineState::Reason::RepeatedStagedKeys, the mixed stream reads 0 while the other
    two carry the line, so the pooled test passes 8 of 8; the pre-pooling test reddened 5 of 5 on
    shed the backlog with no thaw. The no-thaw state is still exercised, but nothing asserts on it.
  • The description of AdaptiveAggregationSpillBacklogSheds says the thread "was about to spill". That
    is exact for AdaptiveAggregationResidueReleases beside it, which is gated on
    result.isTwoLevel() && worth_convert_to_two_level, but the shed hook has no such requirement, so
    on the single-level stream it fires 3-4 times on a producer that will not spill. Left as you wrote
    it.


# 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' \

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@nihalzp
nihalzp added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 4ee25ba Sep 8, 2026
175 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 8, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 8, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 8, 2026
…og when a thawed thread is about to spill
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #118474 to 26.8: Shed the adaptive aggregator's staged backlog when a thawed thread is about to spill
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 can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

6 participants