Skip to content

Apply the memory limit to FixedString values of min/max/any/argMax states - #130682

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fixedstring-single-value-state-arena
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fixedstring-single-value-state-arena

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127561

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

max_memory_usage and max_server_memory_usage now also limit the FixedString values held by min, max, any, anyLast (without RESPECT NULLS), argMin, argMax, anyHeavy, singleValueOrNull and the -ArgMin/-ArgMax combinators. Before, a GROUP BY over large FixedString values could exceed both limits until the server was killed by the OOM killer.

Description

AST fuzzer OOM in dmesg on two unrelated PRs: #124320 (countIfArgMax(big, toFixedString('(a|b)*', 65535)) ... GROUP BY) and #130269 (sumDistinctArgMax(b, toFixedString(.., 1048575)) ... GROUP BY). In both, memory grew past max_memory_usage and max_server_memory_usage until the kernel killed the server.

On 26.10.2.103, SELECT sum(a + b + c) FROM (SELECT number AS k, countArgMax(f) AS a, countArgMin(f) AS b, argMax(number, f) AS c FROM (SELECT number, toFixedString(toString(materialize(1)), 1048575) AS f FROM numbers(1024)) GROUP BY k) SETTINGS max_threads = 1, max_block_size = 1024 is OOM-killed in a 3 GB container although max_server_memory_usage is 2.5 GB.

Single-value states kept a FixedString in a Field, a std::string from operator new, which the memory tracker counts but never refuses. Aggregator::checkLimits refuses only at the end of a block, so one block's state can add its argument column's size again.

SingleValueDataString becomes a template on the column type, and FixedString values now live inline or in the aggregation arena, whose chunks are checked allocations. The serialized state is unchanged (flag + N bytes; checked against the old binary, also across versions through remote). This is the source switch asked about on #127561 (an anyLast(FixedString) state there); it also covers the add path, which the checks after reading or copying states (#127561, #129553) do not. any/anyLast with RESPECT NULLS have their own Field state for every type, String included, and are not changed here.

Validation: the refused queries of the new test peak at 84.2 MB under the 100 MB limit (50 randomized runs; 134.6 MB on master); the query above is refused with MEMORY_LIMIT_EXCEEDED. Local RelWithDebInfo, one thread: max over FixedString(16), 50M rows, 1000 groups, 0.68 s -> 0.29 s; String unchanged.


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

groeneai and others added 2 commits November 11, 2026 01:56
`any`, `anyLast`, `min`, `max`, `argMin`/`argMax` (result and key),
`-ArgMin`/`-ArgMax` keys, `anyHeavy` and `singleValueOrNull` kept a
`FixedString` value in a `Field`, i.e. in a `std::string` allocated by
`operator new`. Such allocations are tracked but never refused by the
memory limit, so one block of a `GROUP BY` could add as much unrefused
state memory as its (checked) argument column before the end-of-block
check in `Aggregator::checkLimits`. With large `FixedString` values the
server was OOM-killed by the kernel although `max_memory_usage` and
`max_server_memory_usage` were set (AST fuzzer "OOM in dmesg").

`SingleValueDataString` becomes a template on the column type and
`FixedString` is dispatched to its second instantiation, so the value
lives inline or in the aggregation arena, whose chunks are checked
allocations. The serialized state stays what `SingleValueDataGeneric`
wrote (a bool flag and the N bytes), so existing states are compatible.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The three refusal lines (`-ArgMax` key, `argMax` key, `max`: one per
dispatcher) each aggregate 1024 x FixedString(65535) in one block under a
100M limit. Both binaries refuse them, so the test checks the peak: before
the fix every refused query had already allocated the whole block's state
(~135 MB of tracked memory) before `Aggregator::checkLimits` refused it at
the end of the block; now the arena chunk that would cross the limit is
refused (~84 MB). The compatibility lines pin the serialized state format,
which stays the one `SingleValueDataGeneric` wrote.

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 runs on the same tree, 1 finding, 0 in the second run) plus my own review of the diff (no blocker or major).

# Sev Finding Verdict Evidence / action
1 ❌ any/anyLast with RESPECT NULLS still keep a FixedString in a Field DISAGREE (separate PR) Real, but other code: AggregateFunctionAnyRespectNulls.cpp has its own state (status byte + Field for every type, String too), not touched here. The changelog entry now says "without RESPECT NULLS" and the description names it.
2 💡 Arena allocations round up to a power of two, so FixedString(N) just above one takes up to 2x N noted Same as String; common sizes are equal or smaller than before (inline up to 48 bytes, no temporary Field per row).

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

Session id: cron:clickhouse-review-slot-8:20261111-034100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test's three refusal lines aggregate 1024 x FixedString(65535) in one block under max_memory_usage = '100M': the old binary's refused queries peak at 134.6-134.8 MB in 21/21 runs, the new one at 84.2 MB in 51/51. Server death: one 2 GiB block plus three FixedString-keyed states in a 6 GB scope (max_server_memory_usage 4 GB) is OOM-killed 3/3 on the old binary; the new one refuses it 3/3 and stays up.
b Root cause explained? Single-value states held a FixedString in a Field (std::string via operator new), tracked but never refused. Aggregator::checkLimits calls CurrentMemoryTracker::check() only after each block, so one block can allocate its whole state on top of the admitted argument column before anything refuses.
c Fix matches root cause? Yes. The value moves into the aggregation arena (or inline), whose chunks are checked allocations, so the limit refuses the state as it grows. No extra per-row check.
d Test intent preserved / new tests added? New 05620_fixed_string_single_value_state_memory_limit: one refusal line per dispatcher (-ArgMax key, argMax key, max), a query_log peak check, and the serialized-state lines with a reference taken from the old binary.
e Both directions demonstrated? Old binary: the check line prints 3 0 in 20/20 randomized runs, every refusal line still refused; new binary: OK 50/50 randomized.
f Fix is general across code paths? All three dispatchers that sent FixedString to SingleValueDataGeneric now use the arena-backed state (any, anyLast, min, max, argMin/argMax value and key, -ArgMin/-ArgMax key, anyHeavy, singleValueOrNull); add, merge, read and copy go through the same methods. Reading 1024 stored max(FixedString(65535)) states in one block (preferred_block_size_bytes = 0) under a 30 MB limit: the old binary finishes at 64.7 MB, the new one refuses it. Not changed: any RESPECT NULLS (its own Field state, String has the same exposure) and Strings nested in Array/Tuple/Map values.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality and LowCardinality(Nullable) arguments are unwrapped before the state is chosen: for the -ArgMax key, the argMax key and max all three are refused at an arena chunk (~103 MiB) on the new binary and only at the end of the block (~135 MiB) on the old one. Small (inline) and large (arena) values, empty input, -If with no rows and several FixedString sizes (2-65535 bytes) give output identical to the old binary.
h Backward compatible? Yes. No setting, and the state format stays a flag followed by N bytes. Hex snapshots match the old binary, and partial states exchanged between an old and a new server via remote give identical results in both directions.
i Invariants and contracts preserved? The String code paths compile from the same bodies (if constexpr branches only for FixedString; git diff -w shows no String token change). The state still occupies MAX_STORAGE_SIZE, and allocatesMemoryInArena() is now true for these functions, so every consumer that already handles String states (merges, window functions, runningAccumulate, ColumnAggregateFunction) passes an arena. Neighbour tests: same results as the old binary.

Session id: cron:clickhouse-impl-slot-4:20261111-022500

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c7d7af0]

Summary: ✅


AI Review

Summary

PR #130682 moves single-value aggregate states over FixedString from Field allocations into inline storage or checked arena allocations, preserving their serialized representation. No actionable findings at c7d7af08f4792bef6fe68fccd182fbb7e9924046. State consumers traced include the aggregate functions and combinators, ColumnAggregateFunction copying/deserialization/finalization, runningAccumulate, arrayReduce, initializeAggregation, window aggregates, and sorted merges; these supply or retain the required arenas. The new regression test distinguishes allocation-time refusal from end-of-block refusal and passed in Fast test.

Missing context / blind spots
  • ⚠️ Broader sanitizer/stateless jobs and automated bugfix validation have no completed results in the available report; the workflow finish check reports dropped bugfix-validation jobs. Completed runs would close this CI coverage gap. No local build was available, so the author's repeated before/after and cross-version measurements were not independently rerun.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c7d7af08f with master a62d3fd1e (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

