Skip to content

Fix parallel replicas over a Distributed table over a Distributed table - #123566

Merged
devcrafter merged 15 commits into
masterfrom
pr-over-dist-over-dist-test
Oct 7, 2026
Merged

devcrafter merged 15 commits into
masterfrom
pr-over-dist-over-dist-test

Conversation

@devcrafter

@devcrafter devcrafter commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

When a query reads a Distributed table whose underlying table on each shard is itself a Distributed table, parallel replicas were silently not used anywhere in the chain if every shard of the outer cluster has a single replica.

ClusterProxy::updateSettingsAndClientInfoForCluster turned allow_experimental_parallel_reading_from_replicas off when no shard of the cluster has more than one replica. That value is part of the settings sent to the shard, so it also disabled parallel replicas for the next hop, where the cluster being read can have several replicas per shard.

Whether a hop itself can use parallel replicas is already decided per shard from the shard's replica count, and a shard that cannot use them declines on its own in canUseParallelReplicasOnInitiator, so the setting does not need to be turned off here. The disable is kept for remote() without a configured cluster, which has no cluster to scope parallel replicas to.

A shard served by a local plan does not go through ReadFromRemote either, so nothing sets cluster_for_parallel_replicas to that hop's cluster. SelectStreamFactory::createForShardImpl now plans such a read with parallel replicas off, unless the local table is itself a Distributed table, where the hop below sets up its own cluster.

Query results were correct before the fix; only the parallel reading was lost.

New integration test test_parallel_replicas_dist_over_dist: two instances, each with its own remote_servers where the cluster named default is that instance's own pair of replicas, joined by an outer_cluster known only to the hub with one single-replica shard per instance. It asserts one parallel-replicas read per instance over all four replicas.

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 parallel replicas not being used when reading a Distributed table whose underlying table is another Distributed table and every shard of the outer cluster has a single replica.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1773-master (included in 26.10 and later)
  • Backported to: 26.9.16.8, 26.8.24.8

devcrafter and others added 2 commits October 1, 2026 14:14
A cluster whose every shard has one replica cannot use parallel replicas
for its own hop, but the disable was written into the settings sent to
the shard, where it also took parallel replicas away from a nested
`Distributed` read over a cluster that can use them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Each instance carries its own `remote_servers`, where the cluster named
`default` is that instance's own pair of replicas, and only the hub knows
`outer_cluster`, the entry point that fans the query out to both. Assert
one parallel-replicas read per instance over all four replicas, which
catches the hop losing parallel replicas as well as a replica dropping
out of the read.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bf1a66d]

Summary: ✅


AI Review

Summary

This PR stops propagating the shard-side parallel-replica disable for named clusters, adds a local-plan guard, and covers the direct Distributed -> Distributed topology with an integration test. The main path is better, but the local-plan guard still misses two supported forwarding wrappers, so the optimization the PR claims to restore is still lost for Alias -> Distributed and trivial View -> Distributed entry points.

Findings
  • ⚠️ Majors
    • [src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:125] castStorage<StorageDistributed> only unwraps StorageProxy layers, so ENGINE = Alias still falls into the branch that zeros allow_experimental_parallel_reading_from_replicas. StorageAlias::read forwards the same local_context to its target in src/Storages/StorageAlias.cpp:283, so a local-shard Distributed -> Alias -> Distributed read with prefer_localhost_replica = 1 still drops parallel replicas on the inner hop. Suggested fix: resolve alias-style forwarding storages before the StorageDistributed check and add an Alias -> Distributed regression case.
    • [src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:125] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/123566#discussion_r4169484288] Trivial View -> Distributed is still misclassified the same way. emplace_local_stream sees a StorageView and zeros allow_experimental_parallel_reading_from_replicas, but createLocalPlan still builds a normal local plan in src/Processors/QueryPlan/DistributedCreateLocalPlan.cpp:15 where the existing trivial-view pushdown path can later inline that view back to StorageDistributed (src/Planner/PlannerJoinTree.cpp:2342, src/Storages/StorageView.cpp:692). Results stay correct, but the optimization this PR is restoring remains off behind a trivial-view wrapper. Suggested fix: treat eligible trivial views as nested Distributed here as well, or resolve the forwarded storage with the view's own snapshot before deciding whether to zero the setting.
Final Verdict
  • ⚠️ Needs changes before merge: the direct nested Distributed case is fixed, but supported Alias and trivial View wrappers still lose parallel replicas on the local-shard path, so the bug fix is incomplete.

LLVM Coverage Report

Measured on commit bf1a66d.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 36/40 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Oct 2, 2026
A shard served by a local plan does not go through `ReadFromRemote`, so
nothing sets `cluster_for_parallel_replicas` to this hop's cluster and the
read is scoped by another one, which throws `UNEXPECTED_CLUSTER` or
`CLUSTER_DOESNT_EXIST`. A nested `Distributed` is the exception: that hop
sets up its own cluster.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bf1a66d0a with master 442f03ed0 (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

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.

Compile time of recompiled translation units

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

Job report

devcrafter and others added 3 commits October 3, 2026 13:11
A `Distributed` hop sends its sub-query to one replica of the shard, and
that replica reads the `MergeTree` with parallel replicas, so the
coordinator is on whichever replica was picked, not on the server the
outer cluster addressed. Which replicas then get ranges is up to the
coordinator, and on this data one can serve the whole read. Assert one
parallel-replicas read per instance instead, and wait for the rows: a
coordinator finishes after the initiator already has all the data.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
It is counted on the coordinator on the query's own pipeline thread, so
it is already in that node's `system.query_log` row, unlike
`ParallelReplicasQueryCount`, which the coordinator's destructor raises.
No waiting needed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter
devcrafter requested review from nickitat and a balanced review from Copilot October 4, 2026 23:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

Review effort: Lite
Findings: 2 Medium severity · 1 Low severity

Open (3)
What changed in this PR

Fixes parallel replicas being unintentionally disabled when querying a Distributed table over another Distributed table (outer cluster shards have single replicas, inner clusters may have multiple replicas), and adds an integration test to prevent regressions.

Changes:

  • Stop disabling allow_experimental_parallel_reading_from_replicas for named clusters just because the current hop’s shards are single-replica; only disable for remote() with no configured cluster.
  • Disable parallel replicas for local-plan shard reads unless the local table is itself a nested Distributed (so the next hop can scope parallel replicas correctly).
  • Add integration coverage for the “dist over dist with single-replica outer hop” topology.
File Description
tests/​integration/​test_parallel_replicas_dist_over_dist/​test.py New integration test asserting parallel replicas are used on the inner hop across two instances.
tests/​integration/​test_parallel_replicas_dist_over_dist/​configs/​spoke.xml Defines the spoke’s per-instance default cluster with 2 replicas.
tests/​integration/​test_parallel_replicas_dist_over_dist/​configs/​hub.xml Defines hub’s default (2 replicas) and outer_cluster (2 single-replica shards).
src/​Interpreters/​ClusterProxy/​executeQuery.cpp Removes over-broad disabling of parallel replicas; keeps disabling only for remote() without a configured cluster.
src/​Interpreters/​ClusterProxy/​SelectStreamFactory.cpp Ensures local-plan shard reads don’t accidentally inherit/retain parallel-replica scoping from a different hop.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

devcrafter and others added 3 commits October 5, 2026 12:43
`isRemote` is true for storages that never go through `ClusterProxy`, so
nothing would set `cluster_for_parallel_replicas` for them, and for a
`Merge` with one `Distributed` child while its other children are read
locally. Also reuse one context copy per call and flush only `query_log`
in the test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
devcrafter and others added 2 commits October 6, 2026 12:27
`ReadFromLocalReplica` and `ReadFromRemoteParallelReplicas` are local to
the server that planned them and have no serialized form, so shipping a
plan built with them fails with `Unknown query plan step`. The shard
decides on parallel replicas on its own. `PlannerJoinTree` already checks
`build_logical_plan`; this was the one place that did not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A lazily loaded table is reached through `StorageTableProxy`, and a table
function through `StorageTableFunctionProxy`, so a direct cast misses a
`Distributed` behind either. `castStorage` is the helper for that.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/// out: it reads without parallel replicas, as it did before.
auto local_context = context;
if (context->canUseTaskBasedParallelReplicas()
&& !castStorage<StorageDistributed>(local_storage, DeferredTable::Load))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

castStorage<StorageDistributed> only unwraps StorageProxy, but ENGINE = Alias is another forwarding wrapper: StorageAlias::read forwards to its target with the same local_context, and StorageAlias::isRemote() delegates to that target.

With prefer_localhost_replica = 1, a local-shard Distributed -> Alias -> Distributed read still enters this branch, clears allow_experimental_parallel_reading_from_replicas, and the inner Distributed hop loses parallel replicas even though the underlying table is exactly the case this PR is trying to preserve.

Please resolve alias-style forwarding storages here as well (or use a helper that unwraps them before the StorageDistributed check), and add a focused Alias -> Distributed regression case.

devcrafter and others added 3 commits October 6, 2026 14:55
`StorageProxy.h` was already included.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There is one coordinator per instance, so finding one among the
instance's nodes is enough.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@KochetovNicolai KochetovNicolai self-assigned this Oct 7, 2026
eliangidoni pushed a commit to eliangidoni/ClickHouse that referenced this pull request Oct 7, 2026
`02980_dist_insert_readonly_replica` breaks its `shard_1.data` replica on
purpose: it empties the replica's `columns` znode and re-attaches the table,
so the attach thread keeps it read-only. The file drops `shard_0` and
`shard_1` only in its last two statements. When stress fault injection
(`memory_tracker_fault_probability`) hits a query before them, the file
stops, the replica survives into the upgrade restart, and the new server
logs the non-retryable attach-thread branch:

  <Error> shard_1.data (ReplicatedMergeTreeAttachThread): Initialization
  failed, table will remain readonly. Error: Code: 27. DB::Exception: Cannot
  parse input: expected 'columns format version: 1\n' at end of stream.

The old server logged the identical line before the upgrade, so it is not a
compatibility signal. Only the retryable branch (`Initialization failed.
Error`) is allow-listed, which is right in general: the read-only branch
carries real upgrade findings (METADATA_MISMATCH, TOO_MANY_UNEXPECTED_PARTS,
BAD_DATA_PART_NAME on other tables).

The new matcher requires the anchored `shard_1.data` attach-thread logger,
the read-only branch, Code 27 and `at end of stream` (an empty `columns`
value) together. Any other table, code or `columns` content still fails the
job. Seen on PR ClickHouse#123566 (Upgrade check (amd_release), 27b84d7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three replicas for the hub, two for the spoke and one for a third
instance, which therefore cannot use parallel replicas at all - the
single-replica one reads its `MergeTree` through a local plan, the path
that has to keep parallel replicas off.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter
devcrafter added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 445f238 Oct 7, 2026
152 checks passed
@devcrafter
devcrafter deleted the pr-over-dist-over-dist-test branch October 7, 2026 21:05
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 7, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 7, 2026
cursor Bot pushed a commit to fneves/ClickHouse that referenced this pull request Oct 10, 2026
It reads every replica as a shard of its own, so there is nothing left for
parallel replicas to split, and the shard number it ships indexes that
numbering rather than the cluster of the same name. Without the shard-scope
check from ClickHouse#113589 the backport of ClickHouse#123566 fails with `Shard number is
greater than shard count` in `03595_parallel_replicas_join_remote`.

ClickHouse#124491

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Oct 11, 2026
Backport #123566 to 26.9: Fix parallel replicas over a Distributed table over a Distributed table
clickhouse-gh Bot added a commit that referenced this pull request Oct 11, 2026
Backport #123566 to 26.8: Fix parallel replicas over a Distributed table over a Distributed table
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). 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.8-must-backport v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants