Repository navigation
Bind the parallel replicas shard scope to the cluster that produced it - #113589
alexey-milovidov merged 47 commits into
Conversation
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.
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
Final-round cold review. Carriers were enumerated independently and only then compared against the Test liveness was traced, not assumed: the six value arms and six usage-oracle lines were checked Base drift was judged per file by content hash rather than by commit count: twelve of fifteen touched |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260805-204300 |
|
cc @devcrafter @KochetovNicolai, could you review this? The |
|
Workflow [PR], commit [bcbe008] Summary: ✅
AI ReviewSummaryThis PR binds the shipped Final Verdict✅ Approve LLVM Coverage ReportMeasured on commit bcbe008.
Changed lines: Changed C/C++ lines covered: 197/212 (92.92%) · Uncovered code |
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).
CI finish ledger — b164bf5Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
No test failed on this head. CIDB over this commit returns exactly one The eight non-green check-runs are all Session id: cron:our-pr-ci-monitor:20260807-040000 |
…el-replicas-foreign-shard-scope
|
🕵 Merged The reason for the merge is the sole red on Verified on the merged tree: No unresolved review threads. The AI Review verdict still reads |
…el-replicas-foreign-shard-scope
|
🕵 Merged The only red on Locally after the merge: all seven changed |
…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]>
|
🕵 Pushed The change. Branch is 70 commits behind master with a same-day merge base and GitHub reports |
|
🕵 @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. The rest of the PR is ready: 11/11 review threads are resolved, the AI Review verdict is |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is quite complicated. Acceptable.
|
Sorry for the late reply, I missed this request. Investigated. The shard failed before the dashboard had anything to judge. At the REPORT stage 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 ( I'll send the fix in a separate PR and link it here. |
|
Fixing PR: #122369. It retries the three uploads the verdict is computed from within the gate's existing 600 s budget, with an |
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]>
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]>
Related: #81738
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results and a
LOGICAL_ERRORwhen a query reads with parallel replicas inside a distributed sub-query whosecluster_for_parallel_replicasnumbers its shards differently from the cluster the query is distributed over: aVIEWcarrying its ownSETTINGS cluster_for_parallel_replicas, a read throughclusterAllReplicasof that same cluster, a cluster built by cluster discovery or by aReplicateddatabase when the two servers see a different set of shards under one name, or a plainremote_serverscluster 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
prepareClusterForParallelReplicasindexes the_shard_numscalar intocluster_for_parallel_replicasas if both described the same cluster. They are independent:_shard_numis shipped by a distributed query's initiator, whilecluster_for_parallel_replicasis a per-query setting any nestedSETTINGSclause can change, including inside aview(...).LOGICAL_ERROR: Shard number is greater than shard count, aborting debug and sanitizer builds.10000090where90is correct.21ef1f1d1c9ba39removed a_cluster_for_parallel_replicasscalar, on the reasoning that the setting alone identifies the cluster; a view with its ownSETTINGSfalsifies that. It is restored as a second column of the_shard_numblock, 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:
clusterAllReplicasderives a renumbered cluster that keeps the name, and cluster discovery andReplicateddatabase clusters renumber whichever shards they can currently see, so their identity is the ordered shard keys they discard; aremote_serverscluster 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 asenable_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
26.10.1.706-master(included in26.10and later)