Skip to content

Cherry pick #113926 to 26.3: Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators - #117670

Merged
robot-ch-test-poll4 merged 10 commits into
backport/26.3/113926from
cherrypick/26.3/113926
Sep 2, 2026
Merged

robot-ch-test-poll4 merged 10 commits into
backport/26.3/113926from
cherrypick/26.3/113926

Conversation

@robot-clickhouse-ci-1

Copy link
Copy Markdown
Contributor

Original pull-request #113926

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 9 commits August 8, 2026 02:00
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 (#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 #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.
`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]>
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]>
…d-state-leak-1367-1a13

Fix memory leaks of abandoned nested states in the -ForEach and -Map combinators
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Sep 2, 2026
# Conflicts:
#	src/AggregateFunctions/Combinators/AggregateFunctionForEach.h
#	src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants