Skip to content

Fix heap-use-after-free in ExecutingGraph::updateNode on runtime node removal - #111017

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-executinggraph-updatenode-uaf-100535
Aug 1, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-executinggraph-updatenode-uaf-100535

Conversation

@groeneai

@groeneai groeneai commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a heap-use-after-free in the pipeline executor that could crash the server when a query removes processors at runtime (for example FINAL with lazy reads or external sort), found by the AST fuzzer.

Description

ExecutingGraph::updateNode keeps a local work-list of Edge * (updated_edges), drained only after the processor work-list empties. When a runtime updatePipeline removes a node, removeNode destroys that node's own edge lists and removeAffectedEdges erases surviving nodes' edges that point to removed nodes. Any of those freed Edge * still queued in updated_edges become dangling, so a later pop reads edge->to on freed memory:

heap-use-after-free  READ of size 8
  ExecutingGraph::updateNode        ExecutingGraph.cpp:320   (auto & node = *edge->to;)
freed by:
  ~Node -> ~list<Edge> -> operator delete
  ExecutingGraph::removeNode        ExecutingGraph.cpp
  ExecutingGraph::updatePipeline    ExecutingGraph.cpp

Commit 1ef2990 already scrubbed the persistent post_updated_*_ports lists for exactly this hazard, but missed the transient local work-list held by the enclosing updateNode frame.

Fix: thread the ids of edges freed during updatePipeline (both removeNode's destroyed edge lists and removeAffectedEdges's erased edges) out to updateNode, and drop them from updated_edges right after updatePipeline returns, by pointer identity (update_info.id is the Edge's own address), so no freed Edge is ever dereferenced. The scrub is a no-op when nothing was removed.

Found by the AST fuzzer on arm_asan_ubsan. Added a deterministic ASAN regression test (Processors.UpdatePipelineFanInRemovalNoUseAfterFree) that reproduces the crash without the fix and passes with it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100535&sha=0fb86507fb4817cb2418012cce69069f92e74972&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

… removal

updateNode keeps a local work-list of Edge* (updated_edges), drained only
after the processor work-list empties. When a runtime updatePipeline removes a
node, removeNode destroys that node's own edge lists and removeAffectedEdges
erases surviving nodes' edges pointing to removed nodes; any of those freed
Edge* still sitting in updated_edges become dangling, so a later pop reads
edge->to on freed memory (heap-use-after-free).

Commit 1ef2990 scrubbed the persistent post_updated_*_ports lists for
this hazard but missed the transient local work-list. Thread the ids of edges
freed during updatePipeline out to updateNode and drop them from updated_edges
by pointer identity (update_info.id == the Edge's own address, so no freed
Edge is dereferenced). No behavior change when nothing is removed.

Found by the AST fuzzer on arm_asan_ubsan.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ASAN gtest Processors.UpdatePipelineFanInRemovalNoUseAfterFree crashes 100% with the scrub disabled (temporary toggle, removed). Single-threaded, not "~1%".
b Root cause explained? updateNode's local updated_edges (raw Edge*) is drained after the processor work-list empties. A later updatePipeline removes a node -> removeNode frees the node's own edge lists (and removeAffectedEdges erases surviving nodes' edges to it). Freed Edge* still queued in updated_edges dangle; the next pop reads edge->to (ExecutingGraph.cpp:320) -> heap-use-after-free.
c Fix matches root cause? Yes. Collect the ids of all edges freed during updatePipeline and scrub them from updated_edges right after it returns, by pointer identity (update_info.id == the Edge's own address -> no freed Edge is dereferenced). Mirrors commit 1ef2990's scrub of the persistent post_updated_*_ports, extended to the transient work-list it missed. Not a band-aid.
d Test intent preserved / new tests added? New regression gtest added (minimal repro: crashes under ASAN without the fix, passes with it). No existing test weakened. Full Processors.* suite 7/7 pass under ASAN.
e Both directions demonstrated? Yes. Without fix: ASAN heap-use-after-free, READ size 8, updateNode ExecutingGraph.cpp:320, freed via removeNode <- updatePipeline (matches the CI signature). With fix: passes; instrumented run scrubbed 7 dangling edges.
f Fix is general across code paths? Yes. Covers BOTH free paths: removeNode (removed node's own edges) and removeAffectedEdges (surviving nodes' edges pointing to removed nodes). The scrub sits at the single point any freed edge could still be referenced. Fixes the root cause, not a symptom.
g Fix generalizes across inputs? N/A (executor lifetime bug, independent of datatypes / type wrappers / settings). Triggers for any runtime node removal while that node's edges are queued; the fix is type-agnostic (operates on Edge* identity).
h Backward compatible? N/A. No setting, no on-disk/wire/replication/metadata format, no protocol change. Pure in-memory executor correctness.
i Invariants and contracts preserved? Yes. Restores the updated_edges "no dangling pointers" invariant right after the mutation that can break it (same invariant the pre-existing post_updated_*_ports scrub upholds). No lock/ownership change; scrub runs on a frame-local devector after re-acquiring the shared lock; relies on the ctor-enforced update_info.id == &edge and never dereferences a freed Edge.

Session id: cron:clickhouse-author-slot-0:20260719-195400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Fix still permits a UAF if another executor thread frees a queued edge during the nodes_mutex read->unique upgrade; freed_edge_ids records only the current call's deletions. DISAGREE The reproduced CI bug (STID 2837-40ba) is single-threaded: the ASAN report shows the READ and the free both on thread T276, same updateNode call. updated_edges is a frame-local devector<Edge*>, and the raw-Edge* work-list + shared->unique->shared upgrade pattern are pre-existing on master (unchanged by this patch); the sibling post_updated_*_ports scrub is likewise current-call-only. Edge frees occur only in updatePipeline under the unique nodes_mutex. The described cross-thread window is a pre-existing property of the executor's lock design that this patch neither introduces nor widens (it strictly improves safety), and is not the reproduced bug. Addressing it would be an unreproduced, speculative executor-wide concurrency refactor — out of scope for this fix.
2 ⚠️ .meta.json task-workspace metadata is in the diff and must not be committed. DISAGREE git show --stat HEAD = 3 files (ExecutingGraph.cpp/.h + the gtest); git status shows .meta.json UNTRACKED — never staged, never committed, not on the pushed branch. The review saw it because the gate appends untracked files to its diff view.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-0:20260719-195400

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @vdimir — could you review this? It fixes a heap-use-after-free in ExecutingGraph::updateNode: when a runtime updatePipeline removes a node, updateNode's local updated_edges work-list keeps raw pointers to that node's freed edges and later dereferences them. The fix scrubs the freed edges from the work-list right after updatePipeline, mirroring the existing 1ef2990 scrub of post_updated_*_ports. Found by the AST fuzzer; includes a deterministic ASAN regression test.

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [493a3ba]

Summary: ✅


AI Review

Summary

This PR teaches ExecutingGraph::updateNode to scrub removed nodes and edges from the remover's local work-lists after updatePipeline, and it adds unit/stateless regressions for runtime pipeline teardown. The single-frame reproducer looks addressed, but the fix is still local to one updateNode frame, so a second executor thread can resume with stale Edge * after another thread removes the same sub-pipeline; I do not think the PR yet satisfies its promised heap-use-after-free fix.

PR Metadata
  • Changelog category is incorrect for the actual change. Replace - Improvement with - Critical Bug Fix (crash, data loss, RBAC).
  • Changelog entry is required for that category and is already specific and user-readable; it is fine once the category is corrected.
Findings

❌ Blockers

  • [src/Processors/Executors/ExecutingGraph.cpp:477-503] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/111017#discussion_r3692449340] The invalidation is still frame-local. Another executor thread can already have released read_lock and be waiting on nodes_mutex with its own updated_edges deque; when this thread removes the sub-pipeline, the waiter never sees update_result.removed_edges, then resumes and still dereferences edge->to on freed storage at line 322. PullingAsyncPipelineExecutor runs updateNode concurrently, so the multi-threaded runtime-removal use-after-free remains reachable even though the single-frame reproducer is fixed. The invalidation needs to live in graph-wide shared state and be revalidated after every nodes_mutex reacquisition, not only inside the remover's frame.
Final Verdict

Changes requested: the current patch fixes the local reproducer but leaves the multi-threaded runtime-removal use-after-free unresolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 19, 2026
@Michicosun Michicosun self-assigned this Jul 19, 2026
…ne contract

Addresses review feedback on PR ClickHouse#111017: IProcessor::updatePipeline requires
to_remove to hold disconnected processors (IProcessor.h:250). The regression
test now disconnects each fan-out output from the coordinator inputs before
pushing the source into to_remove, mirroring the supported runtime-removal path
(MergeTreeCommitOrderSequentialSource::updatePipeline), instead of relying on
dangling port metadata.

disconnect() only severs port linkage; removeNode still destroys the source
node's graph Edge objects, so the freed edges still dangle in updateNode's
work-list. The test therefore still reproduces the exact heap-use-after-free
(STID 2837-40ba): without the scrub it crashes under ASAN (READ of size 8 in an
80-byte Edge region), with the scrub it drains cleanly. Full Processors.* suite
passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai groeneai closed this Jul 20, 2026
@groeneai groeneai reopened this Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ee9d0b7

CI fully finished (Finish Workflow = SUCCESS, 15:31 UTC; no jobs queued/in_progress/pending). This P0 executor heap-use-after-free fix touches only the pipeline executor (ExecutingGraph.cpp/.h + one regression gtest); all 13 core builds and the asan/tsan/msan/binary/release stateless + AST fuzzer + BuzzHouse checks are green. Every red check below has an owner; none is PR-caused.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock (chronic; 644 PRs / 292 master / 30d) #108212 (ours, merged) / #105905 (ours, merged)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky DDL-recovery race (chronic; 506 PRs / 103 master / 30d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error coverage-build shard death (chronic; 210 PRs / 22 master / 30d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Mergeable Check / PR — gated aggregators reflecting the above; clear on re-run
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260720-160000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Completing the test_replicated_table_structure_alter ledger line above: the fixing PR is #111029 (external, open, CI running).

It removes the source rather than repairing the divergence after the fact: a comment-only / settings-only ALTER on a ReplicatedMergeTree was committing a query-scoped metadata snapshot pinned before lockForAlter (by the #107491 access check), overwriting a concurrently applied ALTER_METADATA and silently dropping the added column. #111029 reads the commit-base metadata fresh under the held alter lock (bypass=true) and adds a regression test pinning the exact race.

Our #110030 and #110145 (recovery-repair approaches) were both closed in favor of #111029; it Closes #110036.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5b2bc24

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2153690

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) harness limitation, not a test result: the job aborts as inconclusive because master moved contrib/libcotp after this branch split, so the before-worktree cannot be populated at the merge-base revision. No test ran, and this PR changes no submodule (its diff is 5 files, all under src/ and tests/queries/) a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)
Finish Workflow / Post Hooks (new_tests_check.py) consequence of the row above plus a genuine per-arch no-repro: both functional validators report Failed: 0, Passed: 1 with "Bug does not reproduce on this arch", so 04658_streaming_queries_pipeline_teardown_use_after_free passed on the master-HEAD sanitizer binaries and no arch validated. The gate emits one message for three different input states, which is itself the tracked defect a fix task owns this (investigating at full effort, fixing-PR link to follow on this PR)

All 27 Build (*) jobs, all 7 Unit tests (*) jobs (19508 / 19507 / 19504 / 27321 passed) and every
functional and integration suite are green on this head.

Two notes for whoever picks the branch up next, neither of which is a CI failure:

The new stateless test is numbered 04658_, and my own open #112680 already ships
04658_disable_unknown_fp_name. git will not conflict on that and check_gaps_in_tests_numbers
only rejects gaps of 100 or more, never collisions, so one of the two files needs renumbering before
whichever lands second.

The no-repro verdict is worth a look on its own terms. This is a runtime node-removal use-after-free,
so a test that passes on the master-HEAD asan_ubsan binary is not obviously exercising the freed
path; the shipped .sql may need to force the teardown ordering rather than rely on it.

Session id: cron:our-pr-ci-monitor:20260731-173000

/// updatePipeline may have removed locally recorded edges.
if (!update_result.removed_edges.empty())
{
auto removed_range = std::ranges::remove_if(updated_edges, [&](const void * edge) { return update_result.removed_edges.contains(edge); });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only scrubs updated_edges for the current updateNode frame. Another executor thread can already be parked at the same shared->unique nodes_mutex upgrade with its own local updated_edges: it releases read_lock, waits on nodes_mutex, then resumes with whatever Edge * it queued earlier. If this thread wins the race and removes one of those edges in the meantime, the waiter never sees update_result.removed_edges and still dereferences edge->to on the freed Edge after it re-locks.

So the single-threaded reproducer is fixed, but the same use-after-free is still reachable under multi-threaded runtime removals. This invalidation needs to be visible across all concurrent updateNode frames, not just the caller's local deque.

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.

Agreed on the mechanism, and I do not think it should be fixed here.

I checked the three things that decide it rather than assuming, at head 3628df1:

The gap is real. updated_edges is frame-local (ExecutingGraph.cpp:301; all 9 references in the .cpp and .h are inside updateNode, no member or static spelling), removed_edges is read only at the scrub on :489, and there is no shared edge-lifetime state on the graph to consult. A second frame parked at :479 between read_lock.unlock() on :475 and read_lock.lock() on :503 does keep its own queued Edge *, and it is reachable outside the unit test: MergeTreeCommitOrderSequentialSource::updatePipeline is the only override on master that returns a non-empty to_remove, and the new .sql runs 16 of those sources concurrently.

But it is pre-existing, not introduced. Diffing this file against master, the updated_edges declaration is unchanged, read_lock.unlock() and std::unique_lock lock(nodes_mutex) are unchanged, and the dereference auto & node = *edge->to is master line 311, which is the exact frame in the report this PR exists for. So the cross-frame window is reachable on master today; this patch only shrinks the reachable set by adding a scrub that did not exist before, and widens nothing.

And every observed failure is inside a single frame, which the scrub does cover. For STID 2837-40ba over 60 days CIDB has 4 rows, and in all 4 the freeing thread is the reading thread: #111572 T303/T303, #111099 T396/T396, #111189 T271/T271, #100535 T276/T276. All 4 carry removeNode and updatePipeline; none carries removeAffectedEdges, so the freed edges are the removed node's own list. That is exactly the accumulate-then-free case in one frame.

Making the invalidation visible to frames that are already parked needs shared edge-lifetime state on the graph plus revalidation after every lock re-acquisition. That is an executor-wide concurrency change with its own risk, so it is a separate PR rather than something to fold into a fix for the single-frame use-after-free that is actually reproducing. I am not pushing to this branch; the call is the assignee's.

One note on the scrub itself, since I looked: :489 compares the work-list pointer against update_info.id, which the Edge constructor sets to this, so it is pointer identity and never dereferences freed memory. removeNode contributes the removed node's own edges and removeAffectedEdges the surviving nodes' edges into it, so the union covers every freed edge.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 90/94 (95.74%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 493a3ba

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.

No failures on this head. All 174 check-runs completed, Config Workflow and Finish Workflow are green, 0 queued or in progress, and CIDB reports 0 FAIL/ERROR test rows for this commit.

Session id: cron:our-pr-ci-monitor:20260801-203000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 262da35 Aug 1, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants