Repository navigation
Do not access ports from IProcessor::work() - #119577
alexey-milovidov merged 3 commits into
Conversation
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]>
Internal second-model reviewAn independent reviewer and a second model reviewed this diff before it was pushed, over two rounds. ❌ ❌ The new comments overstated the contract. They said "every port access lives here", which is ❌ The
💡 One open question for the area owner. I kept the changelog category at |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260912-010300 |
|
cc @Michicosun @novikd, could you review this? |
|
Workflow [PR], commit [64ab5b5] Summary: ✅
AI ReviewSummaryThis PR moves the remaining port-state mutations out of Final Verdict✅ Looks good to merge. LLVM Coverage ReportMeasured on commit 64ab5b5.
Changed lines: Changed C/C++ lines covered: 160/162 (98.77%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units14 translation units recompiled, 56 s compile time in total, 14 of them have a recent master baseline. |
ebc4cf4
Related: #118031
Related: #118393
Changelog category (leave one):
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:
PipelineExecutorcallsexecuteTask()atPipelineExecutor.cpp:356and only entersgraph->updateNodeat:379. Two processors breakthat contract, and one of them was caught by the AST fuzzer:
ScatterByPartitionTransform::work()pushed to its output ports.OutputPort::pushData->Port::updateVersion->Port::UpdateInfo::updateappends to that node's ownpost_updated_output_ports, which the executorerase_if-scans for every node under thenodes_mutexwrite lock while reclaiming a retired processor(
ExecutingGraph::removePendingGroup->removeAffectedEdges). The result is a concurrentpush_back/erase_ifon onestd::vector<void *>: reported as a ThreadSanitizer data race,and able to drop or duplicate an edge id, or leave a freed
Edge *behind. Reachable fromordinary 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-buildingpath.
I moved the port access of both into
prepare(), which runs under the graph lock, and leftExecutingGraphalone: with the contract honoured, the only writers ofpost_updated_*_portsrun under
nodes_mutex, so its write lock is exclusive as designed. The scatter keeps hashingand
IColumn::scatterinwork()and hands the chunks over fromprepare(), modelled onCopyTransform; it still refuses to pull a new input chunk before the previous one is fullyhanded over, and still skips a finished output. No other
work(),onCancel()oronAsyncJobReady()body insrc/changes port state (a few read a port header, whichnever reaches
Port::updateVersion).CI provenance:
AST fuzzer (amd_tsan)on2dc6db1.Not caused by that PR, which changes no executor file.
ThreadSanitizer report (reproduced locally, TSAN gtest)
Also noticed and deliberately not changed:
executeJobreadsnode->back_edges.empty()without the lock (
ExecutionThreadContext.cpp:61) whileremoveAffectedEdgeserases from thatlist. 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]