Skip to content

Fix LOGICAL_ERROR in full_sorting_merge JOIN when sharding stream counts diverge - #109393

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-yshaped-join-stream-divergence-sharding
Sep 5, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-yshaped-join-stream-divergence-sharding

Conversation

@groeneai

@groeneai groeneai commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator

No related open issue found.

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 LOGICAL_ERROR (Join is supported only for pipelines with one output port) raised by a merge JOIN when its two sides reached the join with a different number of output ports.

Description

Found by the CI stress and fuzzer jobs, recurring on master across many unrelated runs. Provenance: MasterCI Stress test (experimental, serverfuzz, arm_asan_ubsan, s3) @ 5e67948f8fe5

JoinStep::updatePipeline uses the sharded join only while both sides have the same number of streams, and otherwise falls back to joinPipelinesYShaped. That fallback accepted exactly one port per side and threw LOGICAL_ERROR for anything else, so a plan that left the two sides unequal aborted the query instead of running it.

This makes the fallback usable: a side with more than one stream is merged into a single stream by a MergingSortedTransform keyed by the join keys. Those inputs are already sorted by the join keys, so the merge preserves the order MergeJoinTransform requires. The sharded path is unchanged.

Reproducer on current master, which aborts before this change and returns 20 after it:

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;

The primary-key-range sharding route I originally reproduced was closed upstream by #115352, so the regression test now drives the route above instead. #117826 removes that route's asymmetry in the optimizer; this change keeps the fallback correct for whatever else reaches it.

Regression test 04501_full_sorting_merge_join_shard_stream_divergence, checked against the pre-fix binary (aborts) and against a variant of this change that merges the streams without sorting them (wrong results).


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

…nts diverge

With query_plan_join_shard_by_pk_ranges enabled, a full_sorting_merge JOIN
whose keys are a primary-key prefix is planned for sharding: the pre-join
SortingStep becomes PartitionedFinishSorting and keeps several per-shard
streams on each side. JoinStep::updatePipeline computes
use_sharding = !primary_key_sharding.empty() && streams(L) == streams(R),
so when the two sides end up with a different number of streams (for example
a PREWHERE changes how one side is split into layers) it falls back to the
plain YShaped pipeline. joinPipelinesYShaped then required exactly one stream
per side and aborted the server in debug/sanitizer builds with
"Join is supported only for pipelines with one output port, got N and M".

Merge each side back into a single sorted stream before building the
MergeJoinTransform. The streams are already sorted by the join keys, so a
MergingSortedTransform on those keys preserves the order the merge join needs.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM t AS a ALL INNER JOIN t AS b ON b.c0=a.c0 PREWHERE isNull(a.s) with join_algorithm='full_sorting_merge', query_plan_join_shard_by_pk_ranges=1, enable_analyzer=1, max_threads=8 aborts the debug server every time (three-table self-join variant also).
b Root cause explained? Sharding is planned (primary_key_sharding non-empty via PartitionedFinishSorting, keeps N per-shard streams), but the two sides diverge in stream count, so use_sharding = !empty && streams(L)==streams(R) is false. The YShaped fallback joinPipelinesYShaped required exactly 1 stream/side and threw LOGICAL_ERROR: got N and M.
c Fix matches root cause? Yes. The fallback now merges each side to a single sorted stream (MergingSortedTransform on the join keys) before building MergeJoinTransform, which is exactly what that path needs. No band-aid, no bound widening.
d Test intent preserved / new tests added? New regression test 04501_full_sorting_merge_join_shard_stream_divergence (2-way always-false PREWHERE + 3-way divergent case comparing to hash).
e Both directions demonstrated? Yes. Pre-fix binary (snapshot, ba52cd06) aborts on the repro; post-fix binary (85ddfea0) returns cleanly. 30/30 deterministic passes; results match hash join in a full row-by-row diff (8700 rows) and across max_threads×index_granularity spreads.
f Fix is general across code paths? The joinPipelinesYShaped throw is the single place this class of divergence surfaces for the merge-join path (Paste already resizes to 1). Sibling paths: joinPipelinesRightLeft (hash) already handles unequal streams; joinPipelinesYShapedByShards is only reached when counts match. Root cause fixed at the throw site, not a caller symptom.
g Fix generalizes across inputs? The sorted merge is keyed by the join keys and independent of key datatype/wrappers; verified INNER self-join, 3-way (inner sharded feeding non-sharded outer), and two different-size tables. Correct across max_threads 1/2/8 and index_granularity 1/8/128.
h Backward compatible? Yes. Pure pipeline-build fix, no setting/format/metadata change. Removes a crash; the sharded fast path (equal streams) is untouched.
i Invariants and contracts preserved? Yes. MergeJoinTransform requires one stream per side sorted by the join keys; the added MergingSortedTransform on those keys upholds exactly that (the inputs are already sorted by Sort ... before JOIN), so sort-order and the one-stream-per-side contract hold. Correctness confirmed against hash join.

Session id: cron:clickhouse-worker-slot-1:20260704-093700

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai — could you review this? It fixes a server abort (LOGICAL_ERROR "Join is supported only for pipelines with one output port") in the full_sorting_merge YShaped join path: when query_plan_join_shard_by_pk_ranges plans sharding but the two sides end up with different stream counts, JoinStep falls back to joinPipelinesYShaped which required exactly one stream per side. The fix merges each side to a single sorted stream (by the join keys) before the merge join.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dedf418]

Summary: ✅


AI Review

Summary

This PR makes the full_sorting_merge / parallel_full_sorting_merge YShaped fallback merge divergent multi-stream inputs back to one sorted stream instead of raising LOGICAL_ERROR. I reviewed the current diff, the modified regression test, and all prior discussion and review threads on the current head, and I did not find any remaining correctness, safety, or evidence gaps that warrant a new review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

⚠️ No coverage measurement for commit dedf418: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 4, 2026
The two-way case used PREWHERE isNull(a.s) on a non-nullable String. With
the analyzer, FunctionIsNull::getConstantResultForNonConstArguments folds
isNull() on a non-nullable argument to a constant 0, so the predicate could
be optimized away before the join pipeline is built, making the test stop
exercising the full_sorting_merge stream-divergence path.

Switch to PREWHERE a.c0 > 1000, a range on the primary key that no row
satisfies (max c0 is 299). It is a real column comparison that survives
analysis and is resolved by primary-key range pruning, which fully prunes
one join side to a single stream while the sharded other side keeps several
streams, reproducing the divergence deterministically (verified: aborts on
the pre-fix binary, passes on the fixed one). The three-way case uses the
same primary-key pruning, and a separate non-empty sharded join checks the
result matches the hash join.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch, and fixed in be02341. You are right that isNull(a.s) on a non-nullable String is const-folded under the analyzer (FunctionIsNull::getConstantResultForNonConstArguments returns a constant 0 when use_analyzer is set and the argument type cannot contain null), so relying on it to shape the pipeline is fragile.

I verified the behavior against the pre-fix binary (build ba52cd06, source f9dd12e == current master) via the clickhouse-test harness ([FAIL] pre-fix, [OK] post-fix, 50/50 OK with settings randomization). Two findings worth recording:

  1. Your suggested a.s = '' (and every other data-dependent predicate on s I tried) does not reproduce the crash. EXPLAIN PIPELINE shows both join sides stay sharded (×8) with a.s = '', so use_sharding stays true and the by-shards path is used, no divergence. The isNull fold was actually load-bearing: folding the left PREWHERE to a constant is exactly what pruned the left side down to a single stream while the right stayed at 8 (got 1 and 8).

  2. A range on the primary key reproduces it deterministically and survives analysis. I switched both crash-guard queries to PREWHERE a.c0 > 1000: no row satisfies it (max c0 is 299), so PK range pruning empties one side to a single stream while the sharded side keeps several. This aborts 10/10 on the pre-fix binary (got 8 and 1) and passes on the fixed one. It is a real column comparison, not a constant-foldable expression.

