Skip to content

Check the memory limit while reading aggregate function states - #127561

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

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

Conversation

@groeneai

@groeneai groeneai commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117916
Related: #127334

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 max_memory_usage and max_server_memory_usage not being enforced while reading AggregateFunction states that hold large values (for example anyLast over a large FixedString) from distributed queries and from Native, row, text and Protobuf formats. One block of such states could exceed the limit by gigabytes and get the server killed by the OOM killer.

Description

AST fuzzer (amd_debug, targeted) on #127334 ended with the server OOM-killed at 43.3 GiB (log) while the initiator received anyLastState(FixedString(1048577)) rows from six shards under max_memory_usage = '100M'. This is pre-existing: on 26.8.18.2, a Native read of 4000 such 1 MiB states with max_server_memory_usage = 2G in a 3 GiB container is OOM-killed instead of failing with MEMORY_LIMIT_EXCEEDED.

Root cause: SerializationAggregateFunction::deserializeBinaryBulk fills a block of states with one createAndDeserializeBatch call that never checks the limit. A state whose data lives outside the arena allocates it with operator new, which the memory tracker counts but does not refuse (#117916). The single-state readers (row formats, text formats and CAST from String, Protobuf) check nothing either.

Change: for functions with non-trivially destructible states, createAndDeserializeBatch calls CurrentMemoryTracker::check() after each state that moved the query's memory tracker, before the column owns the state. The single-state readers compare the tracker with the last passing check of the same tracker in the thread, because their callers read the state's bytes into a String first.

Validation: the new test fails on master and passes 50/50 with randomized settings. The fuzzer's query now stops at ~96 MiB. RelWithDebInfo read time: bulk within 1.05x, RowBinary uniq states 1.083x, TSV 1.031x.

Copies of states in ColumnAggregateFunction are handled in #127334, which adds a helper of the same shape there; whichever of the two merges second will switch to the other's.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 23, 2026 07:25
A state whose data lives outside the arena (anyLast/argMax over FixedString,
groupFormat, datasketches, ...) allocates it with operator new, which the
memory tracker counts but never refuses. Reading such states did not check
the limit, so one remote block of 1 MiB anyLast states read gigabytes past
max_memory_usage and the server was OOM-killed.

createAndDeserializeBatch now takes the query's memory tracker (nullptr for
trivially destructible states, which cannot own memory outside the arena) and
checks the limit after each state that moved it, before the column owns the
state. The query's tracker is watched rather than the thread's, because a
remote read runs in a fiber that another thread of the query can resume.

The readers of one state at a time (row formats, text formats and CAST from
String, Protobuf) cannot use a window opened at their entry: their callers,
sometimes several layers up, read the state's bytes into a String first, and
that read is where the untracked memory is flushed. They compare the
tracker with the last passing check of the same tracker in this thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the doc line of checkMemoryLimitIfChanged, which restates its body.

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; 2 rounds, 3 findings, 0 in the second round) plus my own review of the diff.

# Sev Finding Verdict Evidence / action
1 ❌ One state larger than the free memory (e.g. a 1 GiB String inside anyLast(Tuple(String))) is allocated before the check runs DISAGREE That is one unrefused operator new allocation in generic Field reading (#117916), not a missing check between states. This PR bounds the overshoot to one state instead of one block: 95.64 MiB under 100M, and the fuzzer's query stops at ~96 MiB.
2 ❌ The thread-local (tracker, amount) key can match a new query's tracker at a reused address DISAGREE The key is only compared and is written after a passing check, so a match skips checks only while the amount stays the same; the next untracked-memory flush moves it and the next state checks. The cost is one delayed check, the same granularity as everywhere else.
3 ⚠️ The test misses the RowBinary and Protobuf readers; its bound allows 2x the limit AGREE, fixed Added RowBinary and Protobuf (inline schema) arms: both refuse at 96.9 MiB and succeed on master. The bound is now 150 MB. max_server_memory_usage cannot be set from a stateless test; the check walks the whole tracker chain.
4 💡 IAggregateFunction.h now includes Common/MemoryTracker.h noted Needed for the inlined amount read in the devirtualized loop; an out-of-line read would cost a call per state.

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

Session id: cron:clickhouse-review-slot-9:20261023-072900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT s FROM remote('127.0.0.2', view(SELECT initializeAggregation('anyLastState', toFixedString('\0', 1048577)) AS s FROM numbers(400))) SETTINGS max_memory_usage = '100M', prefer_localhost_replica = 0 FORMAT Null reads all 400 MiB on master, every run. The new test 05445 fails on master on every run.
b Root cause explained? Yes. deserializeBinaryBulk fills a block of states with one createAndDeserializeBatch call that never checks the limit, and states such as anyLast over FixedString allocate their data with operator new, which the tracker counts but does not refuse (#117916). The single-state readers (row, text, CAST from String, Protobuf) check nothing either, and their callers read the state's bytes into a String first.
c Fix matches root cause? Yes. The limit is checked per state where states are created from serialized data, only when the query's tracker moved, before the column owns the state. No bounds, tags or data sizes changed.
d Test intent preserved / new tests added? New test 05445_aggregate_state_deserialization_memory_limit: remote (bulk) read refused, refusal amount below 150M, reads through url() in TSV, RowBinary and Protobuf refused (one statement per changed reader), a read below the limit succeeds.
e Both directions demonstrated? Yes. Master: FAIL (the remote, TSV, RowBinary and Protobuf reads all succeed). Fix: OK, and 50/50 with randomized settings (4.4-5.6 s); each url() read alone refuses at ~96 MiB. Two intermediate designs also fail it: a check once per block (refusal at 404.84 MiB, line 2) and a window opened at the single-state reader's entry (TSV arm read in full).
f Fix is general across code paths? Yes. All four readers that create states from serialized data (bulk, row formats, text formats and CAST, Protobuf), plus the buffering wrappers above them (TSVRaw, Array CSV, Variant text), refuse at 96-99 MiB. Copies of states in ColumnAggregateFunction are #127334; the Aggregator merge path already checks per block.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Native, RowBinary, TSV, TSVRaw, CSV, JSONEachRow, Values, Protobuf, nested in Array and Variant, parallel parsing on and off. Round trips of FixedString and uniq states return identical results. Trivially destructible states are not checked at all.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Only queries that exceeded the limit through unrefused operator new memory now fail with MEMORY_LIMIT_EXCEEDED.
i Invariants and contracts preserved? Yes. The check runs before the column takes the state, so a throw leaves the column unchanged (ISerialization.h) and the refused state is destroyed by the existing catch. The per-thread last-check record is written only after a passing check. RelWithDebInfo read time: bulk at most 1.048x, RowBinary uniq 1.083x, TSV 1.031x.

Session id: cron:clickhouse-impl-slot-4:20261023-071200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @antonio2368, could you review this and add the can be tested label so CI runs? Reading AggregateFunction states (Native bulk, row and text formats, Protobuf) now calls CurrentMemoryTracker::check() after each state that moved the query's memory tracker, so states whose data is allocated with operator new (e.g. anyLast over a 1 MiB FixedString) are refused near max_memory_usage instead of a whole remote block getting the server OOM-killed; #127334 is the sibling for copies of states.

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e331a5]

Summary: ✅


AI Review

Summary

Adds memory-limit checks while deserializing non-trivial AggregateFunction states through bulk Native, row, text, and Protobuf readers, with regression coverage for each reader. No actionable defects found in PR head 1e331a5d4954e212d7ed535bdcb952c74409860e; the implementation and the author's reported before/after regression results support approval.

Missing context / blind spots
  • ⚠️ Runtime CI and bugfix-validation results were not available for the current run at review time. No local ClickHouse binary was available for independent execution. Successful CI regression and bugfix-validation jobs would corroborate the author's reported runs.
Final Verdict

Status: ✅ Approve based on source review and the supplied regression evidence, subject to the remaining CI checks.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 23, 2026
@azat azat self-assigned this Oct 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Oct 23, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Oct 23, 2026
@Algunenano

Copy link
Copy Markdown
Member

@groeneai Do you mind explaining what allocations exactly aren't being tracked and why we can't switch those sources to be tracked and allowed to throw?

@groeneai

Copy link
Copy Markdown
Collaborator Author

They are tracked, just never refused. Here it is the std::string inside a Field: anyLast(FixedString(N)) uses SingleValueDataGeneric, which holds its value as a Field (SingleValueData.h#L338), and reading a state resizes that Field's String to N bytes (SerializationFixedString.cpp#L62-L68). Plain operator new goes to CurrentMemoryTracker::allocThrow (memory.h#L126), which enforces the limit only for allocations of at least min_allocation_size_to_throw_on_memory_limit, and the default 0 means never (CurrentMemoryTracker.cpp#L133-L144). Nothing else in the createAndDeserializeBatch loop checks the limit, so a remote block of 65536 such 1 MiB states (64 GiB) is read with nothing to stop it. That is how the fuzzer's server reached 43 GiB under max_memory_usage = '100M'.

Why I didn't switch the sources:

  1. Globally, the switch exists: min_allocation_size_to_throw_on_memory_limit (RFC: Add a server setting to allow any allocation to throw MEMORY_LIMIT_EXCEEDED #105265), opt-in because a throwing operator new breaks exception safety in destructors (MemoryTracker should be used in operator new in a light way #24110). It gates on the size of each allocation, so it only refuses states at least as large as the threshold. Master, Native read under max_memory_usage = '100M':
    • 3000 x 1 MiB states: read in full with threshold 0 and with 8 MiB (above max_untracked_memory, as its docs recommend); refused at 96.61 MiB with 1 MiB.
    • 20000 x 64 KiB states: read in full with 1 MiB; refused at 97.19 MiB only with 64 KiB.
    • This PR with default settings refuses them at the same points, 96.61 MiB and 97.19 MiB.
  2. Per source, here that is Field's String. Field's Array/Tuple/Map are already VectorWithMemoryTracking (Apply *WithMemoryTracking containers to BridgeHelper and some Core subdirectories #106047), but String is a plain std::string returned by reference to ~700 safeGet<String> call sites, so changing its allocator is not a local change. It is also one of several such sources: uniqTheta, for example, keeps datasketches objects that allocate with std::allocator (ThetaSketchData.h#L31).

Creating states from serialized data is the one point all of them pass through, and the check runs before the column owns the state, so a refusal is clean. If you would rather convert Field's String to StringWithMemoryTracking instead, I can do that, but it is a much larger change.

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1e331a5d4 with master 148fa6a24 (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.

Object file sizes

151 object files changed (+1.41 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 16.02 MiB 16.17 MiB +153.09 KiB (+0.93%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSparkbar.cpp.o 5.34 MiB 5.39 MiB +54.50 KiB (+1.00%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.83 MiB 6.88 MiB +51.68 KiB (+0.74%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 7.02 MiB 7.07 MiB +51.29 KiB (+0.71%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.19 MiB 13.23 MiB +50.52 KiB (+0.37%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionRegr.cpp.o 5.92 MiB 5.97 MiB +44.29 KiB (+0.73%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.60 MiB 13.64 MiB +43.32 KiB (+0.31%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.85 MiB 5.89 MiB +39.64 KiB (+0.66%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 6.66 MiB 6.70 MiB +38.46 KiB (+0.56%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionDeltaSumTimes… 3.52 MiB 3.55 MiB +29.91 KiB (+0.83%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArray.cp… 4.62 MiB 4.65 MiB +27.93 KiB (+0.59%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 5.76 MiB 5.78 MiB +26.31 KiB (+0.45%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileGK.cp… 3.30 MiB 3.32 MiB +25.20 KiB (+0.75%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantile.cpp.o 3.60 MiB 3.62 MiB +22.01 KiB (+0.60%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/Combinators/AggregateFunctionM… 4.04 MiB 4.06 MiB +21.76 KiB (+0.53%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.78 MiB 3.81 MiB +21.61 KiB (+0.56%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAny.cpp.o 2.59 MiB 2.61 MiB +20.59 KiB (+0.78%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.09 MiB 3.11 MiB +20.14 KiB (+0.64%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… 3.09 MiB 3.11 MiB +20.14 KiB (+0.64%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.09 MiB 3.11 MiB +20.14 KiB (+0.64%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +173.6 s (+7%) in total before that adjustment.

Job report

@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 this PR's test 05445: the remote() Native read and the url() reads in TSV, RowBinary and Protobuf are all refused at 95.4-96.9 MiB under max_memory_usage = '100M' (master reads them all), 20/20 with randomized settings. The AST fuzzer query that found this on #127334 (6 replicas, 1 MiB anyLastState rows) is refused at 95.4-97.0 MiB, 3/3, no OOM.

So this PR can be closed once #129553 is merged. 05493 does not cover the single-state readers (deserializeBinary(IColumn &), deserializeFromString, Protobuf); the three url() statements of 05445 fail on master and pass with #129553 if you want them (the Protobuf one needs no-fasttest).

@azat

azat commented Nov 5, 2026

Copy link
Copy Markdown
Member

I measured #129553

I didn't ask, but if you want to help, you can check the performance

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

It is slower wherever many small states with a non-trivial destructor are read or merged. Local A/B: master 39b9f2d with and without the #129553 diff, RelWithDebInfo, clickhouse local, one pinned core, max_threads = 1, median of 25 runs (10 for OPTIMIZE):

Query master #129553 #129553 + cheaper check
uniq_stored #2 (2M one-element uniq states) 0.077 s 0.140 s (x1.82) 0.079 s (x1.03)
uniq_states_read_merge #0 1.222 s 1.609 s (x1.32) 1.232 s (x1.01)
uniq_states_read_merge #1 0.667 s 0.848 s (x1.27) 0.679 s (x1.02)
aggregating_merge_tree #0 (OPTIMIZE FINAL) 0.049 s 0.065 s (x1.34) 0.049 s (x1.01)
SELECT s of 10M anyLast(String) states 0.117 s 0.451 s (x3.86) 0.132 s (x1.13)
sum states (trivial destructor) 0.236 s 0.236 s 0.236 s

This matches the PR's Performance Comparison (uniq_stored #2 +77%, confirmed after a restart). The cost is the call: about 30-35 ns per CurrentMemoryTracker::check(), i.e. MemoryTracker::allocImpl(0, true) on each level up to the global tracker, paid for every state.

"Cheaper check" keeps your call sites and only changes the body, so a thread checks after its own tracked memory changed:

void checkMemoryLimitForAggregateFunctionState()
{
    /// The amount of the thread tracker changes only when the thread flushes its untracked memory.
    static thread_local const MemoryTracker * checked_tracker = nullptr;
    static thread_local Int64 checked_amount = 0;

    const MemoryTracker * tracker = CurrentThread::getMemoryTracker();
    const Int64 amount = tracker ? tracker->get() : 0;
    if (tracker == checked_tracker && amount == checked_amount)
        return;

    CurrentMemoryTracker::check();
    checked_tracker = tracker;
    checked_amount = amount;
}

With it, the Native and RowBinary reads of 3000 1 MiB anyLast states and the ensureOwnership query of 05493 are still refused at 96.4-98.0 MiB under max_memory_usage = '100M', as with #129553 (master reads the first two completely and refuses the third at 7.84 GiB).

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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