Skip to content

Do not rewrite a plan that already carries a coordinated read - #113788

Closed
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-storage-merge-double-optimize-parallel-replicas
Closed

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-storage-merge-double-optimize-parallel-replicas

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110518
Related: #113636

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

Fixes a LOGICAL_ERROR: Got read request from replica N for unknown stream ... that aborts the initiator, and wrong results for a read given an in-order optimization, when a plan already using parallel replicas is optimized a second time. Both require parallel_replicas_plan_based = 1, for example a merge table function read; the wrong results also require parallel_replicas_local_plan = 0 and one of the four optimize_*_in_order settings.

Description

A query plan can be optimized more than once, and ReadFromMerge does that for its child plans: in createChildrenPlans, in addFilter, and while building the pipeline.

applyParallelReplicas did not tolerate that. After one run the second pass inlines the local plan, leaving a bare but already coordinated ReadFromMergeTree in the outer plan. A later run collects that read again, because collectReadsToDistribute filters only on mergeTreeReadCanBeShipped, and creates a second coordinator. Only one registers a stream while followers are dispatched against both, so a follower announcing to the second is dropped by the snapshot pin and its next read aborts.

The first fix skips the rewrite on a plan that already carries a coordinated read, the guard the sibling tryMakeDistributed* transforms were given in f34ffbb, which names StorageMerge child plans as the carrier. It can only fire on an already rewritten plan, since is_parallel_reading_from_replicas is set only after a coordinator exists.

Removing that abort exposes a second route to the same message. In-order optimizations run after the rewrite and could order only the local read, not the shipped fragment. Two entry points reach a merged read: ReadFromMerge::requestReadingInOrder, shared by all four, whose ReadFromMergeTree counterparts already declined on isParallelReadingFromReplicas while its own branches did not; and the union branch of optimizeReadInOrder, for a sort arriving from inside the child plan, whose guard recognised only the classic step. Both now decline, losing an optimization and never correctness.

Both routes need the experimental parallel_replicas_plan_based = 1. A classic path route reporting the same message is not addressed here: with that setting off the rewrite returns before the guard, so #110518 is only partly addressed.

Complements #113636, which guards a set-operation transform on the same child plans; that transform is untouched here and the diffs share no file.

Validation

Measured on a three replica cluster, counting Creating parallel replicas coordinator against Created coordinator for stream: a merge read over one table went from 2 coordinators with 1 registered stream to 1 and 1, over two tables from 4 and 2 to 2 and 2, a JOIN over merge from 3 and 1 to 1 and 1. A direct or view read is unchanged.

New test 04817_pr_repeated_optimize_unknown_stream has 19 arms: 11 witnesses, 7 controls, 1 negative. Eight witnesses are merge shapes that abort the server without the fixes. The other three assert by EXPLAIN that the merged child read is still distributed after the guard, that the same holds for the ordered read through a view, and that ordering was declined for the shape shipped without a local plan; a result shows none of them. The controls read the same data by paths that never had the duplicate.

Mutation matrix, each mutant built and asserted separately:

mutant result
remove the rewrite guard the aborting shapes redden, every other arm green
weaken its predicate to any MergeTree read the base table control and plan shape witness redden, so it is not over-broad
revert the read in order decline only the ordered witness reddens alone with the same unknown stream error, paired control green
remove either optimize call in ReadFromMerge 8 existing tests redden for createChildrenPlans, the join runtime filter test for addFilter, so both stay
drop the remote-only arm of the ReadFromMerge guard the shipped-fragment witness reddens alone, every other arm green
revert the new arm of the union guard the view witness aborts, while the pre-round file stays green

Regression slice of stateless tests matching ENGINE = Merge, merge( and the parallel replicas and read in order families: verdict sets identical on both binaries. The new test passes 50 of 50 randomized and 50 of 50 unrandomized runs.

A query plan can be optimized more than once. `ReadFromMerge` does exactly that
for its child plans: `createChildrenPlans` optimizes each one, `addFilter`
optimizes it again when a filter is pushed down, and `buildPipeline` optimizes it
once more while building the pipeline.

`applyParallelReplicas` did not tolerate that. After one run the second pass
inlines the local plan (`optimizeTree.cpp`), which leaves a bare but already
coordinated `ReadFromMergeTree` in the outer plan: the marker is set by
`createLocalParallelReplicasReadingStep`. A later run collects that read again,
because `collectReadsToDistribute` filters only on `mergeTreeReadCanBeShipped`,
and creates a second coordinator for the same read. Only one of the two ever
registers a stream, while followers are dispatched against both, so a follower
announcing to the second one is dropped by the snapshot pin and its next read
request aborts the initiator with `LOGICAL_ERROR: Got read request from replica N
for unknown stream <table>`.

Skip the rewrite on a plan that already carries a coordinated read. The sibling
`tryMakeDistributed*` transforms in `optimizeTreeSecondPass` acquired the same
kind of guard in f34ffbb, which names `StorageMerge` child plans as the
carrier; this gives the parallel replicas rewrite the guard it was missing.

Measured on a three replica cluster, with `create` counting
`Creating parallel replicas coordinator` and `reg` counting
`Created coordinator for stream`:

  merge() over one table   before: create=2 reg=1, aborts   after: create=1 reg=1
  merge() over two tables  before: create=4 reg=2, aborts   after: create=2 reg=2
  JOIN over merge()        before: create=3 reg=1, aborts   after: create=1 reg=1

Reading the same table directly, through a view, with
`parallel_replicas_plan_based = 0`, or with `parallel_replicas_local_plan = 0`
is unchanged at `create=1 reg=1`, which is what the controls in the new test
assert. The guard only fires on a plan that has already been rewritten, since
`is_parallel_reading_from_replicas` is set only after a coordinator exists.

The guard recognises a coordinated read, not a plan that was merely visited, so
one shape is left as it was. When the first pass inserts a split marker but
`createParallelReplicasPlan` declines it because only a single replica is usable
(`ClusterProxy/executeQuery.cpp:991`), the marker stays in the plan and no read
is ever marked, so the guard does not apply. A repeated optimization then nests a
second marker under the first, and cloning the outer one throws
`NOT_IMPLEMENTED: Cannot clone ParallelReplicasSplit plan step`. That shape fails
the same way before and after this change and is not addressed here.

This covers the routes where the duplicate comes from a repeated rewrite, which
needs `parallel_replicas_plan_based = 1`. A classic path route reporting the same
message exists and is not addressed here: with that setting off,
`applyParallelReplicas` returns before the guard, since the optimization setting
it reads is `canUseParallelReplicasOnInitiator() && parallel_replicas_plan_based`
(`src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp:365`),
and that path takes its coordinator from the planner instead.

Partially addresses ClickHouse#110518.
The test asserted the fix's effect only through results, a thrown code or an
`EXPLAIN` of index analysis. None of those can see the guard becoming over-broad
for a `merge()` shape: parallel replicas is an optimization, so a plan that lost
its distribution returns the same number, and the forced index throw comes from
range selection, which runs whether or not the read is coordinated. The file's
only distribution assertion sat under the non-merge control.

Add one arm asserting the plan shape for the `merge()` child directly, so a guard
that skipped a first-time merge plan would redden it. Removing
`createChildrenPlans`' optimize is the mutation that arms it: that reddens the new
arm alone, while the direct-read control and the six aborting shapes stay green.
Reverting the guard leaves the new arm green, since the query aborts before the
distribution can be observed, so it needs its own discriminator.

`merge index analysis` is relabelled a control. It runs through `EXPLAIN`, which
never builds a pipeline, so `ReadFromMerge::buildPipeline`'s optimize is never
reached on it and it passes with and without the fix.

Also trim the opening comment, which restated the coordinator sequence this
message already carries, and name the sibling guard next to the predicate so a
reader sees the pair.
`ReadFromMerge::requestReadingInOrder` now declines when a child plan already
carries a coordinated read.

`applyParallelReplicas` runs before `optimizeReadInOrder`
(`optimizeTree.cpp:379` against `:466`), so by the time read in order is
considered, the child plan holds a local `ReadFromMergeTree` in parallel reading
mode plus a `ReadFromParallelReplicasStep` whose fragment is a separate
`std::shared_ptr<const QueryPlan>` member. `recursivelyApplyToReadingSteps`
walks only `node->children`, so it reorders the local read and cannot reach the
shipped fragment. The local side then announces ordered split streams while the
replicas request the bare table stream, the coordinator does not know it, and
the initiator aborts with the same unknown stream logical error this branch
fixes for the repeated rewrite.

The direct read branches of `optimizeReadInOrder` already guard against this
with `if (reading->isParallelReadingFromReplicas()) return {}` at `:1511`, and
the join variants at `:1180`, `:1300` and `:1421` do the same. None of the four
`ReadFromMerge` branches (`:1233`, `:1322`, `:1442`, `:1532`) had an equivalent.
Before this branch the shape aborted earlier, on the double rewrite, so the
unguarded path was unreachable; removing that abort makes it reachable, which is
why it belongs here rather than being left as pre existing.

Declining is what the guarded direct read branches already do. All four callers
abandon the optimization when `requestReadingInOrder` returns false, so this
loses an optimization on a distributed merged read and never correctness.

Covered by a new arm in the test, with the paired control at
`optimize_read_in_order = 0`. The arm pins `optimize_read_in_order = 1` because
the test runner randomizes it and it gates the optimization.
`ReadFromMerge`'s `planHasCoordinatedRead` tests two step types, and only the
`ReadFromMergeTree` one was covered by the test. With
`parallel_replicas_local_plan = 0` the child plan holds no local read at all:
`createParallelReplicasPlan` takes its `else` branch
(`ClusterProxy/executeQuery.cpp:1029`) and returns just the shipped fragment, so
the plan under `ReadFromMerge` is a lone `ReadFromParallelReplicasStep`. That
step is an `ISourceStep` holding its fragment as a
`std::shared_ptr<const QueryPlan>` member (`ReadFromParallelReplicas.h:51`), so a
`node->children` walk sees nothing inside it and the node has no children.

Delete that arm and both walks in `requestReadingInOrder` go vacuously true: the
guard finds no `ReadFromMergeTree` and declines nothing, and
`recursivelyApplyToReadingSteps` never calls its lambda, so `ok` stays true. The
function then reports success having ordered nothing, and the caller reaches
`sorting->convertToFinishSorting` (`optimizeReadInOrder.cpp:1713`), whose
`MergingSortedTransform` requires every input stream to be sorted. On the base
commit that shape returns the wrong three rows in 6 of 40 runs, so the arm
guards correctness rather than an optimization.

The new arm asserts the plan shape, not the rows: `ORDER BY` sorts either way, so
a result cannot tell a declined ordering from an applied one.
`SortingStep::describeActions` prints `Prefix sort description` only for a
non-empty `prefix_description`, which is assigned exactly twice, in the
`FinishSorting` constructor (`SortingStep.cpp:254`) and in
`convertToFinishSorting` (`:319`), so the count reads whether the conversion
happened. It renders in both the default and the legacy plan format, so no
`explain_query_plan_default` change is needed. The arm pins
`optimize_read_in_order = 1` for the same reason the existing ordered arm does.

`merge ordered` keeps passing without the deleted arm, because its
`parallel_replicas_local_plan = 1` shape still carries a local read in parallel
reading mode; only the remote-only shape needs it.

Also state the two shapes in `planHasCoordinatedRead`'s comment, which described
only the local-plus-fragment one, and backtick two names in the comment added to
`applyParallelReplicas`.
The `merge ordered without local plan` arm said the shape returned the wrong three
rows in 10 of 30 runs. That figure belongs to no measurement: 10 is the wrong-row
count for the same shape at `optimize_read_in_order = 0`, which is a different,
pre-existing defect, and 30 is the correct-row count for the arm's own shape at
`optimize_read_in_order = 1`. The measured figure for this arm is 6 wrong of 40,
which is what the commit adding the arm already states. Attribute it to the query
being explained rather than to the `EXPLAIN` aggregate, since the arm's own oracle
is the plan shape.

The file header said every witness but one killed the server before the fix. There
are two that do not: the one asserting the merged child read is still distributed,
and the one asserting the ordering is declined for a read shipped without a local
plan. Name both.

Comments only, so the reference file is unchanged.
…branch

Read in order has two entry points that can reach a `merge` over a coordinated
child. `ReadFromMerge::requestReadingInOrder` handles a sort that sits above the
`ReadFromMerge` step, and the previous commit taught it to decline. A sort that
arrives from inside the child plan, from a view carrying `ORDER BY`, is decided
instead by the union branch of `optimizeReadInOrder`, which never calls that
method.

That branch already declines for a coordinated read, through
`readingFromParallelReplicas`, but the predicate recognised only
`ReadFromParallelRemoteReplicasStep`, the classic step. A plan-based read reaches
the same leaf as either `ReadFromParallelReplicasStep`, the shipped fragment, or
a `ReadFromMergeTree` in parallel-reading mode, the fragment's local counterpart
once a later optimization has inlined it. Both were read as ordinary local reads,
so the ordering was applied to the local side alone and the two sides announced
different coordination modes: `SELECT sum(value) FROM merge(db, '^v$')` over such
a view aborted the initiator with `Got read request from replica N for unknown
stream T`.

Give the predicate the same two arms `planHasCoordinatedRead` has, for the same
reason. Both mean a coordinator already exists:
`ReadFromParallelReplicasStep` has a single construction site, in
`createRemotePlanFragmentForParallelReplicas`, whose only two callers are both
inside `createParallelReplicasPlan`; and `is_parallel_reading_from_replicas` is
set only after a coordinator exists. The walk is unchanged, since the fragment is
an `ISourceStep` and the inlined read is a `ReadFromMergeTree`, so both are the
leaf it already lands on.

The new test arm reads through a view that carries `ORDER BY`, the shape absent
from the existing arms. Reverting the two arms makes it abort while the other
seventeen stay green.
…rrectly

The `merge ordered view` arm is the only witness for the union branch of read
in order, and its sole assertion was a scalar sum. A purely local read returns
the same number, so if the plan for that shape ever stopped being distributed
there would be no coordinator, no shipped fragment, no coordination mode
mismatch and therefore no abort: the arm would silently become a control and
would pass on a reverted guard.

Pair it with an `EXPLAIN` assertion that the shipped fragment is in the plan,
and put the same query at `enable_parallel_replicas = 0` in the same arm as the
control showing the assertion discriminates rather than matching everything.
Both subqueries pin `optimize_read_in_order`, which the test runner randomizes
and which is what enables the optimization under test.

`enable_parallel_replicas = 0` is the negative control rather than
`parallel_replicas_plan_based = 0`, because the classic step reports
`ReadFromRemoteParallelReplicas`, which does not contain the matched substring;
that control would read 0 for a reason unrelated to distribution.

`EXPLAIN` builds no pipeline, so the new arm cannot abort on any binary. That
is deliberate, as for the two existing plan shape arms: it does not replace the
runtime witness above it, which still aborts the server without the fixes.
@groeneai

groeneai commented Aug 7, 2026

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

An independent cold review plus an adversarial second-model pass ran against this diff. Findings and
verdicts below; everything AGREEd is fixed in the branch.

# Finding Verdict
❌ The rewrite is still not idempotent in one shape: when the first pass inserts a split marker but createParallelReplicasPlan declines it at connection_pools.size() == 1 (ClusterProxy/executeQuery.cpp:991), the marker is left in place and no read is marked, so the new guard does not apply. A repeated optimization then nests a second marker, and cloning a subtree rooted at a marker throws NOT_IMPLEMENTED because ParallelReplicasSplitStep has no clone. Reachable by construction: a single-shard cluster whose only usable replica is the initiator, for example test_shard_localhost. Agreed on the finding, scoped rather than fixed. The behaviour predates this change and is byte-for-byte unchanged by it: the guard cannot fire on a plan that never obtained a coordinator, and neither visitor is touched. Widening the fix here would also mask a surviving duplicate, which this PR deliberately keeps observable. The commit message was retitled and now discloses the residual instead of claiming general idempotency.
⚠️ The changelog named only the LOGICAL_ERROR abort, but the read-in-order half is a wrong-results defect: with parallel_replicas_local_plan = 0 the pre-fix walk reported success having ordered nothing, and the caller then downgraded a full sort to a partial one. Measured: 34 correct / 6 wrong rows over 40 repeats on the parent commit. Agreed. The changelog entry now names both consequences.
⚠️ Two false statements in the new test's comments: a run-count anecdote that matched no measurement (it fused the counts of a different, pre-existing defect), contradicting the commit message's own figure; and a header describing one non-aborting witness where there are two. Agreed. Both corrected against the recorded measurements.
⚠️ The arm census in the PR body was stale after the last round: 16 arms / 8 witnesses where the file has 17 / 9, a dependent "14 other arms" count, and a missing mutation row. Agreed. All re-derived from the test file and corrected.
❌ A merge read over a view that itself carries ORDER BY still aborted with the same unknown stream message. The sort arrives from inside the view, so it sits within the ReadFromMerge child plan and the ordering is decided by optimizeReadInOrder's union branch, never by ReadFromMerge::requestReadingInOrder. That branch's own guard tested only the classic ReadFromParallelRemoteReplicasStep, so it was blind to the plan-based ReadFromParallelReplicasStep and ordered the local read alone. Agreed and fixed. The union guard now also recognises the plan-based fragment and an inlined local read already in parallel-reading mode, giving it the same two arms the StorageMerge helper has. A witness over an ordered view was added, and a mutant reverting just those two arms reddens it alone.
⚠️ The changelog said the wrong results require optimize_read_in_order = 1. ReadFromMerge::requestReadingInOrder has four callers, gated by four independent settings, and each applies an order to unsorted input on a false success; two of the other three are independently randomized in CI. Agreed, wording only. The fix already sat at the single shared entry point, so all four callers were covered; only the published scoping was too narrow. The entry now names the four optimize_*_in_order settings.
💡 The two planHasCoordinatedRead helpers are asymmetric: only the StorageMerge one tests ReadFromParallelReplicasStep. Not changed; the asymmetry is correct. In the remote-only shape a second rewrite finds no MergeTree read at all, so insertion returns early on an empty eligible set and no second coordinator is possible. The StorageMerge helper needs the extra arm because it runs against child plans, where the fragment may not have been inlined, which is what the dedicated mutant for that arm establishes. Adding a redundant arm would imply a reachability that does not exist.
⚠️ The witness added for the ordered-view shape asserts only a scalar sum, which a purely local read returns too, while the one distribution assertion in the file covers a plain merged table rather than the view. If the plan for that shape ever stopped being distributed, the arm would silently degrade from witness to control, and it is the only arm that catches a revert of the union guard. Agreed. A companion EXPLAIN arm now asserts the shipped fragment is in that shape's plan, carrying the same query at enable_parallel_replicas = 0 as the control that proves the assertion discriminates. The runtime witness is unchanged.
⚠️ The arm census in the PR body and in the validation table went stale again when the eighteenth arm was added: 17 arms, 9 witnesses and seven aborting, where the file has 18, 10 and eight. Two further figures were carried over from an earlier round measured against a smaller test file and a narrower regression slice. Agreed. Every count re-derived from the test file by the predicate a reader would run, and the two carried-over figures either scoped explicitly to the file they were measured against or replaced by the current slice.
💡 Smaller corrections, all applied: the changelog entry moved to the present tense per docs/changelog_entry_guidelines.md; the template's Related: links were moved out of the HTML comment so they render; merge() was rewritten as merge in prose, per the repository's convention of naming a function without parentheses; and the description now names both entry points at which ordering is declined rather than only the shared one. Agreed.
⚠️ The description described PR 113636 by a mechanism it no longer uses: "clears make_distributed_plan for the same child plans at the caller". At that PR's current head this is false. It changes exactly one conditional, guarding materializeConstantsForSetOperationBranches with planContainsLogicalExchange, and its second commit restores the setting its first commit had cleared. Agreed. The sentence now describes the guarded set-operation transform instead. The independence claim underneath it was re-verified and holds: the two diffs share no file, this change reads make_distributed_plan nowhere, and its single mention of planContainsLogicalExchange is a doc comment citing the sibling guard rather than code.
⚠️ The arm census went stale a third time when the nineteenth arm was added: 18 arms, 10 witnesses and "the other two" asserting a plan shape, where the file has 19, 11 and three. A mutation row also still said "the other 16 arms stay green", a figure measured when the file had 17 arms. Agreed. Every count re-derived from the test file by the predicate a reader would run: 19 arms as 11 witnesses, 7 controls and 1 negative, with three EXPLAIN witnesses and eight aborting ones. The eight aborting, the 7 controls and the 1 negative are unchanged. The mutation row now states the property rather than a count. The round that added the arm reported these deltas instead of editing a frozen artifact, which is what made them cheap to catch.
💡 The test's header comment still says two plan-shape witnesses. Not changed; disclosed instead. The same stale count as above in a third place. Nothing depends on it: no assertion, oracle or arm reads that sentence, and every arm's own comment is accurate. The reviewer does not edit source and this PR's fix budget is spent, so it is recorded here rather than silently overridden.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT sum(value) FROM merge(currentDatabase(), '^t$') with parallel_replicas_plan_based = 1 on a three replica cluster aborts the initiator 6 of 6 runs on the pristine parent, with the stack frame for frame identical to the CI report, and the new test reports server died on that binary.
b Root cause explained? Yes. A plan can be optimized more than once, and ReadFromMerge optimizes each child plan three times. After the first applyParallelReplicas run, the second pass inlines the local plan, leaving a bare but already coordinated ReadFromMergeTree in the outer plan. A later run collects it again, since collectReadsToDistribute filters only on mergeTreeReadCanBeShipped, and creates a second coordinator. One registers a stream, followers are dispatched against both, and the follower announcing to the other is dropped by the snapshot pin before its read request throws.
c Fix matches root cause? Yes. The non-idempotency belongs to applyParallelReplicas, so the guard is in that function next to the two existing planHas* predicates, mirroring the guard the sibling tryMakeDistributed* transforms received in f34ffbb. Removing that abort exposed a second route through the in-order optimizations, declined at both entry points that can order a merged read: ReadFromMerge::requestReadingInOrder, and the pre-existing readingFromParallelReplicas predicate in optimizeReadInOrder.cpp, which recognised only the classic step. No widened bound, no test tag, no check at the abort site.
d Test intent preserved / new tests added? Yes. New test with 19 arms (11 witnesses, 7 controls, 1 negative), eight of which abort the server without the fixes, the other three asserting by EXPLAIN that the merged child read is still distributed after the guard, that the same holds for the ordered read through a view, and that ordering is declined for the shape shipped without a local plan; no existing test changed or weakened; a regression slice of 618 stems, 629 verdicts per arm, is verdict set identical across the two binaries (name symmetric difference 0; the two wide-run deltas were re-run interleaved three rounds per arm and were identical in all six, so 0 real verdict changes and 0 real reason changes).
e Both directions demonstrated? Yes. Every arm restarts the server and asserts SELECT lower(buildId()) against readelf -n before any verdict, because --binary selects only the client. Coordinators go 2 to 1, 4 to 2 and 3 to 1 on the three witness shapes, and the test passes with the fix while reporting server died without it. Per-arm on the 17 arm file that existed when the ReadFromMerge decline was added: fix 17/17, base 8/17, and a mutant deleting that guard's remote-only arm 16/17 with only its own witness red. The eighteenth arm aborts and stops the runner, so its own mutant is measured as a two run asymmetry on one binary instead: the arm aborts, and the whole pre-round file stays green.
f Fix is general across code paths? Yes. All three ReadFromMerge optimize sites are covered by the one rewrite guard, and separate mutants show each of those optimize() calls is load bearing and must stay: removing the createChildrenPlans one reddens 8 existing prewhere and count pushdown tests, removing the addFilter one reddens the existing join runtime filter test over a Merge table. ReadFromLocalParallelReplicaStep::addFilter is the same class and is covered by construction. On the ordering half the generality question is entry points rather than call sites: ReadFromMerge::requestReadingInOrder is shared by all four in-order optimizations, and the union branch of optimizeReadInOrder is the separate one, reached when the sort arrives from inside the child plan; both now decline, and an instrumented build counts one hit on each of the two new predicate arms for the witness and zero on three negative controls, so neither arm is dead code. collectReadsToDistribute, mergeTreeReadCanBeShipped, subtreeHasUnshippableRead and the fragment marking loop are deliberately untouched, so a surviving duplicate shows up rather than being masked by a second guard.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Witnesses span one and two merged tables, a pushed down filter, both JOIN orientations, forced index analysis, an ordered read, an ordered read through a view carrying ORDER BY, and an ordered read shipped without a local plan; controls span the direct read, a plain view, the same ordered read with read in order off, parallel_replicas_plan_based = 0, parallel_replicas_local_plan = 0 and no parallel replicas. The predicate keys on a plan step rather than on data, so it is type agnostic. Weakening it to any MergeTree read reddens both the base table control and the plan shape witness, showing it is not globally over broad; removing createChildrenPlans' optimize reddens the plan shape witness alone, which is what shows the merged child read specifically is covered.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, no serialization or wire format touched, so no SettingsChangesHistory.cpp entry is owed. The guard only suppresses a rewrite that had already been applied.
i Invariants and contracts preserved? Yes. The invariant the predicate decides is that a plan already carrying a coordinated ReadFromMergeTree is left alone. A plan carrying only a leftover split marker that was never converted, which happens when createParallelReplicasPlan declines because a single replica is usable, is deliberately not recognised and is out of scope: that shape fails identically before and after this change, measured on both binaries. is_parallel_reading_from_replicas is set to true from three places: enableParallelReadingFromReplicasForSerialization and createLocalParallelReplicasReadingStep, both reached only after a coordinator exists, and the constructor argument, whose only true-valued sources are canUseParallelReplicasOnFollower() in StorageMergeTree and StorageReplicatedMergeTree plus deserialization on a replica. The follower sources cannot reach the guard: applyParallelReplicas returns first unless canUseParallelReplicasOnInitiator() && parallel_replicas_plan_based, and initiator and follower are mutually exclusive. So a first time plan on the initiator cannot satisfy the predicate. The guard runs before any fragment is built, so it cannot race the marking loop, and ReadFromParallelReplicasStep has no serialization and a single construction site, so a marked read is always locally produced.

Session id: cron:clickhouse-review-slot-48:20260807-075900

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @tavplubix, could you review this? The plan-based parallel replicas rewrite was not idempotent, so when ReadFromMerge optimizes a child plan a second time it re-distributed an already coordinated read and created a second coordinator, which aborts the initiator with an unknown-stream logical error; the in-order optimizations then needed the same guard, since they could order the local read but never the shipped fragment.

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b0c7c0]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3452) FAIL cidb, issue
Stress test (amd_msan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-4b8a) FAIL cidb
Stress test (arm_debug) FAIL
Logical error: Bad cast from type A to B (STID: 3520-4525) FAIL cidb
Stress test (arm_asan_ubsan, s3) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) FAIL cidb

