Skip to content

Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators - #113926

Merged
Algunenano merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-foreach-combinator-nested-state-leak-1367-1a13
Sep 2, 2026
Merged

Algunenano merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-foreach-combinator-nested-state-leak-1367-1a13

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 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):

Fixes memory leaks of abandoned nested aggregate states.

With the -ForEach combinator, when a row arrived with a longer array than any seen before, the combinator grew its per-element state array and abandoned the old nested states without destroying them, so any heap memory those states owned was never freed. Queries such as quantilesExactForEach over arrays of varying length leaked for the lifetime of the server process.

With the -Map combinator, a nested state was created before the map owned the pointer. Reading a serialized state that repeats a key leaked one state per repeated key on every row, and such a state is now rejected as malformed. Under memory pressure the same ordering could strand a state in add and mergeImpl. Deserializing an AggregateFunction column had the same problem when appending the finished state to the column.

Description

-ForEach

AggregateFunctionForEach::ensureAggregateData grows the per-element state array. It deliberately does not memcpy the old states, because a nested state may contain a pointer into itself (#5751); instead it allocates a fresh arena buffer, creates new_size fresh states, merges the old_size old ones into them, and swaps the pointer. It never destroyed the old states. After the swap nothing holds a pointer to them (destroyImpl walks only array_of_aggregate_datas), so any heap allocation a nested state owned was unreachable and unfreed. The arena is not the leak: the arena frees its own chunks, but a nested state's own malloc is freed only by its destructor.

Found by LeakSanitizer on master (Stress test (amd_asan_ubsan), a7cd48316aab), which reported the two allocation sites this predicts: QuantileExactBase::merge under ensureAggregateData, and QuantileExactBase::add under add.

This reproduces on a plain ASan build with one query and no stress phase, 5/5 deterministically:

SELECT quantilesExactForEach(0.5)(arr)
FROM (SELECT arrayMap(x -> number + x, range(if(number < 8, 1, 2))) AS arr FROM numbers(16));

The second change makes the migration loop exception-safe. QuantileExactBase::merge allocates, so a throw there previously unwound with the state still pointing at the old buffer, leaking every freshly created state. Measured on a fixture that throws mid-loop, that path leaks 12-29 MB against 0 for the fixed build.

Because every path funnels into ensureAggregateData, the same leak is reachable through arrayReduceInRanges, runningAccumulate, and arithmetic on aggregate states (state * N, state + state). All are clean after the fix on an ASan+UBSan build of d65ba26ae8b3.

Present since the create-then-merge design was introduced in 2019 (bd33bf8f96c2). The same fix was proposed in PR 60683 and closed in 2024 only for want of a test, not on its merits; the reproduction above is what that PR lacked.

-Map

AggregateFunctionMap::deserialize allocated a nested state, created it, and then called merged_maps.emplace(key, nested_place). emplace does not insert over a key that is already present, so a repeated key left the fresh state unreachable and undestroyed for the same reason as above: destroyImpl walks only merged_maps.

Unlike the -ForEach leak this one is driven purely by the input bytes, so it repeats on every row:

SELECT sum(length(finalizeAggregation(CAST(materialize(unhex(
    '02'
    || '01' || '06' || '000000000000000001000000000000000200000000000000030000000000000004000000000000000500000000000000'
    || '01' || '06' || '0a000000000000000b000000000000000c000000000000000d000000000000000e000000000000000f00000000000000'
    )) AS AggregateFunction(quantilesExactMap(0.5), Map(UInt8, UInt64))))))
FROM numbers(1000);

Two entries under key 1, each holding 6 values, one past what quantilesExact keeps inline, so the abandoned state owned a heap allocation. On ASan that reports 64000 bytes leaked in 1000 allocations before the fix and nothing after. The old code also silently dropped the second entry.

serialize writes each key exactly once, so a repeated key can only come from a malformed state, and it is now rejected with INCORRECT_DATA.

Present since the combinator was added in 2021 (030e5e625ea4).

Other paths with the same ownership ordering

-Map add and mergeImpl called nested_func->create before merged_maps owned the pointer, so a throw from emplace, which allocates a node and a copy of a String key, stranded the state. Reproduced with quantileDDMap, whose create builds a DDSketch owning three heap allocations: 160 bytes in 3 allocations.

SerializationAggregateFunction has the same shape in all four deserializeFrom* helpers: the try/catch covers the deserialize but the push_back into the column sits outside it. Reproduced with quantileDD under memory_tracker_fault_probability, leaking 1184 bytes on 3 of 150 runs.

ProtobufSerializer is the same shape in both readRow and insertDefaults; both now go through one helper so they cannot drift apart. I could not reproduce it, since the window is one allocation wide; the change only makes the ordering uniform.

Two other candidates turned out not to be problems and are untouched: WindowTransform already reserves workspaces before the loop, so its push_back cannot allocate, and the minmax_count projection in MergeTreeData can only use min, max and count, whose SingleValueDataString keeps large_data in the arena, so no state there owns heap memory.

Unrelated and deliberately not touched here: -ForEach serialize drops its version parameter while deserialize forwards it.


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

Version info

  • Merged into: 26.9.1.532 (included in 26.9 and later)
  • Backported to: 26.8.3.16, 26.7.7.11, 26.6.5.30, 26.3.30.6

AggregateFunctionForEach::ensureAggregateData grows the per-element nested
state array. It deliberately does not memcpy the old states, because a nested
state may contain a pointer into itself (ClickHouse#5751): it allocates a fresh arena
buffer, creates new_size fresh states, merges the old_size old ones into them,
and swaps the pointer. It never destroyed the old states.

After the swap nothing holds a pointer to them, because destroyImpl walks only
array_of_aggregate_datas, so any heap memory an old nested state owned was
unreachable and unfreed for the lifetime of the process. The arena is not the
leak: the arena frees its own chunks, but a nested state's own allocation is
freed only by its destructor. QuantileExact keeps five values inline and
allocates past that, which is why each leaked object is exactly 64 bytes.

Found by LeakSanitizer on master (Stress test (amd_asan_ubsan), commit
a7cd483), which reported both allocation sites this predicts:
QuantileExactBase::merge under ensureAggregateData, and QuantileExactBase::add
under add. It reproduces on a plain ASan build with a single query and no
stress phase, five times out of five.

The destroy runs strictly after the pointer swap: destroying before it would
double-free if any path reached destroyImpl with the state still pointing at
the old buffer, and IAggregateFunction::destroy is noexcept so nothing in
between can throw. The nested_size_of_data != 0 guard mirrors the one on the
merge loop above, because for a zero-size nested state the zero-byte arena
allocation does not advance and the new buffer aliases the old one.

The second hunk makes the migration loop exception-safe. QuantileExactBase
merge allocates, so a throw there previously unwound with the state still
pointing at the old buffer and leaked every freshly created state. Measured on
a fixture that throws mid-loop, that path leaks 12 to 29 MB against zero for
the fixed build. The cleanup bound is new_size rather than old_size, because
every new state was created by this frame and is owned by it until the swap.

Present since the create-then-merge design was introduced in bd33bf8.
The same fix was proposed in ClickHouse#60683 and closed in 2024 for want of a test
rather than on its merits; the reproduction is what that PR lacked.
… see it

A leak sanitizer reports only when the process exits, so a `.sql` test leaves the
report in the long-running test server and Bugfix Validation, which never terminates
that server inside its loop, can never see it. The test becomes a `.sh` that runs its
queries in a short-lived `clickhouse-local` and counts the reports the process leaves
behind, following `04417_sanitizer_allocator_oversized_alloc_no_abort.sh` and
`04699_background_schedule_pool_delay_overflow.sh`.

The count is 0 both on a build without a leak sanitizer and once the leak is fixed, so
one reference file matches every build type, and the value assertions stay to show the
change is leak-only. Each invocation gets its own sanitizer log, which gives the regrow
path and the exception path one count each: reverting either guard alone now reddens
only that guard's count.

Two details of the runner shape the test. Its stderr check runs before the reference is
compared, so a report reaching the runner's own log would fail the test with no useful
diff, and the routed log keeps it out. For the same reason each invocation is a
pipeline: an aborting sanitizer makes the shell write a job status line to stderr, and
the shell writes no status for a pipeline.

The second invocation covers the exception path, which had no committed test. A throw
part-way through the migration merge abandons every state the regrow just created. Each
element holds 4 MiB of values, so the migration doubles a 32 MiB state element by
element and the limit lands inside that loop. `max_block_size` is load-bearing here:
left at its default, the largest allocation is a 16 MiB input block, the throw happens
before the loop is entered and nothing has spilled yet. The limit is armed across a
range wide enough not to be a knife edge, and the number of abandoned allocations
tracks the iteration the throw lands on.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 5 findings adjudicated)

Before opening this PR I reviewed it twice with an independent model, and bounced it back for a
fix round in between. Recording the findings and their dispositions here, including the ones I
disagreed with and the one I am shipping unfixed.

Round 1 - bounced, not published

❌ BLOCKER - the regression test could not fail on master, so the PR could not pass its own
merge gate.
The test was a .sql file asserting only query results. A leak sanitizer reports at
process exit, and in the Bugfix Validation lane the server is alive for both log scans
(functional_tests.py:1004, :1156), the post-shutdown scrape is removed for that lane
(:643-646), and the logs are deleted between build types (:1053). Every row would have stayed
OK on the master-HEAD binary, the inverter would have read no-repro, and
new_tests_check.py:205-225 blocks a bug-fix PR that adds a stateless test unless at least one
Bugfix Validation job reproduces - with the CI-report-link fallback explicitly not accepted on that
branch. Fixed: the test is now a process-scoped .sh that runs the queries in clickhouse-local
and counts the leak reports, following 04417_sanitizer_allocator_oversized_alloc_no_abort.sh and
04699_background_schedule_pool_delay_overflow.sh. It now FAILS on the pristine master ASan build
(diff = exactly the two leak counts, 0,0 to 1,1) and passes here.

❌ BLOCKER - the new exception-safety guard had no committed coverage. Fixed: a
max_memory_usage arm now makes a nested merge throw mid-migration, and the two guards are
pinned independently (separate leak counts, one per invocation). Reverting the destroy loop reddens
only the regrow count; reverting the try/catch reddens only the exception count.

⚠️ Comment formatting (f() vs f, backticked identifiers). Agreed and largely fixed.

⚠️ PR contract. Agreed on present tense per docs/changelog_entry_guidelines.md:48-56.
Disagreed with the rest, with evidence: the freshly fetched PULL_REQUEST_TEMPLATE.md has no
description section, so moving the description above the changelog fields would diverge from it and
reordering a ### header breaks the Config Workflow parse; the template itself keeps relationship
lines inside the HTML comment, and exposing the Related: URL would create a cross-reference
backlink on an unrelated closed PR.

Round 2 - clean, published

Nothing new in the C++ or the test logic. I re-derived the fix independently rather than re-reading
the first round's notes:

  • The post-swap loop calls destroy, not destroyUpToState, which is only safe if no abandoned
    state can be owned by a column. I enumerated all 31 raw insertResultInto call sites in src/
    and every one that can receive a -State result routes isState() to insertMergeResultInto,
    which merges into a fresh state in the column's own arena rather than aliasing
    (ColumnAggregateFunction.cpp:597-607). So no place escapes and is later re-added.
  • Destroying the migrated-from states is safe because QuantileExactBase::merge copies rather than
    steals (QuantileExact.h:60); merge-then-destroy is the same lifecycle as
    Aggregator.cpp:3203-3215.
  • -ForEach is the only carrier: exactly one file in src/ holds a dynamic array of nested
    aggregate states, against 13 combinator files that create nested states at all.

⚠️ One nit shipped unfixed, deliberately. An SQL comment in the test still writes add() where
the repo convention is add. The remainder of the same suggestion - backticking identifiers inside
the --query string - I disagreed with after measuring it: a raw backtick there is command
substitution
, so it deletes the identifier and writes to stderr, and non-empty stderr fails a
stateless test outright (clickhouse-test:3488, checked before the reference diff). The escaped
form works but is against convention: of the 240 stateless .sh files with an indented SQL comment,
239 use no backtick. The bash header comments and the C++ comments do backtick every identifier,
which is where the rule is expressible.

💡 Also disclosed: the zero-size-nested-state guard on the new loop cannot be pinned by any
test. It only matters for a nested function whose sizeOfData() is 0, and such a function's
destroy is necessarily a no-op, so omitting the call is unobservable by construction. The guard is
kept because it prevents merge with aliasing source and destination.

Verified with 3 mutants on separate binaries (each Build ID asserted against the running server),
10 value shapes across 5 nested functions with byte-identical results on both arms, the 7 existing
-ForEach tests unchanged, and 50 randomized runs.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. The queries in the new test, run in one clickhouse-local on an ASan build, leak 8/8 runs with an identical allocation count each run and stdout byte-identical to the fixed build's, so the leak count is the only thing that moves. No stress phase, no fault injection, no server.
b Root cause explained? ensureAggregateData grows the per-element state array by allocating a fresh arena buffer, creating new_size new nested states, merging the old_size old ones into them, then swapping the pointer. It never destroyed the old states. After the swap nothing holds a pointer to them, since destroyImpl walks only array_of_aggregate_datas, so the heap memory a nested state owned is unreachable and unfreed. The arena frees its own chunks; a nested state's own malloc is freed only by its destructor.
c Fix matches root cause? Yes: the missing destroy of the abandoned states is added, at the layer where they are abandoned. No widened bound, no suppression, no defensive check at a crash site. The second hunk closes the same defect on the exception path.
d Test intent preserved / new tests? New test 04812_foreach_combinator_nested_state_leak.sh. A leak sanitizer reports only at process exit, so the test runs its queries in a short-lived clickhouse-local and counts the leak reports; the value assertions are kept alongside, and they are what show the change is leak-only. Two invocations with separate logs give the regrow path and the exception path one leak count each, so each guard is pinned independently. No existing test was weakened; the neighbouring 04420 file was deliberately not extended, since its concern is the zero-size aliasing case.
e Both directions? Yes, through the real test runner on both arms, each server's SELECT lower(buildId()) asserted equal to its binary's build id first. On the pristine master ASan build at our base commit the test FAILS with result differs with reference and empty stderr, the diff being exactly the two leak counts going 0,0 to 1,1; on the fixed build it passes. Values are byte-identical across 8 queries and 5 different nested functions.
f General across code paths? -ForEach is the sole carrier: exactly 1 file in src/ holds a dynamic array of nested aggregate states (array_of_aggregate_datas/dynamic_array_size), against 13 combinator files that create nested states at all, so the 1 is meaningful. -Map allocates one arena slot per key and never reallocates, -Resample fixes its size in the constructor, and the three other arena reallocation sites in src/AggregateFunctions (AggregateFunctionGroupConcat.cpp:24, AggregateFunctionMVTEncode.cpp:122, TimeSeries/AggregateFunctionTimeSeriesGroupArray.h:62) move POD bytes, not aggregate states.
g General across inputs? Measured on both arms: Nullable, LowCardinality, LowCardinality(Nullable), an empty first array, a length 1 to 40 jump, a two-argument nested function (quantilesExactWeightedForEach), multi-quantile parameters, topKForEach and groupUniqArrayForEach, plus the all-NULL zero-size state. 8 of 10 leaked pre-fix (up to 97 allocations); all 10 are clean post-fix with identical values.
h Backward compatible? No setting, format, or on-disk change. SettingsChangesHistory.cpp not applicable.
i Invariants and contracts? The destroy runs strictly after the pointer swap, so no path can reach destroyImpl with the state still pointing at the freed buffer; IAggregateFunction::destroy is noexcept, so nothing between the swap and the loop can throw. The nested_size_of_data != 0 guard mirrors the one on the merge loop above: for a zero-size state the zero-byte arena allocation does not advance, so the new buffer aliases the old one. Instrumentation confirms that state is real, with alias=1 on 5 regrows in 04420. Only states this frame abandoned are destroyed, and no caller can ever reach them, so destroyUpToState semantics are unaffected.

Mutation matrix, all three binaries with their build ids asserted, and the shipped build id returning byte-exactly after the mutants were restored: reverting only the destroy loop reddens the regrow count alone, reverting only the try/catch reddens the exception count alone, and in both cases the other count, the value rows and the memory-limit assertion are unchanged. That per-arm asymmetry is what shows each guard is covered on its own rather than jointly, and that the test is a leak carrier rather than a value test. Reverting the zero-size guard changes nothing, because the only nested function with a zero-sized state is aggregate function Nothing, whose destructor body is empty; the guard is kept as the correct expression of the invariant. Regression slice over all seven -ForEach tests on both the fixed and the pristine base build: verdict sets identical on the six pre-existing tests, 0 regressions. The new test passes 50 randomized runs and 10 consecutive runs.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Algunenano, could you review this? It revives the fix from PR 60683, which was closed in 2024 only for want of a test: ensureAggregateData grows the -ForEach per-element state array by creating fresh nested states and merging the old ones in, but never destroyed the old states, so any heap memory they owned leaked. The new test reproduces it on master in one clickhouse-local process, which is what that PR was missing.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0603e67]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL IGNORED
Bugfix validation (functional tests, amd64) ERROR IGNORED
Bugfix validation (functional tests, aarch64) ERROR IGNORED

