Skip to content

Fix heap-use-after-free in getProcessorsProfileLogInfo for a dangling output peer - #111019

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-profile-log-info-dangling-peer
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-profile-log-info-dangling-peer

Conversation

@groeneai

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

Fixed a heap-use-after-free when collecting system.processors_profile_log parent ids on query finish: a processor could be read through a still-connected output port after its peer processor was already destroyed during pipeline teardown.

Description

IProcessor::getProcessorsProfileLogInfo() built parent_ids by following each connected output port to its peer via port.getInputPort().getProcessor(). A Port keeps its shared_ptr<State> (so it stays isConnected()) and its raw processor pointer even after the peer processor is destroyed, so during streaming pipeline teardown (ExecutingGraph::removeNode erases finished processors while survivors still reference them through ports) this dereferenced a freed processor.

Unlike the debug-only printPipeline variant fixed in #110955, this path is reachable in release builds: finalizeQueryPipelineBeforeLogging gathers the profile info unconditionally on successful query finish, and logProcessorProfile(context, processors) is also called for scalar-subquery / prepared-set logging.

The parent-id computation is moved into the free getProcessorsProfileLogInfo(const Processors &), which has the whole processor set: it maps each input port's shared connection id to the owning processor id, then matches each connected output port through that map. It never dereferences a peer processor, and produces identical parent_ids for well-formed pipelines. This mirrors the connection-identity approach approved in #110955 (Port::getConnectionId()); if #110955 merges first the duplicated accessor drops out cleanly.

… output peer

getProcessorsProfileLogInfo built parent_ids by following each connected output
port to its peer via getInputPort().getProcessor(). A Port keeps its shared State
(so it stays isConnected()) and its raw peer processor pointer even after the peer
processor is destroyed, so during streaming pipeline teardown (ExecutingGraph::removeNode
erases finished processors while survivors still reference them through ports) this
dereferenced a freed processor: a heap-use-after-free read.

Unlike the debug-only printPipeline variant (ClickHouse#110955), this path is release-reachable:
finalizeQueryPipelineBeforeLogging gathers the profile info unconditionally on successful
query finish, and logProcessorProfile(context, processors) is also called for
scalar-subquery / prepared-set logging.

The parent-id computation moves into the free getProcessorsProfileLogInfo(const Processors &),
which has the whole processor set: it maps each input port's shared connection id to the
owning processor id, then matches each connected output port through that map without
dereferencing a peer processor. Output is unchanged for well-formed pipelines. Mirrors the
connection-identity approach from ClickHouse#110955 (Port::getConnectionId()).

Related: ClickHouse#110955
Related: ClickHouse#110834

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@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; 3 findings across 1 full pass + 1 fix round + 1 delta recheck; bounded).

# Sev Finding Verdict Evidence / action
1 ⚠️ Diff includes unrelated local artifacts (config_file_for_test.xml, .meta.json) DISAGREE git show --stat HEAD = exactly the 4 intended files. Both were UNTRACKED worktree runtime files (never staged/committed), so they cannot reach the PR. Deleted for local hygiene anyway.
2 💡 Implementation comments repeat the full bug narrative AGREE — fixed Trimmed both comments (IProcessor.cpp 4->2 lines, ProcessorsProfileLog.cpp 4->3 lines); the teardown narrative now lives in the commit message. Rebuilt (Build-ID changed), regression tests still 2/2 pass.
3 ❌ "Diff only rewrites comments; UAF fix not implemented/tested" DROPPED Delta-scope artifact: the recheck was scoped to the comment-trim round only, which by construction excludes the base commit carrying the executable fix + regression test. Full HEAD verified: connection-id map + getConnectionId() lookup present, peer-deref loop removed (0 occurrences), new 102-line gtest present. The full-diff pass did not raise this.

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-205500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New gtest ProcessorsProfileLog.DoesNotDereferenceDanglingOutputPeer triggers the heap-use-after-free on demand (100%) under ASAN: connect a survivor's output to a peer, destroy the peer, gather profile-log info over {survivor}.
b Root cause explained? Yes. A Port keeps its ref-counted shared_ptr<State> (stays isConnected()) and its raw peer-processor pointer even after the peer processor is destroyed during pipeline teardown (ExecutingGraph::removeNode). getProcessorsProfileLogInfo followed the output port to that peer via getInputPort().getProcessor(), reading freed memory.
c Fix matches root cause? Yes. The parent-id walk no longer dereferences a peer processor: it matches an output port to its peer through the shared-state identity (Port::getConnectionId() == state.get()), building the map in the free overload that owns the whole processor set. Not a guard/retry band-aid — the unsafe deref is removed.
e Both directions demonstrated? Yes. Without fix (Build-ID d97fc28a): ASAN heap-use-after-free, READ of size 8 in the freed 104-byte peer, abort (exit 134). With fix (Build-ID c5a81999): 2/2 tests pass; broader *Processor*:*Pipeline*:*Profile*:*Port* suites 92/92 pass.
d Test intent preserved / new tests added? Yes. New regression gtest with two cases: (1) dangling peer => no UAF, no phantom parent; (2) well-formed pipeline => parent_ids still records the downstream parent (guards against silently dropping legitimate parent links).
f Fix is general across code paths? Yes, and correctly scoped. The bug class is "reading a peer from a torn-down processor set". Exactly two paths hit it: printPipeline (fixed in #110955) and this profile-log path. All other getInputPort()/getOutputPort().getProcessor() sites (ExecutingGraph, Pipe, QueryPipeline, IQueryPlanStep, printPipelineCompact/EXPLAIN) run on live pipelines during construction/analysis where peers are alive by construction. The per-processor method's sole caller is the free overload, so this covers every release funnel.
g Fix generalizes across inputs? Yes. The map/lookup is oblivious to processor type, port count, and header. Multi-input/multi-output processors are covered (loops over all ports). parent_ids values are byte-identical for well-formed pipelines because both sides of a connection share the same state.get() and the proc-id scheme is unchanged.
h Backward compatible? Yes. No setting, on-disk/wire/replication/metadata format change. system.processors_profile_log.parent_ids is unchanged for well-formed pipelines; only the previously-UAF teardown case now safely omits a dangling parent instead of reading freed memory. No SettingsChangesHistory needed.
i Invariants and contracts preserved? Yes. getConnectionId() is a pure read of state.get() (opaque identity; both peers equal). Only the parent_ids loop moved from the per-processor method to the free overload; all other fields untouched. No new throw/noexcept boundary. UnorderedMapWithMemoryTracking respects the memory-tracking contract used elsewhere (and by #110955's printPipeline).

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @KochetovNicolai — could you review this? It fixes a release-reachable heap-use-after-free in getProcessorsProfileLogInfo: the parent-id walk followed an output port to its peer processor, which can already be destroyed during pipeline teardown while the port stays connected. The fix matches ports by shared-state identity (getConnectionId()) instead of dereferencing the peer, mirroring the approved #110955 approach for the debug-only printPipeline path.

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

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c5e5ac]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
Integration tests (amd_msan, 7/8) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR moves system.processors_profile_log.parent_ids off the raw peer-processor pointer and onto shared port-state identity, which is the right direction, but the fix is incomplete in the current branch. The same post-execution logging flow still builds pipeline_dump via printPipeline, and that helper still dereferences the torn-down peer processor, so I would not merge this as-is.

Findings

❌ Blockers

  • [src/Interpreters/ProcessorsProfileLog.cpp:124] The PR removes the dangling dereference from getProcessorsProfileLogInfo, but logProcessorProfile(context, processors) and finalizeQueryPipelineBeforeLogging still call printPipeline on the same post-execution Processors set. printPipeline still follows port.getInputPort().getProcessor() after only isConnected() (src/QueryPipeline/printPipeline.h:62-67, 87-93), while ExecutingGraph::removeNode destroys finished processors out of the shared list (src/Processors/Executors/ExecutingGraph.cpp:65-67). That leaves scalar-subquery logging, prepared-set logging, and normal query-finish logging able to hit the same heap-use-after-free through the dump path. Suggested fix: make the dump builder use the same Port::getConnectionId() lookup that this PR adds for parent_ids, or stop building the dump from torn-down processor sets until printPipeline is hardened.
Tests
  • ⚠️ The new gtest covers only getProcessorsProfileLogInfo. Add a focused regression that reaches logProcessorProfile or finalizeQueryPipelineBeforeLogging on a torn-down processor set so the remaining dump-path dereference is exercised.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
{
if (!port.isConnected())
continue;
/// Only record the parent if the peer input port belongs to a processor in this set.

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.

parent_ids is safe after this change, but the release logging path still hits the same dangling peer when it builds pipeline_dump. logProcessorProfile(context, processors) still calls printPipeline(processors, out, true) (src/Interpreters/ProcessorsProfileLog.cpp:183-189), finalizeQueryPipelineBeforeLogging does the same for normal query finish (src/Interpreters/executeQuery.cpp:636-640), and printPipeline still follows port.getInputPort().getProcessor() after only isConnected() (src/QueryPipeline/printPipeline.h:62-67, 87-93). Because ExecutingGraph::removeNode erases finished processors from the shared Processors list (src/Processors/Executors/ExecutingGraph.cpp:65-67), scalar-subquery logging, prepared-set logging, and query-finish logging can still read a freed peer through the dump path. This needs the same getConnectionId()-based lookup in printPipeline, or the dump needs to be skipped for torn-down processor sets.

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.

Confirmed the deref is real: printPipeline (printPipeline.h) still reads port.getInputPort().getProcessor() after only isConnected(), and the release pipeline_dump reaches it via logProcessorProfile (ProcessorsProfileLog.cpp:188) and finalizeQueryPipelineBeforeLogging (executeQuery.cpp:639).

That printPipeline fix is owned by sibling PR #110955, which rewrites the same function to the identical getConnectionId() map and drops both peer-deref loops (printPipeline.h:62-67 and 87-93). printPipeline is the single free function shared by the debug dump and the release pipeline_dump, so #110955 closes the release path too.

This PR is scoped to parent_ids in getProcessorsProfileLogInfo; #110955 covers printPipeline. Together they close the full surface. Folding the printPipeline rewrite in here would duplicate #110955 on the same lines (add/add conflict) and re-review an approved change, so keeping the split.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 56/59 (94.92%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7c5e5ac

CI fully finished: Finish Workflow, Mergeable Check and CH Inc sync all SUCCESS. Every red
check below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk: 100 master hits in 30d across dozens of unrelated PRs; unrelated to this PR's ProcessorsProfileLog UAF change) #111029 (external, open)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (same signature, same test) #111029 (external, open)
PR gated top-level rollup reflecting the two non-required integration failures above (Mergeable Check is green) #111029 (external, open)

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

@yariks5s yariks5s self-assigned this Jul 20, 2026

@yariks5s yariks5s left a comment

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.

The connection-ID lookup is locally memory-safe, but the surrounding design is risky

  • getProcessorsProfileLogInfo silently stops populating parent_ids. Its name and return type still promise complete information
    -it changes system.processors_profile_log semantics, connections to processors absent from the supplied set just disappear
  • adds another hash-map allocation to every successful query unconditional finish path, also when processor-profile logging is disabled
  • it works around dangling pointers in selected readers instead of fixing their lifetime

I will get back to this PR later.

@yariks5s yariks5s closed this Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, these are fair. Below is what I measured for each point, plus the one design call I would like you to make.

1. getProcessorsProfileLogInfo no longer populating parent_ids. You are right that the signature over-promises, and I checked it is not just a naming issue: on origin/master the member overload has exactly one caller, getProcessorsProfileLogInfo(const Processors &) at src/Interpreters/ProcessorsProfileLog.cpp:103 (git grep getProcessorsProfileLogInfo over the whole tree returns only the declaration, the definition, that call, and the two callers of the free overload: ProcessorsProfileLog.cpp:163 and executeQuery.cpp:646). So no caller consumes parent_ids from the member, but a parent_ids field that is always empty is still a trap for the next caller. If the approach survives, I will drop parent_ids from what the member returns and let the free function own it (a split struct or an out-parameter), so the type stops claiming information the member cannot compute. That is the honest fix for this point, not an argument that the current shape is fine.

2. system.processors_profile_log semantics for peers absent from the supplied set. This is the substantive one. Two things worth separating.

First, what the old code did for such a peer was not "complete information", it was a read of freed memory. Under ASAN the unit test that constructs exactly this state (a survivor whose connected output port points at a destroyed peer) reports on the pre-fix binary:

ERROR: AddressSanitizer: heap-use-after-free on address 0x6fca44134f28
READ of size 8 at 0x6fca44134f28 thread T0
0x6fca44134f28 is located 56 bytes inside of 104-byte region [...]

and aborts (exit 134). The id it would have pushed is reinterpret_cast<uintptr_t> of a freed processor, so the pre-fix value is a stale address, not a resolvable parent.

Second, I measured how often this actually changes what gets logged for well-formed pipelines. On a debug build of current master (26.8.1.1), with log_processors_profiles=1, I compared each query's logged id set against the union of its logged parent_ids:

query shape rows logged parent refs refs to an id not in the set
SELECT sum(v) FROM t 15 15 0
GROUP BY k ORDER BY k LIMIT 5 25 25 0
ORDER BY v DESC LIMIT 3 17 16 0
self JOIN ... ON a.k=b.k 1773 3302 0
scalar subquery in SELECT 21 20 0
WHERE k IN (SELECT ...) 19 17 0
SELECT ... FROM t STREAM (sub-pipeline turnover, killed) 18 24 0

Zero out-of-set parents in every shape, including the streaming one, which is the case where ExecutingGraph::removeNode actually erases processors. So the change is a no-op for the rows users see today; the divergence only appears where the old code read freed memory.

That still leaves your design question, and I do not want to decide it unilaterally: for a peer that is genuinely not in the set, should the row omit the connection (what the PR does now) or record a sentinel parent id so the "complete information" contract holds and a consumer can see that an edge was dropped? The sentinel also answers point 1. I have no preference; tell me which you want and I will implement it.

3. Hash map on every successful finish, also when profile logging is off. Correct, and I would rather fix it than defend it: finalizeQueryPipelineBeforeLogging (executeQuery.cpp:646) builds the info unconditionally, and logProcessorProfile only checks settings[Setting::log_processors_profiles] afterwards (ProcessorsProfileLog.cpp:112). context is in scope at both callers of finalizeQueryPipelineBeforeLogging (the sibling finish_callback at executeQuery.cpp:2042 already captures it), so the enablement check can be hoisted.

Worth noting the same line does something larger unconditionally today, independent of my change: the printPipeline(..., out, true) call two lines below builds the whole GraphViz pipeline_dump string. Measured on the self-join above, that dump is 392 KB (1772 nodes, 3300 edges) built on every successful finish even with log_processors_profiles=0, versus my map, which is one entry per connected input port. If you want, I will hoist the guard so both the map and the dump are skipped when the setting is off; that is a strictly larger win than removing the map and it is a small diff.

4. Working around dangling pointers instead of fixing their lifetime. This is the one I do not want to answer for you. The mechanism is: ExecutingGraph::removeNode (ExecutingGraph.cpp:52-69) erases a finished processor from the shared Processors list and from nodes, the processor itself is destroyed at the end of updateNode via delayed_destruction (ExecutingGraph.cpp:219, :296), and a survivor's OutputPort keeps both its shared_ptr<State> and its raw InputPort *. disconnect is the only thing that resets those (Port.cpp:30-46, which resets both state and the peer pointer), and Port::isConnected() is just state != nullptr, so after a peer dies the port still reports connected while pointing at freed memory.

Fixing the lifetime properly means deciding who owns the invariant: either updatePipeline implementers must disconnect every port of a removed processor before returning it in to_remove (MergeTreeCommitOrderSequentialSource::updatePipeline does disconnect its input, MergeTreeCommitOrderSequentialSource.cpp:451, so the convention half-exists), or removeNode must disconnect the removed node's ports itself, or Port must stop exposing a peer pointer whose target it does not keep alive. Any of those is a much bigger change than this PR, and it is not only about the profile log: on master the same "isConnected() then dereference the peer" pattern is in printPipeline.h:66 and :92, printPipeline.cpp:75, AnalyzePlanStats.cpp:49 and :62, and IQueryPlanStep.cpp:261 and :311.

One thing you should know before choosing that route: #110955 (approved by @ alexey-milovidov, closes #110834) takes the same connection-identity approach for printPipeline. A lifetime rewrite would supersede it, so if that is the direction you want, it is a call for you and @ alexey-milovidov rather than something I should start on my own.

No rush on any of this. When you come back to it, could you also say whether you would prefer #111019 reopened or a fresh PR? The underlying read is still present on master, so I would like to land something for it either way.

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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants