Skip to content

Fix Join is supported only for pipelines with one output port in a parallel_full_sorting_merge join - #117826

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parallel-full-sorting-merge-join-stream-divergence
Nov 10, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-parallel-full-sorting-merge-join-stream-divergence

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117229 (comment)

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 the exception Join is supported only for pipelines with one output port when join_algorithm = 'parallel_full_sorting_merge' is used with max_threads greater than one and the two sides of the join are planned with different thread budgets, for example when one side is a subquery with a trivial LIMIT and the other is a UNION ALL. The same defect also silently disabled the sharded join when both sides were limited to a single thread.

Description

Found by the in-stress AST fuzzer on Stress test (arm_msan) of #117229:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117229&sha=857ef8062ab13fe7870b03d3735acc1303c60b4b&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Reproducer:

SELECT count() FROM (SELECT number FROM system.numbers LIMIT 10) AS l
INNER JOIN (SELECT number FROM system.numbers LIMIT 10
            UNION ALL
            SELECT number FROM system.numbers LIMIT 10) AS r ON l.number = r.number
SETTINGS join_algorithm = 'parallel_full_sorting_merge', max_threads = 4;

On released 26.8.2.7 this is Code: 49 ... got 1 and 4; debug and sanitizer builds abort.

Root cause. optimizeParallelFullSortingMergeJoin scatters both sides into a fixed scatter_partitions, and the join pairs the shards positionally, so each side must keep one stream per shard. SortingStep::fullSort instead decided its final merge from pipeline.getNumThreads, a per-side budget: a trivial-LIMIT subquery gets one thread, a UNION ALL side the sum of its branches. The one-thread side merged back to a single port, the counts diverged, use_sharding was dropped, and joinPipelinesYShaped threw.

The change. Skip that merge when the sort is a fixed-shard-count scatter (src/ +4/-1, one function) - the missing half of 49c76044b106ac5, which made the scatter width use scatter_partitions rather than the thread count. This is the other-layer fix @ vdimir asked for on #109393 rather than the call-site merge he declined there; #115352 closed the primary-key-range route, so #109393 is superseded; its disposition is for its reviewers.

Validation. Both directions on one tree; every statement of the new test 05059 reddens pre-fix or holds as a control; 50/50 sequential and self-parallel green; the 21 existing parallel_full_sorting_merge tests plus the scatter, window and EXPLAIN-shape tests are byte-identical on both binaries. The parallel_full_sorting_merge_join performance test may move, as one-thread sides now shard.

Alternatives considered and rejected
  • Merge the two sides at the joinPipelinesYShaped call site - Fix LOGICAL_ERROR in full_sorting_merge JOIN when sharding stream counts diverge #109393's current diff, declined by @ vdimir; repairs the consumer and leaves the sharding silently off.
  • Resize both sides to one port in JoinStep::updatePipeline when the counts diverge - same objection one step earlier, and that function treats divergence as an inconsistent plan rather than a case to absorb.
  • Skip the scatter when a side's thread budget is one - produces the same divergence with fewer processors, so it does not fix the exception.
  • Refuse to shard at plan time when a side would be single-threaded - not implementable: the budget is computed while the pipeline is built, long after the optimizer runs.
  • Raise that side's budget to scatter_partitions after scattering - would also remove the merge and would run the shards in parallel, but it overrides a budget that was deliberately lowered, changing the resource profile of queries that are not broken. The port count is the contract; the budget is a separate decision, so I left it out of this fix.

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

Version info

  • Merged into: 26.11.1.1790-master (included in 26.11 and later)

groeneai and others added 2 commits September 3, 2026 04:26
`optimizeParallelFullSortingMergeJoin` converts both pre-join sorts with
`convertToScatteredFullSort`, whose contract is one sorted stream per shard
with no final merge, so that the two sides present the same number of ports.
`JoinStep::updatePipeline` relies on that, because it pairs the shards of the
two sides positionally.

`SortingStep::fullSort` decided its final merge from `pipeline.getNumThreads`,
which is a per-side budget rather than a property of the shared plan: a
single-table subquery with a trivial `LIMIT` is planned with one thread, while
a `UNION ALL` side is re-budgeted to the sum of its branches. The one-thread
side therefore merged its shards back into a single port while the other kept
them, the counts diverged, `use_sharding` was dropped, and the single-port
fallback `joinPipelinesYShaped` threw `Join is supported only for pipelines
with one output port`. On a release build the query fails with `Code: 49`;
in debug and sanitizer builds the server aborts. Reachable on the released
26.8.

The same line had a second effect: when both sides were limited to one thread
the merge fired on both, the counts stayed equal, and the sharded join the
optimizer had asked for was silently replaced by a single merge join.

Skip the merge when the sort is a fixed-shard-count scatter. This completes
49c7604, which changed the scatter width from the thread count to
`scatter_partitions` but left the merge-back condition consulting the thread
count. A plain sort and a window-frame partitioned sort are unaffected, since
both have `scatter_partitions` equal to zero.

Found by the in-stress AST fuzzer on the `Stress test (arm_msan)` run of
ClickHouse#117229.

Co-Authored-By: Claude Opus 5 <[email protected]>
…d count

The preceding commit dropped the `pipeline.getNumThreads() == 1` clause from
the final merge condition in `SortingStep::fullSort`. That clause is what makes
a window-frame partitioned sort merge its sorted streams into one when the
pipeline is limited to a single thread, so without it such a sort keeps several
output ports and the step no longer produces the single stream its consumer
expects.

Only the `scatter_partitions == 0` guard belongs there. A fixed-shard-count
scatter must keep one stream per shard; every other partitioned sort keeps the
behaviour it had before.

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 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: 0 blocking findings

An independent cold review and a second-model gate over the whole diff both came back with nothing
blocking. Two things worth a reader's time:

Why six statements for a one-line fix. Each covers a different scenario, none repeats another:
1 and 2 are the two port-count orientations (both appear in CI history); 3 is the wrong-results
oracle, since a fix that only stopped the exception would still pass 1 and 2; 4 and 5 are the two
pipeline shapes, 5 being the silent loss of sharding the changelog also mentions; 6 is the guard
against widening the condition too far, and it is the only statement an over-wide variant reddens.

Both planners, and the one randomized setting that could have moved the plan. The test's output
is byte-identical with enable_analyzer 0 and 1, and with
optimize_sorting_by_input_stream_properties 0 and 1, so it needs no tag and covers the old
interpreter too.

Nit I left alone: the new comment is three lines against one changed condition.

@clickhouse-gh clickhouse-gh Bot closed this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c085219]

Summary: ✅


AI Review

Summary

The change preserves one sorted stream per hash shard in SortingStep::fullSort, even when the two sides of a parallel_full_sorting_merge join have different thread budgets. Ordinary and window partition sorting retain their existing merge behavior. No actionable findings.

Missing context / blind spots
  • ⚠️ CI for the current head, c08521956d9ccf653d8954e31e88b6c5fb0195e3, is still pending. The new regression test passed in the preceding head's stateless run. No local ClickHouse binary was available for an independent run; current-head stateless results would close this validation gap.
Final Verdict

Status: ✅ Approve. No code changes requested.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @antaljanosbenjamin, could you review this? This is the other-layer fix for the invariant discussed on #109393: SortingStep::fullSort decided its final merge from pipeline.getNumThreads, a per-side budget, so one side of a parallel_full_sorting_merge join merged its shards back into a single port while the other kept them, and the single-port fallback then threw. The PR body has a deterministic reproducer and the released-version behaviour.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c08521956 with master b29785d13 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9817e7dad; 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

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

Job report

@vdimir vdimir self-assigned this Sep 3, 2026
/// of its two sides positionally, and the thread count is a per-side budget, not a shared contract.
/// If there are several streams, then we merge them into one
if (pipeline.getNumStreams() > 1 && (partition_by_description.empty() || pipeline.getNumThreads() == 1))
if (scatter_partitions == 0 && pipeline.getNumStreams() > 1

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.

Wouldn't merging all partitions break the whole idea of partitioned sorting and joining?

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.

The condition moved the other way: scatter_partitions == 0 && means a fixed-shard scatter no longer merges its shards back, so one sorted stream per shard now survives into the join. Merging them was the bug: one side ended at 1 output port and the other at 4, use_sharding dropped in JoinStep::updatePipeline, and joinPipelinesYShaped threw got 1 and 4.

After the change the merge fires exactly when the scatter did not partition the streams. scatterByPartitionIfNeeded takes threads = scatter_partitions > 0 ? scatter_partitions : pipeline.getNumThreads() and scatters only when threads > 1, so:

  • partition_by_description empty, or non-empty with getNumThreads() == 1: the scatter did not run, so the streams are not partition-disjoint and merging them is what keeps each window partition contiguous. Both unchanged, and the last statement of the test guards the second one: on a build with the getNumThreads() == 1 clause removed it goes from 1 0 to 0 0, i.e. two non-disjoint streams left unmerged.
  • non-empty with getNumThreads() > 1: scattered by the thread count, one stream per partition, unchanged.
  • scatter_partitions > 0: always scattered into scatter_partitions shards, since optimizeParallelFullSortingMergeJoin returns early on num_shards <= 1 and skipScatterByPartition excludes isSortingForMergeJoin. Those are the shards the join pairs positionally, so they must not be merged.

So the merge only collapses streams that were never partitioned, and both join sides now keep the same shard count whatever their per-side thread budget is. That also fixes the quieter half: with both sides at one thread the sharding was collapsed into a single merge join instead of throwing, which the fifth statement in the test covers.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2657185

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
Docs examples / Function/timeSeriesPrometheusValueToString#0 trunk-side and not reachable from this diff: the documented output box for SELECT timeSeriesPrometheusValueToString(toFloat64(1e-7)) is one character wider than the box the server prints, so the check fails on every tree carrying it #117827 (external, merged 2026-09-03T09:33:59Z), measured ABSENT from this failing tree, so merged master @ 0518a97 to pick it up
CH Inc sync - CH Inc sync (private, not actionable by me)

The rest of the run was clean: 170 check-runs, Config Workflow, Style check and Finish Workflow
all success, 150 praktika nodes OK and 0 dropped, and one non-green CIDB row against a control of
274602. Mergeable Check named Docs examples as its only blocker, so the master merge above is
what clears it.

Session id: cron:our-pr-ci-monitor:20260903-113000

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0518a97

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.

170 check runs: 150 success, 19 skipped, 1 failure.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) job wall-clock timeout, not a test failure: the shard was SIGTERMed at timeout [9000] with exit code -15 after 8991 of 13444 tests, every one of the last 30 reported [ OK ], and the job wrote no Failed: summary. LLVM Coverage was dropped as its dependent step. #116209 (ours, open)

#116209 splits this exact job into two batches (AsyncInsert, s3 storage, parallel, 1/2 and 2/2) in both pull_request.yml and master.yml, so it removes the single-leg 9000 s budget this run exceeded.

Session id: cron:our-pr-ci-monitor:20260903-180000

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 5, 2026
`Keep one output port per shard when a JOIN side reads nothing` (ClickHouse#115352)
pads a nothing-to-read `ReadFromMergeTree` side with one `NullSource` per
layer, so the primary-key-range sharding route this test drove no longer
leaves the two join sides with different stream counts. The query now takes
the by-shards pipeline (`MergeJoinTransform` x 8) and never reaches
`joinPipelinesYShaped`, so the `EXPLAIN PIPELINE` assertion that looked for
the merge went red while the four value assertions started holding on
master as well.

Point the test at the route that still reaches the same throw site. A
`parallel_full_sorting_merge` join scatters both sides into a fixed number
of shards and pairs those shards positionally, but `SortingStep::fullSort`
decides the merge back into one stream per side from that side's own thread
budget, so a trivial-`LIMIT` side collapses to one port while a `UNION ALL`
side keeps its shards.

Three arms on a debug build of this branch, comparing against the hash join:

  pristine master 2f4969d          aborts, `got 1 and 4` at
                                        QueryPipelineBuilder.cpp:373
  sorted merge replaced by an
  unordered `pipe.resize(1)`            0, wrong results
  this branch (build id fae830443...)   1

The middle arm is what the removed `EXPLAIN PIPELINE` assertion covered,
and it covers it without pinning the plan text, so the test also survives
the optimizer-side fix in ClickHouse#117826. 25/25 runs with randomized settings; the
21 `full_sorting` and 4 `join_shard` stateless tests pass, including
`05019_join_shard_by_pk_ranges_pruned_side` from ClickHouse#115352.

The `no-random-merge-tree-settings` tag and the explicit `SET`s are gone
with the table: nothing the runner randomizes reaches the new query, whose
settings are pinned per statement.

No source change: the fix is byte-identical to the approved revision.
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Dear @vdimir, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@alexey-milovidov alexey-milovidov 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.

At least I see no flaws in it.

@alexey-milovidov alexey-milovidov self-assigned this Nov 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 9, 2026
Merged via the queue into ClickHouse:master with commit 4e08dbd Nov 10, 2026
180 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

It was merged today by @ alexey-milovidov (merge commit 4e08dbd), so nothing is left to decide here. On master 41a73dec, the reproducer from the description returns 20 instead of the Join is supported only for pipelines with one output port logical error.

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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants