Skip to content

Bind the parallel replicas shard scope to the cluster that produced it - #113589

Merged
alexey-milovidov merged 47 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-parallel-replicas-foreign-shard-scope
Sep 25, 2026
Merged

alexey-milovidov merged 47 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-parallel-replicas-foreign-shard-scope

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #81738

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 wrong results and a LOGICAL_ERROR when a query reads with parallel replicas inside a distributed sub-query whose cluster_for_parallel_replicas numbers its shards differently from the cluster the query is distributed over: a VIEW carrying its own SETTINGS cluster_for_parallel_replicas, a read through clusterAllReplicas of that same cluster, a cluster built by cluster discovery or by a Replicated database when the two servers see a different set of shards under one name, or a plain remote_servers cluster whose per-server copies number the shards differently while a configuration change rolls out. The shard number shipped by the initiator was applied to the other numbering and selected the wrong shard. Parallel replicas are now declined for such a read.

Description

prepareClusterForParallelReplicas indexes the _shard_num scalar into cluster_for_parallel_replicas as if both described the same cluster. They are independent: _shard_num is shipped by a distributed query's initiator, while cluster_for_parallel_replicas is a per-query setting any nested SETTINGS clause can change, including inside a view(...).

  • Above the other cluster's shard count, the read throws LOGICAL_ERROR: Shard number is greater than shard count, aborting debug and sanitizer builds.
  • In range, no check fires and the read silently returns the wrong shard's data: 10000090 where 90 is correct.

21ef1f1d1c9ba39 removed a _cluster_for_parallel_replicas scalar, on the reasoning that the setting alone identifies the cluster; a view with its own SETTINGS falsifies that. It is restored as a second column of the _shard_num block, so overwriting the number replaces it atomically.

A scope is honoured only when its provenance identifies the same shard numbering, not merely the same cluster name: clusterAllReplicas derives a renumbered cluster that keeps the name, and cluster discovery and Replicated database clusters renumber whichever shards they can currently see, so their identity is the ordered shard keys they discard; a remote_servers cluster is per-server configuration, so its identity is its ordered shards (each shard's <name>, or its replicas when the shards are unnamed) rather than the name. Otherwise parallel replicas are declined at every admission site, giving the same results as enable_parallel_replicas = 0.

Two routes are left as they are. Absent provenance means "trust the shard number", so mixed-version clusters keep today's behaviour; and an out-of-range number whose provenance does match is still thrown on rather than declined, which needs a change of its own.

Each consequence reproduces on unpatched master and passes here. Added a stateless test, an integration test for the wrong-shard read, and gtests for wire cases SQL cannot build.

Closes #101325


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

Version info

  • Merged into: 26.10.1.706-master (included in 26.10 and later)

groeneai and others added 7 commits August 5, 2026 02:17
prepareClusterForParallelReplicas indexes the _shard_num scalar into
cluster_for_parallel_replicas, assuming both describe the same cluster. They
reach the query context through independent channels: _shard_num is
per-connection state shipped over the wire by the initiator of a distributed
query (ReadFromRemote -> RemoteQueryExecutor -> TCPHandler::processData ->
addScalar), while cluster_for_parallel_replicas is an ordinary per-query setting
that any nested SETTINGS clause can change, including one inside a view(...).
Nothing bound the pair, so a shard number produced for one cluster was applied
to another.

Out of range that throws LOGICAL_ERROR "Shard number is greater than shard
count" (an exception, so it aborts only debug and sanitizer builds). In range no
check fires and the read silently returns the wrong shard's data, which is the
more serious half: measured on a two-server topology where the view's parallel
replicas cluster has a different server as its shard 2, the query returned
10000090 where 90 was correct.

21ef1f1 removed a _cluster_for_parallel_replicas scalar on the reasoning
that the setting alone identifies the cluster, and also removed its two
per-engine consumers. A view carrying its own SETTINGS falsifies that premise, so
this restores the provenance.

It travels as a second column of the _shard_num block rather than as a sibling
scalar. That is load bearing: ClusterProxy/executeQuery.cpp forwards every
inbound scalar downstream while ReadFromRemote overwrites only _shard_num, so a
sibling scalar would outlive the number it describes and a new -> old -> new hop
would deliver stale provenance attached to a fresh shard number, recreating the
same wrong-shard read inside the fix. Co-locating them makes any producer's
overwrite atomic, including an older server's single-column write.

A shard scope is honoured only when the provenance names the cluster being
indexed. When it names another cluster, parallel replicas are declined at all
four admission sites and the plain local plan is used, giving results identical
to enable_parallel_replicas = 0. The three sites that call the Context predicate
directly get a separate lenient check rather than the ClusterProxy overload,
because that overload resolves the cluster and therefore throws
CLUSTER_DOESNT_EXIST when cluster_for_parallel_replicas is unset, which those
sites never did before.

Absent provenance means "trust the shard number", so a mixed-version cluster
keeps its shard scoping instead of silently losing it. Clusters built from a host
list previously reported an empty name, which would have authenticated any of
them against any other, so they now take the name their caller already supplies
in ClusterConnectionParameters and an empty provenance value never matches. The
one consumer that keys on an empty cluster name is remote() without a configured
cluster, which passes an empty name and is unaffected.

No assertion is weakened: with admission gated, the existing bounds check
becomes correct rather than misapplied, and a foreign scalar reaching cluster
preparation is now itself a LOGICAL_ERROR.
MergeTreeData::getQueryProcessingStage decides the processing stage for the
non-analyzer path from the raw Context::canUseParallelReplicasOnInitiator, while
StorageMergeTree::read and StorageReplicatedMergeTree::read now additionally
require the shipped shard scope to belong to cluster_for_parallel_replicas.
Before this commit the two predicates were the same, so they agreed; adding the
scope check only to the read guards made them disagree, and the storage then
promised WithMergeableState above a plan that was in fact built locally.
InterpreterSelectQuery therefore set first_stage = false and merged raw rows as
if they were partial aggregate states, skipping the WHERE, before_order_by and
DISTINCT work. Measured on a view whose own SETTINGS name a foreign cluster:
sum over a view filtering `a >= 50` returned 9900 instead of 7450, and a view
computing an aggregate failed with NOT_FOUND_COLUMN_IN_BLOCK. That path is
reached whenever parallel_replicas_only_with_analyzer is off, which
02875_parallel_replicas_cluster_all_replicas sets and a CI flavour runs.

Strengthen the stateless test so it cannot pass on a silent fallback. Both
shards of test_cluster_two_shards_localhost are the same server and table, so
the value alone is also what a wrong-shard read returns; the test now also
counts ParallelReplicasQueryCount per arm, expecting zero for the two arms whose
shard scope is foreign and one for a matching-provenance control, which
distinguishes declining a foreign scope from disabling the feature. Add an
in-range foreign arm, where the bounds check passes and the wrong shard is read
with no error, and the two old-analyzer arms above. Pin
parallel_replicas_plan_based, without which the plan-based path builds locally
and the arms measure nothing.

Add an integration test for the wrong-shard read. A stateless harness cannot
cover it because every shard of the localhost test clusters points at the same
server and table, so no value can distinguish the shards; the new case gives the
two clusters disjoint node groups with distinct per-shard data and asserts the
exact sum. Each cluster's shards carry three replicas, since a single-replica
shard makes updateSettingsForCluster disable parallel replicas for the hop and
the case would measure nothing.
The three arms added first (out-of-range, in-range, matching-provenance
control) pinned prefer_localhost_replica and
parallel_replicas_plan_based but not the analyzer state, so they
inherited whatever profile the CI flavour installs.
tests/config/users.d/analyzer.xml sets allow_experimental_analyzer = 0
in the default profile, installed under --analyzer by
tests/config/install.sh:297, which ci/jobs/functional_tests.py:157 maps
from the "old analyzer" job option; two stateless job families use it.
Context::canUseTaskBasedParallelReplicas returns false at its first
branch when the analyzer is off and parallel_replicas_only_with_analyzer
is true, which it is by default, so parallel replicas were disabled
wholesale in those jobs.

Measured with tests/config/users.d/analyzer.xml symlinked into a
server's users.d/: the matching-provenance control's
ParallelReplicasQueryCount oracle read 0 against its committed reference
value 1, i.e. a deterministic failure of our own test. The two
foreign-scope arms did pass there, but only because both shards of
test_cluster_two_shards_localhost are the same server and table, so
their value 9900 and oracle 0 are also what a plain local read
produces: the two arms carrying the analyzer-path claim would have
exercised nothing.

Pinning rather than tagging: a no-old-analyzer tag would drop the test
from those jobs instead of fixing it. 34 of the 40 stateless tests that
touch parallel_replicas_only_with_analyzer set it to 0 for this reason,
and 02875_parallel_replicas_cluster_all_replicas, whose oracle shape
this test copied, says so in a comment.

The reference file is unchanged: the pins only restore, in those jobs,
the behaviour a default-profile server already has. Verified the run
under the default profile is byte-identical before and after, and
re-ran both mutants against the amended test to confirm neither was
weakened - reverting the MergeTreeData.cpp conjunct still reddens
exactly the two old-analyzer arms, and suppressing the Foreign verdict
still returns the same value 9900 on the in-range arm while flipping its
oracle from 0 to 1. 50/50 randomized runs pass.
getShardScopeForCluster used Context::getScalars(), which returns the whole
std::map<String, Block> by value under the context mutex, and then discarded
every entry but one. The predicate is now reached from five more per-query
sites than before, and scalars can hold large blocks: over-threshold constants
become __getScalar('<hash>') entries in buildQueryTreeForShard. Use the
single-name accessors Context::hasScalar / Context::getScalar instead, matching
what ExecuteScalarSubqueriesVisitor and evaluateScalarSubqueryIfNeeded already
do. Semantics are unchanged, including the early return when no scalar is
present; the block is now a local copy, and the string_view taken from it is
compared while that copy is still in scope.

Also record in 04727 that serialize_query_plan needs no pin there. It was
measured rather than assumed: the setting does suppress parallel replicas for a
read of a plain table, which is why 02947 and 03562 pin it, and removing
03562's pin reproduces that (its oracle goes 1,1 -> 0,0). Every arm of 04727
reads through a view whose own SETTINGS name enable_parallel_replicas, and
QueryTreeBuilder re-applies a view's settings on the shard, restoring the alias
of the setting resolveStorages clears on the serialized-plan path. The shipped
test is byte-identical to its reference under the default profile, under the
distributed plan profile, and under both together.

Co-Authored-By: Claude Fable 5 <[email protected]>
The shard scope compared its shipped provenance to `Cluster::getName`, which
is not sufficient: a derived cluster can carry the same name and a different
shard numbering.

`Cluster(ReplicasAsShardsTag, ...)` makes every replica a shard of its own,
assigning fresh consecutive numbers, and then copies the name of the cluster
it was derived from. `clusterAllReplicas` builds such a cluster, so reading a
view whose own `SETTINGS` name that same config cluster shipped a derived
shard number that authenticated against the config cluster by name. Measured
on `test_cluster_two_shard_three_replicas_localhost` (2 shards, 6 replicas):
the derived cluster has 6 shards, so numbers 3..6 exceed the config cluster's
shard count and throw `Shard number is greater than shard count`, while 1..2
are in range and silently scope the read to an unrelated shard. Both are the
outcomes this change set out to prevent.

Compare the shard numbering instead. `Cluster` gains a separate scope
identity, set to the cluster name by the constructors that establish a
numbering, carried over by `Cluster(SubclusterTag, ...)` (which preserves
each `shard_num`, so `optimize_skip_unused_shards` is unaffected), and
distinguished by `Cluster(ReplicasAsShardsTag, ...)`, whose spelling contains
a space and therefore cannot collide with a cluster name. `getName` keeps its
value for every cluster: it is a resolvable name that `ReadFromRemote` also
assigns to `cluster_for_parallel_replicas`, so the scope identity travels as a
second member rather than replacing it.

An absent provenance column still means "trust the shard number", and an
empty identity still authenticates nothing, so mixed-version behaviour and
host-list clusters are unchanged.
The previous commit gave a derived replicas-as-shards cluster a distinguishable
scope identity, spelled with a space on the reasoning that cluster names come
from XML element names and therefore cannot contain one. That premise is false,
and no non-empty spelling can repair it.

Cluster names and Replicated database names share one namespace. A name that
matches no configured cluster and no discovered one is resolved by
Context::tryGetCluster through tryGetReplicatedDatabaseCluster, and
DatabaseReplicated::tryGetCluster builds that cluster with the database name
verbatim as its ClusterConnectionParameters::cluster_name, which the
DatabaseReplicaInfo constructor stores as the scope identity. Database names
carry no character restriction, so any string a reader can construct is also a
string a user can name a database, and a scope authorized on identity equality
alone is therefore forgeable: a database named after the derived spelling of a
config cluster presents a genuinely renumbered shard number that compares equal
and is honoured. Out of range that is the LOGICAL_ERROR this change exists to
prevent, and in range it reads an unrelated shard.

Leave the identity empty instead. The admission guard already short-circuits an
empty provenance to Foreign before comparing anything, so an empty identity
authenticates nothing by construction rather than by a choice of string. This
costs no coverage: a derived cluster is reachable only as the producer of a
shard scope, never as its target. Both derivation sites register their result
into no map, and none of the three sources getCluster resolves a name through
derives replicas-as-shards, so every admission site reaches its target by name
resolution and can never be handed a derived cluster.

A gtest pins the collision directly, since restoring any distinguishable
spelling leaves every pre-existing arm green and would otherwise ship without a
behavioural mutant.
Both host-list constructors were given `name(params.cluster_name)` when the
shard-scope guard still compared the shipped provenance against
`cluster.getName()`. The guard now compares a dedicated `shard_scope_identity`
member, so nothing in the fix reads `getName()` any more: its body has no
`getName()` call, and the only mention among the unit tests asserts that a
derived cluster copies whatever name it had.

The initializer is therefore dead weight, and it is not free. It was the fix's
only behaviour change outside parallel replicas: the sole consumer keying on an
empty name is `updateSettingsAndClientInfoForCluster`, so naming a
cluster-discovery cluster or a `Replicated` database enabled parallel replicas
on a hop where the empty name had disabled them. A correctness fix should carry
exactly its own behaviour change; naming those clusters, if wanted, belongs in
its own change with its own changelog line.

Restoring both initializers reproduces the previous binary byte for byte, and
leaves every test green, which is what shows the name was unobservable here.
Removing both initializers instead reddens the three unit tests that ship a
non-empty provenance and expect it honoured, which is what shows the identity
they keep is load-bearing.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review, 7 fix rounds, final round clean (click to expand)

Every round ran two independent channels against the then-current head: a cold read of the resulting
code by a reviewer who never edited it, and a separate second-model gate. The final round returned
zero findings in both channels.
The rounds below are what the earlier passes changed.

# Finding Verdict
❌ The processing-stage decision and the storage read guards consulted different predicates, so without the analyzer the stage promised to the initiator and the plan actually built could disagree, so the initiator would merge raw rows as partial aggregate states. AGREE, fixed: both now consult the same predicate on the same context. Two old-analyzer arms pin it (a view filter that must be applied, and a view aggregate that must be found).
❌ The scope was authenticated by comparing the shipped provenance against the cluster name. clusterAllReplicas derives a cluster that renumbers every shard while copying the name, so a derived shard number authenticated against its origin: numbers above the origin's shard count aborted, numbers within it read an unrelated shard. AGREE, fixed: the provenance identifies the shard numbering via a dedicated member, not the name. A derived cluster carries none, and an empty identity authenticates nothing. Two gtests pin both directions; two mutants redden them disjointly.
❌ A derived cluster was given a distinguishable identity spelling. Cluster names and Replicated database names share one namespace, so any value a reader can construct is also a value a user can name a database, which makes the scope forgeable. AGREE, fixed: derived clusters carry no identity at all, pinned by its own gtest.
❌ Three analyzer arms of the new stateless test pinned neither enable_analyzer nor parallel_replicas_only_with_analyzer, so in CI flavours installing the analyzer profile the matching-provenance control would read 0 and the two foreign-scope arms would pass without exercising the fix. AGREE, fixed: the analyzer dimension is pinned on all three arms, with before/after runs under both server profiles and the mutation matrix re-run to confirm no previously-caught mutant was weakened.
❌ The change also gave host-list clusters a name, which was load-bearing only while the guard compared names. Once the guard moved to the dedicated member it became dead weight, and it was the only behaviour change outside parallel replicas: the single consumer keying on an empty name flipped a remote() hop from parallel-replicas-disabled to enabled for cluster-discovery and Replicated-database clusters. AGREE, fixed: both initializers reverted to base behaviour, so this change now carries exactly its own behaviour change. Restoring them reproduces the previously-reviewed binary byte for byte (proving the delta is only those two lines); removing the identity as well reddens exactly the three unit tests that ship a non-empty provenance, which is what shows the two halves are separable and only one is needed.
❌ A description claim ("no getName consumer changes behaviour") and a validation-gate row were false while the above was in place. AGREE, fixed: with the change reverted the claim is true, and the obsolete disclosure was removed rather than reworded. Every countable figure in the gate comment was re-derived; two were wrong and corrected (a mutant-arm tally and an abort attribution).
⚠️ A gate finding held that the new integration test is vacuous in the old-analyzer integration job. DISAGREE. The premise does not hold. ClickHouseInstance computes use_old_analyzer from the environment and then unconditionally clears it when the instance carries a docker tag, which it always does. The only escape is an explicit opt-in, which this module does not pass; the 25 integration tests that do run under the old analyzer all opt in that way. The oracle is also already specific: reverting the fix fails it with a value mismatch, reachable only if the path under test ran.
⚠️ A gate finding asked for a parallel-replicas usage oracle in the integration test. DISAGREE. That assertion would be weaker here, because correct behaviour declines parallel replicas. The value assertion is the stronger oracle: the full-revert mutant fails it with 10000090 against a control of 90.
💡 A comment on a pre-existing line uses "crash" where the project prefers naming the exception. DISAGREE, noted not blocking. That line is in the merge base and appears in neither an added nor a removed line here; rewording it would widen the diff into untouched code. The rule is observed in every comment this change does add.

Final-round cold review. Carriers were enumerated independently and only then compared against the
plan's list; the two agree. The _shard_num scalar has five writers: two ship it over the wire and
both carry provenance, while the other three install it locally into a different context map from
the one the guard reads, so a local shard plan cannot manufacture a scope, which is correct because
the local plan is the local half of a distributed read. Every raw read is gone; all four consumers go
through one helper. All five Cluster constructors were re-classified from their own bodies rather
than from the comments. All three routes into cluster preparation were walked back to an admission
gate, including the plan-based path and the INSERT ... SELECT path, so the remaining assertion is a
fail-closed backstop whose premise is now true.

Test liveness was traced, not assumed: the six value arms and six usage-oracle lines were checked
positionally against the committed reference, and the matching-provenance arm reading 1 is the
anti-vacuity control: without it every other arm's 0 would also be satisfied by parallel replicas
being off entirely. The test-number gap checker was extracted and executed on this head, on master and
on the simulated merged tree, with a positive control confirming it discriminates.

Base drift was judged per file by content hash rather than by commit count: twelve of fifteen touched
files are byte-identical to current master, and the three that drifted do so far from these hunks.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, four arms, each on demand. Exception arm: a MergeTree table, a VIEW over it carrying SETTINGS cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost', then SELECT sum(a) FROM cluster('test_cluster_two_shards_localhost', <db>, v) SETTINGS prefer_localhost_replica = 0. Wrong-results arm: the same shape on a multi-node topology whose PR cluster's shard 2 is a node the outer read never addresses. Old-analyzer arm: the same view, plus enable_analyzer = 0, parallel_replicas_only_with_analyzer = 0, with the filter or the aggregate INSIDE the view. Renumbered-cluster arm: the same view read through clusterAllReplicas of the very cluster the view names, which derives a 6-shard cluster carrying that cluster's name, so shard numbers 3..6 abort and 1..2 read an unrelated shard. None is probabilistic.
b Root cause explained? prepareClusterForParallelReplicas indexes the _shard_num scalar into cluster_for_parallel_replicas, assuming both describe the same cluster. _shard_num is per-connection state shipped over the wire by a distributed query's initiator (ReadFromRemote -> TCPHandler::processData -> addScalar); cluster_for_parallel_replicas is a per-query setting any nested SETTINGS can change, including one inside a view(...). Nothing bound the pair, so a shard number produced for cluster A got applied to cluster B: out of range it throws, in range it reads the wrong shard. Without the analyzer the same scope also decides the processing stage, so the stage and the plan must agree or the initiator merges raw rows as partial aggregate states.
c Fix matches root cause? Yes. It restores the cluster provenance that 21ef1f1d1c9ba39 removed, so the binding itself is repaired, rather than hardening the bounds check. Hardening the bound was considered and rejected: it leaves the in-range wrong-results case completely unfixed. No assertion is weakened; with admission gated the existing LOGICAL_ERROR becomes true instead of misapplied.
d Test intent preserved / new tests added? No test weakened. 04069_parallel_replicas_distributed_lazy_shard_num (which pins the earlier producer-side fix) is deliberately unmodified and still passes. Added a stateless test with six arms (out-of-range, in-range, a matching-provenance control, a renumbered derived cluster, and two old-analyzer arms) whose oracle also counts ParallelReplicasQueryCount per arm, so an arm cannot pass on a silent fallback; an integration test for the wrong-shard read, which a single-server harness structurally cannot cover; and 10 gtests for the cases SQL cannot construct or cannot reach (a single-column _shard_num block, a cluster with an empty name, a cluster name a user could collide with, and the two derived-cluster directions). Every arm has a mutant that reddens it.
e Both directions demonstrated? Yes, on Build-ID-verified binaries asserted both from readelf and from the running server's buildId(). Exception arm: aborts pre-fix with the exact message Shard number is greater than shard count: shard_num=2 shard_count=1 cluster=test_cluster_one_shard_three_replicas_localhost, returns 999000 post-fix. Wrong-results arm: 10000090 pre-fix vs a control of 90, both 90 post-fix; the integration test fails pre-fix with a value mismatch, not an exception. Old-analyzer arms: a view filtering a >= 50 returned 9900 for 7450, and a view computing an aggregate failed NOT_FOUND_COLUMN_IN_BLOCK, both correct post-fix. Renumbered-cluster arm: it passes post-fix with 29700, matching a no-parallel-replicas ground-truth read on the same binary, and it kills the server on the mutant that reverts only the derived cluster's identity handling (Shard number is greater than shard count: shard_num=3..6 shard_count=2, four such aborts). The pristine pre-fix binary also dies on this test, but on the first arm (shard_num=2 shard_count=1) before reaching this one, so that mutant is what isolates this arm. Ten mutants pin the individual claims, one of them returns the SAME value as the fix so that only the parallel-replicas counter distinguishes it, and the two identity-propagation mutants redden disjoint arms. Three redden exactly one arm each and the rest redden two or three; restoring a distinguishable spelling for the derived cluster's identity reddens the two arms that pin its emptiness, and restoring the pre-fix identity for it kills the pre-fix server outright. Unsetting the shard-scope identity on both host-list constructors reddens exactly the three gtests that ship a non-empty provenance and expect it honoured, which is what shows the identity itself is load-bearing there.
f Fix is general across code paths? All four consumers of the scalar now share one helper; all four admission sites decline foreign provenance, enumerated by grep and including the two old-analyzer storage paths that the same historical commit removed the original provenance consumer from; both producers ship provenance. All five Cluster constructors are classified: the config ctor and both host-list ctors establish a numbering and set the identity to the cluster name, SubclusterTag preserves the numbering and copies it, ReplicasAsShardsTag renumbers and so carries no identity, which authenticates nothing. shardNum() reads position 0 only, verified in source, by gtest, and by SQL. The old-analyzer processing-stage decision consults the same predicate, so on that path the stage and the read agree; enumerated by grep, it was the last raw call on a path whose read guard changed.
g Fix generalizes across inputs? Provenance states covered: absent, matching, foreign, empty. Shard numbers: 0 (no scope), in range, out of range. Target clusters: single-shard and multi-shard, config-named and host-list-constructed.
h Backward compatible? Yes, and this is the highest risk, handled in both directions. No setting, default or format change, so no SettingsChangesHistory.cpp entry is due. An older initiator ships a single-column block, which still scopes exactly as today (a dedicated mutant proves that arm is live), and a new initiator's two-column block is read at position 0 by an older shard.
i Invariants and contracts preserved? _shard_num keeps its position and UInt32 type; provenance lives in the same block so overwriting the number replaces its provenance atomically, which a sibling scalar would not. The provenance identifies the shard numbering, not the cluster name, because deriving a cluster keeps the name while possibly renumbering the shards: Cluster(ReplicasAsShardsTag) makes every replica a shard of its own and copies the name, so a name-keyed check would authenticate a derived shard number against its origin (measured: shard numbers 3..6 abort against the 2-shard origin, 1..2 read an unrelated shard). Cluster(SubclusterTag) preserves each shard_num and so carries the identity over, which is why optimize_skip_unused_shards is unaffected; each direction has its own gtest and its own mutant. Cluster::getName and Cluster::name are unchanged for every cluster; the identity is a separate member. Foreign provenance is declined before anything commits to parallel execution, since the cluster-preparation function has no way to fall back to a local plan once entered.

Session id: cron:clickhouse-impl-slot-40:20260805-204300

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai, could you review this? The _shard_num scalar shipped by a distributed query's initiator was indexed into cluster_for_parallel_replicas as if both described the same cluster, so a view carrying its own SETTINGS cluster_for_parallel_replicas (or a read through clusterAllReplicas, which renumbers the shards while keeping the name) applied a shard number to an unrelated numbering: out of range it threw a logical error, in range it silently read the wrong shard. The fix ships the shard numbering's identity alongside the number and declines parallel replicas when the two do not match.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bcbe008]

Summary: ✅


AI Review

Summary

This PR binds the shipped _shard_num scope to an explicit shard-numbering identity and declines parallel replicas when a distributed subquery tries to reuse that scope against a different cluster numbering. After reviewing the current diff, the touched code paths, and the resolved review threads, I did not find any new unresolved correctness, compatibility, or test-coverage issue on the current head.

Final Verdict

✅ Approve

LLVM Coverage Report

Measured on commit bcbe008.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 197/212 (92.92%) · 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 6, 2026
Every arm of 04727 pins `prefer_localhost_replica = 0`, because at 1 the shard
is served locally and ships no `_shard_num` over the wire, so the scope check
is never reached. The pin is correct and load-bearing, but with nothing in the
tree exercising the other value, the reason for it was not demonstrated
anywhere.

Add one arm at `prefer_localhost_replica = 1`. It reads correctly and still
uses parallel replicas for the local shard's own plan; what cannot happen is a
foreign scope being applied.

The arm is a control rather than a witness, and a mutant shows why. Reading the
shard number out of `special_scalars` on the current context -- the only way a
local-path number can be seen at all, since `createLocalPlan` writes it on the
SELECT's own context copy rather than the query context -- makes the arm abort
on `Shard number is greater than shard count`. So honouring a local-path shard
number would reintroduce the failure this test guards against, and the arm
pins that.

Measured on the arm: 20/20 with settings randomization pinned and 20/20 with it
on. The `parallel_replicas` slice is unchanged against pristine master (24 fail
on both, no test failing on only one side).
Comment thread src/Interpreters/Cluster.cpp Resolved
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b164bf5

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link I will post here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Finish Workflow / Post Hooks (new_tests_check.py) not PR-caused: all five Bugfix validation (*) check-runs completed as skipped at 16:34:57Z, so the hook read them as PENDING and reported passed: none. They were dropped because six amd_asan_ubsan jobs were cancelled (not failed) in a 6-minute window (16:04:42Z-16:10:01Z), and Build profile diff + Finish Workflow cancelled after them. Cross-PR in the same 14:00-17:00Z window: the same db disk, old analyzer, 1/6..6/6 shards show job-level errors on 3 distinct PRs, targeted on 4 — while sibling shards 3/6, 4/6, 6/6 and sequential 3/3 passed on this head. Family breadth 14 d: 346 rows / 210 distinct PRs / 0 master measured and closed as a faithful upstream cascade, not a hook defect — write-up #104350 (comment) (10/10 sampled passed: none reds in 12 h were genuine upstream cascades)

No test failed on this head. CIDB over this commit returns exactly one FAIL/ERROR row — the
Post Hooks gate row above. Every test check is green, including Unit tests (asan_ubsan) 19615
passing assertions, (tsan) 19614, (msan) 19611, Fast test 10429, Stateless tests (amd_debug, parallel) 12367, (amd_tsan, parallel) 12302, all four flaky checks and Style check.

