Skip to content

Do not access ports from IProcessor::work() - #119577

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/no-port-access-in-processor-work
Sep 12, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/no-port-access-in-processor-work

Conversation

@groeneai

@groeneai groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118031
Related: #118393

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

IProcessor::work() is documented as unable to access any ports (IProcessor.h:189-194),
because it runs with no graph lock held: PipelineExecutor calls executeTask() at
PipelineExecutor.cpp:356 and only enters graph->updateNode at :379. Two processors break
that contract, and one of them was caught by the AST fuzzer:

ScatterByPartitionTransform::work() pushed to its output ports. OutputPort::pushData ->
Port::updateVersion -> Port::UpdateInfo::update appends to that node's own
post_updated_output_ports, which the executor erase_if-scans for every node under the
nodes_mutex write lock while reclaiming a retired processor
(ExecutingGraph::removePendingGroup -> removeAffectedEdges). The result is a concurrent
push_back / erase_if on one std::vector<void *>: reported as a ThreadSanitizer data race,
and able to drop or duplicate an edge id, or leave a freed Edge * behind. Reachable from
ordinary SQL, since the scatter is inserted for any window-function sort with a non-empty
PARTITION BY, for hash-sharded merge joins and for distributed shuffle.

CreatingSetsTransform::work() closed its input port, the same violation on the set-building
path.

I moved the port access of both into prepare(), which runs under the graph lock, and left
ExecutingGraph alone: with the contract honoured, the only writers of post_updated_*_ports
run under nodes_mutex, so its write lock is exclusive as designed. The scatter keeps hashing
and IColumn::scatter in work() and hands the chunks over from prepare(), modelled on
CopyTransform; it still refuses to pull a new input chunk before the previous one is fully
handed over, and still skips a finished output. No other work(), onCancel() or
onAsyncJobReady() body in src/ changes port state (a few read a port header, which
never reaches Port::updateVersion).

CI provenance: AST fuzzer (amd_tsan) on
2dc6db1.
Not caused by that PR, which changes no executor file.

ThreadSanitizer report (reproduced locally, TSAN gtest)
WARNING: ThreadSanitizer: data race
  Read of size 8 by thread T4:                 <- holds nodes_mutex (write)
    std::vector<void*>::size() / std::erase_if<...>   libcxx/__vector/{vector,erase}.h
    DB::ExecutingGraph::removeAffectedEdges(...)      Runtime/ExecutingGraph.cpp:156
    DB::ExecutingGraph::removePendingGroup(...)       Runtime/ExecutingGraph.cpp:265
    DB::ExecutingGraph::removeReadyGroups(...)        Runtime/ExecutingGraph.cpp:275
    DB::ExecutingGraph::updateNode(...)               Runtime/ExecutingGraph.cpp:502
    DB::PipelineExecutor::executeStepImpl(...)        Runtime/PipelineExecutor.cpp:379

  Previous write of size 8 by thread T2:       <- holds no lock
    std::vector<void*>::push_back                     libcxx/__vector/vector.h:1165
    DB::ScatterByPartitionTransform::work()           Transforms/ScatterByPartitionTransform.cpp
    DB::ExecutionThreadContext::executeTask()         Runtime/ExecutionThreadContext.cpp:58
    DB::PipelineExecutor::executeStepImpl(...)        Runtime/PipelineExecutor.cpp:356

Also noticed and deliberately not changed: executeJob reads node->back_edges.empty()
without the lock (ExecutionThreadContext.cpp:61) while removeAffectedEdges erases from that
list. It is executor-side rather than a processor-contract violation, has no CIDB occurrence,
and #118393 already replaces that read.


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

groeneai and others added 3 commits September 11, 2026 23:37
IProcessor::work() runs with no graph lock held: PipelineExecutor::executeStepImpl
calls context.executeTask() at PipelineExecutor.cpp:356 and only enters
graph->updateNode at :379. That is why IProcessor.h:189-194 states that work()
cannot access any ports.

