Repository navigation
Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators - #113926
Conversation
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.
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 Round 1 - bounced, not published❌ BLOCKER - the regression test could not fail on master, so the PR could not pass its own ❌ BLOCKER - the new exception-safety guard had no committed coverage. Fixed: a
Round 2 - clean, publishedNothing new in the C++ or the test logic. I re-derived the fix independently rather than re-reading
💡 Also disclosed: the zero-size-nested-state guard on the new loop cannot be pinned by any Verified with 3 mutants on separate binaries (each Build ID asserted against the running server), |
Pre-PR validation gate (a-i)
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 |
|
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: |
|
Workflow [PR], commit [0603e67] Summary: ❌
AI ReviewSummaryThis PR fixes real abandoned-state ownership bugs in Findings
Final VerdictStatus: LLVM Coverage ReportMeasured on commit 0603e67.
Changed lines: Changed C/C++ lines covered: 71/92 (77.17%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+82.05 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units10 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. |
CI finish ledger - fd5c074CI is fully finished on this head: 175 check runs, 0 queued or in progress, Session id: cron:our-pr-ci-monitor:20260808-230000 |
`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
left a comment
There was a problem hiding this comment.
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?
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]>
|
Verified, and the sweep is below. The
Two things worth knowing:
I had the same No similar issue in the other combinators. One place has the same ownership question with a different failure mode, so I have not touched it: |
CI finish ledger -
|
| 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
96b9142
Cherry pick #113926 to 26.3: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
… in the -ForEach and -Map combinators
Cherry pick #113926 to 26.6: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
… in the -ForEach and -Map combinators
Backport #113926 to 26.7: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
… in the -ForEach and -Map combinators
Backport #113926 to 26.8: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
Backport #113926 to 26.6: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
Backport #113926 to 26.3: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
…ted states in the -ForEach and -Map combinators
…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.
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]>
Changelog category (leave one):
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
-ForEachcombinator, 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 asquantilesExactForEachover arrays of varying length leaked for the lifetime of the server process.With the
-Mapcombinator, 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 inaddandmergeImpl. Deserializing anAggregateFunctioncolumn had the same problem when appending the finished state to the column.Description
-ForEachAggregateFunctionForEach::ensureAggregateDatagrows the per-element state array. It deliberately does notmemcpythe old states, because a nested state may contain a pointer into itself (#5751); instead it allocates a fresh arena buffer, createsnew_sizefresh states, merges theold_sizeold ones into them, and swaps the pointer. It never destroyed the old states. After the swap nothing holds a pointer to them (destroyImplwalks onlyarray_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 ownmallocis 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::mergeunderensureAggregateData, andQuantileExactBase::addunderadd.This reproduces on a plain ASan build with one query and no stress phase, 5/5 deterministically:
The second change makes the migration loop exception-safe.
QuantileExactBase::mergeallocates, 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 througharrayReduceInRanges,runningAccumulate, and arithmetic on aggregate states (state * N,state + state). All are clean after the fix on an ASan+UBSan build ofd65ba26ae8b3.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.-MapAggregateFunctionMap::deserializeallocated a nested state, created it, and then calledmerged_maps.emplace(key, nested_place).emplacedoes 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:destroyImplwalks onlymerged_maps.Unlike the
-ForEachleak this one is driven purely by the input bytes, so it repeats on every row:Two entries under key 1, each holding 6 values, one past what
quantilesExactkeeps 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.serializewrites each key exactly once, so a repeated key can only come from a malformed state, and it is now rejected withINCORRECT_DATA.Present since the combinator was added in 2021 (
030e5e625ea4).Other paths with the same ownership ordering
-MapaddandmergeImplcallednested_func->createbeforemerged_mapsowned the pointer, so a throw fromemplace, which allocates a node and a copy of aStringkey, stranded the state. Reproduced withquantileDDMap, whosecreatebuilds aDDSketchowning three heap allocations: 160 bytes in 3 allocations.SerializationAggregateFunctionhas the same shape in all fourdeserializeFrom*helpers: thetry/catchcovers the deserialize but thepush_backinto the column sits outside it. Reproduced withquantileDDundermemory_tracker_fault_probability, leaking 1184 bytes on 3 of 150 runs.ProtobufSerializeris the same shape in bothreadRowandinsertDefaults; 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:
WindowTransformalready reservesworkspacesbefore the loop, so itspush_backcannot allocate, and theminmax_countprojection inMergeTreeDatacan only usemin,maxandcount, whoseSingleValueDataStringkeepslarge_datain the arena, so no state there owns heap memory.Unrelated and deliberately not touched here:
-ForEachserializedrops its version parameter whiledeserializeforwards it.Workflow [PR]
Sync PR [sync-upstream/pr/113926]
Version info
26.9.1.532(included in26.9and later)26.8.3.16,26.7.7.11,26.6.5.30,26.3.30.6