The eight non-green check-runs are all cancelled, none failure.

Session id: cron:our-pr-ci-monitor:20260807-040000

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged origin/master into the branch as fa8eef593559 (the branch was 304 commits behind; clean merge, no contrib gitlink drift, and the diff against master is unchanged in scope).

The reason for the merge is the sole red on b29383d01b76: Build profile diff ERROR / RuntimeError: CI logs cluster query failed on the binary_symbols query, i.e. the fleet-wide infra issue #120462. Its fix — #121048, "Build profile diff is green when the CI logs cluster does not answer" — merged into master at 2026-09-21T16:14Z as 1a75e54f4c38, which is now in this branch, so that red should clear on the next run. Everything else on that head was green: 159 SUCCESS, 15 SKIPPED, 0 other red.

Verified on the merged tree: ninja clickhouse unit_tests_dbms exit 0 with no warnings, and the ParallelReplicasShardScope gtest suite passes 27/27. The two surviving admission guards are intact after the merge — Planner/findParallelReplicasQuery.cpp:371 and QueryPlanOptimizationSettings.cpp:429 (the three old-analyzer storage guards died with the code paths master removed, as described on the previous push).

No unresolved review threads. The AI Review verdict still reads Changes requested, but its only Major is the self-labelled [dismissed by author -- discussion_r3729561325] Planner early-gate item, and there are no Minimum required actions — nothing owed.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged origin/master into the branch as e0b3f366a9ad (the branch was 591 commits behind; clean merge, no contrib gitlink drift, and the diff against master is unchanged in scope: the same 17 files).

The only red on fa8eef593559 (1399/1406 OK) was Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 +37.8%. That is a master_head shard, i.e. a baseline-vs-baseline comparison that never executes this PR's code, and it is the known flake tracked in #121456 with the fix #121090 still open. The merge brings the branch current and gives CI a fresh run; I will re-merge once the fix lands.

Locally after the merge: all seven changed dbms translation units and gtest_parallel_replicas_shard_scope.cpp compile with no warnings. No review threads are open (10/10 resolved) and the AI Review verdict lists no required actions.

Comment thread src/Databases/DatabaseReplicated.cpp Resolved
…ame and path, not the path alone

`zookeeper_path` is unique only inside one Keeper: `DatabaseReplicated::getZooKeeper`
resolves the database through `zookeeper_name`, so two unrelated databases mounted at
`aux1:/clickhouse/db` and `aux2:/clickhouse/db` with the same ordered shard names built
the same shard-scope identity, and a `_shard_num` produced by one still looked `Scoped`
on the other - the wrong-shard read (or `Shard number is greater than shard count`)
this PR removes.

The key is now `Cluster::makeKeeperScopeKey(zookeeper_name, zookeeper_path)`, the
length-prefixed `<name>:<path>` form `ClusterDiscovery::makeCluster` already used
inline; both callers share the helper. New gtest arm
`ReplicatedDatabasesSharingThePathOnAnotherKeeperAreForeign`: same path and shard
names on two Keepers are `Foreign`, the same Keeper is still `Scoped`, and moving
characters across the name/path boundary is not the same key. Suite 28/28.

ClickHouse#113589 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed d1582cf1a225, taking up the one open review thread (discussion_r4073271856): the Replicated database shard-scope identity was keyed by zookeeper_path alone, and a path is unique only inside one Keeper. Two unrelated databases mounted at the same path on two auxiliary Keepers with the same ordered shard names built the same identity, so a _shard_num produced by one still looked Scoped on the other.

The change. Cluster::makeKeeperScopeKey(zookeeper_name, zookeeper_path) is the new shared helper, producing the length-prefixed <name>:<path> key that ClusterDiscovery::makeCluster already used inline; DatabaseReplicated::updateCluster and ClusterDiscovery::makeCluster both call it. No change for a database on the default Keeper beyond the prefix. Coverage. New gtest arm ReplicatedDatabasesSharingThePathOnAnotherKeeperAreForeign; ParallelReplicasShardScope suite 28/28 locally, ninja unit_tests_dbms exit 0.

Branch is 70 commits behind master with a same-day merge base and GitHub reports MERGEABLE, so no master merge this time.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: Performance Comparison (arm_release, master_head, 6/6) and provide a fix in a separate PR. If the fix is already in progress, link it here.

This is not a performance regression. fetch_perf_report.py shows 0 slower queries on all six arm shards. The shard failed in the new dashboard gate added by #120927 (perf_dashboard_gate in ci/jobs/performance_tests.py): dashboard did not serve this shard within 600s: HTTP 404 ... test comparison details not found. The problem is fleet-wide. In CIDB the same performance dashboard verdict unavailable: dashboard did not serve this shard within 600s message appears about 40 times a day on master (pull_request_number = 0) every day from 2026-09-19 to 2026-09-22, mostly as no master run for sha ... yet. I found no open issue or PR that fixes it.