Two processors broke that contract. ScatterByPartitionTransform::work() pushed to
its output ports, and OutputPort::pushData -> Port::updateVersion ->
Port::UpdateInfo::update appends to the node's own post_updated_output_ports,
which ExecutingGraph::addEdges wired as that edge's update list. A peer worker
reclaiming a retired processor holds the nodes_mutex write lock and sweeps every
node (removePendingGroup -> removeAffectedEdges), std::erase_if-ing the same
vector. The AST fuzzer reported the resulting data race on amd_tsan; besides the
sanitizer report, a concurrent push_back and erase_if on one std::vector<void *>
can drop or duplicate an edge id or leave a freed Edge * behind. The scatter is
reachable from ordinary SQL: SortingStep::scatterByPartitionIfNeeded inserts it
for any window-function sort with a non-empty PARTITION BY, for hash-sharded
merge joins and for distributed shuffle.

CreatingSetsTransform::work() closed its input port, the same violation on the
set-building path for IN (subquery) and external tables.

Both now do their port work in prepare(), which runs under the graph lock, so
ExecutingGraph needs no change: with the contract honoured, every writer of
post_updated_*_ports runs under nodes_mutex and its write lock is exclusive as
designed. This follows CopyTransform, the contract-conforming fan-out shape.

The scatter keeps the hashing and IColumn::scatter work in work() and hands the
chunks over from prepare(); a single has_output_chunks flag replaces the former
has_data (write-only) and all_outputs_processed pair. prepare() cannot observe a
pulled-but-unscattered chunk, because it only returns Ready right after pulling
and the owning thread runs work() before its next prepare(). Returning PortFull
while chunks are pending preserves the ordering that
optimizeJoinByShards.cpp:549-558 documents as deadlock-relevant: no new input
chunk is consumed until every partition chunk of the previous one is handed over.

CreatingSetsTransform now closes its input one prepare() later on the path that
stops consuming early (the set came from the cache), so the subquery upstream may
produce at most one more chunk, which is discarded when the port closes. That
window already existed between prepare() returning Ready and work() running.
The close cannot be dropped altogether: generate() always returns {}, so
finished_generate is set in the same work() call and the base class returns
through its finished_generate branch, which does not close the input.

An exhaustive scan of the other methods that run outside nodes_mutex found no
further violation: every other void work() body in src/, all 21 onCancel()
overrides, both onAsyncJobReady() overrides and schedule()/scheduleForEvent().

Tests: a TSAN gtest that runs a scatter next to pipeline-update removal churn on
16 threads and reproduces the reported race before the fix; a round-robin case
asserting that a finished output does not wedge the pipeline; and a hash-mode
case asserting that prepare() reports PortFull, rather than consuming another
input chunk, while a scattered chunk is still pending.

Related: ClickHouse#118031
Related: ClickHouse#118393

Co-Authored-By: Claude Opus 5 <[email protected]>
ScatterByPartitionTransform::work() still read the port container via
outputs.size(). IProcessor::inputs/outputs are not universally
construction-immutable: MergeSortingTransform::updatePipeline() appends to
both and IMergingTransformBase::addInput() appends to inputs, and that growth
happens under the nodes_mutex write lock that only prepare() shares. Sizing
the flag vector from the output_size member inside prepare(), where master
and CopyTransform::prepareConsume already do it, removes the last reference
to a graph-owned structure from work().

No behavior change: output_size equals outputs.size() for this processor,
which never grows its own outputs.

Co-Authored-By: Claude Opus 5 <[email protected]>
The executor does not forbid every mention of a port in work(): only a change
of port state reaches Port::updateVersion() and appends to the graph-owned
post_updated_*_ports. Reading a header does not - Port::getHeader() returns
*header off a SharedHeader fixed at construction. Several work() bodies read
port headers, including CreatingSetsTransform::consume() by way of
IAccumulatingTransform::work(), so a categorical "no port access here" claim
is falsifiable in one grep and misstates the invariant a reader has to keep.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent reviewer and a second model reviewed this diff before it was pushed, over two rounds.
Verdicts below; the ones that needed a code change were fixed in this PR, and the re-review of those
fixes found nothing further.

❌ work() still read the port container. was_output_processed.assign(outputs.size(), ...) was left
in ScatterByPartitionTransform::work(). No race for this class (its outputs are fixed at construction),
but IProcessor::inputs/outputs do grow at runtime elsewhere (MergeSortingTransform::updatePipeline,
IMergingTransformBase::addInput) and that growth runs under the same nodes_mutex write lock this fix
relies on. Fixed: the reset moved back into prepare() after the pull, where master and
CopyTransform::prepareConsume have it, so work() now touches no port symbol at all.

❌ The new comments overstated the contract. They said "every port access lives here", which is
falsifiable in one grep: CreatingSetsTransform::consume() reads the input port header, as do four
work() bodies on unmodified master. The enforced invariant is narrower: work() must not change port
state, because only pull, push, close, finish and setNeeded reach Port::updateVersion() and
the graph's post_updated_*_ports, while getHeader does not. Fixed: both comments now say that, and the
same over-claim was narrowed in this PR's description.

❌ The CreatingSetsTransform half had no test that could detect its removal. The new prepare()
override is load-bearing, not defensive: on the set_from_cache early-exit path finished_input and
finished_generate are both set in one work() call, so IAccumulatingTransform::prepare() returns at
its finished_generate branch and never reaches its own input.close(). Without the override the input
stays open and needed while the processor is Finished, and the subquery upstream wedges at PortFull.
The review's own first pass proposed deleting the override as redundant and had to withdraw it, which is
exactly the mistake the missing coverage allows. Fixed: an arm is now recorded in which removing the
override is detected. With the override deleted, 02581_share_big_sets_between_mutation_tasks aborts the
server on Logical error: 'Pipeline stuck' for the cache-hit part tasks (CreatingSetsTransform_2 (Finished) with NumbersRange_0 (PortFull) upstream); it passes in 5.7 s on this PR's tree. For anyone
re-checking that coverage later: use 02581, not 02399_merge_tree_mutate_in_partition. 02399 does
reach the cache-hit branch, but its subquery reads an empty Memory table, so the upstream is already
exhausted and the base class closes the input through its own input.isFinished() path. The wedge needs
an upstream that still has rows to push.

⚠️ Verdict DISAGREE, a TSan oracle for the CreatingSetsTransform half. InputPort::close() bumps
the port version only on the IS_FINISHED 0 to 1 transition, so it appends to the graph's update list at
most once per port lifetime; a single-shot append cannot be driven into a reliable collision the way the
scatter's thousands of pushes can. Covered deterministically instead, per above.

⚠️ Verdict DISAGREE, "prove the concurrency test reddens on the merge-base". It does. On the
unmodified tree with only the test added, ThreadSanitizer fires on iteration 1 with the read side
vector<void*>::size() <- erase_if<..., removeAffectedEdges::$_0> <- removeAffectedEdges <-
removePendingGroup <- removeReadyGroups <- updateNode, and the write side push_back <-
ScatterByPartitionTransform::work() <- executeTask: the reported stack, frame for frame. 200/200
iterations clean after the fix, 283 ms per iteration.

⚠️ Verdict DISAGREE, "the finished-output test passes when the PR is reverted". True, and not the
right liveness test for it: the diff moves the finished-output exclusion into pushOutputChunks(), so the
mutation it must redden against is one applied to the new code. It does, with Logical error: Pipeline stuck. It pins the circular-wait ordering that optimizeJoinByShards.cpp documents.

💡 One open question for the area owner. I kept the changelog category at Not for changelog, on the
precedent of #118031 and because Bug Fix (user-visible misbehavior in an official stable release)
schedules a Bugfix-validation gate that a TSAN-only regression test cannot satisfy. But both sides of this
race are present on the 26.8 release branch (removeAffectedEdges sweeping every node under the
nodes_mutex write lock, and both work() violations), so it is not master-only. If you would rather it
carried a user-facing category, say so and I will change it; and if it should reach 26.8, a label on this
PR once it is merged is the mechanism I would use, not a separate release-branch pull request.

