Skip to content

Fix unknown-stream LOGICAL_ERROR in parallel replicas with projection short-circuit - #111689

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-110518-parallel-replicas-unknown-stream-exact-count
Jul 31, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-110518-parallel-replicas-unknown-stream-exact-count

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #110518

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 ...) that could abort the server when reading with parallel replicas and the query is fully answered by a projection optimization (exact-count, minmax-count, or a stored aggregate/normal projection selecting no ranges) on the initiator.

Description

Found by the fuzzer (issue #110518, STID 5217-5b3d); recurring on master and PRs (e.g. the Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) job: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4d08ee5cf17aeb2983bdf383783ea6c035079de4&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 ).

Root cause: under parallel replicas with a local plan, the initiator normally announces an empty read set to the coordinator when index analysis leaves no ranges, so followers do not initialize the coordinator with a divergent plan (added in the read-in-order reimplementation). When a projection optimization fully replaces the initiator's ReadFromMergeTree with a ReadFromPreparedSource, that step's initializePipeline() never runs and the announcement is skipped, so the coordinator registers no stream for the table. A follower that does not take the same short-circuit then requests a stream the coordinator never registered, throwing Got read request from replica N for unknown stream ... at ParallelReplicasReadingCoordinator::handleRequest.

Four fully short-circuiting paths replace the read this way: the exact-count and minmax-count aggregate projections, and a stored aggregate or normal projection whose read selects zero ranges (readFromParts returns an empty step). Fix: when the short-circuit leaves no parent parts, announce the empty read from the projection optimizer, reusing the same mechanism initializePipeline() uses. The announcement is a no-op unless this is the initiator's local plan under parallel replicas. When a projection is read through its own ReadFromMergeTree (parent parts remain, or the projection read is non-empty), that step announces the base-table stream itself and the new call does not fire.

The bug is a same-version initiator/follower plan divergence that a homogeneous single-server test cluster cannot produce on its own, so the regression test uses a fail point (parallel_replicas_skip_aggregate_projection_on_follower) to force a follower to skip the short-circuit while the initiator takes it. Without the fix each of the four paths aborts the server with the exact error; with it the queries return correct results.

… short-circuit

When a projection optimization fully answers a read on the initiator's parallel-replicas
local plan, it replaces the ReadFromMergeTree step with a prepared source. That step's
initializePipeline() then never runs, so the empty-ranges announcement it would send to the
coordinator (added in the read_in_order reimplementation to prevent followers from
initializing the coordinator with a divergent plan) is skipped and the coordinator registers
no stream for the table. A follower that does not take the same short-circuit then requests a
stream the coordinator never registered, tripping
'Got read request from replica N for unknown stream ...' (LOGICAL_ERROR).

Four fully short-circuiting paths replace the read this way: the exact-count and minmax-count
aggregate projections, and a stored aggregate or normal projection whose read selects zero
ranges. Announce the empty read from the projection optimizer when the short-circuit leaves no
parent parts, reusing the same mechanism initializePipeline() uses.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 3-localhost-replica cluster with the fail point parallel_replicas_skip_aggregate_projection_on_follower, each of SELECT count() FROM t WHERE id = <boundary>, SELECT min(id),max(id),count() FROM t, SELECT sum(v) FROM t WHERE <false> GROUP BY r, and SELECT id FROM t WHERE <false> aborts every time with Got read request from replica N for unknown stream <db>.<table>.
b Root cause explained? Yes. A projection short-circuit (exact-count / minmax-count / stored aggregate or normal projection selecting zero ranges) replaces the initiator's ReadFromMergeTree with a prepared source, so initializePipeline() never runs and the empty-ranges announcement it sends (to register the stream so followers don't diverge) is skipped. A follower that plans a real read then requests an unregistered stream and handleRequest throws.
c Fix matches root cause? Yes. It sends the same empty-ranges announcement from the projection optimizer when the short-circuit leaves no parent parts, restoring the coordinator's stream-registration invariant. It does not weaken the unknown-stream check (that was the approach maintainers rejected on #109202).
d Test intent preserved / new tests added? New test 04545_parallel_replicas_projection_short_circuit_unknown_stream covers all four short-circuit paths with EXPLAIN liveness (projection selected) + a system.query_log oracle (ParallelReplicasHandleRequestMicroseconds > 0) proving a follower actually reached the coordinator request path.
e Both directions demonstrated? Yes. Without the fix (announce calls disabled) all four paths abort the server with the exact unknown stream LOGICAL_ERROR; with the fix all four return correct results and the server stays up. 50/50 harness runs with randomization pass.
f Fix is general across code paths? Yes. Both the aggregate-projection optimizer (minmax, exact-count, stored aggregate) and the normal-projection optimizer are covered; the shared announcement helper lives on ReadFromMergeTree. The non-empty projection-read path is intentionally not touched — that read announces the base-table stream itself.
g Fix generalizes across inputs? Coordination mode is preserved (Default / WithOrder / ReverseOrder from input_order_info, identical to the existing empty-ranges announce). All public occurrences are Default-mode bare streams; in-order splits already announce and stop gracefully. Test covers count(), min/max/count, stored aggregate and normal projections.
h Backward compatible? Yes. No setting, on-disk, wire, or protocol change; the added call is the same announcement the initiator already sends, from one more code path.
i Invariants and contracts preserved? Yes. Upholds the coordinator invariant that the initiator registers every stream it plans, including the empty one; the unknown-stream throw stays intact for genuine bugs. The empty announcement sends an empty ranges description (equivalent to the original empty parts_with_ranges).

Session id: cron:clickhouse-author-slot-4:20260723-192900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 rounds: 1 full pass + 3 stateful re-reviews as the fix widened; all findings verified against the code before acting).

# Sev Finding Verdict Evidence / action
1 ❌ Stored aggregate projection selecting zero ranges detaches the read without announcing (sibling of the exact-count/minmax paths). AGREE — fixed Verified: readFromParts returns an empty step when the projection selects no ranges, then the read is detached with no announce. Generalized the announce guard to !has_parent_parts across all aggregate-projection branches; re-verified the abort both directions.
2 ⚠️ Regression could pass without exercising the short-circuit (disabled-analyzer and randomized optimize_aggregation_in_order disable the projection; result-only asserts pass on an ordinary scan). AGREE — fixed Verified against canUseProjectionForReadingStep + clickhouse-test randomization. Pinned every eligibility setting, added SYSTEM STOP MERGES, EXPLAIN liveness (projection selected) and a system.query_log oracle (ParallelReplicasHandleRequestMicroseconds > 0).
3 ❌ The same zero-range detach-without-announce exists in the sibling optimizeUseNormalProjection.cpp. AGREE — fixed Verified via local A/B: a Default-mode normal-projection zero-range query aborts identically (an ORDER BY variant does not — in-order followers stop gracefully). Applied the same announce fix + extended the fail point to the normal-projection optimizer; added a regression case.
4 💡 Announce-call comments duplicated the PR narrative. AGREE — fixed Trimmed both comments to the local invariant; motivation lives in the commit message and this PR.
5 💡 PR title/description said normal projections were unaffected and omitted the two newly fixed stored-projection paths. AGREE — fixed Updated the title, changelog entry, and description to describe all four short-circuit paths.

Severity: ❌ blocker / ⚠️ major / 💡 nit. All findings were verified against the code and reproduced locally before acting; none were accepted on prose alone.

Session id: cron:clickhouse-author-slot-4:20260723-192900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @devcrafter — could you review this? It fixes the parallel-replicas coordinator unknown stream LOGICAL_ERROR (issue #110518) from the read-in-order reimplementation: when a projection short-circuit (exact-count / minmax-count / a stored aggregate or normal projection selecting zero ranges) fully replaces the initiator's ReadFromMergeTree, initializePipeline() no longer runs so the empty-ranges announcement is skipped and the coordinator registers no stream; a diverging follower then requests it and handleRequest throws. The fix re-sends that announcement from the projection optimizer, reusing the existing empty-ranges path — it does not touch the unknown-stream check itself.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 23, 2026
@clickhouse-gh clickhouse-gh Bot closed this Jul 23, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Jul 23, 2026
…-replicas-unknown-stream-exact-count

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.h
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [370001d]

Summary: ✅


AI Review

Summary

This PR fixes the parallel-replicas unknown stream exception when projection short-circuiting removes the initiator's ReadFromMergeTree before it can register an empty stream with the coordinator. The fix covers both aggregate- and normal-projection paths, reuses the existing empty-announcement behavior in ReadFromMergeTree, and the new regression test exercises all four affected short-circuit cases. I did not find a remaining actionable issue in the current patch.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 24, 2026
The master merge renamed ParallelReadingExtension::sendInitialRequest's
second parameter from 'ranges' to 'description', so the inline argument
comment in announceEmptyReadRangesToCoordinatorIfInitiator no longer
matched the parameter name. arm_tidy enforces bugprone-argument-comment
as -warnings-as-errors, which stopped the build.

Comment-only change: /*ranges=*/ -> /*description=*/.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f494a22

Every failure below has an owner.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (system.metric_log_0 metadata 273438 bytes > max_query_size 262144, QUERY_IS_TOO_LARGE) trunk regression (257 PRs / 7d, 0 master, onset 2026-07-18) #111703 (external, merged 2026-07-24 17:24Z). Build f494a22 predates that merge; a rebuild on current master picks it up.
Mergeable Check / PR rollup of the above via #111703

Session id: cron:our-pr-ci-monitor:20260724-223000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f494a22

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (SystemLog (system.metric_log): Failed to mark the rotated system log table as readonly, Code 229) trunk error-log leak, not PR-caused #111703 (external, merged 2026-07-24T17:24:53Z) - NOT on this branch (git merge-base --is-ancestor eb577ff401a3 f494a22f10be is false), so this build predates the fix; merging master will pick it up

Session id: cron:our-pr-ci-monitor:20260726-163000

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

Changed lines: Changed C/C++ lines covered: 87/88 (98.86%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov mentioned this pull request Jul 31, 2026
1 task done
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into ClickHouse:master with commit f4f2c33 Jul 31, 2026
178 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
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 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.

Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d)

3 participants