Skip to content

Fix LOGICAL_ERROR for unknown stream in parallel replicas coordinator - #109202

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/pr-coordinator-unknown-stream
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/pr-coordinator-unknown-stream

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Related: #101434

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 a LOGICAL_ERROR (Got read request from replica N for unknown stream ...) in parallel replicas reading when a follower plans a read in Default coordination mode while the initiator splits it into ordered sub-streams under parallel_replicas_local_plan = 1.

Description

Under parallel_replicas_local_plan = 1 the initiator pins itself as the snapshot replica and registers only the streams its own local plan produces. For an in-order read that is a set of #split_i streams, so the bare table-name stream is never registered. handleInitialAllRangesAnnouncement already tolerates this: a non-snapshot replica announcing an unregistered stream is dropped and receives an empty response ("you own nothing").

The follow-up ParallelReadRequest for that same dropped stream, however, was only handled gracefully for replicas older than DBMS_PARALLEL_REPLICAS_MIN_VERSION_WITH_ANNOUNCEMENT_RESPONSE. A current-version (protocol 8) replica hit the Got read request from replica N for unknown stream LOGICAL_ERROR (a server abort in debug and sanitizer builds). This is reachable without any version skew: a same-version follower reaches it whenever it plans the read in Default coordination mode (bare-table stream) while the initiator split it WithOrder into #split_i streams. Default requesters do not receive an announcement response, so they build all sources and issue a read request for the dropped bare-table stream.

The fix makes the request guard mirror the announcement guard: when the snapshot replica is pinned and the requester is not the snapshot replica, the request for an unregistered stream is finished gracefully regardless of protocol version. The snapshot replica's registered streams cover the whole read set, so the finished replica loses no work (verified: results and row counts match the single-stream baseline). The LOGICAL_ERROR is preserved for genuinely unexpected streams (no snapshot pinning active, or the snapshot replica itself requesting an unknown stream).

The bug lives in the reworked in-order parallel-replicas reading from #101434 (the < protocol 8 gate there only covers the rolling-upgrade subset). It was found via internal stress testing; there are no public CIDB occurrences yet.

A new failpoint parallel_replicas_force_default_mode_on_follower forces the coordination-mode divergence on a single-server test cluster (which otherwise plans every replica identically), used by the regression test 04498_parallel_replicas_unknown_stream_mode_divergence.

…eplicas

Under parallel_replicas_local_plan=1 the initiator pins itself as the snapshot
replica and registers only the streams its own local plan produces. For an
in-order read that is a set of #split_i streams; the bare table-name stream is
never registered. handleInitialAllRangesAnnouncement already tolerates this: a
non-snapshot replica announcing an unregistered stream is dropped and gets an
empty response ("you own nothing").

But the follow-up ParallelReadRequest for that same dropped stream was only
handled gracefully for replicas older than
DBMS_PARALLEL_REPLICAS_MIN_VERSION_WITH_ANNOUNCEMENT_RESPONSE; a current-version
(protocol 8) replica hit the "Got read request from replica N for unknown
stream" LOGICAL_ERROR (a server abort in debug and sanitizer builds). A
same-version follower reaches this whenever it plans the read in Default
coordination mode (bare-table stream) while the initiator split it WithOrder:
Default requesters do not receive an announcement response, so they build all
sources and issue a read request for the dropped bare-table stream.

Make the request guard mirror the announcement guard: when the snapshot replica
is pinned and the requester is not the snapshot replica, finish the request
gracefully regardless of protocol version. The snapshot replica's registered
streams cover the whole read set, so the finished replica loses no work. The
throw is preserved for genuinely unexpected streams (no snapshot pinning, or the
snapshot replica itself requesting an unknown stream).

Adds a failpoint parallel_replicas_force_default_mode_on_follower that forces the
coordination-mode divergence on a single-server test cluster (which otherwise
plans every replica identically), plus a regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 3-replica cluster with parallel_replicas_local_plan=1, optimize_read_in_order=1, and the new failpoint parallel_replicas_force_default_mode_on_follower, SELECT a FROM t ORDER BY a aborts every time with Got read request from replica 1 for unknown stream default.t.
b Root cause explained? The initiator (snapshot replica) splits the in-order read into #split_i streams and never registers the bare table-name stream. A Default-mode follower requests that bare-table stream; Default requesters get no announcement response, so they issue a read request for it. getCoordinator() returns null, and because the follower is protocol 8 the graceful branch (gated on < protocol 8) is skipped, so it throws. The announcement handler already drops the same stream gracefully; the request handler was inconsistent with it.
c Fix matches root cause? Yes. The request guard now mirrors the announcement drop guard: finish gracefully when snapshot pinning is active and the requester is not the snapshot replica, regardless of protocol version. It removes the inconsistency between the two guards rather than masking the symptom.
d Test intent preserved / new tests added? New test 04498_parallel_replicas_unknown_stream_mode_divergence added. The LOGICAL_ERROR is still raised for genuinely unexpected streams (no snapshot pinning, or the snapshot replica itself), so the guard keeps catching real bugs.
e Demonstrated in both directions? Yes. Without the fix (failpoint present, coordinator reverted) the test aborts the server with the exact error; with the fix it returns the correct baseline (count()=1000000, sum(a)=499999500000) for both ORDER BY and ORDER BY DESC, stable across repeated runs.
f Fix is general, not a narrow patch? Yes. The graceful path is gated on the same condition the announcement guard uses, so it covers every way a non-snapshot replica can reach an unregistered stream (rolling upgrade and same-version mode divergence), not just the one reproduced input.
g Generalizes across inputs? Verified for WithOrder (ORDER BY) and ReverseOrder (ORDER BY DESC); results match the single-stream baseline in both. Plain Default reads, group-by-in-order, and the existing coordinator-mode-collision tests (04278/04303/04304) are unaffected.
h Backward compatible? Yes. No setting, on-disk, wire, or replication format change. replica_protocol_version semantics are unchanged; the new condition only broadens an existing graceful path.
i Invariants preserved? Yes. The snapshot replica remains the authority on the stream set; a finished follower contributes no work and its ranges are covered by the snapshot replica's registered streams (no data loss or duplication, confirmed by the exact row-count/sum assertions). The coordination-mode-mismatch check further down is untouched.

Session id: cron:clickhouse-worker-slot-0:20260702-160900

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @devcrafter @KochetovNicolai could you review? This fixes a LOGICAL_ERROR in the in-order parallel-replicas reading coordinator from #101434: a protocol-8 follower that plans a read in Default mode while the initiator splits it WithOrder requests the unregistered bare-table stream and trips the unknown stream throw. The fix makes the read-request guard mirror the announcement drop guard (graceful finish for a non-snapshot replica under snapshot pinning). Repro + both-directions validation via a new failpoint are in the PR.

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

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f33c41a]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, sequential) FAIL
Server died FAIL cidb, issue
03623_distributed_index_analysis_merge_tree_settings UNKNOWN cidb
03622_explain_indexes_distributed_index_analysis_in UNKNOWN cidb
AddressSanitizer (STID: 2561-447c) FAIL cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR makes the parallel-replicas coordinator treat a non-snapshot replica's follow-up read request for an unregistered stream the same way it already treats that replica's dropped announcement under snapshot pinning: return an empty finish=true response instead of throwing LOGICAL_ERROR. The added failpoint now forces the mode divergence only on genuine followers, and the new regression test exercises both ascending and descending ordered reads. I did not find any remaining correctness, safety, or coverage issues in the current head.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
The flaky-check runs a single execution over 180s under sanitizers because the
test needs a 1M-row table for followers to genuinely issue the bare-table read
request that reproduces the bug (smaller tables let the initiator's splits cover
the read before any follower participates, so the fix path is never exercised).
The long tag exempts the flaky-check 180s per-run limit and reduces its repeat
count, the idiomatic treatment for a correct-but-heavy test. No behavior change.
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 200b14b: tagged the regression test `04498` as `long`.

The flaky-check failed it on amd_debug and amd_asan_ubsan with `Test runs too long (> 180s)` (msan/tsan passed). Not a correctness flake, the coordinator fix is unaffected. The test needs a 1M-row table so followers genuinely issue the bare-table read request that would throw without the fix; with smaller tables the initiator's splits cover the read before any follower participates (verified: at 100k rows the fix path fires intermittently, at 1M it fires 10/10). So the test is legitimately heavy, and `long` (exempts the 180s per-run flaky-check limit, reduces its repeat count) is the right treatment rather than shrinking it.

Re-verified both directions locally after the tag: fix reverted -> server abort `Got read request from replica 1 for unknown stream default.t_pr_unknown_stream` at ParallelReplicasReadingCoordinator.cpp:1295; fix present -> `1 1` / `1 1`.

Session id: cron:clickhouse-worker-slot-1:20260702-193000

… predicate

The test failpoint was gated on !isParallelReplicasLocalPlanForInitiator(),
which is also false on the initiator when local-plan execution is unavailable
(analyzer off, parallel_replicas_prefer_local_replica off, or a Distributed
subquery). By that point requestReadingInOrder has already set input_order_info,
so the failpoint could drop the initiator into spreadMarkRangesAmongStreams,
turning it into an initiator-side wrong-order injection rather than a pure
follower-mode-divergence repro.

Gate on isParallelReplicasLocalPlanForFollower() instead: it requires
collaborate_with_initiator, which is false on the initiator, so the failpoint
now fires only on genuine followers. Verified both directions still hold with
the new gate: test 04498 aborts on a pre-fix binary and passes on the fixed one,
and the followers still issue the bare-table read request that exercises the
coordinator fix path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f33c41a

CI is complete on this head (only the private CH Inc sync remains, which is exempt). No failure below is caused by this PR's diff (a ParallelReplicas reading-coordinator fix + failpoint + one stateless test). This PR touches ParallelReplicasReadingCoordinator.cpp / ReadFromMergeTree.cpp / FailPoint.cpp, none of which is on the failing code paths below.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / AddressSanitizer: CHECK failed: sanitizer_allocator_secondary.h:200 (STID 2561-447c) + Server died host-OOM (frameless ASan-allocator CHECK abort, NO ClickHouse stack frames — documented host-OOM signature; a coordinator PR cannot cause it; 1 hit / 1 PR / 0 master in 30d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log flaky (chronic error-leak family: leftover PostgreSQL-engine test state, AsyncLoader::worker connection timeout to reserved IP 192.0.2.1:5432 — benign, unrelated to parallel replicas) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Mergeable Check / PR rollup of the above resolves once the above clear
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260703-000000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to the finish ledger above — the Upgrade check (amd_release) line has an existing fixing PR, not just a fix task:

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (AsyncLoader connection timeout to 192.0.2.1:5432) flaky (chronic 04210-fixture DatabasePostgreSQL background-pool log noise; RFC-5737 TEST-NET reserved IP, benign, unrelated to parallel replicas) #108560 (ours, open)

The host-OOM ASan-allocator CHECK line (STID 2561-447c) owner is unchanged (a fix task is created; fixing-PR link to follow here).

Session id: cron:our-pr-ci-monitor:20260703-000000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to the finish ledger above. The Stateless tests (arm_asan_ubsan, azure, sequential) line (STID 2561-447c) was classified as a frameless host-OOM ASan-allocator abort. That classification is wrong. The full ASan report has a genuine ClickHouse stack on a background MergeMutate (horizontal merge) thread, and dmesg shows no OOM killer, so this is a real heap-corruption crash, not host-OOM.

The sanitizer_allocator_secondary.h:200 CHECK fires at free time inside Quarantine::DoRecycle on a large chunk whose allocator header is already corrupted. The crashing thread is reading a String .size subcolumn across granules during a compact-part merge:

MergeTask::ExecuteAndFinalizeHorizontalPart::executeImpl   (MergeTask.cpp:1512)
  MergeTreeSequentialSource::generate                      (MergeTreeSequentialSource.cpp:221)
    MergeTreeReaderCompact::readData                       (MergeTreeReaderCompact.cpp:305)
      SerializationString::deserializeBinaryBulkWithSizeStream (SerializationString.cpp:825)
        SerializationNumber<UInt64>::deserializeBinaryBulk  (size stream)