AI Review

Summary

I traced the current PR head through the three touched surfaces: the repeated applyParallelReplicas rewrite guard, the ReadFromMerge::requestReadingInOrder decline, and the union-path decline in optimizeReadInOrder. I did not find a remaining correctness gap in the patched plan-based parallel-replicas path, and the new stateless test covers both the duplicate-coordinator failure and the read-in-order coordination mismatch with reasonable controls against over-broad skipping.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because this workspace has no build directory or ready test binary. As of 2026-08-08 01:28 UTC, Style check, Fast test, and Build (arm_tidy) had completed successfully, but the main build and sanitizer matrix was still queued.
Final Verdict

✅ No blocking issues found in the current PR head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 38/41 (92.68%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 2b0c7c0 - the build was skipped, reused from cache, or predates profile upload.

…present

The previous commit widened `readingFromParallelReplicas` to also return true for a
`ReadFromMergeTree` whose `isParallelReadingFromReplicas` is set. That predicate has a single
caller, which abandons read in order for a whole `UnionStep` as soon as it holds for any child,
so the extra condition also declined ordering for a union whose children are all local reads
of one table: the projection parts and the normal parts of a partially materialized projection.
Such a union has no remote branch, so there is no pair of nodes whose coordination modes could
diverge, and declining only loses the optimization. It regressed
`03814_optimize_read_in_order_projection`, whose second case reported `ReadType: Default` where
`InOrder` is expected, on the `ParallelReplicas` flavour.

The condition is also redundant. Both parallel replicas union constructions pair a local branch
with a remote one, and the remote branch is either `ReadFromParallelRemoteReplicasStep` on the
classic path or `ReadFromParallelReplicasStep` on the plan based path, which are exactly the two
steps the predicate still recognises. A bare `ReadFromMergeTree` is never the remote branch, so
the shipped witness declines through the fragment step instead, and the unknown stream abort
stays pinned.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 2b0c7c000b416a2, which fixes a regression this PR itself caused, and updated the description.

Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) reported 03814_optimize_read_in_order_projection on the previous head. Its second case, a partially materialized projection, expects ReadType: InOrder and got Default, only on the ParallelReplicas flavour and only in that one of fifteen checks that ran the test.

The cause was mine. I had widened readingFromParallelReplicas with a third condition, for a ReadFromMergeTree whose isParallelReadingFromReplicas is set. That predicate has a single caller, which abandons read in order for a whole UnionStep as soon as it holds for any child, and the partial projection case is a union of two ordinary local reads of one table: the projection parts and the normal parts. There is no remote branch in that union, so no pair of nodes whose coordination modes could diverge, which is the condition the guard exists for, and declining only lost the optimization.

The condition was also redundant. Both parallel replicas union constructions pair a local branch with a remote one, and the remote branch is either ReadFromParallelRemoteReplicasStep on the classic path or ReadFromParallelReplicasStep on the plan based path, built at ClusterProxy/executeQuery.cpp:915 and :955 and at ParallelReplicasLocalPlan.cpp:373 respectively. Those are exactly the two steps the predicate still recognises, and a bare ReadFromMergeTree is never the remote branch. So dropping the third condition is a deletion of five lines with nothing added.

I instrumented each condition separately to establish that rather than argue it. The shipped witness in the new test declines through the fragment step, while 03814 declined only through the condition I removed. The matrix, each mutant built and its build id asserted:

binary 04817 03814
before either fix aborts, unknown stream not reached
only the classic condition aborts, unknown stream not reached
without the fragment condition passes InOrder becomes Default
previous head passes InOrder becomes Default
this head passes passes

The two rows in the middle are what show the fragment condition is load bearing and the removed one was not, so the unknown stream witness stays pinned.

For regressions I ran every stateless test matching read in order, ReadType: or Prefix sort description, plus every test creating a PROJECTION: 361 tests, 366 verdicts, same server on both binaries. The verdict sets differ only by 03814 moving to passing. Two tests first looked like new failures and are not: both hit the runner timeout while their runs on the other binary took 1.49 and 2.28 seconds, and rerunning that pair alone on both binaries passes in the same time on each. The new test passes 50 of 50 randomized and 50 of 50 unrandomized runs.

I did not add a test arm for this. 03814 is already the exact witness, since it fails on the previous head and passes here, and a partial projection arm inside the new test would sit above a union that does carry a remote branch, making it a control rather than a witness. I checked that by probing it before writing any reference.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2b0c7c0

CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both green, last check completed 2026-08-08T06:06:22Z. Counted by conclusion:
154 success, 17 skipped, 4 failure, plus one CIDB-only row (see the note at the end).

Every failure below has an owner: a fixing PR (mine 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
AST fuzzer (amd_debug, targeted, old_compatibility) / Invalid number of columns in chunk pushed to OutputPort (STID 2270-3452) trunk bug in normal-projection optimization with a correlated subquery. The fuzzer mutated one of this PR's own tables, which is why it needs saying explicitly that the shape is not mine: the fingerprint is a scalar (SELECT col) inside WHERE over a table carrying a PROJECTION, and over 90 days it has fired on 23 distinct unrelated PRs and once on master, starting 2026-06-26, well before this branch existed #111401 (mine, open)
Stress test (arm_debug) / Logical error: Bad cast from type A to B (STID 3520-4525) trunk bug: reading only a dotted Nested member's subcolumn from a part written before an ALTER ... MODIFY COLUMN added a type wrapper casts ColumnString to ColumnNullable #113925 (mine, open)
Stress test (amd_msan) / Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-4b8a) trunk bug: a skip index whose on-disk type is stale relative to a pending ALTER MODIFY COLUMN is deserialized against the new type, giving null map size = 1, nested column size = 0. 3 rows in 90 days, on this PR and 2 other unrelated ones #112484 (mine, open)
Stress test (arm_asan_ubsan, s3) / same message (STID 6726-6444) same root cause, the set-skip-index arm of that call site. 32 rows in 90 days across 28 distinct unrelated PRs, plus 3 master failures #112484 (mine, open)
Build (arm_release) / Post Hooks CI telemetry, not a build failure: the build-profile hook's INSERT INTO build_time_trace into the shared CI logs cluster was rejected with HTTP 500. This is the post-fix residual, so the merged retry hardening is deliberately not linked here (see below) a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

None is PR-caused. This diff is 3 source files, +49/-1: applyParallelReplicas.cpp,
optimizeReadInOrder.cpp and StorageMerge.cpp, plus one new stateless test. It touches no
projection-optimization path, no Nested subcolumn read path, no skip-index deserialization and no
CI telemetry script.

On the Post Hooks row specifically, the retry hardening in #113409 merged 2026-08-06T00:05Z and is
already present in this build
(ci/jobs/scripts/log_cluster.py at this commit carries its marker, and
so does master), so merging master would not turn the row green. The retry count is itself the
fix-presence oracle: pre-fix code emits one LogCluster query failed with code 500 warning, post-fix code
emits eight, and this row has eight, i.e. every retry ran and was exhausted. Over the last 7 days that
post-fix shape accounts for 463 rows across 316 distinct PRs and 66 master failures, so it is a live
residual rather than a stale build, and per ledger rule 3d it gets its own owner instead of a link to
#113409.

One note for anyone re-deriving these numbers from the check list alone: the Post Hooks row is
invisible to the GitHub check-runs API, because Build (arm_release) reports success (the hook runs
after the job's own status is fixed). It is only visible in the CI database, which is why the failure
count above is 4 by check conclusion but 5 by failing row.

Session id: cron:our-pr-ci-monitor:20260808-070000

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Another symptom of the same root cause, found by the AST fuzzer on #109891: SELECT ... WHERE notIn(_block_offset, (SELECT DISTINCT 257 FROM merge('^tab__fuzz_1') FINAL WHERE y = '')) aborts with the logical error !is_parallel_reading_from_replicas in ReadFromMergeTree::spreadMarkRanges (ReadFromMergeTree.cpp:3612) during ReadFromMerge::buildPipeline — the re-optimized child plan leaves a bare coordinated ReadFromMergeTree that is then built through the FINAL path. Report. The guard here should cover it.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

It does not cover it. I reproduced that abort on this PR's head 2b0c7c0, with the same stack, so it is a different route.

The guard lives in applyParallelReplicas, and that whole optimizer pass only runs when parallel_replicas_plan_based is on (QueryPlanOptimizationSettings.cpp:365). Your carrier runs with it off, which is the default, so neither of the two guards this PR adds is ever consulted. Setting it to 1 does make the query pass, but vacuously: EXPLAIN then shows no ReadFromRemoteParallelReplicas step at all, so parallel replicas is simply not engaged and nothing can abort. I nearly reported that green as coverage.

The route it actually takes is the FINAL check in Planner.cpp:2295, which disables task based parallel replicas but only looks at TableNode:

auto * table_node = it->as<TableNode>();
if (!table_node)
    continue;

merge('^tab__fuzz_1') FINAL is a TableFunctionNode, so it is skipped, parallel replicas stays on, and the follower reaches StorageMergeTree::read:385, which sets enable_parallel_reading from canUseParallelReplicasOnFollower() and parallel_replicas_for_non_replicated_merge_tree with no FINAL check. ReadFromMerge::buildPipeline then builds that marked read down the FINAL branch and :3612 asserts the mark is clear. isTableNodeEligibleForParallelReplicas in findParallelReplicasQuery.cpp:55 has the same blind spot.

Two arms isolate it. A FINAL subquery reading the MergeTree table directly, without merge(), passes with parallel replicas engaged; merge() without FINAL also passes. Clearing parallel_replicas_for_non_replicated_merge_tree also makes it pass, matching the second conjunct above.

This is already fixed in your open #110972, whose Planner.cpp:2304-2307 reads modifiers off both TableNode and TableFunctionNode, with a comment naming FROM merge(...) FINAL. Marker table_function_node->getTableExpressionModifiers counts 0 on master and 1 at its head 63fde4f, and 04612_parallel_replicas_merge_tables.sql is absent on master and has FINAL coverage there. So I am not changing anything here, and not opening a competing PR. This is the same STID 2508-3f82 I answered on #100377 on 2026-08-07; I re-measured it today rather than reusing that answer, since both heads have moved.

Each arm ran on its own fresh server: the abort kills the server, so later queries in one run return Connection reset by peer whether or not they would abort.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 3, 2026
@alexey-milovidov alexey-milovidov removed the blocker This issue / pr blocks a new release label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing this as obsolete: the route it guards was closed on master by a different fix, and all three hunks are now inert.

I merged origin/master (ee489d39675) into this head (2b0c7c0) — two conflicts, both textual — built the result, and measured each hunk instead of arguing from the code. Each of the three sites was instrumented with its own LOG_ERROR marker, and the marked binary was run against the PR's own test, 04836/04837/04838, a 234-test slice matching parallel replicas, read in order and Merge, and a 20-arm hand probe covering every shape in the test with parallel_replicas_allow_merge_tables both off and on.

Hunk Times fired Effect of removing it
applyParallelReplicas.cpp, the planHasCoordinatedRead rewrite guard 0 none
StorageMerge.cpp, the requestReadingInOrder decline 0 none
optimizeReadInOrder.cpp, readingFromParallelReplicas recognising ReadFromParallelReplicasStep 18 none — the plan is byte-identical

Why the two Merge guards cannot fire

getChildPlanOptimizationSettings (StorageMerge.cpp:796) now sets optimization_settings.enable_parallel_replicas = false unconditionally for every child-plan optimization, and createChildrenPlans clears the setting in the child context as well unless keep_parallel_replicas_for_children holds (:1049, :1102). applyParallelReplicas returns at its very first line for a child plan, so the pass cannot run a second time on one, and a child plan can never come to carry a coordinated read. Both guards are unreachable by construction, not merely unexercised.

The same bug family already has a fix and a test on master

tests/queries/0_stateless/04836_merge_table_parallel_replicas_duplicate_announcement.sh is on master, and its header names the fix explicitly: "the enable_parallel_replicas clear in ReadFromMerge::createChildrenPlans". Same root cause, different fix, already pinned by its own regression test.

The third hunk fires but changes nothing

It fires only for a sort that cannot be shipped — sortingCanBeShipped rejects hasPartitions, so a window sort leaves the union under a full SortingStep:

└──Sorting (Sorting for window 'PARTITION BY a ORDER BY b ASC')
   └──Union
      ├──ReadFromMergeTree (default.t_win3)
      │     Read type: Default
      └──ReadFromParallelReplicas (...)

Reverting only that hunk, rebuilding, and confirming through /proc/<pid>/exe which binary was actually serving, the plan is unchanged: the local branch stays at Read type: Default either way, because buildInputOrderInfo returns nothing for it regardless of the guard. So the guard declines an optimization that was never going to be applied. Keeping it would also pull against the direction of cfdb45f4f49 ("Apply read in order with ORDER BY for plan-based parallel replicas"), which makes read in order work on the plan-based path rather than decline it.

The test no longer discriminates

04817_pr_repeated_optimize_unknown_stream fails on master in three arms — merge ordered view plan shape, merge plan shape and merge ordered without local plan — because it asserts that a merge read is distributed, which master now does only behind parallel_replicas_allow_merge_tables, off by default. With that setting on, all nineteen arms pass identically with the patch and with it fully reverted. No arm aborts a server on either binary.

The FINAL carrier from #113788 (comment of 2026-08-09) is gone too

merge(...) FINAL no longer engages parallel replicas at all — EXPLAIN shows a bare ReadFromMerge, while the same query without FINAL shows the union. My earlier answer attributed this to #110972; that pull request was closed unmerged, so the credit belongs to the !InterpreterSelectQuery::isQueryWithFinal(query_info) conjunct of keep_parallel_replicas_for_children instead.

What is left

#110518 stays open. The message is still reported in CI most weeks — 5 rows in the last 25 days, against 20 to 35 a day before 2026-08-01 — but through other shapes: the recent carriers name jd_r and t_pr_read_mode, not a Merge read. Those remaining routes are unrelated to this diff.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, and the closure is right. I checked the three claims it rests on rather than reading them off your description: getChildPlanOptimizationSettings sets enable_parallel_replicas = false unconditionally (StorageMerge.cpp:798), applyParallelReplicas returns on !settings.enable_parallel_replicas as its first statement (applyParallelReplicas.cpp:690), and createChildrenPlans clears the setting in the child context (:1102) unless keep_parallel_replicas_for_children holds (:1048). Both Merge guards are unreachable.

One correction, and it is mine rather than yours: the #110972 attribution was my claim, in #113788 (comment), not anything you wrote. #110972 closed unmerged on 2026-08-17, and the coverage I cited with it, 04612_parallel_replicas_merge_tables.sql, is not on master either. I should have re-checked its state instead of carrying that claim forward. CIDB supports your credit assignment: the !is_parallel_reading_from_replicas signature has zero rows since 2026-08-16 22:40:58, against 12 in the 45 days up to it, so the shape went quiet without #110972 ever merging.

On which conjunct does the work: at today's defaults parallel_replicas_plan_based and parallel_replicas_allow_merge_tables are both false, so keep_parallel_replicas_for_children is false already and :1102 clears the setting regardless of FINAL. !InterpreterSelectQuery::isQueryWithFinal(query_info) is what keeps the route closed once both are on, which is the only configuration that could still reach it, and the description of parallel_replicas_allow_merge_tables names that case. So it is closed either way.

scanhex12 pushed a commit to aaron276h/ClickHouse that referenced this pull request Sep 4, 2026
…ing a read

With parallel_replicas_plan_based = 1, a query over a system log table or a
SQL SECURITY DEFINER view failed on the initiator with

    LOGICAL_ERROR: Next task callback is not set for query with id: <uuid>

applyParallelReplicas marks the coordinated read with
enableParallelReadingFromReplicasForSerialization, which deliberately attaches
no callbacks: the step is only serialized and shipped to replicas, where
deserialize rebuilds it and resolves the callbacks from the context.
createParallelReplicasPlan then clones that fragment once more to build the
initiator's local arm, and ReadFromMergeTree::clone() passed the
marked-but-callback-less state back through the constructor. The constructor
cannot distinguish "marked for serialization" from "replica side, resolve from
the context", so it took its context fallback, and an initiator holds no
coordinator callback.

Ordinary plan-based queries survive that fallback only because Context's copy
constructor carries the callbacks TCPHandler installed. Instrumenting the
constructor showed the fallback is taken on the ordinary path too, and merely
happens to find a callback there. The failing shapes read under a context built
fresh from the global context, which never holds them: a system log storage, or
a DEFINER view.

clone() now copies the flag and both callback optionals directly, so a copy no
longer re-derives state from the context. All three fields move together:
restoring only the flag would drop the callbacks of a marked read that has them,
which getParallelReadingExtension asserts on. The constructor's context fallback
is unchanged, since deserialize, StorageMergeTree::read and
StorageReplicatedMergeTree::readLocalImpl rely on it on a follower.

Both branches of that fallback were reachable with the same state: with the
first one made non-throwing, the same query threw the sibling message from
Context::getMergeTreeReadTaskCallback, so copying both optionals is required.

Still reproduced with both in-flight Merge route fixes applied (ClickHouse#112849,
ClickHouse#113788), so this is a separate defect rather than one of those routes.

Related: ClickHouse#111677
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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