Skip to content

Exclude inactive replicas when sizing parallel replicas - #107805

Merged
alexey-milovidov merged 19 commits into
masterfrom
fix-parallel-replicas-skip-inactive-nodes
Jul 3, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
fix-parallel-replicas-skip-inactive-nodes

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 17, 2026 •

Copy link
Copy Markdown
Member

Related: #57968

Problem

The parallel replicas reading coordinator distributes mark segments across replicas by consistent-hashing them into replicas_count buckets, where replicas_count is 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 a Replicated database — 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_replicas wall time skew (busiest / median rows) Σ(worker rows) / actual
100 (= configured, incl. inactive) 108.9 s 15.1× (39.96 B vs 2.64 B) 1.82× (redundant reads)
50 (= active replicas) 50.9 s 1.4× (5.37 B vs 3.78 B) 1.04×

is_active in system.clusters already 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

prepareConnectionPoolsForParallelReplicas now consults the same liveness signal system.clusters uses (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 (e.g. non-Replicated clusters), inconsistent with the cluster definition, or reports zero active replicas.

Integration test added (test_parallel_replicas_skip_inactive_replicas): a Replicated database across three nodes, one stopped so it stays registered but is_active = 0; the test asserts the coordinator is created with replicas_count=2 (the active count) rather than 3.

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

  • Merged into: 26.7.1.502 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3fa1a5]

Summary: ✅


AI Review

Summary

This PR fixes the main single-shard inactive-replica skew and the INSERT SELECT coordinator-reuse race, and the new regression tests cover those happy paths well. I would still keep this as Request changes: the local INSERT SELECT reuse path can still wrap a null coordinator in an engaged std::optional, and the active-replica sizing still drops back to "use all replicas" for shard-scoped distributed queries, both for Replicated databases and for the shared-catalog Cloud path.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterInsertQuery.cpp:739, src/Interpreters/ClusterProxy/executeQuery.cpp:1320-1340] buildLocalInsertSelectPipelineForParallelReplicas can legitimately return an empty LocalPlanParallelReplicasInfo when the second plan build sees only one usable replica and executeQueryWithParallelReplicas keeps the query local. This call still passes parallel_replicas_info.coordinator as a std::optional<ParallelReplicasReadingCoordinatorPtr>, so a null shared_ptr becomes an engaged optional, the reuse branch runs, and release builds dereference (*coordinator) instead of just returning the already-built local pipeline.
    Suggested fix: detect !parallel_replicas_info.coordinator in buildInsertSelectPipelineParallelReplicas and return local_pipeline directly, or pass std::nullopt and make executeInsertSelectWithParallelReplicas treat that as the non-reuse path.

⚠️ Majors

  • [src/Interpreters/ClusterProxy/executeQuery.cpp:685-687] database_cluster == cluster is still too strict for distributed-table subqueries over multi-shard Replicated databases. prepareClusterForParallelReplicas narrows _shard_num queries with getClusterWithSingleShard(...), which creates a new Cluster object while preserving the per-replica database shard/replica names that tryGetReplicasInfo needs. Because this pointer check rejects that subcluster, liveness falls back to "unknown" and inactive replicas in the selected shard are counted again, so the original skew bug survives exactly in the distributed mode this helper was added to support.
    Suggested fix: accept shard subclusters of the database cluster by matching replica identities or by reading the full-cluster liveness once and projecting it onto the selected shard.
  • [src/Interpreters/ClusterProxy/executeQuery.cpp:657] The Cloud/shared-catalog branch has the same shard-scope hole. For _shard_num queries it re-fetches liveness by cluster_name, so the returned replica info still describes the full cluster; prepareConnectionPoolsForParallelReplicas then clears it on the size mismatch with the selected shard and falls back to all registered replicas. Inactive replicas in the chosen shard therefore still create the same coordinator skew in ClickHouse Cloud.
    Suggested fix: derive shared-catalog liveness from the actual cluster object (or otherwise project the full-cluster info onto the selected subcluster) before returning it.
Final Verdict

❌ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 17, 2026
@tiandiwonder tiandiwonder self-assigned this Jun 18, 2026
alexey-milovidov and others added 3 commits June 18, 2026 01:06
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@groeneai please take the followup once this pr has been merged.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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]>
alexey-milovidov and others added 2 commits June 18, 2026 01:20
`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]>
alexey-milovidov and others added 3 commits June 19, 2026 18:03
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 9c16d283823..398fa243497, addressing the remaining review feedback:

  • Failpoint regression test for the local-replica safeguard (tiandiwonder's "needs a regression test" / "Worth a failpoint test" points). Added a REGULAR failpoint parallel_replicas_force_local_replica_inactive that forces the initiator's liveness to false right before the force-active safeguard runs — the transient ZooKeeper window (the initiator's own active ephemeral momentarily missing) can't be reproduced deterministically from outside. New integration test test_parallel_replicas_local_replica_forced_inactive enables it and asserts the query still succeeds and the coordinator is still sized for all active replicas. Removing the safeguard makes the local replica get filtered out and the test fail with 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.
  • = false instead of {} for ReplicasInfo::replicas_belong_to_shared_catalog, as requested.

The only remaining open thread is the optional total_nodes_count / mark_segment_size alignment in ReadFromMergeTree, which @groeneai is taking as a separate follow-up PR after this merges (non-blocking, can't go out of range).

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 BuzzHouse (amd_debug) red (Inconsistent AST formatting, STID: 1941-26fa) is unrelated to this change — it is a pre-existing AST-formatting bug for a no-argument window function in CODEC, fixed separately in #107806. The Integration tests (amd_llvm_coverage, 4/5) "ERROR" was a job-level issue (the detailed report shows 1364/1367 passed, 0 failed), and LLVM Coverage was DROPPED as a downstream dependency of that job.

alexey-milovidov and others added 2 commits June 23, 2026 05:58
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 346cedbb6ac..5d6acd40a13, addressing the remaining blocker on the INSERT SELECT path (the reused-coordinator finding from cursor[bot]/clickhouse-gh that @tiandiwonder confirmed).

Fix. executeInsertSelectWithParallelReplicas no longer recomputes the active replica set when a coordinator already exists from the local SELECT pipeline. The coordinator is sized from a liveness snapshot while the local pipeline is built; calling prepareConnectionPoolsForParallelReplicas a second time could observe a different is_active set and either assign a replica number out of range for the already-sized coordinator (Replica number (N) is bigger than total replicas count (M)) or silently drop a replica without markReplicaAsUnavailable. Instead, the exact connection pools and local replica numbering decided for the coordinator are now captured from the ReadFromParallelRemoteReplicasStep when it is dropped from the plan (dropReadFromRemoteInPlan returns them via LocalPlanParallelReplicasInfo) and carried into the remote-pool pass, so both passes share one snapshot. The fresh prepareConnectionPoolsForParallelReplicas call now runs only on the path that has no coordinator yet. Added chasserts tying the reused pool count to ParallelReplicasReadingCoordinator::getReplicasCount and the local index to getSnapshotReplicaNum.

Test. New ONCE failpoint parallel_replicas_insert_select_drop_active_replica drops one active non-local replica from the first (coordinator-building) snapshot only, deterministically reproducing the liveness drift between the two passes. New integration test test_parallel_replicas_insert_select_coordinator_reuse enables it, runs an INSERT SELECT with parallel replicas, and asserts every row is inserted and the reused coordinator stays consistent (sized for 2 while all 3 are actually active); without the fix the second pass assigns the out-of-range replica and the coordinator rejects it.

Verified locally: clean build, the new integration test passes, and the existing 03394_pr_insert_select* stateless tests still pass.

The only remaining open thread is the optional total_nodes_count follow-up, which @groeneai is taking in a separate PR after this merges.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (CI triage)

Re-checked CI for 502d5fae (current branch tip):

  • AI Review: ✅ Approve. 154/154 functional tests pass; all earlier review points are addressed (failpoint regression tests, the INSERT SELECT coordinator-reuse fix, the force-local-active safeguard, the suitability-probe failpoint-consumption fix, and = false).
  • The only open thread is the optional total_nodes_count / mark_segment_size alignment in ReadFromMergeTree, which @tiandiwonder marked non-blocking and @groeneai is taking as a separate follow-up PR after this merges.
  • Both red checks are the same hung-check and are unrelated to this change — Hung check failed, possible deadlock found #107941. I pulled the amd_tsan hung stack: the blocked thread is in QueryAnalyzer::resolveFunction → IExecutableFunction::execute (constant-folding under executeASTFuzzerQueries / TCPHandler), with no parallel-replicas / coordinator / ClusterProxy / RemoteQueryExecutor frames anywhere. The CI summary already links both stress jobs to Hung check failed, possible deadlock found #107941 (open).

Branch tip is the CI SHA; 272 commits behind master, but the merge-base is < 1 day old and the reds are not fixable from master, so I did not re-merge (it would only reset the green CI and re-roll the same flaky hung-check).

Net: ready to merge once the stress hung-check (#107941) is re-run or overridden.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-triaged 502d5fae and re-ran the two failed stress jobs.

  • AI Review: ✅ Approve on the current tip; no code change needed.
  • All inline review threads are resolved except the optional total_nodes_count / mark_segment_size alignment in ReadFromMergeTree, which is non-blocking and @groeneai is taking as a separate follow-up PR after this merges.
  • The only two red checks are both the chronic hung-check flake Hung check failed, possible deadlock found #107941 (CI already links them to that open issue). I re-pulled the stacks: the blocked thread is under TCPHandler::runImpl → executeASTFuzzerQueries → QueryAnalyzer::resolveFunction (constant-folding in the AST fuzzer), with no parallel-replicas / coordinator / ClusterProxy / RemoteQueryExecutor frames — unrelated to this change. Both other stress variants are green.
  • Not re-merged: master has not touched any file this PR modifies since the merge-base (< 2 days old), so a re-merge would only re-roll the same flaky hung-check without validating anything.

Since the previous run had fully completed, I triggered a fresh re-run of Stress test (amd_tsan) and Stress test (arm_tsan). Ready to merge once they clear (or the hung-check is overridden).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI re-triage for 502d5fae (some state changed since the last triage).

Public stress reruns failed again (still the chronic hung-check flake, non-blocking). The two Stress test (amd_tsan) / Stress test (arm_tsan) jobs re-run earlier both completed and failed again on Hung check failed, possible deadlock found. I pulled the fresh hung_check.log from both: there is exactly one hung query — the AST fuzzer's SELECT formatQuery($$SELECT [[[[[… (deeply-nested array), and its stack is entirely QueryAnalyzer::resolve* → executeQueryImpl → TCPHandler::runImpl (constant-folding recursion). Zero ParallelReplicas / ReadingCoordinator / ClusterProxy / RemoteQueryExecutor frames on either variant. This is #107941, unrelated to this change. These jobs are not required (Mergeable Check is green), so they won't self-clear on re-run — the hung-check just needs to be overridden.

CH Inc sync red = three unrelated Cloud-only flakes (I re-triggered them). The private sync PR is ClickHouse/clickhouse-private#61367 (same head 502d5fae); all three failing shards are Cloud-only and untouched by this PR:

  • Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) — same Hung check flake; the private CI itself logged Marking … as flaky (matched … issue: #107941).
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/7) — test_refreshable_mv_no_multi_read::test_refreshable_mv_attach_without_multi_read (refreshable-MV, Cloud-only) plus ZooKeeper connection-retry errors.
  • Stateless tests (amd_asan_ubsan, SharedCatalog, meta in keeper, s3 storage, parallel) — 03052_shared_merge_tree_move_replace_partition failed on Code: 999. Coordination::Exception: … Connection loss during the test's _cleanup_database (CREATE/DROP DATABASE) step, i.e. a Keeper infra hiccup, not a test-assertion failure.

I re-ran the three failed private shards (run 28419042694).

No re-merge: master has not touched any of the 20 files this PR modifies since the merge-base (< 2 days old), so a re-merge would only re-roll the same flaky hung-check without validating anything.

Only real blocker left: the Changes requested review from @tiandiwonder (2026-06-18) is stale — every "required" inline thread has since been resolved (the one open thread is the explicitly-optional total_nodes_count / mark_segment_size follow-up that @groeneai is taking as a separate PR), and the AI Review verdict is ✅ Approve. A re-review/dismissal would unblock the merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI re-triage for 502d5fae — state improved since the last triage; no code change needed.

  • CH Inc sync is now green. The three Cloud-only private shards you re-triggered (ClickHouse/clickhouse-private#61367, same head) passed, so the sync check flipped from red to SUCCESS. Mergeable Check and Style are also SUCCESS, and the AI Review verdict is ✅ Approve on the current head.

  • Independent hung-check verification (both TSan variants). Because this PR is in the parallel-replicas path, I pulled the fresh hung_check.log from both Stress test (amd_tsan) and Stress test (arm_tsan) and confirmed the flake is unrelated:

    • Each has exactly one hung query (Row 1, no Row 2): query_id 83668267…, query: SELECT formatQuery($$SELECT [[[[[… (deeply-nested array), is_cancelled: 1, elapsed ~1570 s — the AST-fuzzer constant-folding recursion.
    • There are ClusterProxy::prepareClusterForParallelReplicas / Context::getClusterForParallelReplicas / buildQueryPlanForParallelReplicas frames elsewhere in the dump, but they belong to a separate, still-progressing fuzzer thread — the global stack dump lists all threads. No parallel-replicas query is in the hung-query list, and there are zero ParallelReplicasReadingCoordinator / RemoteQueryExecutor / prepareConnectionPoolsForParallelReplicas frames on the hung path.
    • This is #107941. These jobs are not required (Mergeable Check is green) and won't self-clear on re-run — the hung-check just needs to be overridden.
  • No re-merge. The 3-way merge with master is clean (mergeable: MERGEABLE). One modified file, src/Common/FailPoint.cpp, was touched on master since the merge-base (the new failpoint names don't collide, so no conflict), but none of those commits fix the hung-check flake, and the merge-base is only ~2 days old — a re-merge would only re-roll the same flaky hung-check without validating anything.

Net: ready to merge once the non-required hung-check (#107941) is overridden and the stale Changes requested review (2026-06-18) is superseded by a fresh review — every "required" inline thread is resolved; the sole open thread is the explicitly-optional total_nodes_count / mark_segment_size follow-up that @groeneai is taking as a separate PR after this merges.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@tiandiwonder — re-requesting your review to supersede the stale Changes requested verdict from 2026-06-18 (commit c971d8cea, now 8 commits behind 502d5fae).

Every "required" inline thread you raised has since been addressed and resolved:

  • all_groups.<db> prefix handling in getActiveReplicasForParallelReplicas (d5e70f2c927);
  • ReplicasInfo::replicas_belong_to_shared_catalog default-initialized to = false (8d02fce5be6);
  • local-initiator replica force-activated so a transiently-missing active znode can't trigger INCONSISTENT_CLUSTER_DEFINITION, with the parallel_replicas_force_local_replica_inactive failpoint test (aacd6652b85, 398fa243497);
  • both integration tests switched to a data-reading SELECT sum(key) so optimize_trivial_count_query no longer short-circuits the coordinator (9c16d283823);
  • the INSERT SELECT coordinator-reuse blocker (reused pools + local index captured via LocalPlanParallelReplicasInfo, chasserted against getReplicasCount/getSnapshotReplicaNum) plus the suitability-probe failpoint-consumption fix (502d5faed2c).

The only open thread is your explicitly-optional total_nodes_count / mark_segment_size alignment in ReadFromMergeTree, which @groeneai is taking as a separate follow-up PR after this merges — non-blocking here.

AI Review is ✅ Approve on the current head, CH Inc sync, Mergeable Check, and Style are green; the only red checks are the chronic hung-check flake #107941 (non-required; pure AST-fuzzer / QueryAnalyzer constant-folding stacks, zero parallel-replicas frames). Could you convert the stale verdict to a fresh review so the merge can proceed?

…as-skip-inactive-nodes

# Conflicts:
#	src/Interpreters/ClusterProxy/executeQuery.h
#	src/Storages/MergeTree/ParallelReplicasReadingCoordinator.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-merged master to resolve a newly-arisen conflict (head 502d5fae → merge 8836ae9a24).

My earlier triages said "no re-merge" because master had not touched any of this PR's files. That precondition changed: since the last triage, #101434 (read_in_order) merged into master and reworked the parallel-replicas coordinator / local-plan path, touching two files this PR also modifies. The branch went MERGEABLE → CONFLICTING/DIRTY, so a re-merge became required (not optional) to keep the PR mergeable.

Both conflicts were purely additive and I kept both sides:

  • src/Interpreters/ClusterProxy/executeQuery.h — kept master's new canUseLocalPlanForParallelReplicas declaration alongside this PR's LocalPlanParallelReplicasInfo struct and the changed dropReadFromRemoteInPlan return type.
  • src/Storages/MergeTree/ParallelReplicasReadingCoordinator.h — kept master's new setSnapshotReplicaNum alongside this PR's getReplicasCount accessor.

Semantic integration verified (not just textual). master's setSnapshotReplicaNum now pins the snapshot replica to the initiator-local replica_num during local-plan build (ParallelReplicasLocalPlan.cpp → coordinator->setSnapshotReplicaNum(replica_number)), and this PR's INSERT SELECT coordinator-reuse path chasserts local_replica_index == getSnapshotReplicaNum() (executeQuery.cpp). Both derive from the same local replica index (findLocalReplicaIndexAndUpdatePools → createLocalPlanForParallelReplicas → dropReadFromRemoteInPlan's getExcludePoolIndex()), so they compose consistently — the pin makes the reuse chassert deterministic rather than relying on the first-announcement side effect. I traced every call site of dropReadFromRemoteInPlan, canUseLocalPlanForParallelReplicas, setSnapshotReplicaNum, getSnapshotReplicaNum, and getReplicasCount; all signatures/uses are consistent and no master-introduced caller expects the old dropReadFromRemoteInPlan return type.

I did not run a local full build (submodules are not initialized in this worktree, and the merge pulls in ~1800 master commits); CI will build the merged tree across the full matrix. mergeable is back to MERGEABLE.

Remaining blockers are unchanged from the previous triage: the stale Changes requested review (@tiandiwonder, 2026-06-18, now many commits behind) and the non-required hung-check flake #107941. The sole open thread is the explicitly-optional total_nodes_count / mark_segment_size follow-up @groeneai is taking as a separate PR after this merges.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's "Request changes" finding in 86c9a47.

After re-merging master (which brought in the read_in_order rework of the parallel-replicas path), the AI review flagged that getActiveReplicasForParallelReplicas re-derived the liveness source purely from the cluster_for_parallel_replicas name and always consulted a same-named Replicated database. Since Context::getCluster resolves a configured/discovered cluster before a Replicated database of the same name, a configured cluster that shadows such a database would be fed into DatabaseReplicated::tryGetReplicasInfo, whose ZooKeeper paths are built from the (missing) database replica names — so every replica reads as inactive and the coordinator collapses onto the local replica.

Fix: only trust the database liveness when the resolved cluster really is this database's own cluster (matched against tryGetCluster / tryGetAllGroupsCluster); otherwise keep the previous "liveness unknown → use all replicas" behaviour, matching how system.clusters treats such configured clusters. Added test_parallel_replicas_cluster_shadows_replicated_db covering the name-collision case.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Fixed a real CH Inc sync build failure in d19f8659f87 (not a flake, as earlier triage assumed).

The #if CLICKHOUSE_CLOUD branch in getActiveReplicasForParallelReplicas called SharedDatabaseCatalog::instance().tryGetReplicasInfo(cluster), but SharedDatabaseCatalog has no tryGetReplicasInfo member (that method exists on DatabaseReplicated, not the shared catalog). The public build compiles this branch out, so it only surfaced in the private/Cloud sync build:

executeQuery.cpp:649: error: no member named 'tryGetReplicasInfo' in 'DB::SharedDatabaseCatalog'

Fix: use getClusterWithReplicasInfo(cluster_name).second, the same accessor system.clusters uses to report is_active for the shared catalog cluster (StorageSystemClusters.cpp). The name is already matched to the plain or all_groups. spelling, and the existing downstream size / zero-active checks keep the result safe.

The two open AI-review findings (multi-shard _shard_num subcluster liveness at executeQuery.cpp:678, and the null-coordinator INSERT SELECT reuse path at InterpreterInsertQuery.cpp:739) are unchanged by this commit and still awaiting a design decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master into the branch (d19f8659f87..d3fa1a5f81c) to pick up #109254, which was merged into master earlier today. #109254 adds 04319_skip_unavailable_shards_mode_table_missing to the macOS skip list — that test was a deterministic hang on Fast test (arm_darwin) (a macOS loopback-shard issue, not a flake), so it was the only non-flake red gating the required Mergeable Check and would never self-clear without this master merge.

The merge is clean (no conflicts). The only change master brought to ClusterProxy/executeQuery.cpp is the orthogonal skip_unavailable_shards_mode setting propagation from #79091 (in updateSettingsAndClientInfoForCluster), which does not touch the parallel-replicas coordinator-sizing logic; both prior fixes are intact (the database_cluster == cluster liveness guard and the Cloud getClusterWithReplicasInfo build fix).

Remaining state: the two AI-review findings — the multi-shard _shard_num sub-cluster liveness (executeQuery.cpp, if (database_cluster == cluster) is pointer-strict for getClusterWithSingleShard sub-clusters; fail-safe, falls back to all-replicas) and the null-coordinator INSERT SELECT reuse path (InterpreterInsertQuery.cpp) — are still open and await your design/scope decision (implement with regression tests, or defer as scoped follow-ups like the total_nodes_count one). The remaining Stateless tests (amd_tsan, 2/2) red is the 02884_authentication_quota TSan timing flake.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.50% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.70% -0.10%

Changed lines: Changed C/C++ lines covered: 105/146 (71.92%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 3, 2026
Merged via the queue into master with commit 510fb73 Jul 3, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-parallel-replicas-skip-inactive-nodes branch July 3, 2026 21:47
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 3, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…licas-skip-inactive-nodes

Exclude inactive replicas when sizing parallel replicas
jsc0218 pushed a commit to jsc0218/ClickHouse that referenced this pull request Nov 20, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants