Skip to content

Fix Coordination mode mismatch when same table is read in multiple modes - #106043

Closed
Algunenano wants to merge 3 commits into
ClickHouse:masterfrom
Algunenano:fix-pr-coord-mode-mismatch
Closed

Algunenano wants to merge 3 commits into
ClickHouse:masterfrom
Algunenano:fix-pr-coord-mode-mismatch

Conversation

@Algunenano

Copy link
Copy Markdown
Member

ParallelReplicasReadingCoordinator kept one ImplInterface per stream id (table name). When a single query plan read the same table in two different coordination modes — for example, a sharded-aggregator subquery (announces Default) alongside an in-order subquery (announces WithOrder) on the same table — the second announcement threw LOGICAL_ERROR: Coordination mode mismatch for stream <table>.

Key the map by (stream_id, mode) instead, so each mode gets its own coordinator. Part distribution and replica accounting were already per-coordinator, so making them per-mode is a strict generalization. The follow-up sanity check in handleRequest that re-validated the mode after lookup is no longer reachable and is removed.

Repro (no stress randomization needed):

CREATE TABLE t (a String, b UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT toString(rand() % 100000), number FROM numbers(300000);
INSERT INTO t SELECT toString(rand() % 100000), number FROM numbers(300000);

SELECT
    (SELECT sum(s), count() FROM (SELECT a, sum(b) AS s FROM t GROUP BY a
        SETTINGS enable_sharding_aggregator = 0, optimize_aggregation_in_order = 1))
    =
    (SELECT sum(s), count() FROM (SELECT a, sum(b) AS s FROM t GROUP BY a
        SETTINGS enable_sharding_aggregator = 1, optimize_aggregation_in_order = 1));
-- before: Code: 49. Coordination mode mismatch for stream default.t: got WithOrder, expected Default

Closes #106039.

cc @devcrafter @nickitat (parallel replicas coordinator), @nihalzp (the TODO in 03928_sharded_aggregation_negative.sql referencing this bug is now resolved and the subquery is restored).

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

Fix LOGICAL_ERROR: Coordination mode mismatch for stream when a single query reads the same table in different coordination modes with parallel replicas (for example, a sharded-aggregator subquery alongside an in-order subquery on the same table).

…modes

`ParallelReplicasReadingCoordinator` kept one `ImplInterface` per stream
id (table name). When a single query plan read the same table in two
different coordination modes — for example, a sharded-aggregator
subquery (announces `Default`) alongside an in-order subquery
(announces `WithOrder`) on the same table — the second announcement
threw `LOGICAL_ERROR: Coordination mode mismatch for stream <table>`.

Key the map by `(stream_id, mode)` instead, so each mode gets its own
coordinator. Part distribution and replica accounting were already
per-coordinator, so making them per-mode is a strict generalization.

Restores the in-order subquery in `03928_sharded_aggregation_negative`
that was commented out as "buggy" and adds a focused regression test
`04278_parallel_replicas_coordinator_mode_collision`.

Closes ClickHouse#106039
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2726109]

Summary: ❌


AI Review

Summary

This PR fixes a ParallelReplicasReadingCoordinator collision when one query reads the same table in both Default and ordered coordination modes by keying coordinators with (stream_id, mode). The regression test now deterministically enables parallel replicas, but the coordinator identity change also removes the previous fail-closed behavior for a real initiator/remote mode divergence on one logical read, so I am requesting changes.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp:1319] stream_to_coordinator now treats (stream_id, mode) as the stream identity. That fixes the intended two-subquery case, but it also makes an unsupported cross-replica mode divergence look like two valid coordinators. If the initiator announces Default and a remote replica announces or requests WithOrder for the same logical read, the coordinator no longer raises the old mismatch exception; instead each coordinator sees only part of the replica set and can assign the same table ranges independently, risking duplicate or missing rows.
    Suggested fix: make stream_id unique per logical read step and keep mode validation within that logical stream, or add an explicit guard that rejects cross-replica mode divergence while still allowing distinct logical reads of the same table to use different modes.
Tests

⚠️ Please add a focused regression that proves real initiator/remote mode divergence for one logical read still fails closed or is impossible after the stream identity change. The new 04278_parallel_replicas_coordinator_mode_collision test covers the desired two-mode query, but not this negative case.

Final Verdict

Status: ⚠️ Request changes

Minimum required action: preserve fail-closed handling for cross-replica coordination-mode divergence, or make the stream id carry enough logical-read identity that (stream_id, mode) cannot mask that divergence.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 28, 2026
@pamarcos pamarcos self-assigned this May 28, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 28, 2026
-- The sharded-aggregator subquery scatters rows by hash and disables read-in-order,
-- so it announces `Default`. The in-order subquery announces `WithOrder`. Both
-- subqueries share the same `ParallelReplicasReadingCoordinator` instance.
SELECT

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 regression query does not force parallel replicas, so in a normal stateless run it can execute as a local MergeTree read and never touch ParallelReplicasReadingCoordinator. Reverting the coordinator change would still pass unless the runner happens to randomize enable_parallel_replicas.

Please make the test deterministic by setting the parallel-replicas inputs explicitly before this query, e.g. automatic_parallel_replicas_mode = 0, enable_parallel_replicas = 1, max_parallel_replicas > 1, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost', and parallel_replicas_for_non_replicated_merge_tree = 1.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Fixes a LOGICAL_ERROR: Coordination mode mismatch for stream thrown when a single query reads the same table via parallel replicas in two different coordination modes (e.g., a Default-mode sharded-aggregator subquery alongside a WithOrder-mode in-order subquery). The ParallelReplicasReadingCoordinator previously keyed its per-stream ImplInterface map by stream_id alone and rejected a second announcement that arrived in a different mode. The fix changes the map key to (stream_id, mode), so each mode gets its own independent coordinator (part distribution and replica accounting were already per-coordinator, so this is a strict generalization). The redundant post-lookup mode check in handleRequest is removed since it is now unreachable.

Changes:

  • Compose the coordinator map key from stream_id + CoordinationMode via a new coordinatorMapKey helper, update getCoordinator/getOrCreateCoordinator signatures accordingly, and pass the bare stream_id to the underlying coordinator constructors/log lines.
  • Remove the now-unreachable mode-mismatch checks in getOrCreateCoordinator and handleRequest, and extend the "without ranges announcement" error to include the mode.
  • Add a regression test 04278_parallel_replicas_coordinator_mode_collision and restore the previously-disabled subquery in 03928_sharded_aggregation_negative (plus its reference).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

File Description
src/Storages/MergeTree/ParallelReplicasReadingCoordinator.h Update getCoordinator signature to take CoordinationMode; refresh comment to describe the new (stream_id, mode) keying.
src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp Introduce coordinatorMapKey, use composite key in lookups/inserts, drop unreachable mode-mismatch checks, and include mode in the "without ranges announcement" error.
tests/queries/0_stateless/04278_parallel_replicas_coordinator_mode_collision.sql / .reference New regression test reading the same table in two coordination modes within one query.
tests/queries/0_stateless/03928_sharded_aggregation_negative.sql / .reference Restore the previously-commented-out "Aggregation in order enabled" subquery now that the underlying bug is fixed.