The three-way case now uses the same PK pruning, and a separate non-empty sharded three-way self-join checks the result equals the hash join. Reference is unchanged in spirit (0 / 0 / 1).

… join

The two divergent-path queries in 04501 prune the left side to zero rows, so
the YShaped fallback (the new MergingSortedTransform merge to a single sorted
stream) only runs on an empty side. That proves the exception is gone but not
that the fallback joins rows correctly.

Add a RIGHT join with the same PREWHERE that empties the left (`a`) side and
keeps the sharded right (`b`) side non-empty (8 vs 1 stream). The counts
diverge, so the fallback runs and merges `b`'s several sorted streams into one;
because it is a RIGHT join, every `b` row reaches the output. Compare the row
count and a row-order-independent checksum of the joined columns against the
hash join, which does not use this pipeline, so a duplicate, drop or mis-order
bug in the merge would change the result.

Verified: the new query aborts the pre-fix server (divergence path is hit) and,
with the fix, matches the hash join. cityHash64 sum plus count detect drops,
duplicates and content corruption.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f4eb5f1

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) / 03532_window_function_and_null_source_max_threads flaky (randomized query_plan_optimize_join_order_randomize collapses the crazy-max_threads pipeline so LIMIT_EXCEEDED 290 is not raised; PR-only, 0 master over 30d across ~30 unrelated PRs, unrelated to this PR's full_sorting_merge JOIN fix) #109330 (external, open)
Mergeable Check / PR rollup of the above owned via #109330

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109393&sha=f4eb5f1801698d80c81edad3aea6e3099b24c678&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%202%2F2%29

Session id: cron:our-pr-ci-monitor:20260704-230000

groeneai and others added 3 commits July 28, 2026 04:36
Two gaps in the regression test, each verified by mutation:

The test silently checked nothing whenever the randomized optimize_read_in_order
came up 0, because join sharding is only planned on top of a read-in-order
FinishSorting. Pin it: with optimize_read_in_order = 0 the new plan assertion
below fails.

Every divergent case has one side pruned to zero rows, and once one side is
exhausted the merge join emits the rest of the other without comparing keys, so
the result comparisons passed even with the sorted merge replaced by an
unordered resize(1). The divergence only arises with a side pruned empty, since
any surviving row leaves both sides sharded and equal, so there is no non-empty
fallback case to compare against the hash join; assert the sorted merge in the
plan instead. That assertion fails for the resize(1) mutant.

Making that assertion possible also fixes a real gap: joinPipelinesYShaped
collects the processors it adds so that EXPLAIN PIPELINE shows them, but the new
sorted merge was added through Pipe::addTransform with no collector set, so it
executed while being invisible in the plan.

Also trim the comment on the fix to the local invariant, and drop the misordering
claim from the empty-side case, which cannot observe it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `ParallelReplicas` stateless job enables parallel replicas for every
query (tests/config/users.d/enable_parallel_replicas.xml, installed by
`--parallel-rep`). `optimizeJoinByShards` returns early for a
`ReadFromMergeTree` with parallel reading enabled
(optimizeJoinByShards.cpp:30, `isParallelReadingEnabled()`), so nothing
shards, the stream counts never diverge, and the fallback this test exists to
cover is never reached. `EXPLAIN` confirms it: the plan carries no `Sharding:`
line and reads through `ReadFromRemoteParallelReplicas`.

The four value comparisons still held vacuously there; only the plan-shape
assertion added in 24c26cd noticed, which is what turned silent
non-coverage into a red check.

Verified against a local server configured exactly like the CI job (three
replicas of one shard, parallel replicas enabled by profile): without the pin
the run reproduces the CI diff (line 4, `1` -> `0`); with the pin the plan
regains `Sharding:` on both divergent queries and prints the join-stage
`MergingSortedTransform 8 -> 1`, and the file matches the reference in 32 runs
across `max_block_size` 1..65409. A plain server is unaffected either way.

Also backtick `JOIN` and `YShaped` in the header comment.
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7777683

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.

CI is fully finished on this head: Finish Workflow = success (2026-07-28T15:49:15Z), Config Workflow = success, 174 check-runs, 0 queued or in progress, ingestion buffer elapsed.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / UndefinedBehaviorSanitizer: undefined behavior (STID 0250-4a9f) pre-existing trunk UB, sanitizer builds only: src/Functions/toStartOfInterval.cpp:293:80 runtime error: signed integer overflow in the origin + offset addition of the origin overload, reached with a near-Int64::min DateTime64. Keyed on the source frame rather than the STID bucket, because the bucket is parameter-blind: 87 hits / 73 unrelated PRs / 9 master over 30 days, first seen 2026-06-29. Nothing in the full-sorting-merge-join stream-divergence path this PR touches participates. fixing PR #112045 (external, open)

Not caused by this PR. The previous head's two reds are both gone: the PR-caused 04501_full_sorting_merge_join_shard_stream_divergence failure is fixed in 7777683 (the test was asserting a plan shape that parallel replicas never produces, so the four value comparisons had been passing vacuously), and the AST fuzzer (arm_asan_ubsan) Cannot serialize FutureSetFromSubquery with no query plan did not recur. Fast test, Style check and Build (arm_tidy) are green on this head.

Session id: cron:our-pr-ci-monitor:20260728-150000

alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
When `parallel_sorted_merge` (or `query_plan_join_shard_by_pk_ranges`)
shards a join by primary-key ranges but a data-dependent `PREWHERE`
prunes one side down to a single empty stream at pipeline-building time,
the stream counts diverge and the fallback used to hit the logical error
`Join is supported only for pipelines with one output port`. Merge each
side's per-shard streams (sorted by the join keys) back into one sorted
stream with `MergingSortedTransform` and run the single-stream merge
join, as the algorithm documents. Same approach as #109393, applied at
the `JoinStep` sharding fallback.

Addresses the AI review Blocker on `4daf2d47d0d8`.
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded in mechanism. Recording that here rather than acting on it; the disposition is yours.

The invariant this pull request merges at the joinPipelinesYShaped call site is broken in two
places upstream of that site, which is the objection @ vdimir raised on 2026-08-10.

I am not closing this.

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 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.
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

The Fast test red at 7b22c7538773 was my own regression test, made stale by the master you merged: #115352 pads a nothing-to-read ReadFromMergeTree side with one NullSource per layer, so the primary-key-range route that test drove now keeps equal stream counts on both sides, takes the by-shards pipeline and never reaches joinPipelinesYShaped. Its EXPLAIN PIPELINE assertion went red, and its value assertions started holding on master too.

dedf418a54ac re-aims the test at the route that still reaches the same throw site (a parallel_full_sorting_merge join, where SortingStep::fullSort decides the merge-back per side from that side's own thread budget) and drops the plan-text pin. Three arms on a debug build: pristine master aborts with got 1 and 4 at QueryPipelineBuilder.cpp:373; replacing the sorted merge with an unordered pipe.resize(1) gives wrong results; this branch matches the hash join. 25/25 runs with randomized settings, and the 21 full_sorting plus 4 join_shard stateless tests pass.

No source change: the fix is byte-identical to the revision you approved. I also re-derived the description, whose reproducer was the closed route.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

4 object files changed (+377.93 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/QueryPipeline/QueryPipelineBuilder.cpp.o 356.29 KiB 734.21 KiB +377.93 KiB (+106.08%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into ClickHouse:master with commit 159e005 Sep 5, 2026
344 of 345 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
@rschu1ze

rschu1ze commented Sep 7, 2026

Copy link
Copy Markdown
Member

This PR seems a quickfix, we should not have ignored @vdimir's comment

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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