Repository navigation
Exclude inactive replicas when sizing parallel replicas - #107805
Conversation
The parallel replicas reading coordinator distributes mark segments by hashing them into `replicas_count` buckets, where `replicas_count` comes from the number of replicas in the cluster (`ParallelReplicasReadingCoordinator` is created with `max_replicas_to_use`, derived from `getAllNodeCount`). When the cluster contains replicas that are registered but inactive - e.g. stale registrations left over after autoscaling, or a stopped replica in a `Replicated` database - they were still counted. Segments hashed to those inactive buckets become "phantom" work that only the source replica picks up, concentrating a large fraction of the data on a single node and producing a severe work-distribution skew. `prepareConnectionPoolsForParallelReplicas` now consults the same `is_active` signal exposed in `system.clusters` (via `DatabaseReplicated::tryGetReplicasInfo`, or `SharedDatabaseCatalog` in ClickHouse Cloud), drops inactive replicas from the pool set, and sizes the coordinator by the number of active replicas. It falls back to the previous behaviour when liveness is unknown, inconsistent with the cluster definition, or reports zero active replicas. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [d3fa1a5] Summary: ✅
AI ReviewSummaryThis PR fixes the main single-shard inactive-replica skew and the Findings❌ Blockers
Final Verdict❌ Request changes |
…as-skip-inactive-nodes
This PR added `#include <Databases/DatabaseReplicated.h>` to
`ClusterProxy/executeQuery.cpp`, which brought `ReplicasInfo` under
clang-tidy in that translation unit and surfaced a pre-existing
`cppcoreguidelines-pro-type-member-init` error: the `bool
replicas_belong_to_shared_catalog` field was left uninitialized.
Default-initialize it with `{}`, matching the sibling `ReplicaInfo`
struct. Fixes the `Build (arm_tidy)` failure.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The style check requires an `__init__.py` in every integration test directory. Add the empty file for `test_parallel_replicas_skip_inactive_replicas` to fix the `Style check` failure. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| size_t available_replicas = shard.getAllNodeCount(); | ||
| if (!is_active.empty()) | ||
| { | ||
| available_replicas = std::count(is_active.begin(), is_active.end(), true); |
There was a problem hiding this comment.
optional: ReadFromMergeTree still derives ParallelReadingExtension::total_nodes_count from getAllNodeCount (registered count) while the coordinator is now sized by this active count, so mark_segment_size is computed for the registered count. Harmless (no skew, no out-of-range), just leaves segment sizing inconsistent with coordinator sizing — could align it to the active count too.
There was a problem hiding this comment.
Acknowledged — this is the harmless inconsistency you noted: ReadFromMergeTree.cpp:511 still sizes total_nodes_count (and hence mark_segment_size) from getAllNodeCount(). Aligning it to the active count cleanly needs the active-replica computation shared with that code path, so I left it out of this fix to keep the scope tight; tracking it as a follow-up. No skew or out-of-range as you said.
There was a problem hiding this comment.
followup (optional, fine as a separate PR): source total_nodes_count from the active replica count too, so segment sizing matches the coordinator sizing. Non-blocking here — it can't go out of range (replica numbering is bounded by replicas_count), and smaller segments if anything balance better, so no skew is reintroduced.
There was a problem hiding this comment.
@groeneai please take the followup once this pr has been merged.
There was a problem hiding this comment.
Will do. Once this merges I'll open a separate PR sourcing ParallelReadingExtension::total_nodes_count (the mark_segment_size derivation in ReadFromMergeTree.cpp) from the active replica count via the getActiveReplicasForParallelReplicas helper added here, so segment sizing matches the coordinator sizing. Tracking it now.
`clickhouse-gh` pointed out that the liveness lookup missed `all_groups.<db>` `Replicated` database clusters: `tryGetReplicatedDatabaseCluster` (used by `Context::tryGetCluster`) strips `DatabaseReplicated::ALL_GROUPS_CLUSTER_PREFIX` before resolving the database, but `getActiveReplicasForParallelReplicas` looked the database up by the prefixed cluster name directly. So with `cluster_for_parallel_replicas = 'all_groups.<db>'` the liveness vector came back empty and the coordinator fell back to counting inactive replicas again. Strip the `all_groups.` prefix before the `DatabaseReplicated` lookup, mirroring `tryGetReplicatedDatabaseCluster`, and also accept the shared-catalog all-groups cluster name in the `CLICKHOUSE_CLOUD` path (mirroring `StorageSystemClusters`). Add `test_parallel_replicas_skip_inactive_replicas_all_groups`: the same inactive-replica scenario over the `all_groups.<db>` cluster, asserting the coordinator is sized by the active replica count. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`tiandiwonder` pointed out that the local replica is the initiator and is online by definition, but if its own `active` znode is transiently missing it would be reported inactive, filtered out of the pool here, and then `findLocalReplicaIndexAndUpdatePools` would throw `INCONSISTENT_CLUSTER_DEFINITION` - turning a query that used to run into an error. Force the local replica's liveness slot to active before counting and filtering, identifying it the same way `findLocalReplicaIndexAndUpdatePools` does (host name and port against `shard.local_addresses`). This keeps the available-replica count and the pool set consistent. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`tiandiwonder` pointed out that `SELECT count()` is answered from metadata by `optimize_trivial_count_query`, which never engages parallel replicas, so the reading coordinator is not created and the `replicas_count=2` assertion would fail even when the fix is correct. Switch both tests to `SELECT sum(key)`, a genuine data-reading query that exercises mark distribution. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…as-skip-inactive-nodes
…catalog
Switch the default member initializer of `ReplicasInfo::replicas_belong_to_shared_catalog`
from `{}` to `= false`, as requested in review. Both forms value-initialize the field and
silence the `cppcoreguidelines-pro-type-member-init` warning under `-Werror`, but the
explicit `= false` is clearer for a `bool`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…point test The safeguard that keeps the local (initiator) replica in the parallel-replicas pool even when liveness reports it inactive was previously untested: the existing test would still pass if the safeguard were removed, because the transient ZooKeeper window (the initiator's own `active` ephemeral momentarily missing) cannot be reproduced deterministically from outside - it is recreated on the next reconnect. Add a REGULAR failpoint `parallel_replicas_force_local_replica_inactive` that forces the local replica's liveness to `false` on the initiator right before the safeguard runs, and an integration test (`test_parallel_replicas_local_replica_forced_inactive`) that enables it and asserts the query still succeeds and the coordinator is still sized for all active replicas. Without the safeguard, the local replica would be filtered out and `findLocalReplicaIndexAndUpdatePools` would throw `INCONSISTENT_CLUSTER_DEFINITION`. The force-active block is refactored to find the local replica index once (the same way `findLocalReplicaIndexAndUpdatePools` identifies it) so both the failpoint and the safeguard reference it. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed
The only remaining open thread is the optional The C++ changes were verified to compile against the merged tree. The integration test could not be run locally (no container build here) — relying on CI. The |
…as-skip-inactive-nodes
…as-skip-inactive-nodes
…licas The INSERT SELECT path builds the local SELECT pipeline first - which creates the `ParallelReplicasReadingCoordinator` and sizes it from a liveness snapshot (`is_active`, see `system.clusters`) - and only then builds the remote pipelines. `executeInsertSelectWithParallelReplicas` called `prepareConnectionPoolsForParallelReplicas` a second time to build those remote pools, recomputing the active replica set from a fresh liveness snapshot. If a replica's liveness changed between the two passes, the recomputed set could diverge from the one the coordinator was sized with: a larger set assigns a replica number that is out of range for the already-sized coordinator (rejected with `Replica number (N) is bigger than total replicas count (M)`), and a smaller set silently drops a replica without `markReplicaAsUnavailable`, leaving the coordinator waiting on an announcement that never comes. Carry the exact connection pools and local replica numbering decided while building the local pipeline (captured from the `ReadFromParallelRemoteReplicasStep` removed from the plan) into the remote-pool pass, so it reuses the coordinator's replica set instead of recomputing liveness. The fresh `prepareConnectionPoolsForParallelReplicas` call now runs only on the path that has no coordinator yet. Add a `ONCE` failpoint `parallel_replicas_insert_select_drop_active_replica` that drops one active non-local replica from the first (coordinator-building) snapshot only, and an integration test (`test_parallel_replicas_insert_select_coordinator_reuse`) that uses it to deterministically reproduce the liveness drift and assert the reused coordinator and remote pool set stay consistent. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Fix. Test. New Verified locally: clean build, the new integration test passes, and the existing The only remaining open thread is the optional |
…as-skip-inactive-nodes
…oordinator The `test_parallel_replicas_insert_select_coordinator_reuse` regression test arms the `ONCE` failpoint `parallel_replicas_insert_select_drop_active_replica` before running the `INSERT SELECT`. But `buildInsertSelectPipelineParallelReplicas` first calls `isSuitableForInsertSelectWithParallelReplicas`, which builds a throwaway parallel-replicas plan only to detect whether the `SELECT` reads with parallel replicas. Building that discarded plan runs the same connection-pool preparation (`prepareConnectionPoolsForParallelReplicas`) as the real coordinator-building pass, so it consumed the `ONCE` failpoint first. The executed coordinator was then sized for all 3 active replicas, and the test passed even with the old recompute behaviour it is meant to guard against. Suppress the test failpoint while the discarded suitability-probe plan is built (via the thread-local `in_insert_select_suitability_probe`), so the `ONCE` drop lands on the executed coordinator. The coordinator is now genuinely sized for 2 replicas while all 3 are active; a second pass that recomputed liveness would assign an out-of-range replica number and the coordinator would reject it, so the test fails without the reuse fix and passes with it. Addresses the AI review on #107805 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Status (CI triage) Re-checked CI for
Branch tip is the CI SHA; 272 commits behind Net: ready to merge once the stress hung-check (#107941) is re-run or overridden. |
|
Re-triaged
Since the previous run had fully completed, I triggered a fresh re-run of |
|
CI re-triage for Public stress reruns failed again (still the chronic hung-check flake, non-blocking). The two
I re-ran the three failed private shards (run No re-merge: Only real blocker left: the |
|
CI re-triage for
Net: ready to merge once the non-required hung-check (#107941) is overridden and the stale |
|
@tiandiwonder — re-requesting your review to supersede the stale Every "required" inline thread you raised has since been addressed and resolved:
The only open thread is your explicitly-optional
|
…as-skip-inactive-nodes # Conflicts: # src/Interpreters/ClusterProxy/executeQuery.h # src/Storages/MergeTree/ParallelReplicasReadingCoordinator.h
|
Re-merged My earlier triages said "no re-merge" because Both conflicts were purely additive and I kept both sides:
Semantic integration verified (not just textual). I did not run a local full build (submodules are not initialized in this worktree, and the merge pulls in ~1800 Remaining blockers are unchanged from the previous triage: the stale |
…cluster Address AI review: `getActiveReplicasForParallelReplicas` re-derived the liveness source from the `cluster_for_parallel_replicas` name and always consulted a same-named `Replicated` database. But `Context::getCluster` resolves a configured or discovered cluster before a `Replicated` database of the same name, so when a configured cluster shadows the database, the resolved `cluster` is the configured one. Its replica addresses carry no `database_shard_name`/`database_replica_name`, so `DatabaseReplicated::tryGetReplicasInfo` probes non-existent ZooKeeper nodes (`.../replicas/|/active`) and reports every replica inactive. The coordinator then collapses onto the local replica, so the new active-replica sizing silently disables parallel replicas for that setup. Only trust the database liveness when the resolved cluster really is this database's own cluster (matched against `tryGetCluster`/`tryGetAllGroupsCluster`). Otherwise leave liveness unknown and keep the previous "use all replicas" behaviour, matching how `system.clusters` reports such configured clusters with an unknown `is_active`. Add integration test `test_parallel_replicas_cluster_shadows_replicated_db`, where `cluster_for_parallel_replicas` names a configured cluster that shares its name with a `Replicated` database and asserts the coordinator is sized by all online replicas rather than falling back to the single local replica. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI review's "Request changes" finding in 86c9a47. After re-merging Fix: only trust the database liveness when the resolved cluster really is this database's own cluster (matched against |
| /// Only trust the database liveness when the resolved cluster really is this database's own | ||
| /// cluster (`system.clusters` likewise reports such configured clusters with unknown `is_active`). | ||
| const ClusterPtr database_cluster = all_groups ? replicated->tryGetAllGroupsCluster() : replicated->tryGetCluster(); | ||
| if (database_cluster == cluster) |
There was a problem hiding this comment.
database_cluster == cluster is too strict for the distributed-table path. prepareClusterForParallelReplicas narrows _shard_num queries to not_optimized_cluster->getClusterWithSingleShard(...), and Cluster::SubclusterTag builds a fresh Cluster object while preserving the shard's database_shard_name / database_replica_name metadata. So for a multi-shard Replicated database, the shard-scoped cluster can still be this database's own cluster for liveness purposes, but it will never compare equal to replicated->tryGetCluster() here.
That drops is_active back to "unknown" for every distributed subquery over such a database, so inactive replicas in the selected shard are counted again and the original work-skew bug survives in the very mode prepareClusterForParallelReplicas exists to support. Please accept shard subclusters of the replicated-db cluster here (for example by comparing replica identities or by projecting the full-cluster liveness onto the selected shard) instead of requiring pointer identity.
| auto [local_pipeline, coordinator] = buildLocalInsertSelectPipelineForParallelReplicas(query, table, context); | ||
| return ClusterProxy::executeInsertSelectWithParallelReplicas(query, context, std::move(local_pipeline), coordinator); | ||
| auto [local_pipeline, parallel_replicas_info] = buildLocalInsertSelectPipelineForParallelReplicas(query, table, context); | ||
| auto coordinator = parallel_replicas_info.coordinator; |
There was a problem hiding this comment.
This can still be null even after the earlier suitability probe succeeded. The probe and the real local-plan build are separate passes; if liveness shrinks in between (for example the non-local replicas go inactive, so executeQueryWithParallelReplicas hits connection_pools.size() == 1 and returns only the local plan), dropReadFromRemoteInPlan yields {} here.
Passing that null shared_ptr into executeInsertSelectWithParallelReplicas is unsafe because the parameter type there is std::optional<ParallelReplicasReadingCoordinatorPtr>: std::optional becomes engaged even when the contained shared_ptr is null. The reuse branch then runs with empty pools / no replica index and hits local_replica_index.value() or (*coordinator) instead of simply falling back to the already-built local INSERT SELECT pipeline. Please detect the empty parallel_replicas_info.coordinator here and return local_pipeline directly (or pass std::nullopt and handle that as the non-reuse path).
The parallel-replicas liveness lookup called
`SharedDatabaseCatalog::instance().tryGetReplicasInfo(cluster)`, but
`SharedDatabaseCatalog` has no `tryGetReplicasInfo` member, so the
`CLICKHOUSE_CLOUD` build failed to compile `executeQuery.cpp`. The public
build compiles this branch out (`SharedDatabaseCatalog` is Cloud-only), so
the error was only caught by the private sync build ("CH Inc sync": build
failed at `executeQuery.cpp:649`).
Use `getClusterWithReplicasInfo` instead - the same accessor
`system.clusters` uses to report `is_active` for the shared catalog cluster.
It looks the info up by the already-matched name (the plain or the
`all_groups.` spelling), and the existing downstream size and zero-active
checks keep the result safe if it ever mismatches.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Fixed a real The Fix: use The two open AI-review findings (multi-shard |
…as-skip-inactive-nodes
|
Merged The merge is clean (no conflicts). The only change Remaining state: the two AI-review findings — the multi-shard |
| const String & catalog_cluster_name = SharedDatabaseCatalog::instance().getClusterName(); | ||
| if (cluster_name == catalog_cluster_name | ||
| || cluster_name == SharedDatabaseCatalog::ALL_GROUPS_CLUSTER_PREFIX + catalog_cluster_name) | ||
| replicas_info = SharedDatabaseCatalog::instance().getClusterWithReplicasInfo(cluster_name).second; |
There was a problem hiding this comment.
This still drops back to "liveness unknown" for shard-scoped shared-catalog queries. prepareClusterForParallelReplicas turns _shard_num requests into getClusterWithSingleShard(...), but this branch re-reads replica info by cluster_name only, so replicas_info stays at full-cluster cardinality and then gets cleared in prepareConnectionPoolsForParallelReplicas when it does not match the selected shard's getAllNodeCount().
That means distributed subqueries over a multi-shard shared-catalog cluster will keep counting inactive replicas in the chosen shard, so the same work-skew this PR fixes for single-shard/shared-name cases still survives in ClickHouse Cloud. Please project the shared-catalog liveness onto the selected subcluster (or otherwise prove the returned info corresponds to cluster) before returning it here.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 105/146 (71.92%) · Uncovered code |
…oordinator The `test_parallel_replicas_insert_select_coordinator_reuse` regression test arms the `ONCE` failpoint `parallel_replicas_insert_select_drop_active_replica` before running the `INSERT SELECT`. But `buildInsertSelectPipelineParallelReplicas` first calls `isSuitableForInsertSelectWithParallelReplicas`, which builds a throwaway parallel-replicas plan only to detect whether the `SELECT` reads with parallel replicas. Building that discarded plan runs the same connection-pool preparation (`prepareConnectionPoolsForParallelReplicas`) as the real coordinator-building pass, so it consumed the `ONCE` failpoint first. The executed coordinator was then sized for all 3 active replicas, and the test passed even with the old recompute behaviour it is meant to guard against. Suppress the test failpoint while the discarded suitability-probe plan is built (via the thread-local `in_insert_select_suitability_probe`), so the `ONCE` drop lands on the executed coordinator. The coordinator is now genuinely sized for 2 replicas while all 3 are active; a second pass that recomputed liveness would assign an out-of-range replica number and the coordinator would reject it, so the test fails without the reuse fix and passes with it. Addresses the AI review on ClickHouse#107805 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…licas-skip-inactive-nodes Exclude inactive replicas when sizing parallel replicas
The reading coordinator is sized by the active replicas of `cluster_for_parallel_replicas`, at most `max_parallel_replicas` (ClickHouse#107805), but `ReadFromMergeTree` still passed the registered replica count of the cluster as `total_nodes_count`, which `chooseSegmentSize` uses to pick the automatic `mark_segment_size`. With stale registrations of a `Replicated` database, or a cluster larger than `max_parallel_replicas`, the heuristic divided by replicas that take no part in the query. Extract the liveness half of `prepareConnectionPoolsForParallelReplicas` into `getParallelReplicasLiveness` and add `getReplicasCountForParallelReplicas`, which counts replicas by the coordinator's rules. `ReadFromMergeTree` computes it once per step (the liveness may be a Keeper read, and a read in order builds an extension per split) and uses it for every `ParallelReadingExtension`. The `chooseSegmentSize` trace line now logs the count, and the existing integration test checks it with one of three replicas stopped and with `max_parallel_replicas = 2`. Related: ClickHouse#107805 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #57968
Problem
The parallel replicas reading coordinator distributes mark segments across replicas by consistent-hashing them into
replicas_countbuckets, wherereplicas_countis derived from the number of replicas in the cluster (getAllNodeCount). When the cluster contains replicas that are registered but inactive — e.g. stale registrations left over after autoscaling, or a stopped replica in aReplicateddatabase — they were still counted. Segments hashed to those inactive buckets become "phantom" work that only the source replica can pick up, so a single replica ends up reading a large fraction of the data while the others sit idle.This was observed on a 50-replica service whose cluster definition had drifted to 100 entries (50 active + 50 stale,
is_active = 0). A full-table aggregation (~170 B rows) was gated by one replica reading ~24% of the data:max_parallel_replicasis_activeinsystem.clustersalready reported only 50 active replicas, but the coordinator ignored it and sized itself by the full count.This is a regression from #57968 (24.1), which concentrated leftover/unclaimed segments on the source replica "to preserve cache locality"; before that change, any replica could steal them, so the distribution stayed even — matching reports that this used to work well on older versions.
Fix
prepareConnectionPoolsForParallelReplicasnow consults the same liveness signalsystem.clustersuses (DatabaseReplicated::tryGetReplicasInfo, orSharedDatabaseCatalogin ClickHouse Cloud), drops inactive replicas from the pool set, and sizes the coordinator by the number of active replicas. It falls back to the previous behaviour when liveness is unknown (e.g. non-Replicatedclusters), inconsistent with the cluster definition, or reports zero active replicas.Integration test added (
test_parallel_replicas_skip_inactive_replicas): aReplicateddatabase across three nodes, one stopped so it stays registered butis_active = 0; the test asserts the coordinator is created withreplicas_count=2(the active count) rather than3.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a severe work-distribution skew with parallel replicas when the cluster contains inactive replicas (for example, stale entries left after autoscaling). Such replicas are no longer counted by the reading coordinator, so work is balanced across the online replicas instead of piling onto a single one.
🤖 Generated with Claude Code
Version info
26.7.1.502(included in26.7and later)