@clickhouse-gh clickhouse-gh Bot closed this Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New TSAN gtest Processors.UpdatePipelineRemovalWithConcurrentScatter: unit_tests_dbms --gtest_filter='Processors.UpdatePipelineRemovalWithConcurrentScatter' --gtest_repeat=200 under TSAN_OPTIONS=halt_on_error=1. Fired on iteration 1 before the fix.
b Root cause explained? work() runs with no graph lock (PipelineExecutor.cpp:356 vs :379), which is why IProcessor.h:189-194 forbids port access there. ScatterByPartitionTransform::work() pushed to its outputs, so Port::UpdateInfo::update() appended to that node's post_updated_output_ports unlocked, while a peer thread erase_if-swept every node's copy of that vector under the nodes_mutex write lock (removePendingGroup -> removeAffectedEdges).
c Fix matches root cause? Yes. The unlocked writer is removed at its source: port access moves into prepare(), which runs under the graph lock. ExecutingGraph is untouched and no guard is added at the crash site.
d Test intent preserved / new tests added? 3 new tests, no existing test weakened. Each new oracle is mutation-verified: the concurrency test reddens on the unfixed tree; the finished-output test reddens (Pipeline stuck) when a finished output is allowed to block the handover; the pending-chunk test reddens when prepare() stops returning PortFull. The CreatingSetsTransform::prepare() half needs no new test: deleting that override makes the existing 02581_share_big_sets_between_mutation_tasks abort the server with Logical error: 'Pipeline stuck' on the cache-hit part tasks, while it passes on this PR's tree.
e Both directions demonstrated? Yes. Scatter: Build-ID d39a8b325ea3a8085a47ba059d96cf2d4f6b3143 (pre-fix) races on iteration 1; Build-ID 8bbbccf8a6f012648af1023fc8450bf05200143d (the tree being merged) is 200/200 iterations, 0 reports. Sets: Build-ID 75339b03b212b6bbac11b90ac33bdaf01ea83797 (override deleted) aborts on 02581_share_big_sets_between_mutation_tasks; Build-ID 49b2803ab165de68bfabfbd1f2b59082c6767337 (this tree) passes it.
f Fix is general across code paths? Yes. Every carrier of the invariant enumerated on this base: all void work() bodies in src/ (only the two fixed ones touch ports), 21 onCancel() overrides (none do), both onAsyncJobReady() overrides (fd/packet work only), schedule()/scheduleForEvent() (fd only). grep post_updated_ finds no reader or writer outside ExecutingGraph.{h,cpp}.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Both scatter modes covered: round-robin (whole chunk to one output, empty-chunk skip, ChunkInfo preserved) and hash partition (row-wise split, every row exactly once), plus the finished-output and zero-output edges.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or metadata change, so no SettingsChangesHistory.cpp entry. prepare() may now return PortFull where it previously returned Ready for a partial push, which is the accurate status for a node holding undeliverable data.
i Invariants and contracts preserved? Yes. No new input chunk is pulled until every partition chunk of the previous one is handed over (the ordering optimizeJoinByShards.cpp:549-558 documents as deadlock-relevant), asserted directly; a finished output never blocks progress; per-output content and push order unchanged (generateOutputChunks untouched); CreatingSetsTransform still closes its input exactly once (InputPort::close() is idempotent).

Session id: cron:clickhouse-impl-slot-6:20260912-010300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @novikd, could you review this? ScatterByPartitionTransform::work and CreatingSetsTransform::work changed port state, so Port::updateVersion appended to the graph-owned post_updated_output_ports with no lock held, while the removal sweep erase_ifs that same vector under the nodes_mutex write lock. Both now do their port work in prepare, so ExecutingGraph needs no change.

@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64ab5b5]

Summary: ✅


AI Review

Summary

This PR moves the remaining port-state mutations out of ScatterByPartitionTransform::work and CreatingSetsTransform::work into prepare(), and adds regression coverage for the scatter race and liveness cases. I did not find a remaining correctness, concurrency, test, or PR-metadata issue in the current diff.

Final Verdict

✅ Looks good to merge.

LLVM Coverage Report

Measured on commit 64ab5b5.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 160/162 (98.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 64ab5b5dc with master 30c98e714 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

14 translation units recompiled, 56 s compile time in total, 14 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
@Michicosun

Copy link
Copy Markdown
Member

@groeneai, how is this related to #118393?

Merged via the queue into ClickHouse:master with commit ebc4cf4 Sep 12, 2026
174 of 344 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog 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