The rest of the PR is ready: 11/11 review threads are resolved, the AI Review verdict is Approve, and every other check on d1582cf1a225 is green.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is quite complicated. Acceptable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 25, 2026
Merged via the queue into ClickHouse:master with commit 06108f9 Sep 25, 2026
177 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Sorry for the late reply, I missed this request.

Investigated. The shard failed before the dashboard had anything to judge. At the REPORT stage play.clickhouse.com refused the connection (Failed to establish a new connection: [Errno 111] Connection refused), so Insert raw query metrics data, Insert historical data and Insert report aggregates each printed CIDB not ready - skipping ... and passed. These uploads are fail-open because they used to be informational only, but since #120927 the dashboard computes the verdict from the tables these steps upload. The gate then waited 600 s for data that was never sent and failed the shard. The dashboard still has no data for this shard today.

It is the common case. Outside the nightly master shape that #121847 fixed (none since it merged), 76 shards failed with this message since 2026-09-22, 70 of them today between 19:05 and 19:49 UTC on 21 PRs and on master. In 74 of the 76 jobs every upload step was skipped or its insert failed (Connection refused, TOO_MANY_SIMULTANEOUS_QUERIES or a read timeout from play.clickhouse.com); in the other 2 the uploads went through and the dashboard was only late: it serves both runs now. No open PR changes this path.

I'll send the fix in a separate PR and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR: #122369. It retries the three uploads the verdict is computed from within the gate's existing 600 s budget, with an insert_deduplication_token so a retried INSERT that had already committed is not doubled. If one of them still did not land, the gate fails at once and names it instead of waiting for the dashboard. A shard without a verdict still fails.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 26, 2026
The REPORT-stage uploads of a performance shard probed CIDB once and
skipped the whole step when that probe failed ("CIDB not ready -
skipping"), and a failed INSERT was not retried either. That was fine
while the tables were informational (ClickHouse#108712), but since ClickHouse#120927 the
performance dashboard computes the master_head verdict from exactly
these tables. A CIDB refusal of seconds or an overload of minutes
therefore dropped the shard's rows, and perf_dashboard_gate then waited
600 s for data that was never sent and failed the shard with "dashboard
did not serve this shard within 600s", blaming the dashboard.

Measured: ClickHouse#113589 arm 6/6 skipped all three uploads on "Connection
refused" and failed after 614 s. On 2026-09-25 a CIDB overload
(TOO_MANY_SIMULTANEOUS_QUERIES, read timeouts) failed 70 shards on 21
PRs and master. In 74 of the 76 occurrences since 2026-09-22 that are
not the time zone shape fixed by ClickHouse#121847, an upload was skipped or
failed. The same run of ClickHouse#122252 is the control: amd 1/6 uploaded and
got its verdict in 2 s, while arm 6/6 skipped the uploads and failed.

Now one helper runs all four INSERT sites. In master_head mode the
three tables the verdict is computed from (query_metric_runs_v1,
query_metrics_v2, perf_test_times_v1) are retried every 60 s until one
600 s deadline, which is taken when the uploads start and shared with
the gate's wait. The other tables keep a single attempt, and nothing is
sent after the deadline. Every attempt carries the same
insert_deduplication_token, because some INSERTs that timed out on the
client had committed on the server. If one of the three inputs was not
uploaded, the gate fails at once and names it instead of polling the
dashboard. A shard without a verdict still fails, as ClickHouse#120927 designed,
and release_base keeps its single call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-564d)

4 participants