Skip to content

Release the adaptive aggregation drain residue before spilling on query memory - #117326

Merged
nihalzp merged 9 commits into
ClickHouse:masterfrom
groeneai:release-adaptive-drain-residue-before-baseline-spill
Sep 4, 2026
Merged

nihalzp merged 9 commits into
ClickHouse:masterfrom
groeneai:release-adaptive-drain-residue-before-baseline-spill

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 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 when enable_adaptive_aggregator is on. Intermediate data the adaptive aggregator held and could not release kept a thread on the baseline algorithm flushing its own hash table on every block, so each block wrote a temporary file and the merge then allocated a reader per file. That data is now written out first.

Description

Related: #111459, #115038

enable_adaptive_aggregator promises that when draining is not enough "the shared table spills to disk through the ordinary external aggregation" (Settings.cpp:4394). It does not.

executeOnBlock's spill check compares query-wide memory, but flushing frees only the checking thread's own table. While the session's shared drain table stays below adaptive_pressure_spill_min_keys no sweep writes it, so for a thread back on the baseline path that residue alone holds the reading over the threshold and every following block spills again. initGenerate then builds one SourceFromNativeStream per file, which is where the limit is hit. On 00084_external_aggregation statement 2: 339 parts, 1 before the thaw and 338 after.

releaseAdaptiveDrainResidue writes the residue out regardless of the part floor, then re-reads query memory with the sweep mutex and the whole in-flight budget held, so refills and in-flight writes cannot enter the reading. It runs only where that spill would, so it never adds one. Same query: 7 to 15 parts.

One residual left alone: the pre-existing tail sweep destroys its reservation just before the table it stands for, handing that budget on a moment early.

One question for the owner. The reading still counts transient adaptive memory this thread cannot release, as it has always counted every peer's local table. Making it exact means quiescing publication at every over-threshold block, changing this feature's throughput contract; bounding the read-back would bound RAM whatever the part count. Neither is implemented. Which do you prefer?

26.8 is affected, with the setting on by default there; please apply v26.8-must-backport (I do not hand-author release-branch PRs).

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117190&sha=c10c2e3eee0d8e912567a15cc694e41b07accfa3&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

Validation

New test 05054_adaptive_aggregator_baseline_spill_residue.sh, parallel-safe, four scenarios, 2.8 to 3.0 s per run: 12/12 unrandomized and 100/100 randomized green, no run differing from the reference. On the base commit it fails 3/3 with this task's own signature, Code: 241 ... While executing SourceFromNativeStream, at 289.4 MiB.

Scenario 1 pins max_memory_usage at 286.1 MiB. Measured peaks, 6 runs per rung from 100 to 900 MB: at most 190.7 MiB with the fix, above 381.5 MiB on base, so the limit sits between the arms with about 1.5x clearance on the fix side. A second channel bounds the temporary files by the sweep count rather than by a constant, beside positive release, sweep and thaw counts, so it cannot pass without engaging the aggregator, and a file-count regression under the limit still reds it. Files-to-sweeps ratio: 3.476 to 4.065 on base, 0.310 to 0.562 with the fix, six runs each.

00084_external_aggregation statement 2, adaptive path forced, 15 runs per arm, thawing runs only: base 11/15 thawing runs at 19 to 324 temporary files, with fix 13/15 at 7 to 15 files, and the spilled volume unchanged on both arms at 213 to 223 MB compressed.

Scenario 2 covers a session where no thread ever froze, so there is no shared table to release, and asserts it went external anyway. Scenario 3 is the negative control: a residue exists and memory is over the threshold, but no table is two-level, so nothing is written at all. Scenario 4 carries a live count() per key and asserts the exact totals, so a lost state contribution moves the sum; both totals are already correct on base, so it is a regression guard, not a reproducer.

Also green: 00284_external_aggregation*, 01576_if_null_external_aggregation, 02933_group_by_memory_usage and the rest of the adaptive family; an in-memory thaw still reports zero temporary files, the lost-row tripwire never fired, and cancellation returns QUERY_WAS_CANCELLED.


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

Version info

  • Merged into: 26.9.1.653 (included in 26.9 and later)
  • Backported to: 26.8.3.29

groeneai and others added 6 commits August 31, 2026 02:20
…ry memory

`enable_adaptive_aggregator`'s own setting description states that when
draining the backlogs early is not enough to get back under the external
threshold, "the shared table spills to disk through the ordinary external
aggregation" (`src/Core/Settings.cpp:4394`). It does not, and an external
`GROUP BY` can exceed `max_memory_usage` as a result.

The baseline spill check in `Aggregator::executeOnBlock` compares
`getCurrentQueryMemoryUsage()`, which is query-wide, but flushing can only free
the checking thread's own table. The session's shared drain table is detached
and written only once it holds `adaptive_pressure_spill_min_keys` distinct keys
(`AdaptiveAggregationKernels.cpp:1622`), so below that floor no sweep ever
writes it and it stays resident until the merge. For a thread that has returned
to the baseline path that residue alone holds the reading over the threshold;
`writeToTemporaryFile` re-initializes the thread's table but not the residue,
so the condition is still true on the next block. Each block therefore leaves a
temporary file holding a single block's keys, and
`AggregatingTransform::initGenerate` eagerly builds one
`SourceFromNativeStream` per file, each with up to 1 MiB of read buffer. The
memory limit is hit there, on the read-back, not during aggregation.

Measured on `00084_external_aggregation`'s second statement, which runs at
three times its external threshold: 339 temporary parts, 332 of them KiB-scale,
and 1 written before the thaw against 338 after it. The failing CI runs
show the same shape at a larger scale, 840 parts with 824 KiB-scale.

Write the residue out regardless of the part floor, then re-read query memory
and decide the spill from that. The sample is taken with `pressure_sweep_mutex`
held, so no sweep can refill the table, and with the whole in-flight detached
byte budget held, which is granted only when nothing is being serialized and
which prevents a new detach from starting; those are the same two exclusions
the existing tail branch already takes together, so this adds no
synchronization primitive and no new lock order. Nothing subtracts from or
otherwise adjusts a memory reading: the code changes the world and then
re-reads it.

The value is kept in a separate `spill_decision_memory` local.
`current_memory_usage` still feeds `result_size_bytes`, the two-level
conversion decision and the `min_free_disk_space` disk reservation, so only the
spill condition changes.

All four ways a thread reaches the baseline path (the thaw between blocks and
mid-block, the `TooFewDistinctKeys` give-up, and the pressure stand-down) fall
through to this one site in the same `executeOnBlock` invocation, and the guard
tests only that the thread is on the baseline path, never the reason it got
there. `mergeOnBlock`'s identical-looking check has no adaptive producer in
scope and runs after the finish barrier, where `drainStagedChunksAtFinish`
already owns the shared table.

The shared table is created by the first `freezeAdaptive`, so a session in
which no thread ever froze has none while a learning thread can still reach the
baseline path by giving up. The helper therefore returns early unless
`initialized` is set, using the acquire load the repository already uses for
that pointer. Without that guard
`04650_adaptive_aggregator_pressure_spill.sh` segfaults.

The new test asserts the part count next to a positive pressure-sweep count and
a positive thaw count, so it cannot pass by never engaging the adaptive
aggregator, and its second scenario drives the session in which no thread
freezes.

Not addressed here: the read-back is the general defect, since the baseline
path alone produced 467 parts on the same test's first statement, and bounding
the number of concurrent `SourceFromNativeStream` would hold the documented
merge bound whatever the part count.

Co-Authored-By: Claude Opus 5 <[email protected]>
… table under the lock

Review round on the previous commit found two defects in the release path.

The gate that decided whether to release the shared drain table tested only
that the thread was on the baseline algorithm, that an external threshold was
set, and that query memory was over it. The spill it exists to serve, ten lines
below, additionally requires the thread's own table to be two-level and worth
converting. On an over-threshold block failing either of those the release
therefore wrote the shared table where the unpatched code wrote nothing at all,
and because the existence of a temporary file is what makes `initGenerate`
choose the external merge over the in-memory bucket-parallel one, an
aggregation that used to merge in memory would start merging through temporary
files, with `should_produce_results_in_order_of_bucket_number` forced on. The
gate now carries the same two conjuncts. Measured on a query in that regime: 6
temporary files and `ExternalAggregationMerge` before, 0 and an in-memory merge
after, with the residue and the thaw unchanged.

The guard on a session where no thread ever froze read the shared table's
`shared_ptr` outside `pressure_sweep_mutex`, while all three sites that assign
it hold that mutex. Splitting it leaves the atomic check where it was and moves
the pointer test after the lock is taken.

`worthConvertToTwoLevel` is an OR whose bytes arm compares the cross-thread
aggregator tracker against `group_by_two_level_threshold_bytes`, and a table
keeps its type across a flush, so both new conjuncts hold on the blocks the
reported failures were spilling on: the fix still takes the same query from 19
to 324 temporary files down to 7 to 14, with the spilled volume unchanged.

The test's oracle changes with it. A constant bound on the file count is not
scale-invariant, so it is replaced by a liveness counter,
`AdaptiveAggregationResidueReleases`, and a relationship: the files written may
not outnumber the pressure sweeps. Measured over six runs an arm, that ratio is
3.50 to 3.82 unpatched and 0.343 to 0.482 patched. A second scenario now
asserts that it really went external, so it cannot pass having skipped the path
it covers, and a third is a negative control for the narrowed gate: a residue
exists and memory is over the threshold, but no table is two-level, and nothing
is written.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review round on the previous commit found that the
`uniqExact(number % 5000) AS a` alias in the new test was never executed.
`RemoveUnusedProjectionColumnsPass` keeps an unused subquery aggregate only
when the subquery has no `GROUP BY`, all three scenarios have one, and nothing
outside the subqueries referenced the alias, so the analyzer pruned it. The
fixture has always been a keys-only `GROUP BY`, and `EXPLAIN QUERY TREE` shows
no `uniqExact` anywhere in the analyzed tree. The comment claiming fat states
was wrong twice over: `400000` is a multiple of `5000`, so every row of a group
shares one `number % 5000` value and each state would have held exactly one
element even had it survived.

Consuming the alias in the outer query instead was tried first, and rejected by
measurement. Aggregate states then exist in every producer table and in the
residue, compressed spill volume rises from about 46 MB to about 57 MB, the
external threshold is re-crossed sooner after the release, and the ratio of
files written to pressure sweeps moves to 0.517 to 0.589 across six runs. That
leaves under a factor of two against the assertion's bound of one file per
sweep, where the keys-only fixture leaves 0.310 to 0.562.

Deleting the alias is execution-equivalent rather than merely equal in the
numbers: for both inner shapes the two forms produce byte-identical
`EXPLAIN QUERY TREE` and `EXPLAIN actions = 1` output, and the inner
`Aggregating` step carries keys and no aggregates. Twelve interleaved run pairs
on one binary confirm it, splitting six to six.

The comment now describes the residue as the dominant resident term through the
count and the width of its keys, which is what the shape selection established.

Co-Authored-By: Claude Opus 5 <[email protected]>
The release samples query memory again and hands that sample to the spill
decision, but the reservation for the file the decision then writes was still
built from the reading taken before the release. The stale term is exactly the
residue, whose bytes at that moment also occupy disk in the temporary file the
release just wrote, so the request double counts them. This is a hard rejection
rather than a hint: the sum becomes `reserve_size` in
`TemporaryFileOnLocalDisk`, where a failing reservation throws
`NOT_ENOUGH_SPACE`. It is reachable on default settings, because
`min_free_disk_space_for_temporary_data` defaults to 0, which leaves
`reserve_size` equal to the stale reading rather than making it zero, so the
free space check always runs. The residue is bounded by the part floor of a
million keys plus one batch's overshoot, so the over-request is hundreds of
megabytes.

The local holding the reading is seeded from the pre-release value, so on every
path where the release did not run or returned nothing the emitted size is
unchanged.

The null check on the shared drain table was unreachable.
`initAdaptiveSession` assigns the pointer before storing `initialized` with
release ordering, so the acquire load above already implies non-null, and all
three sites that replace the table install a fresh one under the coordinator
lock before releasing it; five sibling reads dereference it unchecked. Its
comment documents a real invariant and moves to the first read under the lock.

The comment on the quiescing reservation claimed the whole budget is granted
only when nothing is in flight. A sweep that has claimed its batch and released
the coordinator lock has not reserved yet, so that batch is resident and
unreserved inside the sample. The comment now claims only what the budget and
the lock actually buy: no detached table or reserved writer is in flight.

The new test's first scenario now runs under `max_memory_usage = 300000000`, so
it asserts the end-to-end outcome the changelog claims rather than the part count
relationship alone. The value is measured, not picked: on a ladder of six runs per
rung per arm the base arm exceeds the limit at 200, 300 and 400 MB while the fix
stays under it from 200 to 900 MB, so the limit sits at the middle rung of a
two-fold window with a rung of clearance on either side, and all eighteen base-arm
failures are `MEMORY_LIMIT_EXCEEDED` while executing `SourceFromNativeStream`,
which is the signature the CI report carries. The files-to-sweeps bound is
untouched, so a regression that inflates the file count without crossing the limit
is still caught.

Co-Authored-By: Claude Opus 5 <[email protected]>
The three sites that swap the session's shared drain table moved the live
pointer out of the session and only then allocated its successor. `std::move`
on a `shared_ptr` nulls the source and an assignment evaluates its right-hand
side first, so a throw inside `createAdaptiveDrainTable` left
`early_drain_variants` null while `initialized` stayed true, and nothing
catches it. That helper is a chain of tracked allocations, a two-level table
`init` and up to 256 arenas, and the whole path runs only while query memory is
over the external threshold with the residue still resident, so
`MEMORY_LIMIT_EXCEEDED` is reachable exactly there. Eleven reads dereference
the pointer entitled only by the `initialized` release/acquire pairing, so a
producer sweeping or releasing in the window before cancellation quiesces the
query would dereference null. Each site now constructs the replacement first
and installs it with two moves that cannot throw.

This corrects a wrong premise in an earlier round of this pull request rather
than fixing it silently: that round deleted a null check on this pointer and
justified the deletion by asserting the three swap sites install a fresh table
under the coordinator lock before releasing it. They did, but only on the
non-throwing path. The deletion stands, and is now correct for the reason it
claimed, because the invariant holds on the exception path too; guarding one of
eleven reads would have left the other ten trusting an invariant the code could
still break.

The reorder costs nothing. `Arena`'s constructor only records the sizes, so an
empty drain table is its control blocks and hash header, and holding both for
the length of two moves does not add a second residue.

Co-Authored-By: Claude Opus 5 <[email protected]>
The three scenarios in `05054_adaptive_aggregator_baseline_spill_residue`
aggregate keys only: each inner query projects the group key alone, so
`params.aggregates_size` is zero and no assertion in the file can observe an
aggregate state travelling through the release. The reported failure this change
exists to prevent is state-carrying, a `uniq` over a second column, so the guard
ran on a strictly weaker shape than the defect.

The fourth scenario aggregates `count` per key and asserts both exact totals,
400000 groups over 6000000 rows, in place of the file-to-sweep ratio, which
stays in the first scenario and is not perturbed. A lost or corrupted state
contribution moves the sum. It pins no memory limit, because a live aggregate
raises the spilled volume and this scenario checks results rather than the
limit.

This is a regression guard for a class that has not been observed, not a
reproducer. `releaseAdaptiveDrainResidue` writes through the same
`spillDetachedAdaptiveTable` as the three pre-existing sweep sites and detaches
in the same shape, so nothing here suggests the serialization is wrong for
aggregate states, and on the base binary both totals are already correct. What
the base binary fails is the liveness assertion, because the counter does not
exist there.

The round-4 commit 5056fbf states that the over-request it removes is
bounded by the part floor and therefore "hundreds of megabytes". That magnitude
does not hold. Across five configurations there were 610 spill sites, of which
exactly one carried an over-request at all, at 2.0 MB, a factor of 1.02. The
mechanism is mutual exclusion: the stale term is bounded by the bytes the
release just freed, and a spill follows a release only when that amount was too
small to bring the reading back under the threshold, so a large stale term and a
following spill cannot coexist. That change itself is correct and stays, because
the emitted size is seeded from the pre-release reading and so is provably
unchanged on every path where the release did not run; only its stated magnitude
was wrong.

Co-Authored-By: Claude Opus 5 <[email protected]>
@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 Aug 31, 2026
@groeneai

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

Pre-publication review of this change: a cold code review by the publishing reviewer plus an
independent-model pass (engine: codex) over the full diff and its callers, repeated after each of six
fix rounds. 25 findings, all adjudicated. Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE and
DROPPED are terminal and carry recorded evidence.

# Sev Finding Verdict Evidence / action
1 ❌ The no-table guard read early_drain_variants outside pressure_sweep_mutex, racing the sweeps that replace it AGREE, fixed Raised independently by both reviewers. The atomic initialized check stays first; the pointer read moved under the lock. The clause was also redundant: initAdaptiveSession release-stores initialized after the pointer, so the acquire load implies non-null
2 ❌ The release gate was a strict superset of the spill condition it serves, omitting result.isTwoLevel() and worth_convert_to_two_level, so it wrote the shared table out on blocks where nothing would have been written AGREE, fixed Gate now matches the spill predicate exactly. Without it a part could appear where none existed, and a part existing is what makes initGenerate choose the external merge over the in-memory bucket-parallel one
3 ⚠️ Scenario 2 proved only that threads gave up without freezing, not that the guarded path was reached AGREE, fixed It asserted nothing implying query memory crossed the external threshold, so it could stay green with the helper never called. It now asserts the query went external, which with finding 2 fixed is an exact witness for the gate
4 ⚠️ The part-count oracle was an absolute bound of 150 against a measured 49 to 65 AGREE, fixed Too loose one way (a degradation to ~140 parts passed) and fragile the other (the count is not scale-invariant). Replaced with a release counter plus a bound relative to the pressure-sweep count, measured on both arms
5 💡 One comment stated a design tradeoff rather than a local invariant AGREE, fixed Trailing sentence dropped, moved to the commit message. The rest state non-obvious domain properties and are deliberately kept
6 💡 Writing the shared table out more often resets the running group-count bound the drain holds, so with group_by_overflow_mode = 'throw' a query could fail to throw where it did DROPPED Accurate, deliberately not actioned: both pre-existing detach sites already reset that bound, so this is a degree change inside an already best-effort check, and no input reaching an observable wrong outcome was found
7 💡 mergeOnBlock carries a spill check of the same shape against the same query-wide reading DISAGREE Structurally unreachable with a residue: AggregatingTransform::consume makes only_merge and the adaptive path mutually exclusive at the single call site, so mergeOnBlock has no session handle; and a downstream merging transform consumes output emitted only after the finish drain has drained the residue
8 💡 The new test lacks the long tag its siblings carry WITHDRAWN Raised by the reviewer and then measured wrong: the file runs in 2.8 to 3.0 s, so the run-time gate is nowhere in reach and the tag would only remove it from every lane that skips long tests
9 💡 Coverage of the mixed case, one thread on the baseline algorithm while a peer is still frozen, is argued rather than exercised ACKNOWLEDGED Per-thread asymmetry could not be constructed from a stateless source: the freeze decision is a function of a thread's own key count and numbers_mt feeds every thread the same distribution. The guard tests only that a thread is on the baseline path, never why, so all four routes there reach the same site in the same call
10 ❌ The residue write goes through the zero-reservation temporary-file path, so it does not keep min_free_disk_space_for_temporary_data free the way the baseline spill it can replace does DISAGREE Mechanism real, promise not: that setting defaults to 0, and the zero-reservation path is the only one this feature has ever used for detached drain tables, from three call sites carrying the bulk of its spill volume. The same bytes reach disk on the unpatched build, at merge time instead. Measured 49 to 66 files per query against one release, so the reserving baseline writes still happen dozens of times in the same query
11 ⚠️ An unused uniqExact alias in the new test is prunable, so the executed fixture is a keys-only GROUP BY and its comment about fat states is untrue AGREE, fixed Confirmed by measurement: EXPLAIN QUERY TREE run_passes = 1 contains uniqExact zero times. Alias deleted, comment corrected; provably behaviour-neutral (byte-identical EXPLAIN QUERY TREE and EXPLAIN actions = 1, and a 12-pair interleaved A/B separates 6-6, sign test p = 1.0). The state-coverage half of this finding was NOT settled here and came back as findings 14 and 20
12 ⚠️ The negative control's flip under the mutant was recorded from a single run AGREE, fixed Repeated 3x with a same-channel shipped control: 3/3 mutant runs flip nothing written at all to 0, 3/3 shipped runs hold it at 1, deterministically on every counter. That zero also cannot flake: the only other writers are gated on a floor of a million keys and the query's key space is four hundred thousand
13 💡 The description groups two shorthand Related references instead of one full URL per line DISAGREE The template's relationship block carries one full URL per line and that block is what the automation reads. The shorthand line exists because the link has to be visible in the rendered body, which the leading comment is not
14 ⚠️ With the pruned alias deleted the fixture has no aggregate at all, so a state mis-serialized through the new write is unobservable, and the failure this fix prevents is state-carrying AGREE, fixed in round 6 Re-raised after the round-2 remedy, correctly. The round-3 attempt put a live aggregate into all three scenarios and 9 of 92 runs failed on one line, the files-to-sweeps ratio; finding 20 records how it was finally resolved. Not agreed with, and not actioned: any suggestion the write itself is at risk. The helper calls the same spillDetachedAdaptiveTable as the three pre-existing sweep sites
15 ⚠️ The helper unlocks the coordinator mutex around each write and loops, so in a mixed session a peer can refill the table and one call can write several sub-floor files AGREE, bounded Mechanism real and unprovoked (see finding 9). The stated harm, a return of the original reader fanout, is refutable: every refill is preceded by a pressure-sweep increment before the drain, so released files cannot exceed sweeps, which is exactly the bound the test asserts. The defect wrote one part per block, 504 parts against 137 sweeps; with the fix 45 to 77
16 ❌ All three sites that replace the shared drain table moved the live pointer out before allocating its successor, so a throw inside createAdaptiveDrainTable left the pointer null while the session still reported itself initialized AGREE, fixed std::move nulls the source and an assignment evaluates its right-hand side first. That helper is a chain of tracked allocations running only above the external threshold with the residue resident, so MEMORY_LIMIT_EXCEEDED is reachable exactly there, and eleven reads dereference the pointer entitled only by the flag's release/acquire pairing. Fixed at the source: each site now builds the replacement first and installs it with two moves that cannot throw
17 ⚠️ An earlier round of this review deleted a null check on the shared table as unreachable, on a premise that does not hold on the exception path AGREE, fixed Self-correction, stated rather than fixed silently. The premise held only on the non-throwing path. Finding 16's reorder makes it true unconditionally, after which the deletion is correct for the reason it claimed. The commit message says so
18 ⚠️ The description carried three countable claims that no longer matched the shipped tree: the part range, the whole fix-arm comparison row, and what the test's base arm fails on AGREE, fixed Part range is 7 to 15; the fix-arm figures are recomputed from the shipped binary rather than carried over. Not attributable to any code change: a same-load control on the previous binary gave the identical range, and a disk-reservation size cannot move a part count
19 💡 The test pins a hard-coded max_memory_usage, the same class of artifact whose exhaustion produced this task AGREE, shipped with the number stated Chosen by measurement: six runs per rung from 100 to 900 MB bracket the peaks at at most 190.7 MiB with the fix against above 381.5 MiB on base, so the pinned 286.1 MiB sits between the arms with about 1.5x clearance. Raising it to 400 MB was rejected: the base arm would then sit about 2 MiB above the limit, a knife edge on the arm whose reddening is the point. Measured on a Debug build; if a pinned limit here is unwelcome, the file-count channel stands without it
20 ⚠️ Third raise of the state-coverage gap: the only scenario proving the release aggregates keys only, so no assertion observes a state contribution travelling through the new write AGREE, fixed in round 6 The round-3 terminal verdict on this was the reviewer's own and was wrong: it read "no placement both observes the release and leaves the ratio oracle intact" as terminal, which is true only across the three existing scenarios. A fourth scenario need not carry that oracle. It aggregates count() per key and asserts 400000 groups over 6000000 rows, so a lost or corrupted contribution moves the sum; the ratio oracle stays in scenario 1, unperturbed. 112 runs, no differing line
21 ⚠️ The round-4 commit message states the stale disk-reservation term it removes made the over-request "hundreds of megabytes" AGREE, self-corrected Measured: 1 of 610 spill sites across five configurations carried one at all, of 2.0 MB, a factor of 1.02. The mechanism is mutual exclusion, since the stale term is bounded by the bytes the release just freed and a spill follows a release only when that was too little. The change is right and stays; only the stated magnitude was wrong. Commits are not rewritten here, so the round-6 commit message carries the correction
22 💡 releaseAdaptiveDrainResidue is public in a high-fan-out header although its only caller is executeOnBlock DISAGREE Considered, not changed: the header groups the adaptive helpers together and this is the sixth fix round on a header with wide fan-out
23 💡 The closing quiesce asks for the whole detached-bytes budget while holding pressure_sweep_mutex, so it stalls every producer over the trigger until nothing is in flight DISAGREE Termination proved by reading: holding that lock blocks entry to both sweep paths, and the one reservation taken without it is taken by a thread that has already left the lock, so the in-flight writer set is bounded by max_threads and drains. Lock order is the same everywhere, coordinator mutex then budget mutex, so no cycle. The pre-existing tail branch already waits on this budget under the same lock
24 💡 The release counter is incremented before a write that is a no-op on a cancelled session, so a cancelled query can count a release that wrote nothing DISAGREE Matches the convention of the counters beside it: the pressure-sweep counter is likewise incremented before the drain it names
25 ⚠️ The description asserted that removing the guard on the absent shared table makes scenario 2 segfault AGREE, removed The 2x2 behind that sentence was measured on an earlier tree carrying a second null-check clause since removed, and on that tree deleting the initialized check alone did not segfault; only removing both clauses did. The shipped tree has one clause, so the measured both-absent arm is the equivalent one, but the sentence stated the outcome without that qualification. Dropped from the description rather than restated: it is mutation-coverage detail

Two limits, both also in the description: this fixes the post-thaw fragmentation behind the reported
failures, not every way that test can fail (a second, distinct mode grows during the frozen phase and
never reaches this site), and the spill check still counts transient adaptive memory this thread
cannot release, exactly as it has always counted every peer's local table.

Round 6 changed test files only, so the code the final gate pass reviewed is the code that publishes.
The quiescing device is the pre-existing adaptive_pressure_detached_bytes_budget; this change
introduces neither that constant nor a new one.

Session id: cron:clickhouse-review-slot-9:20260831-105900

@clickhouse-gh clickhouse-gh Bot closed this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1854dce]

Summary: ✅


AI Review

Summary

This PR fixes the adaptive-aggregation case where a thread that has already fallen back to the baseline path keeps spilling its own hash table because query-wide memory still includes unreleased shared drain residue. The current head now releases that residue before the spill decision, refreshes the spill reservation from the refreshed reading, and preserves the initialized => early_drain_variants != nullptr invariant at every shared-table replacement site. I did not find a remaining correctness, concurrency, or contract issue in the shipped diff.

Missing context / blind spots
  • ⚠️ Build (arm_tidy) was still in progress at review time, so this review does not include its final result.
Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

⚠️ No coverage measurement for commit 1854dce: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test 05054_adaptive_aggregator_baseline_spill_residue.sh fails on the base commit bb113c3849bb09f3 (10/10 in round 0, re-confirmed in round 1). On 00084_external_aggregation's second statement, with the adaptive path forced on every run, the fragmentation signature reproduced in 11 of 15 base runs and Code: 241 itself in 4 of 15.
b Root cause explained? Yes. The baseline spill check in executeOnBlock (Aggregator.cpp:2490) compares getCurrentQueryMemoryUsage(), which is query-wide, but flushing frees only the checking thread's own table. Below adaptive_pressure_spill_min_keys no sweep writes the session's shared drain table (AdaptiveAggregationKernels.cpp:1624), so once a thread is back on the baseline path that residue alone holds the reading over the threshold; re-initializing the thread's table leaves it in place, so every following block spills again. AggregatingTransform::initGenerate then builds one SourceFromNativeStream per temporary file, which is where the limit is hit. Pinned by measurement: of 339 parts in one base run, 1 was written before the thaw and 338 after, and 332 of the 339 were KiB-scale.
c Fix matches root cause? Yes. It changes the world and then re-reads: the residue is written out regardless of the part floor, an in-flight adaptive write is waited out, and getCurrentQueryMemoryUsage() is sampled again with the sweep mutex and the whole in-flight budget held. It performs no arithmetic on any memory reading, adds no setting, no session state and no new synchronization primitive, does not raise a limit or widen a bound, and leaves both existing drain routines and all four standDown sites byte for byte.
d Test intent preserved / new tests added? 00084_external_aggregation is untouched, deliberately: it is the coverage. New stateless test 05054, dataset-free and parallel-safe with no no-parallel tag, using the family's clickhouse-local + system.events idiom (04650, 04654, 05042). Its oracle bounds the temporary files by the number of pressure sweeps rather than by a constant, so it stays meaningful at any scale, beside a positive release count, sweep count and thaw count, so it cannot pass by never engaging the adaptive aggregator. Measured ratio of files to sweeps: 3.476-4.065 on base, 0.310-0.562 with the fix over six runs per arm, so the bound of one file per sweep needs a 3.48x fall to false-pass and a 1.78x rise to false-fail. (An earlier six-run sample read 3.50-3.82 / 0.343-0.482, i.e. a 2.07x rise; a 12-pair interleaved control on one binary showed that range was under-sampled, and the wider figures above are the honest ones.) Scenario 2 additionally asserts the query went external, so it cannot pass having skipped the path it covers; scenario 3 is a negative control in which a residue exists and memory is over the threshold but no table is two-level, and nothing is written at all. Scenario 4 carries a live count aggregate state through the release and asserts the exact totals, 400000 groups over 6000000 rows, in place of the ratio, so a lost or corrupted state contribution moves the sum; it is a regression guard for a class not observed rather than a reproducer, since both totals are already correct on base. Scenario 1 also carries max_memory_usage = 300000000, chosen from a measured ladder rather than picked: the base arm fails 6/6 at 200, 300 and 400 MB while the fix passes 6/6 at 200 through 900 MB, so X sits at the middle rung of a 2x window with a rung of clearance on each side. That gives the test two independent failure channels, one end-to-end and one mechanism-level: a full regression exceeds the limit and throws, and a partial one whose file count explodes while memory stays under it still trips the files-to-sweeps bound.
e Both directions demonstrated? Yes, on Build ID 27b3f97b3fd19f7b805d7d82eb157eb057f498bf, asserted equal to the running server's buildId() before any test ran. 05054: FAIL on base 3/3 (now with the exact CI signature Code: 241 ... While executing SourceFromNativeStream), 12/12 PASS unrandomized and 100/100 PASS with randomization on, i.e. 112 runs of the four-scenario file with zero differing lines. 00084 statement 2, thawing runs only: base 19-324 files (median 159, 11/15 runs), fixed 7-15 files with no overlap (the round-1 sample read 7-14; a same-load control on the pre-change binary reproduces 7-15 in the same session, so the extra file is box variance and not the change). ExternalAggregationCompressedBytes is unchanged at 212.9-221.7 MB vs 214.2-219.6 MB, so the file count did not fall by spilling less data, and results match the .reference byte-for-byte on both arms.
f Fix is general across code paths? Yes. All four ways a thread reaches the baseline path (the thaw between blocks :2379 and mid-block :2329, the TooFewDistinctKeys give-up :2436, and the pressure stand-down :2448 added by #115038) fall through to the single fixed site in the same executeOnBlock invocation, and the guard tests only adaptive->isBaseline(), never the reason. Every other site testing max_bytes_before_external_group_by was enumerated and is not a carrier: :2410 is the frozen drain trigger and a frozen thread never spills its own table; :5053 is in mergeOnBlock, which has no adaptive producer in scope and runs after the finish barrier where drainStagedChunksAtFinish owns the shared table; the two writeToTemporaryFile sites in AggregatingTransform.cpp (:1328, :1479) are finish-path. The exception-safety invariant this PR also has to keep has its own carrier set, enumerated the same way: all four createAdaptiveDrainTable call sites. Three of them install the result into the session's shared pointer (:1536, :1627, :1702) and all three now build the replacement before detaching the live table; the fourth (:1660) assigns to a function-local table, so a throw there leaves no shared state to observe.
g Fix generalizes across inputs (params/datatypes/wrappers)? Adaptive admission rejects LowCardinality and Nullable keys outright (AggregatingStep.cpp:378-383), so those wrappers cannot reach the fixed path. Aggregate-state matrix exercised green across the family: count, sum, argMin, min(String), uniq (00084), WITH TOTALS, Nothing-state. 05054's first three scenarios reach the fixed site with a keys-only GROUP BY, i.e. zero aggregate functions, which is the degenerate end of that matrix; EXPLAIN actions = 1 confirms their inner Aggregating step carries keys and no Aggregates: line. Making those three state-carrying was implemented and rejected: with a live count state the pressure-sweep counter the ratio oracle divides by collapsed in about one run in seven while the file count held, and the bound went false in 9 of 92 runs, all on that one line. The collapse is measured; its mechanism is not established, and the reservation term total_size_of_aggregate_states feeds (AdaptiveAggregationKernels.cpp:1642) is not it, since the regime is chosen at :1602 from the batch's record count alone. The state-carrying case is therefore covered by a fourth scenario, which asserts exact totals instead of the ratio and so does not depend on the sweep count: 400000 groups over 6000000 rows, AdaptiveAggregationResidueReleases at 1 in 8 of 8 raw probes, 112/112 green. Boundaries covered: empty residue (hasData() false, loop skipped), null residue (impossible by construction on both the normal and the exception path; see below), cancelled query (returns empty), and a residue refilled by a still-frozen peer (released again on the next over-threshold block).
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, removed or re-defaulted, and no serialization or on-disk format change, so SettingsChangesHistory.cpp is correctly untouched. The only observable difference is when a thread spills; results are unchanged. 26.8 ships enable_adaptive_aggregator on with the same code and is affected, so a v26.8-must-backport label is requested in the description rather than a hand-authored release-branch PR.
i Invariants and contracts preserved? Lock order is unchanged: the helper waits for spill budget while holding pressure_sweep_mutex, exactly as the existing tail branch does (:1616-1623), and no thread anywhere holds a reservation while waiting for that mutex, so progress always comes from a writer that can finish. The disk write happens only after sweep_lock.unlock(), matching :1629-1631. Inside the loop the SpillReservation is declared before the table so reverse-order destruction frees the table first on the throwing path, and detached.reset() precedes reservation.release() on the normal path. spill_decision_memory is a separate local, so current_memory_usage still feeds result_size_bytes, worthConvertToTwoLevel and the two-level conversion unchanged. The disk reservation for the file that decision writes is sized from the refreshed reading too, since sizing it from the pre-release one would double-count the residue bytes that are at that moment occupying disk in the file the release just wrote; the local is seeded from current_memory_usage, so wherever no release ran the emitted size is identical to before. A cancelled query returns QUERY_WAS_CANCELLED with no crash, no LOGICAL_ERROR and nothing left behind; the check_nothing_left lost-row tripwire never fired on either arm, and the finish-barrier drain still runs. The shared table is read only under pressure_sweep_mutex, matching all three sites that write it. The absent-session case is guarded by the acquire-load of initialized, paired with the release-store in AdaptiveAggregation.cpp:52-59; mutation testing showed that clause alone prevents the segfault that removing the guard entirely produces in 04650_adaptive_aggregator_pressure_spill.sh and in scenario 2 of the new test, so the redundant null check that had followed it was removed rather than left to mask a future invariant break. That removal was justified in an earlier round by the claim that initialized implies the pointer is set, which held only while nothing threw: the three sites that swap the shared table detached it and then allocated its successor, and createAdaptiveDrainTable is a chain of tracked allocations reached only while query memory is over the external threshold, so a MEMORY_LIMIT_EXCEEDED there left the pointer null with initialized still true. Each site now constructs the replacement first and installs it with two noexcept moves, which makes the invariant hold on the exception path as well. It is load-bearing for 17 dereferences of that pointer, none of which tests it for null: 16 in AdaptiveAggregationKernels.cpp (14 via ->, two via * in the drainStagedBatch calls at :1555 and :1609) plus AggregatingTransform.cpp:1394. Proven rather than argued: with the allocation forced to fail once on the release path, the pre-reorder source segfaults on a second thread at :1692 (AggregatedDataVariants::hasData(), reached from Aggregator.cpp:2483) after that thread logs the pointer as null, while the reordered source returns a clean Code: 241 with no crash.

Session id: cron:clickhouse-impl-slot-40:20260831-102900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @nickitat, could you review this? The baseline spill check in executeOnBlock reads query-wide memory, but flushing frees only the checking thread's own table, so the session's shared drain table left resident below the part floor keeps every later block over the threshold and each block then writes its own temporary file. This writes that table out first and re-reads memory before deciding.

@nihalzp nihalzp self-assigned this Aug 31, 2026
The scenario meant to observe an aggregate state travelling through the
residue release aggregated a lone count(), which Aggregator.cpp:765-769
classifies as is_simple_count. Frozen producers then stage a CountPayload of
inline multiplicities instead of an AggregatePayload of row references and
prepared instructions, so its totals could not see the general
aggregate-state release and spill path at all, while the reported failure it
stands for aggregates uniq(SearchPhrase).

Measured by deleting the state contribution from the staged drain, so that
the AggregatePayload drain emplaces its keys and creates its states but skips
executeAggregateInstructions: the whole file still matched its reference byte
for byte. The same count(), placed next to a second aggregate, reports
4099456 instead of 6000000 against that mutant, and the added sum reports
16162926352704 instead of 17999997000000, identically over three runs.

Two aggregates rather than one non-count aggregate make is_simple_count
structurally unreachable for this query, instead of resting on sum not being
count, and keep the existing row-count total meaningful. Sum over
numbers_mt is exact, so the oracle stays a pair of exact totals that the
outer query consumes.

112/112 green, 12 with --no-random-settings and 100 randomized, and the
release still fires in the scenario.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1854dce8b with master dfde23932 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 87b02d7

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64) and Bugfix validation (functional tests, aarch64) both ERROR at ci/jobs/functional_tests.py:734 with AssertionError: Could not find master builds in S3, before any server starts, so neither job measured a test; a new trunk-wide onset at 19:00Z today with zero occurrences in the preceding 7 days, 23 distinct pull requests so far and still rising a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases result differs from the reference on the old analyzer lane, and it is trunk-wide rather than specific to this branch: 84 rows over 72 distinct pull requests and 12 true-master commits on 08-31 alone #117364 (external, merged 2026-08-31 22:05Z), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) job-level container-memory abort with no failing test assertion; 277 rows over 269 distinct trees and 25 true-master commits on 08-31 #117202 (external, merged 2026-08-31), absent from this tree, and it provably does not clear 6/6. A fix task holds the residual, blocked on the integration-test capacity decision I put to the maintainers at #115963 (comment)
Finish Workflow / new_tests_check.py direct cascade of the row above: the hook reds when no per-arch Bugfix validation job reports OK or XFAIL, and both functional arms ERRORed while both integration arms were skipped for having no integration-test changes a fix task is created (the same one as the Bugfix validation row)

None of the rows above is caused by this pull request.

On the 03707_autopr_unsupported_cases row: the test collects parallel-replicas statistics from the
query plan, which only the analyzer builds, so on the old analyzer lane every shape it checks
reported no statistics. #117364 forces the analyzer in the test itself. It merged at 22:05:00Z, and
compare reports this head diverged from its merge commit c9ed88dbecbb, so the run predates the
fix. On true master, the 7 runs after that merge are clean against 2 to 4 failures per hour before
it. I am not merging master here purely to re-run CI, to keep the review load down.

On the /docker row: the /docker cgroup that bounds the nested test containers is capped at
40.78 GiB, and docker compose stop signals every node of a cluster at once, so each node that
outlives the 60 s deadline attaches gdb at the same moment, holding about 3.4 GiB of anonymous
memory each on an ASan build. #117202 serialises those attaches. Measured caveat, stated so it is
not a surprise later: on master trees that do contain #117202, shards 2/6 and 5/6 are clean but
6/6 still fires, so that PR is deliberately not linked as this row's owner.

Session id: cron:our-pr-ci-monitor:20260831-233000

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Bugfix validation / Finish Workflow red on this pull request (Could not find master builds in S3): #117433. The reference master binaries moved to REFs/master/<sha>/masterci/build_<type>/clickhouse when the artifact prefix gained a workflow-name segment, and find_master_builds still spelled the old path.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0bdab02

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

170 check runs at this head: 150 success, 18 skipped, 2 failure. Config Workflow, Style check and
Finish Workflow are all success. Mergeable Check names both reds verbatim
(Failed: AST fuzzer (arm_asan_ubsan),Docs examples), and neither is reachable from this diff, which
touches the aggregator plus one new stateless test and has 0 files under the parallel-replicas, TimeSeries
or docs paths.

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / Logical error: Can't determine table for parallel replicas (STID 3634-41e5) pre-existing trunk defect in findParallelReplicasQuery: the fuzzed CTE chain joining subqueries with ANY RIGHT JOIN and ANY LEFT JOIN makes the eligibility traversal and the table lookup disagree #110020 (mine, open), which is the fix for that mechanism
Docs examples / Documentation examples 2105 of 2226 examples ok, 121 not ok of which 124 known, and the single unexpected one is Function/timeSeriesPrometheusValueToString#0: the documented response box for SELECT timeSeriesPrometheusValueToString(toFloat64(1e-7)) does not match the produced output. Trunk-side, in src/Functions/TimeSeries/timeSeriesPrometheusValueToString.cpp #117789 (external, open)
CH Inc sync build failed CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260903-080000

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 3, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@nihalzp
nihalzp added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit d57d352 Sep 4, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-synced-to-cloud The PR is synced to the cloud repo labels Sep 4, 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 4, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 4, 2026
Backport #117326 to 26.8: Release the adaptive aggregation drain residue before spilling on query memory
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 8, 2026
… about to spill

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 <[email protected]>
arc1999 pushed a commit to arc1999/ClickHouse that referenced this pull request Oct 9, 2026
`parts stay far below the block count` failed twice in `Stateless tests
(arm_binary, parallel)` (PRs ClickHouse#123144 and ClickHouse#122138) and cannot tell the
defect from a thread that was descheduled.

The baseline spill decision reads query-wide memory. A frozen thread that
gets no CPU while the others thaw and finish the stream keeps its frozen
table and staged records resident (20.5-25 MiB measured), so the thawed
threads spill one part per block with the residue release in place. Under
the SIGPROF half of the CI thread fuzzer (P=0.02, up to 2 s) the fixed
engine writes 61-62 parts and prints exactly the CI line.

The line is also vacuous. Without the release (master before ClickHouse#117326, or
the release block deleted) scenario 1 writes 53-58 parts, under the bound
of 60, so the line passes on the defect. It became so when the rows were
cut from 3M to 1M (499b6e7, bce9bf4) while the thaw point stayed
at 524288 staged records, about 52 blocks before the end of the stream.

The release stays covered by `residue released` and by scenario 4's
`released with live states`: both read 0 on the two defect binaries in
every run and 1 on the fixed engine in every run.

Measured with clickhouse-local (amd_binary of master a2e4282 unless
noted):
- new test: identical to the reference on the debug, ASan and amd_binary
  builds; clickhouse-test --test-runs 50 -j 50 on debug: 50/50 OK;
  thread fuzzer P=0.1/100 ms and P=0.02/2 s, 400 runs each: 0 diffs.
  The current test on the same rig: 1/800 (`parts stay far below the
  block count 0`).
- defect binaries: the new test fails 6/6 on the two counter lines; the
  current parts line passes 6/6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

5 participants