Skip to content

Fix a heap-use-after-free on pipeline edges queued in a concurrent executor frame - #116103

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-executing-graph-cross-frame-edge-uaf
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-executing-graph-cross-frame-edge-uaf

Conversation

@groeneai

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

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

Related: #111017

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. When one frame takes the lock exclusively and retires a processor group, destroying the node frees its edges, but the existing cleanup reached only the removing frame's own list. A frame parked at either gap updateNode makes in nodes_mutex then resumes and dereferences a freed Edge.

Rather than tracking those lists, this keeps the edges. An edge of a removed processor is pointed at a single permanently Finished node and moved to a list that lives as long as the graph, so a queued pointer stays valid; updateNode skips a finished node without reaching its processor, so it cannot reach the removed one either. No frame has to be tracked.

The cost is that retired edges are not freed before the graph is. MergeTreeCommitOrderSequentialSource, the one production path that removes processors, retires 26 edges of 64 bytes per removal, so a subscribed stream grows by about 1.6 KB per snapshot replacement without bound. That needs enable_streaming_queries, which is experimental and off by default. The live graph does not grow: nodes peaked at 103 to 129 entries.

CI reported this at auto & node = *edge->to; eight times over 120 days on eight unrelated pull requests, always arm_asan_ubsan, in buckets STID 2837-40ba and STID 1003-358c. Three are cross-thread.

Replacing the retention with a plain erase reproduces the use-after-free at the same statement. The pre-existing Processors.UpdatePipelineFanInRemovalNoUseAfterFree catches that in 40 of 40 runs over four CPU pinnings, single-threaded: one frame fills its work list, frees edges further down the same loop, then pops a stale one. Master scrubbed the list at that point; this change drops the scrub and retains instead. The new concurrent test covers the cross-frame case and catches the same mutant in 1 of 20 runs alone. With the retention, 30 of 30 clean, and 30 of 30 for the whole Processors suite.

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

The rate has since risen sharply, and the failure now reaches master. In STID 2837-40ba over the last 60 days, the 5 hits before #115584 landed on 2026-08-22 are all AST fuzzer (arm_asan_ubsan); the 8 hits after it span 6 jobs — Stress test (amd_tsan), Stress test (amd_asan_ubsan), Stress test (arm_asan_ubsan), Stateless tests (amd_asan_ubsan, distributed plan), Stateless tests (arm_asan_ubsan, targeted) and AST fuzzer (arm_asan_ubsan). #115584 defers removal into removeReadyGroups, which any frame may call at either gap updateNode makes in nodes_mutex, so the window a parked frame can be caught in got much wider, and plain stateless runs now hit it too.

The master occurrence is a heap-use-after-free at the same auto & node = *edge->to;, cross-thread: T462 frees the edges in removeReadyGroups -> removePendingGroup -> removeNode -> ~Node while T552 pops one of them. That is the freeing path this change removes, since retireAffectedEdges retires every edge of a removed node before eraseNode runs.

Report on 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


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

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two review rounds (a cold code review plus a second-model gate) before publishing. The first raised
one blocker and two majors and sent the change back; this round found nothing further.

# Severity Finding Verdict
1 ❌ blocker The work-list cleanup in removePendingGroup ran after the first edges were freed. Collecting the remaining edge ids allocates, the global operator new routes through the memory tracker, and min_allocation_size_to_throw_on_memory_limit is 0 by default, so a query near max_memory_usage can throw there; nothing catches it, so the throw released nodes_mutex with freed edges still published Agreed, fixed. Removal is split into a pass that only identifies what will go away and a pass that destroys it, with the cleanup in between, so every allocation happens while the edges it names are still alive. No try/catch, nothing marked noexcept
2 ⚠️ major Publication was per frame, so every updateNode iteration on every thread took a new graph-global std::mutex twice. Before this change updateNode took no graph-global exclusive lock at all, and no measurement accompanied the new cost Agreed, fixed by narrowing instead of measuring: publication now covers only the two windows in which the frame holds no nodes_mutex, the only time a removal can run. A control arm publishing in just one of the two still reproduces the bug in 4 of 30 runs, so both are load-bearing
3 ⚠️ major The new test asserted that every retired batch had been destroyed. That is not the oracle for this defect, it is stricter than a neighbouring assertion in the same file that has already gone red on master, and its precondition is scheduling rather than structure Agreed, dropped. The test keeps a check that the pipeline actually ran, with the sanitizer report as the oracle, matching the sibling use-after-free test in the same file
4 ⚠️ major Add a deterministic barrier or test hook to force the cross-frame window Not adopted. Every user-overridable extension point inside both windows runs under the shared lock, so parking there deadlocks the freeing thread, and the remedy reduces to a production failpoint that was implemented and then measured non-load-bearing (the mutant reproduces 7 of 12 runs with it disabled). Instrumented counters show the fixture reaches the cross-frame state in 3 of 3 runs, with the counter's sensitivity confirmed by a positive control on an unrelated test
5 💡 nit A comment explained the fix rather than the local invariant Agreed, moved to the commit message

One thing noticed and deliberately left alone: a duplicate ProcessorPtr inside a single removal
group used to be rejected with a LOGICAL_ERROR, because the map entry was erased on the first pass.
After the identify-then-destroy split both passes succeed, so such a group would destroy the same
node twice. I could not construct that input, since to_remove comes only from a processor's own
updatePipeline and the one production producer moves a pipe's processor list. The previous
behaviour on the same input was also unsound, for the reason in row 1.

Not defects, verified rather than assumed: the Node * work list needs no publication (a node cannot
be removed before it is Finished, and a Finished node is never queued); dump()'s two lock-free
callers run only after every executor thread has joined; Port::UpdateInfo back-pointers are cleared
by disconnect(), which every producer calls before removal.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter="Processors.UpdatePipelineConcurrentRemovalDoesNotFreeQueuedEdges" on an address,undefined build. On a tree with only the new scrub call disabled it reports heap-use-after-free in 10 of 60 runs, ~0.3 s per run, no server and no fuzzer. Instrumented counters confirm the fixture reaches the defect state (a queued edge of another frame is freed), so the failing interleaving comes from the fixture's structure rather than from luck.
b Root cause explained? Yes. updateNode keeps pending edge updates in a work list local to its frame and pushes into it under only a shared lock on nodes_mutex. Several frames therefore run at once with private work lists. When one frame takes the lock exclusively and retires a group, destroying a node frees its edges, but the previous cleanup could only reach the removing frame's own list. A frame parked at one of the two gaps updateNode makes in nodes_mutex resumes and dereferences a freed Edge at auto & node = *edge->to;. The same window also opened from a second direction: an allocation between the first free and the cleanup can throw, and the throw unwound past the cleanup.
c Fix matches root cause? Yes. Each frame's work list is published on the graph while that frame holds no nodes_mutex, and the freed edges are dropped from every published list at removal time, under the exclusive lock the removal already holds. Removal is ordered so that everything is identified while still alive, then the lists are cleaned, then anything is destroyed, which makes the ordering total rather than incidental. No guard at the crash site, no widened bound, no weakened assertion, no defensive retry. Comparison is by edge identity, never a dereference of freed memory.
d Test intent preserved / new tests added? Yes. No existing test is modified, weakened or retagged; UpdatePipelineMultipleCoordinatorsMultithreaded, UpdatePipelineFanInRemovalNoUseAfterFree, UpdatePipelineDeferredRemovalOfUnfinishedProcessors and UpdatePipelineRemovalIsNotStrandedByCancellation are untouched and pass 20 of 20 each. One new test added, reusing the existing fixtures in that file. Its oracle is the sanitizer report, matching the convention of the sibling use-after-free test in the same file.
e Both directions demonstrated? Yes, with a third arm that separates a working fix from a dead fixture. Without the fix: heap-use-after-free, READ of size 8, cross-thread, crash statement auto & node = *edge->to; at the same column as the CI report, freeing stack removeReadyGroups -> removePendingGroup -> node destruction -> operator delete on an Edge list node, 10 of 60 runs. With the fix: 0 of 30. Publishing in only one of the two gaps: 4 of 30, which is what shows both gaps have to be covered.
f Fix is general across code paths? Yes. Edge objects are freed at exactly two sites, node destruction (which frees the node's own edge lists) and the pass over surviving nodes whose edges point at removed nodes. Both funnel through removePendingGroup, which is where the cleanup sits, so one hook covers both, and removeReadyGroups' aggregated result is covered by construction. Both gaps in nodes_mutex are covered, and the coverage of each is measured rather than argued. Outside ExecutingGraph the edge lists have a single reader and no writer. The node work list is deliberately unchanged: a node cannot be removed before it is Finished, and a Finished node is never queued.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers are not applicable, this is a lifetime defect over an identity set. The relevant matrix is pipeline shape and it was swept: fan-in 8/16/64, chain depth 1/2/6/7, 4 and 16 executor threads, retirement of drained and of still-running batches. No use-after-free in any configuration with the fix; the mutant reports one in the deep-chain configurations.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting, no default change, no serialization or on-disk format, no public interface change, no experimental gate; updateNode's signature and return values are unchanged. No SettingsChangesHistory.cpp entry is owed.
i Invariants and contracts preserved? Yes. Lock order is nodes_mutex then the new list mutex and never the reverse, so no lock cycle exists. Every allocation on the removal path happens while the edges it names are still alive, so no path can free an edge that is still published, including the error paths. After the frame-local cleanup is deleted every access to a work list is under nodes_mutex, which is what makes mutating a parked frame's container safe; the deleted block held no lock at all. Publication is RAII and covers every exit from both gaps, and steady-state updateNode takes no graph-global exclusive lock. Processors.* ran 50 times under the sanitizer with no failure and no Pipeline stuck error.

Session id: cron:clickhouse-impl-slot-7:20260824-092400

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5fc863e]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR changes ExecutingGraph so queued pipeline edges are retired to a sentinel Finished node instead of being freed while another executor frame may still hold an Edge *, and it adds focused regressions for duplicate to_remove entries plus the queued-edge lifetime bug. After reviewing the current diff, the surrounding executor code, the real PipelineUpdate::to_remove producer in MergeTreeCommitOrderSource, and all prior discussion threads, I did not find an unresolved correctness, concurrency, or evidence issue in the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 5fc863e.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.10% +0.10%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 231/244 (94.67%) · 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 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Fgrtue @vdimir, could you review this? A updateNode frame keeps queued edge pointers in a frame-local list across the two gaps it makes in nodes_mutex, so a concurrent frame retiring a processor group freed edges that were still queued elsewhere; the fix publishes each frame's list for the duration of those gaps and drops the freed ids from every published list at removal time, under the exclusive lock the removal already holds.

…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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5fc863e94 with master 4539487f3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9904bd278; 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

9 object files changed (+17.55 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Executors/ExecutingGraph.cpp.o 158.45 KiB 174.97 KiB +16.53 KiB (+10.43%)

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

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

Job report

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.
/// gap in `nodes_mutex` and cannot resume before this exclusive section ends. Dropping them
/// from every published work list before anything is destroyed is what keeps those frames
/// from dereferencing freed memory.
scrubRemovedEdges(result.removed_edges);

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.

Could we maybe come up with a simpler solution that doesn't involve heavy synchronization and tracking nodes in a global list? Maybe some throwaway storage to keep edges "invalid" without destroying them? It might leak a bit of memory, but I assume we don't do heavy graph updates, so there will only be a few. Or maybe there are other ideas?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured the premise first, and it does not hold: on the one production path that removes processors, graph updates are not rare, so the leak is unbounded rather than "a few".

MergeTreeCommitOrderSequentialSource::updatePipeline is the only override in src/ that fills to_remove non-empty (all others set .to_remove = {}), and it retires the whole snapshot sub-pipeline per commit. Counters on a live SELECT ... STREAM, stream liveness asserted per arm:

arm groups retired nodes edges live nodes
baseline 112 838 1676 23
+30 commits 142 1048 2096 23
+90 more commits 232 1678 3356 23

Exactly 1 group / 7 nodes / 14 edges per commit, linear, while the live graph stays flat at 23. So retention scales with commits, which the user controls and which does not end for a subscribed stream: sizeof(Node) 272, sizeof(Edge) 64, so about 2800 bytes per commit, 267 MiB per 100k. Retired nodes also cannot just stay in nodes, since removePendingGroup walks that list twice per removal.

Two parts of your idea do work. Keeping the object alive is enough to make the read benign: a node is removable only once last_processor_status == Finished, and the drain skips a Finished node without touching its processor. And keeping only Edge objects, repointing each retired edge at one permanently-finished sentinel node, keeps nodes flat and needs no per-frame tracking. That is genuinely simpler than this PR, at 896 bytes per commit, still unbounded.

On cost here: the extra mutex is taken where a frame drops nodes_mutex, not per edge (93 acquisitions vs 3468 edges in the same run, 2.7%), and the list is intrusive so updateNode does not allocate.

If you prefer the sentinel form and accept unbounded growth for long streams, I will switch to it. enable_streaming_queries is experimental and off by default, so that growth is only reachable with the feature enabled.

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.

go ahead

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the published form then. If you meant the sentinel variant instead, say so and I will switch. CI is green on 99ed654.

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.

second option

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to the sentinel variant in d4d1541. Retired edges keep their identity, get pointed at one permanently Finished node, and move to a list that lives as long as the graph; a frame that resumes and pops one finds a finished node and skips it without reaching a processor. The published work-list registry, its mutex, both guards and the removed-edge id sets are gone, so the executor is 129 lines lighter than the previous form.

Validated the same way: replacing the retention with a plain erase gives the use-after-free back at auto & node = *edge->to;, cross-thread, in 11 of 30 runs, and 0 of 30 with it, plus 30 of 30 for the whole Processors suite. Instrumentation confirms a retired edge really is read after retirement in 6 of 30 runs, so the retention is what closes it rather than the timing changing.

Two things worth flagging on the accepted trade-off. Retention on the production path is 26 edges per removal, so about 1.6 KB per snapshot replacement rather than the 896 bytes per commit I estimated earlier, and nodes stays flat as expected (103 to 129 entries on the streaming query). I also tried to bound the growth inside this design and could not: a "reclaim when no frame sits in a lock gap" counter never fires, because the removing frame is itself in the gap when it calls removeReadyGroups. Any bound needs the per-frame tracking you asked me to drop, so I left it unbounded and documented the cost in the PR description instead.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d4d1541

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'in' (STID 0250-41a5) logical error, not PR-caused (349 rows across 260 pull requests in 30 days, 29 of them on master; the aborting query is SELECT * FROM merge(currentDatabase(), 'row_policy_table') FINAL, which reaches FunctionIn::executeImpl through FilterTransform, whereas this PR only changes ExecutingGraph edge lifetime) #114058 (ours, open)

Session id: cron:our-pr-ci-monitor:20260826-003000

alexey-milovidov added a commit that referenced this pull request 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

Copy link
Copy Markdown
Member

These commits are now merged into #117129, which re-lands #115584 and cannot go in without them. Leaving this open as the standalone fix, since the race predates #115584 and this is still the change to land if #117129 is dropped again.

Master removed `ExecutingGraph::dump` in cf9eeda, the revert of "Print
Pipeline on Unfinished Processor Removal". This branch predates that revert, so
the three-way merge drops the helper along with the four call sites it shipped
with, but keeps the call inside this branch's own removal guard. That leaves one
orphaned reference:

  src/Processors/Executors/ExecutingGraph.cpp:249:25: error: use of undeclared identifier 'dump'

which broke `Build (arm_tidy)` and `Fast test` on an otherwise unchanged head.

Reproduced on the merged file content (one error, same line and column) and
verified clean with this change. The processor name stays in the message, since
that is what identifies the repeated entry.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The standalone form stopped building against post-revert master: the three-way merge drops ExecutingGraph::dump together with its four call sites, but keeps the call this branch added in the duplicate-removal guard, so Fast test and Build (arm_tidy) both failed on use of undeclared identifier 'dump' at ExecutingGraph.cpp:249. 5fc863e drops that argument, matching the post-revert message style. Reproduced the error on the merged file content, and verified the same content compiles clean with the change.

That is now the only line where this branch differs from the copy in #117129, where dump still exists, so the argument can be restored there if the re-land goes in.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5fc863e

Every failure below has an owner: a fixing PR (ours 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 (unit tests) inconclusive fail-close, neither a reproduction nor a refutation: submodule state differs between the merge-base 80ad8a50e7dd and the checkout fixed in this PR: the base refresh is owed here and the fix commit lands on this branch

That verdict is base drift, not this change. Master moved contrib/aws-c-http and contrib/cctz and
removed contrib/spdlog and contrib/wasmedge (hence .gitmodules) in the 3699 commits since the
merge-base, while this PR touches three files under src/Processors and changes no submodule state.
ci/jobs/unit_tests_bugfix_validation_job.py fails close in exactly that case by design, because the
before-worktree can only be populated at the checkout's submodule revisions. Merging master refreshes
the merge-base and lets the validator run.

Nothing else is red at this head: the 171 praktika nodes are 141 OK, 28 SKIPPED, the one ERROR above,
and the root PR node that it fails. 0 DROPPED, and CIDB has no other failing row at this sha. The two reds of d4d15419dbd9
(Fast test and Build (arm_tidy), both from master deleting ExecutingGraph::dump) are fixed here.

Session id: cron:our-pr-ci-monitor:20260830-143000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the row above: no base refresh is coming here, and the owner is not this PR.

Bugfix validation (unit tests) already passed at 99ed654 (2026-08-24) and at d4d15419 (2026-08-25). The only change since that pass is 5fc863e: one file, +2/-3, dropping an argument from an exception message, and it leaves the message substring the new gtest asserts on unchanged. So the inconclusive verdict at this head comes from base motion alone, and no validation signal was lost.

Refreshing the merge-base would let the validator run again, but it also re-runs every currently green check here and can go inconclusive again the next time master moves a submodule, so I am leaving the base as it is. It would also diverge these commits from the verbatim copy in the re-land PR.

Owner for that row: a fix task is created (fixing-PR link to follow on this PR).

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

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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