8 object files changed (+404.24 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 16.07 MiB 16.23 MiB +163.06 KiB (+0.99%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsMinMax.cpp.o 2.65 MiB 2.76 MiB +116.94 KiB (+4.32%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAny.cpp.o 2.59 MiB 2.70 MiB +111.25 KiB (+4.19%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.75, programs/clickhouse-keeper ×0.84 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.6 s 12.0 s +7.0 s (+143%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.9 s 9.2 s +6.3 s (+219%)
Compile time of recompiled translation units

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

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

Job report

@Algunenano Algunenano 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 fixes the memory limit for FixedString only. Every type that still goes through SingleValueDataGeneric keeps the value in a Field allocated with operator new, and that allocation is never refused. So argMax(x, [big]), argMax(x, tuple(big)), Map, and any/anyLast with RESPECT NULLS should still be able to exceed max_memory_usage and max_server_memory_usage within one block. Instead of adding one specialized state per type, could you remove Field from single-value states altogether? Please prototype and measure these two approaches, preferring the first:

1. Arena-backed state with no Field and no IColumn. Store the value in the aggregation Arena, the same way SingleValueDataString does, so allocations are checked:

  • Use serializeValueIntoArena to store the value and deserializeAndInsertFromArena to produce the result.
  • For min/max/argMin/argMax, also store the serializeAsComparable encoding and compare with memcmp. Check whether one encoding can serve both purposes (comparable and decodable) so each value is stored only once.
  • Reuse the existing allocation when the new value fits.

2. One-row column state. Route every type without a dedicated state to the existing SingleValueDataGenericWithColumn and delete SingleValueDataGeneric and canUseFieldForValueData. Column buffers come from the checked Allocator. This is the fallback if approach 1 is slower or can't keep the current semantics.

For both, please verify:

  • Serialized states are byte-identical to the current ones (bool flag plus serializeBinary) for Array, Tuple, Map, Nullable, LowCardinality, Decimal, UUID, IPv6 and nested combinations. Write states with the old binary and read them with the new one, and also check across versions through remote.
  • min/max ordering matches the current Field comparison, including NaN inside Array/Tuple, NULL inside Tuple/Array, and empty arrays. This is the most likely place for either approach to diverge from Field::operator<.
  • The memory limit is enforced with the large values wrapped in Array, Tuple and Map, not only FixedString.

Please measure both approaches against master with one thread and with the default thread count:

  • min/max/any/argMax over Array(UInt64), Tuple(UInt64, String), Array(String) and Map(String, UInt64), with small and large values, and with few and many groups.
  • The common case where a group's value is replaced often (for example, ascending input for max), since that drives the reallocation cost.
  • Peak memory per group, not only time.
  • A control showing String and the numeric types are unchanged.

If approach 1 keeps the current semantics and is not slower, a separate FixedString state is no longer needed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'll prototype both approaches on this PR, starting with the arena-backed state, and post the results for each point you listed here (state compatibility, min/max ordering, the memory limit with large Array/Tuple/Map values, and time plus per-group peak memory against master) before this needs another look.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Results for both prototypes against master a9d24f9 (RelWithDebInfo; both prototypes are local, nothing is pushed yet).

  • A1: arena state. The value is its serializeValueIntoArena bytes, up to 16 bytes inline. The functions that compare (min, max, argMin/argMax key, -ArgMin/-ArgMax, anyHeavy, singleValueOrNull) also keep a memcmp key that reproduces the Field order (NULL first, NaN last, Array/Tuple/Map lexicographic). any, anyLast and the argMin/argMax result keep only the value. RESPECT NULLS uses the same storage.
  • A2: every type without a dedicated state goes to SingleValueDataGenericWithColumn; SingleValueDataGeneric and canUseFieldForValueData are deleted.

State compatibility. A1 writes the same bytes as master in 237 (function, type) cases (Array, Tuple, Map, Nullable, LowCardinality, Decimal, UUID, IPv6, nested combinations, NaN payloads, RESPECT NULLS). Master and A1 read each other's states identically, and mixed-version remote (master initiator over an A1 shard, and the reverse) returns the same results. A2 writes 2 different states (sumArgMax over Array(Nullable(Float64)) and over BFloat16 with NaN).

Ordering. A1 matches master on 780 queries: 41 value sets (NaN, -0 and NULL inside Array/Tuple, empty arrays, Map prefixes, LowCardinality(Nullable) in Tuple, ...) x 14 functions x 3 input orders, with and without GROUP BY, and through -State/-Merge. A2 changes results: with one row per block, min over [nan], [1.] returns [nan] (master [1]), any(Map) under GROUP BY returns another row's value, and a signaling NaN keeps its bits where master quiets it.

Memory limit. One correction: numeric Array/Tuple/Map values are already refused on master, because Field keeps elements in VectorWithMemoryTracking (src/Core/Field.h:23): any(arrayWithConstant(8192, number)) over 1024 groups stops at 98.8 MB under max_memory_usage = 100M. What is not refused is the bytes of a String or FixedString at any depth. Over 512 groups of 32 KiB strings in Array(String), Tuple(UInt64, String) and Map(String, String) (any, anyLast, max, argMax key and result, anyHeavy, any_respect_nulls) under max_memory_usage = 10M, master peaks at 19.2 MB, A1 at 8.6-9.6 MB, A2 at 9.7-9.8 MB. A server with max_server_memory_usage = 4G in a 6 GB cgroup, 16384 groups of [toFixedString(..., 65535)]: master is OOM-killed 3 of 3 times, A1 (3 of 3) and A2 (2 of 2) throw MEMORY_LIMIT_EXCEEDED and stay up.

Time and peak memory per group, prototype / master: 306 rows (min, max over ascending and descending input, any, argMax key and result; 1 and 16 threads on 16 pinned cores; 16 groups and 100K-1M groups; Memory tables), median of 5 rotated rounds, every row above 1.05 re-run 7 rounds ABBA.

Type A1 time, median (max) A1 peak, max A2 time, median (max) A2 peak, max
Array(UInt64), 4 / 256 elements 0.53 (1.00) / 0.49 (1.00) 1.00 1.66 (5.00) / 0.46 (1.00) 1.69
Map(String, UInt64), 4 / 64 entries 0.30 (0.83) / 0.32 (1.00) 1.00 0.90 (1.84) / 0.25 (1.50) 1.61
Tuple(UInt64, String), 8 / 256 chars 0.76 (1.00) / 0.96 (1.50) 1.68 2.89 (9.66) / 2.19 (5.86) 3.19
Array(String), 4 x 8 / 64 x 16 chars 0.81 (0.95) / 1.04 (1.42) 1.65 1.77 (3.61) / 0.96 (1.16) 2.44
FixedString(16) / FixedString(256) 1.14 (1.62) / 0.86 (1.14) 1.71 2.61 (7.48) / 1.46 (3.00) 1.79
UUID / IPv4 / IPv6, 1M groups 1.29 / 1.77 / 1.05 (1.96) 1.00 2.52 / 3.06 / 2.77 (4.56) 1.79
Enum8 / Date32 / BFloat16, 1M groups 1.27 / 1.33 / 1.68 (2.07) 1.00 2.34 / 2.30 / 2.50 (3.57) 1.74
RESPECT NULLS: Nullable(UInt64) / String / Array(UInt64) 1.01 / 1.19 / 0.63 1.00 6.31 / 4.46 / 2.56 3.32
remote state path (Array, Tuple) 0.56-0.80 0.98 1.81-2.91 3.50
Control: String / UInt64 0.99 / 0.99 (1.05) 1.00 1.00 / 1.00 (1.20) 1.12

Where A1 loses:

  1. Fixed-width types that Field holds inline without allocating (UUID, IPv4, IPv6, Enum8, Date32, BFloat16, FixedString(16)): the profiles put the cost in key encoding, arena allocation and the conversion at the result exit.
  2. Long String-heavy keys with few groups (1.2-1.4x on Array(String) of 64 x 16 chars): A1 encodes the whole candidate key before comparing, while the Field comparison stops at the first different element.
  3. Peak per group up to 1.7x on large String-heavy values, because the comparable key is a second copy next to the value. One encoding serves both only for FixedString and IPv6, whose arena bytes are already the order key. For other types it cannot: the key has to map -0.0 and 0.0 (and every NaN) to the same bytes, and serializeAsComparable has no decoder, no Array/Tuple/Map support, and puts NULL last where Field puts it first.

The A1 diff is +1038/-209 lines in src/, most of it the key encoder. A2 is slower on 214 of 306 rows and changes results, so it does not work as the fallback.

Neither prototype keeps the current semantics without being slower somewhere. Which should I push?

  1. A1 for every type, as measured.
  2. A1, except for the fixed-width types that Field holds inline today (UUID, IPv4, IPv6, Enum*, Date32, BFloat16). Those move to SingleValueDataNumeric, as Date and DateTime already do, so no Field is left. This variant is not measured yet; I would check order and state bytes for those types the same way before pushing.
  3. A1 only for types that can contain String or FixedString. Every other type keeps its Field state.

In every option the String/FixedString rows stay as measured above. I would take 2.

@Algunenano

Copy link
Copy Markdown
Member

Need to think several times about this. I don't like neither of the approaches

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.

2 participants