Skip to content

Fix window functions that return aggregate states ignoring the memory limits - #126026

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:check-memory-limit-in-window-aggregate-states
Closed

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

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111892

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 window functions that return aggregate function states (for example uniqThetaState(x) OVER ()) ignoring max_memory_usage and max_server_memory_usage. Each output row gets its own copy of the state, so such a query could use many times the configured limit and get the server killed by the OOM killer.

Description

On 26.8.18.2, clickhouse local running SELECT uniqThetaState(number) OVER () FROM numbers(100000) FORMAT Null is OOM-killed in a 3 GiB container although max_server_memory_usage is 2G, because neither the query nor the server limit is checked while the window writes the states.

Found by the AST fuzzer on master (report): a uniqThetaOrDefaultTupleState(...) OVER (...) over 240000 rows from remote() reached 14.69 GiB against a 9.31 GiB query limit.

Root cause: WindowTransform::computeReadyRows writes all ready rows of a block in one work() call, and a window function whose result is a state gives every row its own copy. uniqTheta states use std::allocator and groupBitmap states use malloc; such allocations are tracked but never refused, so nothing in that loop stopped the query.

Change: when some window function returns a type that can hold an aggregate state (AggregateFunction, or a Dynamic/JSON value), WindowTransform checks the memory limit after each row whose allocations have reached the current thread's memory tracker (every max_untracked_memory, 4 MiB by default). ColumnAggregateFunction::ensureOwnership, which copies all states a column shares in one loop (reached by leadInFrame and finalizeAggregation), checks the same way. Cost over 20M rows: countState() OVER (...) +1.0%, count() OVER (...) -0.3%, finalizeAggregation of shared countState states +1.8 to +3.3%.

Validation: the new test fails on master and passes with the fix. On the fuzzer's query shape the initiator now stops at 954 to 957 MiB against a 1G limit instead of 1.9 to 5.6 GiB, and two such queries keep a server capped at 5.59 GiB at 4.6 to 5.9 GiB peak RSS instead of 15.3 GiB.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 15, 2026 12:56
A window function whose result is an aggregate function state copies a
state into every output row (`insertMergeResultInto`, `insertResultInto`
of a state-typed result, `lagInFrame` of a state column). With a frame
over the whole partition each copy is the whole-partition state, so the
query needs rows x state size. `uniqTheta` states are `datasketches`
sketches using `std::allocator` and `groupBitmap` states use `malloc`;
such allocations are tracked but never refused
(`min_allocation_size_to_throw_on_memory_limit` for `operator new`), and
`computeReadyRows` computes all ready rows of a block in one `work()`
call with no limit check, so nothing stopped the query before it passed
both `max_memory_usage` and `max_server_memory_usage`.

The AST fuzzer on master got the server OOM-killed this way: a
`uniqThetaOrDefaultTupleState(...) OVER (GROUPS BETWEEN UNBOUNDED
PRECEDING AND UNBOUNDED FOLLOWING)` over 240000 rows from `remote()`
reached 14.69 GiB against a 9.31 GiB query limit.

When some window function returns a type that can hold aggregate states
(`AggregateFunction`, `Dynamic`, `JSON`), check the memory limit after
each row whose allocations have reached the current thread's memory
tracker, which happens every `max_untracked_memory`.
`Aggregator::checkLimits` does the same per block for the same reason.
Windows that return no states only pay one branch per row.

`ColumnAggregateFunction::ensureOwnership` copies all states a column
shares in one loop. `leadInFrame` over a column that repeats one state
gets there at the end of a block, so one row could copy a block of
states before the window's check. Check the limit in that loop the same
way, reading the thread's memory tracker once before the loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the sentence narrating the gated check in computeReadyRows and the comment restating the last-check field names.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds): 6 findings agreed and fixed, 0 dismissed
  • ❌ Agreed, fixed: checking every 64 rows leaves up to 63 rows of state copies unchecked, plus every block tail. A groupBitmap copy (allocated with malloc) has no size bound. The check now runs after each row whose allocations have reached the thread's memory tracker.
  • ❌ Agreed, fixed: a Dynamic/JSON result can hold a state that is copied per row, but the type check did not see it. The flag now also covers types with a dynamic structure.
  • ❌ Agreed, fixed: the groupBitmap test line relies on malloc being tracked, which needs jemalloc, so it would fail in ASan/TSan/MSan builds. The test is tagged out of those, like 01961_roaring_memory_tracking.
  • ❌ Agreed, fixed: leadInFrame over a column that repeats one state first shares the states, then ColumnAggregateFunction::ensureOwnership copies a whole block of them in one loop, before the window's per-row check runs. That loop now checks the limit the same way.
  • ⚠️ Agreed, fixed: the "nothing new since the last check" test compared amounts of possibly different thread trackers after the processor moved to another thread. It now remembers the tracker too.
  • ⚠️ Agreed, fixed: hasDynamicSubcolumns is true for every Map, so state-free Map windows took the checking path. It is now hasDynamicStructure.
  • 💡 Noted: lagInFrame over a state column is covered by the same result-type check (measured), so it has no separate test line.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT uniqThetaState(number) OVER () FROM numbers(3800) SETTINGS max_memory_usage = '180M', max_block_size = 65536 FORMAT Null" succeeds on master every time although the query peaks at 242.99 MiB (limit 171.66 MiB); master still succeeds with the limit at 2M.
b Root cause explained? Yes. WindowTransform::computeReadyRows writes all ready rows of a block in one work() call, and a window function whose result is an aggregate state gives every row its own copy of the (whole-frame) state. uniqTheta states use std::allocator and groupBitmap states use malloc; such allocations are tracked but never refused, and the loop had no limit check, so memory grew by rows x state size past both limits.
c Fix matches root cause? Yes. The window checks the limit itself while it writes rows that can hold states: after each row whose allocations have reached the thread's memory tracker (every max_untracked_memory) and after a move to another thread, when some result type contains AggregateFunction, Dynamic or JSON. ColumnAggregateFunction::ensureOwnership, which copies all states a column shares in one loop, checks the same way. Same reason as Aggregator::checkLimits. No global policy change, no bounds widened.
d Test intent preserved / new tests added? Yes. New 05401_window_aggregate_state_memory_limit: five lines that must fail with MEMORY_LIMIT_EXCEEDED (-State window, any(s) over a state column, a Dynamic value holding a state, 60 rows of a large groupBitmap state in one block, finalizeAggregation(materialize(s)) over a column repeating one state) plus a positive control (3800 3800).
e Both directions demonstrated? Yes. Master: the test fails, all five refusal lines succeed (30/30 randomized runs for the first four). Revision checking every 64 rows: fails 20/20, exactly the Dynamic and groupBitmap lines succeed. Revision without the ensureOwnership check: fails 20/20, exactly the finalizeAggregation line succeeds; leadInFrame(s) OVER () there is refused only at 241.44 MiB against 171.66 MiB, the fix at 173.38 MiB. Fix: 50/50 randomized runs pass. Fuzzer's remote() shape with a 1 GiB limit: master stops at 1.9 to 5.6 GiB, fix at 954 to 957 MiB. Two concurrent queries on a server capped at 5.59 GiB: master peaks at 15.6 GiB RSS, fix is refused at the cap (4.6 to 5.9 GiB peak RSS over five runs).
f Fix is general across code paths? Yes. The flag is keyed on the result type, so every path that writes states into output rows is covered: insertMergeResultInto (-State), insertResultInto and the frame-unchanged self-copy (any/anyLast/argMax of a state, also inside Dynamic), windowInsertResultInto (lagInFrame of a state, measured to copy per row), and the bulk copy in ColumnAggregateFunction::ensureOwnership that leadInFrame reaches at the end of a block (also reached by finalizeAggregation). The check is per row, so a short block of large states is covered too, and a processor resumed on another executor thread checks on its first row there. Aggregator already checks per block.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured refused on the fix and bypassed on master: -StateForEach, -StateMap, -OrDefault/-Tuple, Nullable argument, anyLast/argMax/groupArray of a state, a state cast to Dynamic, groupBitmap states, lagInFrame, partitioned and running frames. count() OVER () and state-free Map results (lagInFrame(map(...))) do not take the checking path; countState()/count() window timings within noise (+1.0% / -0.3%).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Queries that silently exceeded max_memory_usage now get MEMORY_LIMIT_EXCEEDED, which is the documented contract.
i Invariants and contracts preserved? Yes. The check runs after a fully written row for all workspaces, so all result columns of the block have equal length at the throw point; the transform's destructor already frees the workspace states. The early returns (frame not yet visible, cancellation) are unchanged. In ensureOwnership the existing catch destroys the states created so far, so a refusal leaves the column a valid view (the failpoint gtest of that loop passes).

Session id: cron:clickhouse-impl-slot-4:20261015-122800

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6316917]

Summary: ❌

job_name test_name status info comment
Config Workflow FAIL
can_be_tested FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Dockers Build (amd) DROPPED
Dockers Build (arm) DROPPED
Dockers Build (multiplatform manifest) DROPPED
Style check DROPPED
Code Review DROPPED
Docs check (Mintlify) DROPPED
Fast test DROPPED
Build (arm_tidy, 1/4) DROPPED

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

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @antonio2368, could you review this? A window function that returns an aggregate state copies the state into every output row, and those copies (operator new/malloc) are tracked but never refused, so WindowTransform::computeReadyRows and ColumnAggregateFunction::ensureOwnership now check the memory limit while they copy; computeReadyRows is also changed by #125749.

@Michicosun

Copy link
Copy Markdown
Member

not now

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

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants