Skip to content

Check the memory limit while copying shared aggregate function states - #127334

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:check-memory-limit-while-copying-aggregate-states
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:check-memory-limit-while-copying-aggregate-states

Conversation

@groeneai

@groeneai groeneai commented Oct 22, 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):

Queries that copy aggregate function states shared by a column (finalizeAggregation(materialize(<state>)), materialize(<state>) + <state>, window functions returning states, neighbor or lagInFrame over a state) now respect max_memory_usage and max_server_memory_usage and fail with MEMORY_LIMIT_EXCEEDED, instead of copying past every limit until the server is OOM-killed.

Description

Related: #117916

Reported on #108090: AST fuzzer (amd_debug) OOM-killed the server at 45 GB RSS with a fuzzed neighbor over an anyLastState of a 1 MiB FixedString.

On 26.8.18.2 and 26.9.19.9, SELECT finalizeAggregation(materialize(initializeAggregation('argMaxState', 1, toFixedString('x', 1048577)))) FROM numbers(4000) is OOM-killed in a 3 GiB container with max_server_memory_usage = 2G.

A ColumnAggregateFunction that must own the states it references copies each one (in ensureOwnership, the forced-ownership loop of insertRangeFrom, and insertFrom(ConstAggregateDataPtr), used by state arithmetic and window functions returning states), so one shared state becomes N copies. For anyLast or argMax over a FixedString, each copy allocates a Field with operator new, which the memory tracker counts but does not refuse; none of these paths checked the limit.

Both loops now call CurrentMemoryTracker::check() after each copied state that moved the memory tracker (overshoot: max_untracked_memory plus one state per thread). insertFrom(ConstAggregateDataPtr) checks before each copy if the tracker moved since the previous call on the thread, which also catches the right operand's merge after it. insert(Field) (how lagInFrame copies its default) checks after every state with a non-trivial destructor. This also refuses the window function repro of #126026, without its WindowTransform change.

Cost: 1-3 ns per state copied one per call (+8-19% on micro-benchmarks such as materialize(countState) + countState), 0-4% when one call copies many states.

The new test fails on master and passes with the fix (tagged no-asan, no-tsan, no-msan: sanitizers do not track these copies). For the Buffer path, where only max_server_memory_usage applies, an INSERT copies 4.27 GB on master and the fix refuses it at 2.2 GB under 2G.


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

A `ColumnAggregateFunction` can reference states it does not own. When
it must own them it deep-copies each one (`create` + `merge`), either
all at once in `ensureOwnership` or row by row in the forced-ownership
loop of `insertRangeFrom`. A constant source turns one state into N
copies, and for `anyLast` / `argMax` over a `FixedString` each copy is a
`Field` allocated with `operator new`, which the memory tracker counts
but never refuses. Nothing in either loop checked the limit, so
`neighbor(<1 MiB state>, 10)` over `numbers(2147483647)` copied a whole
block of states and the AST fuzzer server was OOM-killed at 45 GB RSS
while the server tracker was already refusing other allocations.
`neighbor(S, -10)` takes the second loop (the defaults come first and
set forced ownership), as do `lagInFrame` and per-row `insertFrom`.

In both loops, check the limit after each copied state whose
allocations reached the current thread's memory tracker, reading the
tracker once before the loop. Inside a `MemoryTrackerBlockerInThread`
(e.g. a `Buffer` insert) the blocked levels do not move, so the checker
watches the first level that does. `insert(Field)` and `tryInsert` (how
`lagInFrame` copies its default into every row outside the frame) check
once per state that can own memory outside the arena: part of what they
copy, the `Field`, is allocated by the caller, so a check gated on the
tracker moving during the call can miss it. The overshoot is bounded by
`max_untracked_memory` plus one state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

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

Pre-publication review by an independent model (engine: codex; 3 rounds, 4 findings, 0 in the last round) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Inside a MemoryTrackerBlockerInThread (the Buffer append, StorageBuffer.cpp:770) the watched thread tracker does not move, so max_server_memory_usage is never checked while copying AGREE, fixed the checker watches the first level the blocker does not block; Buffer insert of 4000 shared 1 MiB states at max_server_memory_usage = 2G: 4.27 GB before, Code: 241 at 2.2 GB after
2 💡 Fall back to total_memory_tracker for threads without a ThreadStatus DISAGREE query limits only exist through the thread's tracker chain (CurrentMemoryTracker.cpp:34-66); pool jobs always get a ThreadStatus (ThreadPool.cpp:1330)
3 ❌ lagInFrame(x, offset, default) copies the default state into every row outside the frame through insert(Field), which no loop check covers AGREE, fixed one check per state with a non-trivial destructor in insert(Field) / tryInsert; test line added (fails on master and on the previous head, passes now)
4 ⚠️ No automated test covers the Buffer (blocked tracker) path DISAGREE only max_server_memory_usage applies there (a stateless test cannot set it), and CI unit tests run on sanitizer builds, which do not track these copies; validated manually (row 1)
5 💡 The test drives the copies only through the deprecated neighbor, and its header names only anyLast AGREE, fixed finalizeAggregation(materialize(...)) line added; header names anyLast and argMax

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261022-055500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. neighbor(<1 MiB anyLastState>, 10) and (..., -10) over numbers(300) at max_memory_usage = '100M': master succeeds 10/10, fix refuses 10/10; lagInFrame(s, 1000, s) OVER (): master succeeds 3/3, fix refuses 3/3; the CI-shape query is a memcg OOM kill on master and MEMORY_LIMIT_EXCEEDED at 2.1 GB with the fix.
b Root cause explained? Both ColumnAggregateFunction copy loops (ensureOwnership, the forced-ownership loop of insertRangeFrom) and insert(Field) turn one shared state into N owned copies; for anyLast/argMax over FixedString each copy is an operator new allocation the tracker counts but never refuses, and none checked the limit.
c Fix matches root cause? Yes. The check is where the copies are made: inside both loops, and after each deserialized state that can own memory outside the arena in insert(Field)/tryInsert; no caller-side guard, no setting.
d Test intent preserved / new tests added? New 05442_aggregate_state_copy_memory_limit: four refusal queries (finalizeAggregation(materialize(...)), lagInFrame with a default, neighbor +10 / -10) plus a value-checking positive control; sanitizer tags measured (ASan's operator new does not reach the tracker).
e Both directions demonstrated? Master: FAIL on all four refusal lines. Fix: OK, 50/50 randomized runs. Loops-only head: FAIL on the lagInFrame line only; ensureOwnership-only build: FAIL on the -10 line only. Buffer insert at max_server_memory_usage = 2G: master 4.27 GB, fix refuses at 2.2 GB.
f Fix is general across code paths? Both copy loops and both Field inserts: neighbor with either sign, finalizeAggregation(materialize(...)), lagInFrame/leadInFrame, any(s) OVER (), sorted merges, if over states. WindowTransform's per-row -State writes are out of scope.
g Fix generalizes across inputs (params/datatypes/wrappers)? Independent of the state type (refusal measured with anyLast(Nullable(FixedString)) and argMax(UInt8, FixedString)); states with a trivial destructor skip the insert(Field) check; under a MemoryTrackerBlockerInThread the first unblocked level is watched; threads without a tracker skip the check.
h Backward compatible? (maintainer-approved exception only) Yes. No format or setting change; only queries that already exceeded the memory limit while copying now get MEMORY_LIMIT_EXCEEDED.
i Invariants and contracts preserved? ensureOwnership throws inside the existing try, whose catch destroys the partial copies (ColumnAggregateFunction.EnsureOwnershipExceptionLeavesCorruptedState passes); insertRangeFrom throws between rows and insert(Field) after the state is fully deserialized, so every inserted row stays valid.

Session id: cron:clickhouse-impl-slot-6:20261022-052000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @Avogar, could you review this and add the can be tested label so CI runs? Copying shared aggregate function states in ColumnAggregateFunction (ensureOwnership, the forced-ownership loop of insertRangeFrom, insert(Field)) allocated with operator new for states like anyLast over a 1 MiB FixedString, which the tracker counts but never refuses, so neighbor, lagInFrame or finalizeAggregation(materialize(...)) over a state could OOM the server; these loops now call CurrentMemoryTracker::check().

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5c83c6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) ERROR
OOM in dmesg ERROR cidb

AI Review

Summary

This PR closes the unchecked-copy hole in ColumnAggregateFunction by enforcing memory-limit checks across the ownership-copy loop, the row-by-row ownership path, the pointer-based copy path used by aggregate-state arithmetic and -State window outputs, and the Field insertion path used by explicit window defaults. I read the current diff and prior discussion, verified that the earlier pointer-overload finding is fixed in the current code, and I did not find any remaining contract violations in the changed surface.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-data-types Type system & core datatypes used across query planning/execution. labels Oct 22, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 22, 2026
Comment thread src/Columns/ColumnAggregateFunction.cpp Resolved
…pointer

`ColumnAggregateFunction::insertFrom(ConstAggregateDataPtr)` creates a new
state and merges the given one into it. Aggregate function state arithmetic
(`executeAggregateAddition`, one call per row) and every `-State` result
inserted through `insertMergeResultInto` (window functions, `arrayReduce`,
`initializeAggregation`, `runningAccumulate`) use it, so a shared state is
copied once per row, with `operator new` allocations that the memory tracker
counts but does not refuse. Before this change,
`SELECT materialize(S) + S FROM numbers(300)`, with `S` an `argMaxState` over
a 1 MiB `FixedString`, succeeded at `max_memory_usage = '100M'` with 545 MB
RSS, and so did `uniqThetaState(number) OVER ()` over 3800 rows at 180M.

The check runs before the copy, so a refusal leaves the column unchanged. It
compares with the tracker value seen by the previous call on the same thread,
not with the value at the start of the call: in
`materialize(argMaxState(0, tuple(''))) + argMaxState(1, tuple(<1 MB String>))`
the copies are made by `insertMergeFrom` of the right-hand state after
`insertFrom` returned, so a per-call comparison never sees them (that query
still succeeded at 542 MB RSS with one). An unconditional
`CurrentMemoryTracker::check()` per call was 2.8x slower on a cheap
`anyLastState(String)` addition in a debug build. `insertMergeFrom` itself is
not checked: the merging algorithms and `TotalsHavingTransform` merge every
row into one state, which does not multiply it.

RelWithDebInfo, 11 interleaved runs, medians: `materialize(countState) +
countState` over 50M rows +8% (0.9 ns per row), the same with
`anyLastState(String)` +11.5% (1.8 ns), `countState() OVER (ORDER BY number
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)` over 20M rows +5.4%, the same with
`anyLastState(String)` +3.5%.

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

clickhouse-gh Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e5c83c6c1 with master 9a14a7bed (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

8 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/google-cloud-cpp-cmake/__/google-cloud-cpp/google/cloud/storage/internal/object_requests.cc: 5.3 s

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e5c83c6

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / OOM in dmesg not fixed by this PR, and present on master: the fuzzed query reads one 1 MiB anyLastState per row from remote shards, and Native deserialization of the AggregateFunction column (SerializationAggregateFunction::deserializeBinaryBulk) creates those states without a max_memory_usage refusal. This PR changes only state copies inside ColumnAggregateFunction; the same remote read passes max_memory_usage = '100M' by over 2 GiB on master and on this head a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20261023-040008

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) / OOM in dmesg row of the ledger above: #127561.

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks complex, let's try simpler alternative - #129553
But let's keep it open for now

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

I measured #129553 (applied to master 39b9f2d, debug build) against the repros of this PR. Every one that still reproduces on master is refused:

  • 1 MiB states x300 at max_memory_usage = '100M': finalizeAggregation(materialize(...)), neighbor(s, 10), neighbor(s, -10), state +, any(s) OVER (); also uniqThetaState(number) OVER () x3800 at 180M.
  • the Support DEFAULT expressions inside Tuple data types #108090 neighbor query over 3000 rows at 1G (master: 3.2 GB RSS).
  • a Buffer INSERT of 4000 shared states at max_server_memory_usage = 2G, refused at 1.86 GiB (master lets it through at 4.3 GB RSS).

So this PR can be closed once #129553 is merged. 05493 covers the remote read and ensureOwnership only; the other lines of this PR's 05442 can be moved over as is if you want them, except lagInFrame(s, 1000, s), which master no longer reproduces.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-data-types Type system & core datatypes used across query planning/execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants