Repository navigation
Print Pipeline on Unfinished Processor Removal, including the executor edge use-after-free fix - #117129
Print Pipeline on Unfinished Processor Removal, including the executor edge use-after-free fix#117129alexey-milovidov wants to merge 13 commits into
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.
…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`.
|
Workflow [PR], commit [5e1e05f] Summary: ✅
AI ReviewSummaryThis PR re-lands the Missing context / blind spots
Final Verdict✅ No new review findings in the current diff. LLVM Coverage ReportMeasured on commit 5e1e05f.
Changed lines: Changed C/C++ lines covered: 294/309 (95.15%) · Uncovered code |
`#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
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+42.64 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 units627 translation units recompiled, 3880 s compile time in total, 627 of them have a recent master baseline. |
…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).
|
fixed in #118031 |
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):
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
#115584re-landed, with#116103merged in, because#115584on its own reopens aheap-use-after-freein the executor.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.updateNodereleases that lock at two points, and a frame parked at either one can resume and dereference anEdgethat another frame freed meanwhile.#111017fixed only the same-frame case, by scrubbing the removing frame's own list; it cannot reach the lists of other frames.#115584did not introduce the race, but it widened it considerably: removal is deferred intoremoveReadyGroups, 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 bucketSTID 2837-40baover the 60 days before the revert, the 5 occurrences preceding#115584are allAST fuzzer (arm_asan_ubsan), while the 8 following it span 6 jobs and reachedmaster: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
masterfailure is cross-thread and shows the exact path#116103closes:T462frees a removed node's edges inremoveReadyGroups->removePendingGroup->removeNode->~Node, whileT552pops one of them and readsauto & node = *edge->to;.#116103fixes it by retention rather than by tracking frames:retireAffectedEdgesmoves every edge of a removed node into a list that lives as long as the graph, points it at a permanentlyFinishedstand-in node, and runs before the node is erased. A queued pointer therefore stays valid, andupdateNodeskips aFinishednode without reaching its processor.This branch is
masterwith#115584restored plus#116103, which was green apart from the unrelatedNot-ready Setflake 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::updatePipelineretires a whole read round of a subscribedFROM ... STREAMquery on every round).retireAffectedEdgesunqueues 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'sPort::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, everyupdateNodeframe 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]