The regression test needs the parallel-replicas path to fire deterministically
(default user profile + random-settings sweeps are not a guarantee), so opt in
via `enable_parallel_replicas` + the standard 3-replica test cluster.
The previous shape (both subqueries pin `optimize_aggregation_in_order = 1`
in their inner SETTINGS) passes on unpatched master — inner SETTINGS only
scope to the inner SELECT, so the outer planner sees the default and both
reads go through in Default mode. Move the in-order flag to the outer query
and pin the inner SETTINGS to 0 so the standard-aggregator path is planned
as `WithOrder` while the sharded path stays `Default`, which is the
collision the fix targets.
ParallelReplicasReadingCoordinator::getOrCreateCoordinator(const String & stream_id, CoordinationMode mode)
{
const auto & key = stream_id;
const auto key = coordinatorMapKey(stream_id, mode);

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.

⚠️ Keying stream_to_coordinator by (stream_id, mode) also makes a real cross-replica mode divergence look like two valid coordinators. The previous check failed closed when the initiator and a remote replica planned the same stream_id in different modes; there are still planner guards/comments for exactly that unsupported case in projectionsCommon, optimizeReadInOrder, and topKThroughJoin.

With this change, an initiator announcement in Default and a remote announcement/request in WithOrder for the same logical read create separate coordinators, so each coordinator sees only part of the replica set and can assign the same table ranges independently instead of raising the mismatch exception. That can produce duplicate or missing rows instead of the old LOGICAL_ERROR.

Please keep a fail-closed guard for cross-replica mode divergence, or make stream_id unique per logical read step and retain the mode validation inside that logical stream. The regression case should then use two distinct logical stream ids, not just the mode, to represent the two subqueries.

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.

Thanks for the careful read.

This change does not break compatibility. The wire format is the same. stream_id is still database.table and mode is still its own field on every announcement and request. The only thing that changes is the initiator's in-memory map key, from stream_id to (stream_id, mode). That key is never serialized.

So in a mixed cluster:

  • old initiator with any follower behaves like today.
  • new initiator with an old follower works. The follower sends (stream, mode) on every message, which is all the new initiator needs to look up the right coordinator.
  • new initiator with a new follower works.

No protocol version bump is needed. No version gate is needed. No rolling upgrade coordination is needed. The fix takes effect as soon as the initiator is upgraded.

I do want to acknowledge the tradeoff you raised. The old if (mode != coord->getCoordinationMode()) throw was also catching the case where the initiator and a follower planned the same logical read in different modes. With this change, those two announcements go to two different coordinators, each waits for replicas that never arrive, and the query hangs or hits a timeout instead of throwing LOGICAL_ERROR. Worse observability, not worse correctness. In exchange the fix resolves a real reproducer (#106039) and the test author's TODO.

The cleaner long term shape you suggested (per logical read stream_id, mode check kept inside each bucket) would need a protocol version bump and a DBMS_PARALLEL_REPLICAS_MIN_VERSION_WITH_UNIQUE_STREAM_ID style gate, because the convention for what string goes into stream_id is part of the contract both sides have to agree on. PR #101434 already uses a similar suffix shape for splits. Evolving in that direction is up to the maintainers. cc @devcrafter

@nickitat

nickitat commented May 28, 2026 •

Copy link
Copy Markdown
Member

As of today, we have kept the "contract" that all replicas should agree on the read mode for the given table. It cannot work otherwise, simply because we have only one coordinator, and coordinators for different modes are distinct C++ objects.
This query seems to indeed produce an error:

SELECT trimBoth(explain)
FROM
(
    SELECT *
    FROM viewExplain('EXPLAIN', 'distributed = 1, actions = 1', (
        SELECT
            sum(s),
            count()
        FROM
        (
            SELECT
                a,
                sum(b) AS s
            FROM t
            GROUP BY a
            SETTINGS enable_sharding_aggregator = 0, optimize_aggregation_in_order = 1
        )
    ))
)
WHERE (explain LIKE '%ReadFromMergeTree%') OR (explain LIKE '%ReadType%')


   ┌─trimBoth(explain)─────────────┐
1. │ ReadFromMergeTree (default.t) │
2. │ ReadType: Default             │
3. │ ReadFromMergeTree (default.t) │
4. │ ReadType: InOrder             │
   └───────────────────────────────┘
Received exception from server (version 25.12.1):
Code: 49. DB::Exception: Received from mt9euiu6ua.eu-west-1.aws.clickhouse-staging.com:9440. DB::Exception: Replica 2 decided to read in WithOrder mode, not in Default. This is a bug. (LOGICAL_ERROR)

So, we need to make replicas agree on the read mode.

@pamarcos pamarcos removed their assignment May 28, 2026
@pamarcos

Copy link
Copy Markdown
Member

@nickitat I removed myself from assignee, since you obviously know more about this part. Feel free to assign it to yourself.

@nickitat

Copy link
Copy Markdown
Member

@nickitat I removed myself from assignee, since you obviously know more about this part. Feel free to assign it to yourself.

Thanks. I didn't mean to break the chain of command ) But I felt like this issue genuinely requires either Igor or me.

@nickitat nickitat self-assigned this May 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 30/37 (81.08%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@nickitat

nickitat commented Jun 1, 2026

Copy link
Copy Markdown
Member

Attempting to fix here: #106243

@Algunenano

Copy link
Copy Markdown
Member Author

@nickitat 's PR is much better. Closing this in favor of the extended fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Coordination mode mismatch for stream A: got B, expected C (STID: 6117-68e9)

4 participants