Repository navigation
Fix LOGICAL_ERROR in full_sorting_merge JOIN when sharding stream counts diverge - #109393
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260704-093700 |
|
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 |
|
Workflow [PR], commit [dedf418] Summary: ✅
AI ReviewSummaryThis PR makes the Final Verdict✅ No new findings. LLVM Coverage Report |
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]>
|
Good catch, and fixed in be02341. You are right that I verified the behavior against the pre-fix binary (build
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 ( |
… 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]>
CI finish ledger — f4eb5f1Every 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
Session id: cron:our-pr-ci-monitor:20260704-230000 |
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code |
CI finish ledger - 7777683Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head:
Not caused by this PR. The previous head's two reds are both gone: the PR-caused Session id: cron:our-pr-ci-monitor:20260728-150000 |
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`.
|
Superseded in mechanism. Recording that here rather than acting on it; the disposition is yours. The invariant this pull request merges at the
I am not closing this. |
`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.
|
The
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. |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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.
159e005
No related open issue found.
Changelog category (leave one):
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 mergeJOINwhen 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)@5e67948f8fe5JoinStep::updatePipelineuses the sharded join only while both sides have the same number of streams, and otherwise falls back tojoinPipelinesYShaped. That fallback accepted exactly one port per side and threwLOGICAL_ERRORfor 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
MergingSortedTransformkeyed by the join keys. Those inputs are already sorted by the join keys, so the merge preserves the orderMergeJoinTransformrequires. The sharded path is unchanged.Reproducer on current master, which aborts before this change and returns
20after it: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]