Skip to content

Print Pipeline on Unfinished Processor Removal, including the executor edge use-after-free fix - #117129

Closed
alexey-milovidov wants to merge 13 commits into
masterfrom
revert-117128-revert-115584-print_pipeline_on_unfinished_processor_removal
Closed

alexey-milovidov wants to merge 13 commits into
masterfrom
revert-117128-revert-115584-print_pipeline_on_unfinished_processor_removal

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Reverts #117128, re-landing #115584 together with the use-after-free fix it needs.

Related: #115584
Related: #116103
Related: #117128
Related: #111017

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

Fix a heap-use-after-free in the query pipeline executor. When a processor removed itself from a running pipeline, graph edges could be freed while pointers to them were still queued for processing in another executor thread.

Description

This is #115584 re-landed, with #116103 merged in, because #115584 on its own reopens a heap-use-after-free in the executor.

ExecutingGraph::updateNode keeps pending edge updates in a work list local to its own frame, filled under only a shared lock on nodes_mutex, so several frames hold private lists at once. updateNode releases that lock at two points, and a frame parked at either one can resume and dereference an Edge that another frame freed meanwhile. #111017 fixed only the same-frame case, by scrubbing the removing frame's own list; it cannot reach the lists of other frames.

#115584 did not introduce the race, but it widened it considerably: removal is deferred into removeReadyGroups, which any frame may call at either of those two points, so removals became both far more frequent and reachable from more call sites. In bucket STID 2837-40ba over the 60 days before the revert, the 5 occurrences preceding #115584 are all AST fuzzer (arm_asan_ubsan), while the 8 following it span 6 jobs and reached master:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=9593cfadad22b8112fd28a6fbabece49cade9890&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

That master failure is cross-thread and shows the exact path #116103 closes: T462 frees a removed node's edges in removeReadyGroups -> removePendingGroup -> removeNode -> ~Node, while T552 pops one of them and reads auto & node = *edge->to;.

#116103 fixes it by retention rather than by tracking frames: retireAffectedEdges moves every edge of a removed node into a list that lives as long as the graph, points it at a permanently Finished stand-in node, and runs before the node is erased. A queued pointer therefore stays valid, and updateNode skips a Finished node without reaching its processor.

This branch is master with #115584 restored plus #116103, which was green apart from the unrelated Not-ready Set flake tracked as #107619.

On top of that, the lifetime of a retired edge is bounded, so that a query which keeps reconfiguring its pipeline does not accumulate one removed sub-pipeline per round (MergeTreeCommitOrderSource::updatePipeline retires a whole read round of a subscribed FROM ... STREAM query on every round). retireAffectedEdges unqueues the edge from the update list of the node owning it and drops the registration a surviving peer port may still hold on that edge's Port::UpdateInfo, so a frame entering after the retirement has nowhere left to pick the pointer up from; only the frames already running at retirement time can hold it. Every retirement therefore opens a batch tagged with a generation, every updateNode frame records the generation it entered at, and a departing frame destroys the batches no remaining frame could have picked up. Measured with the fan-in regression test (4 coordinators, 16 threads, 160 retirements per pipeline): at most 2 batches are retained at any moment, flat across all generations.


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

groeneai and others added 10 commits August 24, 2026 07:34
…utor frame

ExecutingGraph::updateNode keeps pending edge updates in a work list local to
its own frame and pushes into it while holding only a shared lock on
nodes_mutex. Because that lock is shared, several frames run at once, each with
a private work list. When one frame takes the lock exclusively and retires a
processor group, removeNode destroys the node and frees its edges, but the
cleanup could only reach the work list of the frame doing the removal. A frame
parked at one of the two gaps updateNode makes in nodes_mutex then resumed and
dereferenced a freed Edge.

Each frame's work list is now published on the graph, and the freed edges are
dropped from every published list at removal time, under the exclusive lock the
removal already holds. This is the treatment already applied to the persistent
post_updated_*_ports lists. Comparison is by edge identity and never
dereferences freed memory, and because the scrub runs inside the exclusive
section that frees the edges, no edge can be reallocated at the same address in
between. Publishing is done with an intrusive list so entering updateNode
allocates nothing.

The frame-local cleanup this replaces ran with no lock held at all, between the
unlock and the re-lock, so keeping it alongside the published lists would have
introduced a new race. It is deleted.

Node pointers need no equivalent treatment: removeNode refuses a processor that
is not Finished, and a Finished node is never queued for preparation.

CI reported this as a heap-use-after-free at "auto & node = *edge->to;" six
times over 90 days on six unrelated pull requests, always on arm_asan_ubsan.
Two of those reports have different reading and freeing threads, which the
frame-local cleanup cannot account for.

The new test reproduces it deterministically: with the scrub removed it reports
the same use-after-free at the same statement with the same freeing stack in 9
of 30 runs, and 0 of 30 with the fix in place.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113332&sha=c982642a8a1f3cf5619ba4faf7b9cd3af78f188c&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
Two follow-up corrections to the previous commit.

The scrub ran after the edges had already been destroyed. Removing a node
freed its edges, and only then did the surviving nodes' affected edges get
collected into a set and the published work lists cleaned. Both of those
set insertions allocate, and the global operator new routes through the
memory tracker, which raises MEMORY_LIMIT_EXCEEDED once a query approaches
max_memory_usage; min_allocation_size_to_throw_on_memory_limit is 0 by
default, so a small set node is enough. Nothing on the path catches it, so
the throw unwound past the scrub and released nodes_mutex with freed edges
still published, which is the same use-after-free from a different
direction.

Removal is now split into a pass that only identifies what will go away and
a pass that destroys it, with the scrub in between: findNodeToRemove and
collectAffectedEdges read, eraseNode and eraseAffectedEdges destroy. Every
allocation happens while the edges are still alive, so no path can free an
edge before the work lists have been cleaned.

A work list also no longer stays published for the whole frame, only across
the two gaps the frame makes in nodes_mutex. A frame that holds the shared
lock cannot be raced by a removal, which needs the lock exclusively, so
publication buys nothing there while costing two acquisitions of a
graph-global mutex per executor loop iteration on every thread. Gaps are
entered only on a pipeline update or a ready removal group. Registering
only in the second gap is not sufficient: with the first gap unregistered
the use-after-free still reproduces in 4 of 30 runs.

An assertion in the new test that every retired batch had been destroyed is
dropped. The oracle for this defect is the sanitizer report; that assertion
instead depended on a later updateNode iteration happening to run, and a
weaker form of it over far fewer objects has already gone red once on
master.

The reproduction rate quoted in the previous commit is superseded: with the
scrub removed the current tree reports the same use-after-free at the same
statement, with different reading and freeing threads, in 10 of 60 runs, and
0 of 30 with the fix in place.
…ed-from warning

`removePendingGroup` collects the nodes of a pending group first and erases them
afterwards, so that the published work lists are cleaned while every edge is still
alive. That split made a duplicate entry in `IProcessor::PipelineUpdate::to_remove`
worse than before: the collection loop appended the same node twice, and the second
`eraseNode` then worked on a node the first call had already destroyed. Before the
split the duplicate was rejected by the second `processors_map` lookup, because the
first pass had erased the entry.

`to_remove` is documented as a set, so reject a repeated processor while the group is
still intact. The check sits in the collection loop, above every destructive step, so
it cannot reintroduce the throw-past-cleanup window the split exists to close.

Also stop the test fixture from reusing `current_batch` after it has been moved into
`to_remove`. It builds the next batch in a local and assigns it back, which keeps the
same behaviour and clears two `clang-analyzer-cplusplus.Move` diagnostics that failed
the arm_tidy build.
The check for a processor listed twice in `to_remove` sat in `removePendingGroup`,
which a repeated *unfinished* processor never reaches. `updatePipeline` derives
`not_finished` from the raw `to_remove` list, so such a processor is counted twice,
while `removed_processors` and the graph hold a single entry for it and
`accountFinishedProcessorInGroup` can only decrement once. The group's counter
never reaches zero, `findGroupReadyForRemoval` never returns it, and its
processors stay in the graph after being disconnected.

Move the check to the point where the group is built, before the counter is
derived from the list, and drop the now unreachable one.

Measured against the merge base with the state forced at the construction site:
the group counter goes from 2 to 3 while entries into `removePendingGroup` drop
from 7 to 6, identically on both sides, so this is a pre-existing hole rather
than a regression. No in-tree `updatePipeline` produces a repeated entry today.

The new death test drains a pipeline that retires a batch listing its unfinished
transform twice. Without the check it reports "failed to die" with no sanitizer
report, which is the stranding this closes.
The repeated-entry check only looked within the current `to_remove` list, so a
processor queued for removal by an earlier `updatePipeline` call was accepted a
second time. `not_finished` is counted from the raw list, while
`removed_processors` keeps the first group for a given processor and
`accountFinishedProcessorInGroup` decrements only that one. The second group's
counter therefore never reaches zero, `findGroupReadyForRemoval` never returns
it, and its processors stay in the graph after being disconnected.

Consult `removed_processors` alongside the per-call set, so both the intra-list
and the cross-call repetition are rejected at the same point, before the counter
is derived from the list.

The wedge is not a regression: `accountFinishedProcessorInGroup` and
`findGroupReadyForRemoval` are byte-identical to the merge base, and no in-tree
`updatePipeline` produces a repeated entry today. The sole production source of a
non-empty `to_remove` moves a pipe's own processor list out on each call.

The new death test retires a batch holding an unfinished transform and lists that
transform again on the next call. Without the cross-call term it reports "failed
to die" with no sanitizer report, which is the silent stranding this closes,
while the existing intra-list test still passes.
Two blocks restated the commit message instead of the property that holds at
that spot.
Switch to the alternative offered during review: rather than publishing each
frame's pending-edge work list so a removing frame can scrub it, keep every
edge of a removed processor alive and point it at a permanently finished
sentinel node. A frame parked at a gap in nodes_mutex then finds its queued
edge still valid, and skips it because the node it now names is finished.

This drops the intrusive list of published work lists, its mutex, the guard
objects at both lock gaps, and the removed-edge id sets that existed only to
drive the scrub, for a net 120 lines removed. The cost is that retired edges
are never freed before the graph is: sizeof(Edge) is 64 bytes, and the one
production path that removes processors retires 240 edges per commit in the
regression fixture, so a long-running subscribed stream grows without bound.
That growth is only reachable with enable_streaming_queries, which is
experimental and off by default.

The live graph stays flat, which is what makes this viable: nodes.size()
peaked at 608 to 728 across runs of the regression test while retired edges
reached 38400.
`collectAffectedEdges` and `eraseAffectedEdges` lost both their definitions and
their only caller when edge removal became edge retirement, so the header was
declaring two functions that do not exist.

Also backtick the two function names in comments this branch introduced, per
the convention in `.claude/CLAUDE.md`.
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e1e05f]

Summary: ✅


AI Review

Summary

This PR re-lands the updatePipeline change together with a generation-based retired-edge reclamation scheme and stronger executor regression coverage. I did not find a remaining correctness issue in the current head: retired edges are now kept only until every pre-retirement updateNode frame exits, duplicate to_remove entries are rejected before they can strand not_finished, and the two prior clickhouse-gh review concerns no longer hold in the current code.

Missing context / blind spots
  • ⚠️ I did not run gtest_update_pipeline locally because this checkout has no build* directory. A targeted local run of that test binary would close the remaining local-validation gap.
Final Verdict

✅ No new review findings in the current diff.

LLVM Coverage Report

Measured on commit 5e1e05f.

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: 294/309 (95.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 30, 2026
`#115584` defers processor removal into `removeReadyGroups`, which any
executor frame may call at either gap `updateNode` makes in `nodes_mutex`.
That widened an existing window in which a frame parked at such a gap resumes
and dereferences an `Edge` another frame has freed, so re-landing `#115584`
without `#116103` would restore the `heap-use-after-free` at
`auto & node = *edge->to;` reported on `master` as `STID 2837-40ba`.

Related: #116103
Related: #115584
@alexey-milovidov alexey-milovidov changed the title Revert "Revert "Print Pipeline on Unfinished Processor Removal"" Print Pipeline on Unfinished Processor Removal, including the executor edge use-after-free fix Aug 30, 2026
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5e1e05fef 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

4 object files changed (+42.64 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Executors/ExecutingGraph.cpp.o 158.45 KiB 212.86 KiB +54.41 KiB (+34.34%)

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

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

Job report

…t-115584-print_pipeline_on_unfinished_processor_removal
Retiring an edge of a removed node kept it alive until `ExecutingGraph`
teardown. A subscribed `FROM ... STREAM` query retires a whole read-round
sub-pipeline on every round (`MergeTreeCommitOrderSource::updatePipeline`), so
executor memory grew with the number of completed rounds instead of with the
live graph, and a long-running subscription would eventually hit
`max_memory_usage`.

Retention now lasts only as long as a frame that can still reach the edge:

- `retireAffectedEdges` unqueues the edge from the update list of the node
  owning it, and drops the registration a surviving peer port may still hold on
  the edge's `Port::UpdateInfo`. Together with `update_list` being cleared, this
  leaves no place a frame entering later could pick the pointer up from, so only
  the frames already running at retirement time are of interest.
- Every retirement opens a batch tagged with a generation, and every
  `updateNode` frame registers the generation it entered at. When a frame
  leaves, batches no remaining frame could have picked up are destroyed.

Measured with the fan-in cycling regression test (4 coordinators, 16 threads,
160 retirements per pipeline): at most 2 batches are retained at any moment,
and the retained edge count stays at 0-240 instead of growing with the
generation.

The concurrent regression test repeats its pipeline 32 times, because the race
it covers was measured at roughly one failure in six single runs, which a
single pass would usually let through. All 12 tests of
`gtest_update_pipeline.cpp` pass (2.4 s in a release build).
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@Michicosun

Copy link
Copy Markdown
Member

fixed in #118031

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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