Repository navigation
Conversation
…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.
Internal second-model reviewTwo review rounds (a cold code review plus a second-model gate) before publishing. The first raised
One thing noticed and deliberately left alone: a duplicate Not defects, verified rather than assumed: the |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260824-092400 |
|
Workflow [PR], commit [5fc863e] Summary: ❌
AI ReviewSummaryThis PR changes Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 5fc863e.
Changed lines: Changed C/C++ lines covered: 231/244 (94.67%) · Uncovered code |
|
cc @Fgrtue @vdimir, could you review this? A |
…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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes9 object files changed (+17.55 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 units26 translation units recompiled, 131 s compile time in total, 26 of them have a recent master baseline. |
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); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Keeping the published form then. If you meant the sentinel variant instead, say so and I will switch. CI is green on 99ed654.
There was a problem hiding this comment.
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`.
CI finish ledger - d4d1541Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260826-003000 |
`#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
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.
|
The standalone form stopped building against post-revert That is now the only line where this branch differs from the copy in #117129, where |
CI finish ledger - 5fc863eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
That verdict is base drift, not this change. Master moved Nothing else is red at this head: the 171 praktika nodes are 141 OK, 28 SKIPPED, the one ERROR above, Session id: cron:our-pr-ci-monitor:20260830-143000 |
|
Correction to the row above: no base refresh is coming here, and the owner is not this PR.
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). |
Changelog category (leave one):
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::updateNodekeeps pending edge updates in a work list local to its own frame, filled under only a shared lock onnodes_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 gapupdateNodemakes innodes_mutexthen resumes and dereferences a freedEdge.Rather than tracking those lists, this keeps the edges. An edge of a removed processor is pointed at a single permanently
Finishednode and moved to a list that lives as long as the graph, so a queued pointer stays valid;updateNodeskips 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 needsenable_streaming_queries, which is experimental and off by default. The live graph does not grow:nodespeaked at 103 to 129 entries.CI reported this at
auto & node = *edge->to;eight times over 120 days on eight unrelated pull requests, alwaysarm_asan_ubsan, in bucketsSTID 2837-40baandSTID 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.UpdatePipelineFanInRemovalNoUseAfterFreecatches 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 wholeProcessorssuite.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. InSTID 2837-40baover the last 60 days, the 5 hits before #115584 landed on 2026-08-22 are allAST 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)andAST fuzzer (arm_asan_ubsan). #115584 defers removal intoremoveReadyGroups, which any frame may call at either gapupdateNodemakes innodes_mutex, so the window a parked frame can be caught in got much wider, and plain stateless runs now hit it too.The
masteroccurrence is aheap-use-after-freeat the sameauto & node = *edge->to;, cross-thread:T462frees the edges inremoveReadyGroups->removePendingGroup->removeNode->~NodewhileT552pops one of them. That is the freeing path this change removes, sinceretireAffectedEdgesretires every edge of a removed node beforeeraseNoderuns.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%29Workflow [PR]
Sync PR [sync-upstream/pr/116103]