AI Review

Summary

This PR fixes real abandoned-state ownership bugs in -ForEach, -Map, SerializationAggregateFunction, and ProtobufSerializerAggregateFunction, and the current code changes themselves look correct. I still cannot approve it because the committed regression coverage does not exercise the AggregateFunctionMap::mergeImpl exception path that this PR also changes, so one advertised leak carrier remains unpinned.

Findings

⚠️ Majors

  • [dismissed in thread -- https://github.com/Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators #113926#discussion_r3905473543] [src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp:212] The PR now fixes the ownership window in mergeImpl, but tests/queries/0_stateless/05056_map_combinator_state_stranded_on_throw.sql:8 still aggregates raw Map rows through quantileDDMap(...)(m) with max_threads = 1, which drives add and never feeds AggregateFunction(...Map...) states into mergeImpl. That leaves the second leak carrier unproven by committed coverage even though this hunk changed it.
    Suggested fix: add a small state-to-state regression, for example materialize quantileDDMapState rows first and then run a quantileDDMapMerge query under the same memory-limit arm so master leaks and this branch does not.
Final Verdict

Status: ⚠️ Request changes
Add one focused regression that specifically routes the -Map leak through mergeImpl (...MapState producer plus ...MapMerge consumer under the same failure arm). The current 05056 test still only proves add.

LLVM Coverage Report

Measured on commit 0603e67.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 71/92 (77.17%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0603e6764 with master 8627fa22f (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

6 object files changed (+82.05 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/Combinators/AggregateFunctionM… 1.46 MiB 1.53 MiB +81.30 KiB (+5.46%)

716 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

10 translation units recompiled, 40 s compile time in total, 10 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 +4.3 s (+12%) in total before that adjustment.

Job report

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fd5c074

CI is fully finished on this head: 175 check runs, 0 queued or in progress, Finish Workflow success. No check failed, so there is nothing to own.

Session id: cron:our-pr-ci-monitor:20260808-230000

Algunenano and others added 2 commits September 1, 2026 12:41
`AggregateFunctionMap::deserialize` created a nested state and then called
`emplace`, which does not insert over a key that is already present, so a
repeated key in a serialized state left the fresh state unreachable and
undestroyed. `serialize` writes each key once, so a repeated key only comes from
malformed input and is now rejected. Taking the map slot before creating the
state also closes the window where a throw from `emplace` stranded a created
state.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

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

I've reviewed the code (looks good) and fixed a similar issue in -Map combinator. @groeneai Can you please have a look and verify it's correct and there are no similar issues?

@Algunenano Algunenano changed the title Fix memory leak of abandoned nested states in the -ForEach combinator Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators Sep 1, 2026
Algunenano and others added 3 commits September 1, 2026 13:57
Both paths called `nested_func->create` before `merged_maps` owned the pointer.
`emplace` allocates a node, and a copy of the key when it is a `String`, so a
throw there stranded the fresh state, which `destroyImpl` can never reach
because it walks only `merged_maps`. Reproduced with `quantileDDMap`, whose
`create` builds a `DDSketch` owning three heap allocations: 160 bytes leaked in
3 allocations under a leak sanitizer.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…eFunction

All four deserialize helpers created a state, guarded the deserialize with a
try/catch that destroys on failure, and then pushed the pointer into the column
outside that guard. `push_back` on the column's `PaddedPODArray` allocates
through the memory tracker, so a throw there stranded a state nothing could
reach. Reproduced with `quantileDD` under `memory_tracker_fault_probability`,
which leaked 1184 bytes on 3 of 150 runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`readRow` builds a state with `stringToData` and then pushes it into the column
outside any guard, so a throwing `push_back` would strand it. This is the same
shape as the SerializationAggregateFunction sites, but I could not reproduce it:
it needs a protobuf input harness, and the window is one allocation wide. The
change only makes the ownership ordering uniform.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`insertDefaults` had the same unguarded `push_back` as `readRow`, which the
previous commit fixed in only one of the two places. Both now go through
`pushBackOrDestroy` so the ownership ordering cannot drift apart again. Still
not reproduced, same as before: the window is one allocation wide.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Verified, and the sweep is below.

The -Map fixes are correct. I reproduced each window on an ASan build of master with quantileDDMap, whose create owns three heap allocations, and re-ran on a build carrying the fix:

entrypoint master with the fix
add (AggregateFunctionMap.cpp:189) 160 B in 3 allocations 0
mergeImpl (:221) 480 B in 9 allocations 0
deserialize (:290) 160 B in 3 allocations 0

Two things worth knowing:

  • Your deserialize change closes more than the duplicate-key path. On master, reading AggregateFunction(quantileDDMap(0.01), Map(UInt64, Float64)) states back from a table leaks from :290 on an allocation failure alone, with no repeated key: 15 of 30 runs under memory_tracker_fault_probability, nothing with the injection off.
  • 05056 arms add, and I confirmed it does: on master that query reports 160 bytes in 3 allocations at :189 alongside the expected MEMORY_LIMIT_EXCEEDED, and nothing with the fix, with the second query returning 20000. Nothing arms mergeImpl specifically, because a fault reaches the state construction before the merge. Building the states first, in a Memory table, and arming the failure only on the merge is what produced the 480 bytes above, if you want that covered too.

I had the same add/mergeImpl change ready when you pushed 0659429; it is equivalent, so I dropped it rather than duplicate yours.

No similar issue in the other combinators. AggregateFunctionTuple::create and AggregateFunctionResample::create already roll back their partial loops. -If, -Array, -Merge, -State, -SimpleState, -OrFill, -Null and -Distinct make a single nested create inside their own create, so a throw means the combinator state was never created and the caller never destroys it; -Distinct builds its own Data first, but its sets are HashSetWithStackMemory<..., 4>, so nothing is on the heap at that point.

One place has the same ownership question with a different failure mode, so I have not touched it: -ArgMin/-ArgMax runs nested_function->destroy(place) followed by nested_function->create(place) in add, mergeImpl and mergeStateFromDifferentVariant. A throw from create leaves a destroyed state in the slot, and the combinator's destroy then destroys it a second time, so it is a double destroy rather than a leak. Its own create also builds the Key after the nested state, so a throw there abandons the state. I have not reproduced either.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0603e67644ddd26b9cf95563177f6b48acdca7bf

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
Bugfix validation (functional tests, amd64 / aarch64), Finish Workflow / new_tests_check.py both per-arch jobs abort about 4 s in on assert build_urls, "Could not find master builds in S3": master build artifacts moved under a normalized workflow-name prefix, so find_master_builds probes the old key and matches nothing, and new_tests_check.py then reds the post hook because no per-arch job reported OK or XFAIL #117580 (external, merged 2026-09-01T22:06:23Z), rule 3c: absent from this tree
Upgrade check (amd_release) / Error message in clickhouse-server.log 04510_mutation_query_plan_only_virtual_columns asserts a mutation failure on purpose, and _table cannot be materialized in a mutation, so a background MutatePlainMergeTreeTask logs Code: 16 ... Unexpected const virtual column: _table and the upgrade check scrapes that line out of the server log #117218 (mine, open)

The build-lookup break is not specific to this pull request: the same assertion fires on 101 distinct pull requests over 121 commits since 2026-08-31 19:31Z, and in the 7 days before that onset the same two jobs recorded 8752 rows with zero occurrences of it. #117580 rewrites the probed key to include the workflow name. I measured it ABSENT from this tree: the symbol it adds has 0 occurrences at 0603e676 against 1 at its own merge commit 41b739a45086, with a pre-fix negative control at 0. Both jobs here ran at 19:56Z, about two hours before it landed.

The upgrade-check row has the same shape: 41 hits on 41 distinct pull requests since 2026-08-30 22:48Z, and none on master. That error is raised by a test that expects it, so the only change needed is to stop the log scraper treating it as a server error, which is what #117218 does.

I have not merged master to pick #117580 up. The recent commits on this branch are not mine, so a master merge from me would land on top of work in progress that is not mine to move; naming the merged owner here is enough, and one merge picks it up whenever the branch is next advanced.

Mergeable Check reports Failed: Workflow Post Hook,Upgrade check (amd_release), which counts only the jobs it gates on. The table above covers every non-OK, non-SKIPPED node of result_pr.json apart from the PR roll-up itself (173 nodes: 147 OK, 19 SKIPPED, 5 FAIL, 2 ERROR), so it also covers the rows Mergeable Check does not gate.
CH Inc sync was success at this head, so nothing here is exempt.

Session id: cron:our-pr-ci-monitor:20260901-223000

@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 2, 2026
@Algunenano
Algunenano enabled auto-merge September 2, 2026 11:21
@Algunenano
Algunenano added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit 96b9142 Sep 2, 2026
170 of 175 checks passed
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 2, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Sep 2, 2026
Cherry pick #113926 to 26.3: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
robot-clickhouse added a commit that referenced this pull request Sep 2, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Sep 2, 2026
Cherry pick #113926 to 26.6: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
robot-clickhouse added a commit that referenced this pull request Sep 2, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #113926 to 26.7: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #113926 to 26.8: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
clickhouse-gh Bot added a commit that referenced this pull request Sep 2, 2026
Backport #113926 to 26.6: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
Algunenano added a commit that referenced this pull request Sep 3, 2026
Backport #113926 to 26.3: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…ted states in the -ForEach and -Map combinators
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 4, 2026
…y carries

My open PR ClickHouse#113926 ("Fix memory leaks of abandoned nested states in the -ForEach and -Map
combinators") gained commit `be0cdb16e128` earlier today, fixing this same leak in this same
loop: the duplicate-key `INCORRECT_DATA` rejection, the `destroy` of the nested state it
abandons, and a stateless test for it. That PR is the elder and dedicated owner of the leak,
so carrying a second copy here would only ask a reviewer to referee a duplicate of my own
making.

What stays is the allocation half, which is what this PR is about and which ClickHouse#113926 does not
contain: `AggregateFunctionMapCombinatorData<String>::readKey` still reads its declared size,
refuses it above `DEFAULT_MAX_STRING_SIZE`, and grows the key from the bytes actually read
instead of reserving the declaration. ClickHouse#113926 does not touch `readKey`, so the two changes do
not overlap.

The two 04401 assertions that exercised the rejection go with it, as does
`05056_aggregate_map_duplicate_key_state_leak`, whose oracle now has no fix to observe here.
That test is kept in `.scratch/handoff-05056-for-113926/`: it is stronger coverage than
ClickHouse#113926's `.sql`, because an at-exit leak is invisible to a test that only asserts an error
code, and it is available to whoever finishes that PR. The bounded `readKey` read keeps its
own 04401 coverage.
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
AGG: abandoned nested aggregate states -> leak.
Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/113926.PROD263.txt).
Upstream patch unchanged, with its test(s): 04812_foreach_combinator_nested_state_leak, 05055_map_combinator_duplicate_key_state, 05056_map_combinator_state_stranded_on_throw.

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

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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 Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants