Repository navigation
Fix ScatterExchangeStep crash on a multi-bucket source (make_distributed_plan over Merge of Distributed) - #108401
Conversation
ScatterExchangeStep::createSinkAndSourcePair rejected any source with more than one bucket with a LOGICAL_ERROR. This is reachable from SQL: aggregating over a Merge table whose children are Distributed tables crashed the server with 'ScatterExchangeStep should have one source shard, got 8' when make_distributed_plan=1 (issue ClickHouse#107946). StorageMerge::ReadFromMerge builds its children at a post-FetchColumns stage and converts each child plan to a distributed plan on its own (ReadFromMerge::buildPipeline -> QueryPlan::buildQueryPipeline -> convertToDistributed). The per-child plan therefore carries a ScatterExchange above an already-bucketed distributed read, so the scatter sees several source buckets (distributed_plan_default_reader_bucket_count, 8 by default) and the assertion aborts the server. Scatter is documented as a special case of Shuffle whose source bucket count is 1, and it already reuses ShuffleSend/ShuffleReceive as its sink/source. Neither step requires a single source bucket: ShuffleSend runs per source bucket and ShuffleReceive reads every source bucket for its destination bucket. So when the source happens to expose several buckets, the same pair correctly repartitions all source buckets into the requested result buckets, i.e. behaves as a plain shuffle - which is exactly what optimizeExchanges already does when it rewrites a Scatter over a Gather into a ShuffleExchange. Drop the assertion and let the multi-bucket source flow through. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-1:20260624-162039 |
|
cc @davenger @KochetovNicolai — could you review? |
|
Workflow [PR], commit [b9d94d5] Summary: ✅
AI ReviewSummaryThis PR fixes the original Findings
Tests
Final Verdict
|
…on test The CI test profile (tests/config/users.d/limits.yaml) sets max_rows_to_group_by to 10G, and make_distributed_plan rejects aggregation with a non-zero limit (Code 344, SUPPORT_IS_DISABLED). That fired before the query could reach the ScatterExchangeStep path, so the Fast test for this regression failed without exercising the fix. clickhouse-test also randomizes prefer_localhost_replica. With it set to 0 the Distributed engine serializes the per-child plan to the localhost replica, where the experimental BlocksMarshalling step is not deserializable (Code 47, UNKNOWN_IDENTIFIER). That path is unrelated to the crash, which happens earlier while building the per-child plan. Pin both settings so the query deterministically reaches the multi-bucket ScatterExchangeStep. EXPLAIN distributed=1 confirms the per-child plan still carries a ShuffleExchange over a bucketed ReadFromMergeTree (the step that threw 'should have one source shard, got 8' before the fix), so crash-path coverage is preserved. 20/20 runs pass under full CI randomization. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Fixed the Fast test failure on the new regression test ( Two CI-environment settings masked the crash path:
Session id: cron:clickhouse-worker-slot-4:20260624-181800 |
Pin distributed_plan_max_rows_to_broadcast = 0 and distributed_plan_default_reader_bucket_count = 3 so the distributed read is neither broadcast nor single-bucket, which guarantees the per-child scatter sees a multi-bucket source and the removed guard is actually exercised (verified: the test fails with the pre-fix binary and passes with the fix). Add a non-empty assertion through the same Merge over Distributed topology, filtering on the real underlying table names that _table exposes, so the test proves rows survive the multi-bucket scatter, not only that the no-row reproducer no longer throws. Reword 'crashed the server' / 'survive' / 'abort' to 'raised the LOGICAL_ERROR exception' / 'throw', since release builds throw an exception rather than crash. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Updated the regression test and exception wording per the two review comments. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260624-231100 |
CI finish ledger - 789c2ede1116Every 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
No PR-caused failure on this head. (The earlier Session id: cron:our-pr-ci-monitor:20260625-030000 |
…atter-multishard-merge-107946
The tryMakeDistributed* transforms are not idempotent, and StorageMerge child plans and set subplans are optimized more than once. The second pass wrapped the same aggregation or join step again, stacking a second layer of exchanges on the plan and breaking it at split time. Co-Authored-By: Claude Fable 5 <[email protected]>
Every destination bucket of a BroadcastExchange receives a full copy of the input, so feeding those buckets into another exchange would send the same rows once per copy. Track this property of the fragment task set during the plan split and throw instead of building a plan that duplicates rows. Co-Authored-By: Claude Fable 5 <[email protected]>
…duplication Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
| }); | ||
| } | ||
|
|
||
| /// Some plans are optimized more than once (e.g. StorageMerge child plans, set subplans). The |
There was a problem hiding this comment.
This guard is now the only proof point for the set subplans half of the fix, but the added regressions only cover StorageMerge (04367, 04613). I could not find a make_distributed_plan test that actually goes through DelayedCreatingSetsStep::makePlansForSets and then re-enters plan->buildQueryPipeline(...) for a runtime set (GLOBAL IN / IN (SELECT ...)).
Since that is the other known double-optimization path called out in the PR description, we are still shipping the broader contract without a regression that would fail if set plans keep stacking a second exchange layer. Please add a focused runtime-set reproducer here, or narrow the claim back to the StorageMerge path that is actually covered.
Co-Authored-By: Claude Fable 5 <[email protected]>
| "make_distributed_plan does not support WITH TOTALS, ROLLUP, CUBE or extremes"); | ||
| /// Reject reads whose coordinator snapshot/part-order state a worker cannot reproduce. | ||
| if (optimization_settings.make_distributed_plan) | ||
| if (make_distributed_plan) |
There was a problem hiding this comment.
This also gates the validation pass, and that breaks the StorageMerge read-in-order path.
optimizeReadInOrder builds the ReadFromMerge child plans first (buildInputOrderFromSortDescription calls merge->getSelectedTables() / getAllChildPlans()), then calls merge->requestReadingInOrder(...) afterwards. At that point the child plans may already contain logical exchanges from the first optimization pass, and ReadFromMergeTree::requestReadingInOrder only sets query_info.input_order_info / updates the sort description; it does not clear the previously computed distributed_read_bucket_count or distributed_read_buckets.
With the new !planContainsLogicalExchange(root) guard, the second buildQueryPipeline pass skips checkDistributedReadSupported, so that now-unsupported child read stays marked as bucketed until makeDistributedPlan reuses serializeDistributedReadBuckets() again (or, on the remote path, fails much later in ReadFromMergeTree::serialize). The idempotence fix should only skip the tryMakeDistributed* rewrites; the validations still need to run on already-distributed plans because later passes can mutate ReadFromMergeTree.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 50/53 (94.34%) · Uncovered code |
4d08ee5
The previous commit cleared `make_distributed_plan` in the optimization settings of the child plans of `ReadFromMerge`, but that disabled the whole distributed planning of the children, and a `Merge` table over `Distributed` tables intentionally converts each child plan to a distributed plan on its own (see #108401). This failed the `Fast test` on 04367_distributed_plan_merge_scatter_multishard: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113636&sha=d2b378e20bfae32ba1ace67846ff6c59f235f8be&name_0=PR&name_1=Fast%20test Fix it at the actual defect instead: `materializeConstantsForSetOperationBranches` exists because plan serialization stores only names and types, so constness is re-derived per step after a fragment is deserialized. A plan with no logical exchange steps is never split into serialized fragments (`convertToDistributed` keeps it as a single stage executed in this process), so the rewrite must not touch it. Gate the rewrite on `planContainsLogicalExchange`, and restore the plain optimization settings for the child plans of `ReadFromMerge`. Verified locally: 04812_merge_children_distributed_plan_const_mismatch fails with `Block structure mismatch` on the unpatched binary and passes with this change; 04367_distributed_plan_merge_scatter_multishard, 04613_distributed_plan_merge_broadcast_join and 04319_distributed_plan_set_operation_const_columns (and the rest of the distributed_plan family, 22 tests) pass. Co-Authored-By: Claude Fable 5 <[email protected]>
The previous commit cleared `make_distributed_plan` in the optimization settings of the child plans of `ReadFromMerge`, but that disabled the whole distributed planning of the children, and a `Merge` table over `Distributed` tables intentionally converts each child plan to a distributed plan on its own (see ClickHouse#108401). This failed the `Fast test` on 04367_distributed_plan_merge_scatter_multishard: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113636&sha=d2b378e20bfae32ba1ace67846ff6c59f235f8be&name_0=PR&name_1=Fast%20test Fix it at the actual defect instead: `materializeConstantsForSetOperationBranches` exists because plan serialization stores only names and types, so constness is re-derived per step after a fragment is deserialized. A plan with no logical exchange steps is never split into serialized fragments (`convertToDistributed` keeps it as a single stage executed in this process), so the rewrite must not touch it. Gate the rewrite on `planContainsLogicalExchange`, and restore the plain optimization settings for the child plans of `ReadFromMerge`. Verified locally: 04812_merge_children_distributed_plan_const_mismatch fails with `Block structure mismatch` on the unpatched binary and passes with this change; 04367_distributed_plan_merge_scatter_multishard, 04613_distributed_plan_merge_broadcast_join and 04319_distributed_plan_set_operation_const_columns (and the rest of the distributed_plan family, 22 tests) pass. Co-Authored-By: Claude Fable 5 <[email protected]>
…hard-merge-107946 Fix ScatterExchangeStep crash on a multi-bucket source (make_distributed_plan over Merge of Distributed)
Closes: #107946
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
LOGICAL_ERRORexception (ScatterExchangeStep should have one source shard, got 8) and duplicated rows when querying aMergetable overDistributedtables or views with the experimental settingmake_distributed_plan = 1.Description
Root cause: the
tryMakeDistributed*transforms are not idempotent, and some plans are optimized more than once.StorageMergeoptimizes each child plan when it creates it andbuildQueryPipelineoptimizes it again when the child pipeline is built (set subplans take a similar double path throughmakePlansForSetsandbuildQueryPipeline). The second pass matched the same aggregation or join step again and stacked a second layer of exchanges on top of the first one:MergeofDistributedtables: the stackedScatterExchangesaw the first pass's shuffle result buckets at plan split time and threwScatterExchangeStep should have one source shard, got 8(issueLogical error: 'ScatterExchangeStep should have one source shard, got 8'withmake_distributed_plan=1+Mergetable #107946).Mergeover a view joining a big table with a small (broadcast-able) table: the stackedScatterExchangelanded on top of the first pass'sBroadcastExchangeand re-partitioned the broadcast copies as if they were a partition, returning every row 8 times.Fixes:
optimizeTreeSecondPassskips them when the plan already contains aLogicalExchangeStep(exchanges are created only by these transforms, so their presence means the plan was distributed already).makeDistributedPlannow tracks whether a fragment's tasks produce copies of the same data (the case right after aBroadcastExchange) and throws aLOGICAL_ERRORif another exchange would consume such copies as a partition source, so a plan shape that would duplicate rows fails at plan time instead of returning wrong results.The first commit in this PR relaxed the
ScatterExchangeStepsingle-source guard; a later commit restores it.ScatterExchangedeclares a single source bucket, and a multi-bucket repartition isShuffleExchange's job (optimizeExchangesrewrites a scatter over a gather into it), so with the transforms applied once per plan the guard holds again and catches a mislabeled plan at plan time.Tests (both check the query plan shape with
EXPLAINand verify row counts):04367_distributed_plan_merge_scatter_multishard(reworked): the reproducer from the issue; theEXPLAINshows the per-child plans underReadFromMergewith a single layer of exchanges. Fails on master with theLOGICAL_ERROR.04613_distributed_plan_merge_broadcast_join(new): the broadcast join duplication. Verified against locally built binaries: without both fixes it returns every row 8 times; with fix 2 alone it throws the newLOGICAL_ERROR; with both fixes it returns correct rows. Neither test's split-time plan contains aScatterExchange(the scatters are fused into aShuffleExchangeor optimized away, as theEXPLAINreferences show), so the restored guard does not fire on them.The reporter (qoega) suggested the localized guard-relaxation direction; deeper analysis showed the double transform application underneath, which this PR now fixes at the root.
The same exception signature (
ScatterExchangeStep should have one source shard) was also produced by the AST fuzzer on several PR runs, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108129&sha=8aaab301293dd91ed33f6628d8e888802566c69a&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 (AST fuzzer (arm_asan_ubsan)).Version info
26.7.1.1341(included in26.7and later)