Skip to content

Keep one output port per shard when a JOIN side reads nothing - #115352

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-join-by-shards-pruned-side
Aug 19, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-join-by-shards-pruned-side

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #115057
Related: #109393

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) for a full_sorting_merge JOIN with query_plan_join_shard_by_pk_ranges enabled when one of the two sides is pruned to no parts at all - by the primary key, by column statistics, or because the table is empty.

Description

A JOIN sharded by primary-key ranges pairs the shards of its two sides positionally, so both sides have to produce exactly one output port per layer. optimizeJoinByShards builds the layers from the parts of all the sources at once and hands every source the same number of them, and ReadFromMergeTree::readByLayers keeps the port of an empty layer occupied by substituting a NullSource for it.

That invariant did not hold for a source that reads nothing at all: ReadFromMergeTree::initializePipeline replaced the whole side with a single NullSource before it ever reached the layers. A side pruned to zero parts therefore arrived at the JOIN with one port while the other side kept its layers, the stream counts disagreed, JoinStep stopped using sharding, and the YShaped pipeline it went to instead accepts only a single port per side:

Logical error: 'Join is supported only for pipelines with one output port, got 1 and 2'

The fix emits one NullSource per layer, so the number of ports stays what the plan says it is. The layers are only ever set by optimizeJoinByShards (gated by query_plan_join_shard_by_pk_ranges, off by default) and are ignored for a read coordinated across parallel replicas, so for every other query the pipeline is unchanged.

The comment at the JoinStep fallback claimed that the regular pipeline handles diverging stream counts. That is true for joinPipelinesRightLeft (hash) but not for the merge-join path, and it is what made the missing invariant look intentional, so it is corrected as well.

This replaces the approach in #109393, which merged the diverging streams back together inside joinPipelinesYShaped; @vdimir asked there for the invariant to be fixed at its source instead, which is what this pull request does. The throw in joinPipelinesYShaped is left in place.

Reproducer (the second query is the shape from the CI report - the sharded side keeps its layers while the other side is pruned away):

CREATE TABLE t_l (k UInt64) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 128;
CREATE TABLE t_r (k UInt64) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 128;
INSERT INTO t_l SELECT number FROM numbers(1000);
INSERT INTO t_r SELECT number FROM numbers(1000);

SET query_plan_join_shard_by_pk_ranges = 1, join_algorithm = 'full_sorting_merge', max_threads = 4;

SELECT count() FROM t_l AS l JOIN (SELECT * FROM t_r WHERE k > 1000000) AS r ON l.k = r.k;
SELECT count() FROM (SELECT * FROM t_l WHERE k > 1000000) AS l LEFT JOIN t_r AS r ON l.k = r.k;

How the CI report maps onto this

The failing test in the report is 03447_analyzer_correlated_subqueries_tpc_h (TPC-H Q2), run by the settings randomizer with query_plan_join_shard_by_pk_ranges = 1 and join_algorithm = 'full_sorting_merge'. Replaying that query with the report's own settings, EXPLAIN PLAN indexes=1 shows the sharded join with one side gone:

Join (JOIN YShaped)  part ⋈ partsupp
  Join conditions: p_partkey = ps_partkey
  Sharding: [(p_partkey = ps_partkey)]
  ├── ReadFromMergeTree (part)       Parts: 0 | Granules: 0    <- pruned by the statistics on p_size
  └── ReadFromMergeTree (partsupp)   Parts: 1 | Granules: 1

part is pruned to Parts: 0 and collapses to a single port; partsupp keeps one port per layer.

CI report this starts from:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=172d9bf947f5081ddd3288073fe0cf6be664b924&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29

The stack is one of the most frequent stress and AST-fuzzer failures at the moment: 57 hits of this exact STID 4488-4e11 since 2026-05-27 (5 of them on master), plus 21 more of the two sibling stacks 4488-4590 and 4488-4a91.

Verification

  • The reproducer above, the one from PK-range join sharding: pruned side yields 1 port, non-sharded fallback throws #115057, and the new test 05019_join_shard_by_pk_ranges_pruned_side all abort on a master binary (got 4 and 1) and pass with the fix.
  • The new test also compares the sharded result against join_algorithm = 'hash' with count() plus a cityHash64 checksum for the LEFT/RIGHT cases, where every row of the surviving side reaches the output. This covers the semantics of the padded pipeline, not only the disappearance of the exception.
  • TPC-H Q2 from 03447_analyzer_correlated_subqueries_tpc_h with the report's full settings passes.
  • All 1061 local stateless tests matching join, and the primary-key-sharding tests (03357, 03668, 03774, 04065, 04251, 04517, 04655, 04812), pass.

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

Version info

  • Merged into: 26.8.1.1724 (included in 26.8 and later)

A JOIN sharded by primary-key ranges (`query_plan_join_shard_by_pk_ranges`)
pairs the shards of its two sides positionally, so both sides have to produce
exactly one output port per layer. `optimizeJoinByShards` builds the layers
from the parts of all the sources at once and hands every source the same
number of them, and `ReadFromMergeTree::readByLayers` keeps the port of an
empty layer occupied by substituting a `NullSource` for it.

That invariant did not hold for a source that reads nothing at all:
`initializePipeline` replaced the whole side with a single `NullSource` before
it ever reached the layers. A side pruned to zero parts - by the primary key,
by column statistics, or simply because the table is empty - therefore arrived
at the JOIN with one port while the other side kept its layers. The stream
counts disagreed, `JoinStep` stopped using sharding, and the `YShaped`
pipeline it went to instead accepts only a single port per side:

    Logical error: 'Join is supported only for pipelines with one output port, got 1 and 2'

Emit one `NullSource` per layer instead, so the number of ports stays what the
plan says it is. The comment at the `JoinStep` fallback claimed that the
regular pipeline handles diverging stream counts; that is true for
`joinPipelinesRightLeft` (hash) but not for the merge-join path, so it is
corrected as well.

Found by the CI stress and AST fuzzer jobs, where the settings randomizer
enables `query_plan_join_shard_by_pk_ranges` for 30% of the runs: 57 hits of
this stack since 2026-05-27, 5 of them on master. The report this commit
starts from (`03447_analyzer_correlated_subqueries_tpc_h`, TPC-H Q2, where
`part` is pruned to `Parts: 0` by the statistics on `p_size` while `partsupp`
keeps two layers):

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=172d9bf947f5081ddd3288073fe0cf6be664b924&name_0=MasterCI&name_1=Stress%20test%20%28arm_debug%29
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [286dd88]

Summary: ✅


AI Review

Summary

This PR fixes the query_plan_join_shard_by_pk_ranges merge-join path when one ReadFromMergeTree side is pruned to zero parts by preserving the planned number of output ports instead of collapsing the read to a single NullSource. I did not find a remaining correctness or compatibility issue in the current code: the layered invariant is restored at the source, the parallel-replicas and distributed-read paths still explicitly bypass layered output, the new stateless test covers both predicate-pruned and empty-table cases, and the PR CI is all green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 21/22 (95.45%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 286dd8844 with master 9ca234c82 (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
Binary Master PR Δ
programs/clickhouse-stripped 701.98 MiB 698.95 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, that's clear.

@alexey-milovidov alexey-milovidov self-assigned this Aug 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 19, 2026
Merged via the queue into master with commit 0a03d0a Aug 19, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-join-by-shards-pruned-side branch August 19, 2026 22:15
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

PK-range join sharding: pruned side yields 1 port, non-sharded fallback throws

2 participants