This is the known String .size-subcolumn merge heap-corruption family (upstream tracker #106370), and it has an open fix.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / sanitizer_allocator_secondary.h:200 CHECK (STID 2561-447c) + Server died heap corruption reading a String .size subcolumn across granules during a background merge (not host-OOM, not caused by this PR's diff) #109020 (ours, open)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109202&sha=f33c41acaaeda1f0ee08761d11827f77c6e2759f&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29

Session id: cron:clickhouse-worker-slot-6:20260703-005500

@nickitat nickitat self-assigned this Jul 4, 2026
@nickitat

nickitat commented Jul 4, 2026

Copy link
Copy Markdown
Member

@groeneai, the situation when different nodes choose different reading modes for the same table within the same query is a logical bug and should never happen. This is why there are no public CIDB occurrences, and you had to fake it with a failpoint.

@nickitat nickitat closed this Jul 4, 2026
@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, and I will not reopen. I checked whether the divergence is reachable on a real path, and it is not, so the coordinator guard should keep throwing rather than tolerate it.

The coordination mode is a pure function of query_info.input_order_info (Default when it is unset or direction is 0, otherwise WithOrder/ReverseOrder by sign), and that field is set only via ReadFromMergeTree::requestReadingInOrder. #106243 already closed the one real way the initiator and followers could diverge (the initiator's local plan optimized under the outer query's in-order settings while replicas re-plan the subquery under its own) by grafting the subquery's in-order gating settings into the initiator's local-plan optimization. That graft covers every optimization that can call requestReadingInOrder (optimizeReadInOrder, optimizeAggregationInOrder, optimizeDistinctInOrder, tryReuseStorageOrderingForWindowFunctions), and the comment there keeps that list authoritative.

So there is no non-failpoint path to the unknown-stream read request. The LOGICAL_ERROR is a correct invariant guard: if it ever fires in the wild it points at a new ungrafted in-order optimization, and the fix belongs at the source, not in the coordinator. Thanks for the review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat

Reopening the evidence, not the PR. The premise here was "no public CIDB occurrences ... you had to fake it with a failpoint" and "different nodes choose different reading modes for the same table is a logical bug that should never happen". Both are now contradicted by master data, and the recurring signature is NOT the mode divergence I built the failpoint for.

The guard fires on master 2x since the ruling (plus 4 unrelated PRs), all Stress/ParallelReplicas:

The crashing query in the tsan hit is SELECT count() FROM source_table WHERE id > 100 (03636_storage_alias_basic). No ORDER BY, so input_order_info is null and both initiator and follower pick Default mode. The unknown stream is the bare table name test_3.source_table (no #split_i for that name anywhere in the run). So there is no reading-mode divergence at all - your proof that mode is a pure function of input_order_info holds. This is a stream-registration timing race in pure Default mode:

  1. ParallelReplicasLocalPlan.cpp:259 pins snapshot_replica_num to the initiator.
  2. A non-snapshot follower announces the bare Default stream. It is dropped because the stream is not registered yet and the announcer is not the snapshot replica (handleInitialAllRangesAnnouncement, the if (snapshot_replica_num) guard) - empty response, no coordinator created.
  3. In Default mode the initiator does not even send the announcement response: RemoteQueryExecutor.cpp send_response = announcement.mode != CoordinationMode::Default.
  4. MergeTreeReadPoolParallelReplicas::getTask never inspects the announcement outcome; when buffered_ranges is empty it unconditionally calls sendReadRequest. (The InOrder pool consumes the response and stays empty when dropped, which is why only Default is exposed.)
  5. If that read request reaches the coordinator before the initiator's own local-plan announcement registers the bare stream, getCoordinator()==null and line 1295 throws. Stress/thread-fuzzer scheduling delays the initiator's local read and widens the window.

So the divergence you closed on is real, but it is registration ordering under snapshot-pinning, not coordination mode. I could not reproduce it on a single-process test cluster because 127.0.0.x all resolve to one server and the announce/request ordering serializes (the drop-guard never fires); it needs genuinely separate networked replicas, which only the Stress + azure ParallelReplicas jobs have.

If you agree, the source fix is one of: (a) make the Default follower pool treat a dropped/empty announcement as "no work for this stream" and stop, mirroring the InOrder pool; or (b) register the initiator's bare Default stream before any follower read request can be served. Happy to implement whichever you prefer - want to confirm the direction with you first since you own this path.

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.

3 participants