Skip to content

Do not narrow a pipe that contains a fan-out which must push to all of its outputs - #121227

Merged
nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:pipeline-stuck-narrow-scatter-fanout
Sep 30, 2026
Merged

nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:pipeline-stuck-narrow-scatter-fanout

Conversation

@groeneai

@groeneai groeneai commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121125

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 Pipeline stuck logical error when a query combined a merge join using join_algorithm = 'parallel_full_sorting_merge' with a step that glues independent streams together, such as reading from a Merge table, or a UNION ALL narrowed by max_streams_for_union_step. Such a query now runs instead of failing.

Description

narrowPipe glues independent streams behind a ConcatProcessor to keep the number of open sources down, and that Concat demands its inputs one at a time: only the current input is marked needed, advancing when that one finishes. A ScatterByPartitionTransform has the opposite requirement: it cannot take its next chunk until every output has accepted a share of the current one.

Put one above the other and they deadlock. The lanes feeding the Concat's later inputs are never demanded, so the scatter cannot hand over those shares and parks in PortFull, where it can neither pull nor finish; the lane the Concat is waiting on is fed by the same scatter, so it never finishes either. PipelineExecutor then throws Pipeline stuck for a valid query, aborting a debug or sanitizer build. ReadFromMerge narrows its streams, so a Merge table or merge() over a view whose body holds a sharded join reaches this with no unusual setting; max_streams_for_union_step reaches it through UnionStep.

narrowPipe now returns early when any processor in the pipe answers a new IProcessor::requiresAllOutputsPushable(), overridden by the three processors carrying that contract: ScatterByPartitionTransform, CopyTransform and ForkProcessor.

The guard is per pipe, not per port, so a pipe holding such a fan-out is left wide even where the fan-out sits under a ResizeProcessor and could not wedge. Separating those cases would turn ResizeProcessor demanding all of its inputs into a deadlock-safety guarantee instead of an implementation detail. Narrowing bounds open sources and memory and is never a correctness requirement; both call sites already suppress it conditionally.

The new test aborts 10/10 without the fix and passes 10/10 with it, reverting only the guard returns it to red, and a negative control asserts a pipe with no fan-out is still narrowed.

Found by CI on #121125, Stress test (amd_debug) @ d8d2fdd31141bcfecd558d690da6d35f21c98c31.


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

Version info

  • Merged into: 26.10.1.1113-master (included in 26.10 and later)

…f its outputs

narrowPipe glues independent streams behind a ConcatProcessor to keep the
number of open sources down. A ConcatProcessor demands its inputs strictly
one at a time: it calls setNeeded() on the current input only, and advances
when that input finishes. A ScatterByPartitionTransform has the opposite
requirement: pushOutputChunks() leaves all_outputs_processed false for any
non-finished output with a non-empty share whose canPush() is false, and
prepare() then returns PortFull, so the scatter cannot take its next chunk
until every output has accepted a share of the current one.

Put one above the other and they deadlock. The lanes feeding the Concat's
later inputs are never demanded, so their prepare() is never called at all
(state NotStarted); the scatter cannot push those shares and parks in
PortFull, where it can neither pull nor finish; so the lane the Concat is
waiting on never finishes either, and the Concat never advances to the next
input. PipelineExecutor::finalizeExecution then throws Pipeline stuck.

This is reachable without any unusual setting beyond the join algorithm:
ReadFromMerge::readFromMerge narrows the streams of the tables it reads, so
a Merge table or merge() over a view whose body contains a sharded merge
join hits it, and max_streams_for_union_step reaches it through UnionStep.
A window function with PARTITION BY builds the same fan-out, though the
Resize the window step places above it keeps that path awake in practice.

Decline to narrow such a pipe. narrowPipe returns early when any processor
in the pipe answers the new IProcessor::requiresAllOutputsPushable(),
overridden by the three processors carrying that contract:
ScatterByPartitionTransform, CopyTransform (the GROUPING SETS copier, with
byte-identical accounting in prepareGenerate) and ForkProcessor (identical
accounting, no users today, so the override states the contract).
ResizeProcessor moves data between any ready pair and has no such contract.

Narrowing is a memory and file-handle optimization, never a correctness
requirement, and both call sites already suppress it conditionally
(should_not_narrow in StorageMerge, allow_narrowing in UnionStep), so this
is a third reason in the shape the code already has; the pipeline simply
stays wide, which is what the same query already gets when either existing
suppression fires. Buffering the un-pushable shares inside the scatter was
rejected as unbounded memory, the design already refused for the
BufferedShardByHashTransform family; making Concat demand all of its inputs
would delete the optimization it exists for.

The comment in optimizeJoinByShards that excluded the full-sort path from
this deadlock class is corrected: the drain it relies on only helps a lane
that some consumer has already demanded.

Found by CI on ClickHouse#121125, Stress test (amd_debug) at commit
d8d2fdd.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 20, 2026
@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; 1 gate finding plus 5 from my own
cold review; bounded: 1 full pass + 1 fix round + 1 delta recheck). No source line changed during
review.

# Sev Finding Verdict Evidence / action
1 ⚠️ DelayedJoinedBlocksTransform carries the same all-outputs contract and is left unmarked, so a narrowPipe Concat could starve it (src/Processors/Transforms/JoiningTransform.cpp:568-581) DISAGREE The Concat is never what demands those lanes. Every path that builds this transform ends with an unconditional left->resize(num_streams) (QueryPipelineBuilder.cpp:723, :739), and Pipe::resize with default arguments always inserts a ResizeProcessor there (its skip needs numOutputPorts()==1 && num_streams==1, while that pipe has 2*num_streams ports). ResizeProcessor::prepare latches is_reading_started and then marks every input needed the first time any single output is pushable (ResizeProcessor.cpp:57-62), so the fan-out's lanes stay demanded whichever output the Concat has reached. The sibling case was measured: a scatter under the window path, likewise resized above, does not wedge on the unfixed tree, 0/10 directly and through merge(). Marking it anyway would suppress narrowing for nearly every JOIN pipe, since max_bytes_ratio_before_external_join defaults to 0.5 and makes the default hash algorithms a SpillingHashJoin, whose hasDelayedBlocks() is unconditionally true (SpillingHashJoin.h:107)
2 💡 DelayedJoinedBlocksTransform and DelayedPortsProcessor are missing from the invariant-carrier enumeration, which was built by grepping for the accounting vectors DISAGREE Same reason as 1, so the code is right; recording them here instead. DelayedPortsProcessor should stay unmarked on its own merits too: in its gate shape (assert_main_ports_empty=true, used by CreatingSets, MaterializingCTE, ReadFromMemoryStorage) it always marks its output-less gate inputs needed (DelayedPortsProcessor.cpp:129-137), so it cannot starve, and marking it would disable narrowing for every query with a set or CTE gate
3 💡 The guard is per pipe, so it also fires where the fan-out could not wedge (window PARTITION BY, and GROUPING SETS via AggregatingStep.cpp:468 with the unconditional resize at :561) DISAGREE Scoping it would turn ResizeProcessor's latch into a deadlock-safety guarantee rather than an implementation detail, so a later change that demanded inputs lazily would reopen the deadlock with no test to catch it. Stated in the PR description instead of left for a reviewer to find. Happy to narrow it if you would rather pay that coupling
4 💡 The draft changelog entry named a window function with PARTITION BY as a producer of the failure, which was measured not to wedge AGREE, corrected before publication The entry now names only the merge join. The window vector is still covered by the guard, and its EXPLAIN assertion in the test reddens if the guard is removed, but it was never a second deadlock vector
5 💡 The description did not state what the guard costs AGREE, corrected before publication The trade-off is now in the description, within the same length
6 💡 Does any PR text claim GROUPING SETS was deadlocking? DROPPED It does not. CopyTransform is declared for the contract, like ForkProcessor; its one narrowable user is resized above, and its other two are on a sink path where a pipe cannot be narrowed

Also checked and clean: both narrowPipe callers tolerate a pipe wider than the requested width;
the other three ConcatProcessor sites cannot be fed by a marked fan-out (totals ports, one
table read, single-port exchange pipes); ResizeProcessor, StrictResizeProcessor, the
fractional and negative limit and offset transforms, DroppingTransform and LimitTransform were
each read and carry no such contract; the early return cannot change results, since narrowPipe
regroups streams and does not preserve order; query 1 of the test is red without the fix for a
structural reason rather than a lucky shuffle, because max_streams_for_union_step = 1 puts every
port in one Concat; and every setting the test's oracles depend on is pinned per query, so the
CI settings randomizer cannot reach them.

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-review-slot-10:20260920-180109

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation (a-i)
# Check Result
a Deterministic repro 10/10 abort without the fix, one exact command; pipeline structure asserted (ScatterByPartitionTransform + Concat both present) before executing anything
b Root cause explained ConcatProcessor demands inputs one at a time; ScatterByPartitionTransform cannot consume again until every output accepted a share. narrowPipe puts the first above the second, so undemanded lanes never start, the scatter parks in PortFull, and the lane the Concat waits on never finishes
c Fix matches root cause Guard sits where the illegal topology is created; narrowPipe is the only place that glues independent streams behind a Concat. No widened bound, no no-random-* tag, no check at the throw site
d Test intent preserved, test added No existing test weakened; 04051_max_streams_for_union_step, which asserts Concat in EXPLAIN PIPELINE, stays green. New test has 3 reddening oracles plus a negative control
e Both directions 10/10 red without, 10/10 green with, stdout byte-exact. Reverting only the guard and keeping the predicate returns it to 10/10 red; restoring it rebuilds bit-identically
f General across code paths Predicate on IProcessor, so it covers all three processors with this contract (ScatterByPartitionTransform, CopyTransform, ForkProcessor); ResizeProcessor has no such contract. All four ConcatProcessor construction sites audited; both narrowPipe callers go through QueryPipelineBuilder::narrow, so one guard covers both
g Generalizes across inputs Not a data-typed fix: no column, value or type is read. The parameter that matters is the shard and port count, exercised at 4 shards over 8 ports and at the degenerate width-1 Concat
h Backward compatible No setting, no default change, no serialization change, nothing for SettingsChangesHistory.cpp. A pipe with such a fan-out keeps more streams, the same fallback the call sites already take when their existing suppressions fire
i Invariants and contracts The new virtual is const and returns a constant, so it cannot perturb port state or scheduling; the early return happens before any port is touched, so the pipe is left exactly as passed, on every path

Also: the original CI statement and the merge() vector were both reproduced and are both fixed. 63-test regression set run on both trees, identical outcome (4 pre-existing environment failures, byte-identical output on both). 50 runs with randomized settings and 50 without, all green.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5fafe0]

Summary: ✅


AI Review

Summary

This PR teaches narrowPipe to leave a pipe wide when it already contains a fan-out that cannot make progress while any downstream lane is undemanded, which matches the ConcatProcessor deadlock described in the PR. I checked the touched processors, the two narrowPipe call sites, the remaining ConcatProcessor construction sites, and the prior discussion thread; the current code is consistent with the intended invariant, and the added regression test plus negative control are sufficient for this change. I did not find any remaining correctness, safety, or compatibility issues.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit c5fafe0.

Metric Baseline Current Δ
Lines 88.20% 88.10% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 79.50% 79.40% -0.10%

Changed lines: Changed C/C++ lines covered: 12/14 (85.71%) · 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 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dffd2c7

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
Build profile diff infra, not reachable from this diff: the job aborts before it emits any leaf, with RuntimeError: CI logs cluster query failed after requests.exceptions.ReadTimeout on t6h0zvqlgy.us-east-2.aws.clickhouse-staging.com (job 106197587130) #121048 (external, open); #118708 (ours, open)

PR is the praktika rollup and carries no failure of its own: it is red only because the
Build profile diff leaf above is. Mergeable Check, Finish Workflow and CH Inc sync are
all green on this head.

Measured on this head: 176 contexts, 156 SUCCESS / 18 SKIPPED / 2 FAILURE, and CIDB records
zero FAIL/ERROR test rows, consistent with the job aborting in Python before emitting leaves.

Session id: cron:our-pr-ci-monitor:20260921-050309

@nickitat
nickitat enabled auto-merge September 30, 2026 21:38
@nickitat
nickitat added this pull request to the merge queue Sep 30, 2026
Merged via the queue into ClickHouse:master with commit e1a19d4 Sep 30, 2026
348 of 349 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 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-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default 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