Repository navigation
Conversation
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.
Internal second-model review (click to expand)An independent cold review plus an adversarial second-model pass ran against this diff. Findings and
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-48:20260807-075900 |
|
cc @devcrafter @tavplubix, could you review this? The plan-based parallel replicas rewrite was not idempotent, so when |
|
Workflow [PR], commit [2b0c7c0] Summary: ❌
AI ReviewSummaryI traced the current PR head through the three touched surfaces: the repeated Missing context / blind spots
Final Verdict✅ No blocking issues found in the current PR head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 38/41 (92.68%) · Uncovered code |
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.
|
Pushed
The cause was mine. I had widened The condition was also redundant. Both parallel replicas union constructions pair a local branch with a remote one, and the remote branch is either 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
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, I did not add a test arm for this. |
CI finish ledger - 2b0c7c0CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
None is PR-caused. This diff is 3 source files, On the One note for anyone re-deriving these numbers from the check list alone: the Session id: cron:our-pr-ci-monitor:20260808-070000 |
|
🕵 Another symptom of the same root cause, found by the AST fuzzer on #109891: |
|
It does not cover it. I reproduced that abort on this PR's head The guard lives in The route it actually takes is the auto * table_node = it->as<TableNode>();
if (!table_node)
continue;
Two arms isolate it. A This is already fixed in your open #110972, whose Each arm ran on its own fresh server: the abort kills the server, so later queries in one run return |
|
🕵 Closing this as obsolete: the route it guards was closed on I merged
Why the two
|
|
Agreed, and the closure is right. I checked the three claims it rests on rather than reading them off your description: 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, On which conjunct does the work: at today's defaults |
…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
Related: #110518
Related: #113636
Changelog category (leave one):
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 requireparallel_replicas_plan_based = 1, for example amergetable function read; the wrong results also requireparallel_replicas_local_plan = 0and one of the fouroptimize_*_in_ordersettings.Description
A query plan can be optimized more than once, and
ReadFromMergedoes that for its child plans: increateChildrenPlans, inaddFilter, and while building the pipeline.applyParallelReplicasdid not tolerate that. After one run the second pass inlines the local plan, leaving a bare but already coordinatedReadFromMergeTreein the outer plan. A later run collects that read again, becausecollectReadsToDistributefilters only onmergeTreeReadCanBeShipped, 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 namesStorageMergechild plans as the carrier. It can only fire on an already rewritten plan, sinceis_parallel_reading_from_replicasis 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, whoseReadFromMergeTreecounterparts already declined onisParallelReadingFromReplicaswhile its own branches did not; and the union branch ofoptimizeReadInOrder, 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 coordinatoragainstCreated coordinator for stream: amergeread 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, aJOINovermergefrom 3 and 1 to 1 and 1. A direct or view read is unchanged.New test
04817_pr_repeated_optimize_unknown_streamhas 19 arms: 11 witnesses, 7 controls, 1 negative. Eight witnesses aremergeshapes that abort the server without the fixes. The other three assert byEXPLAINthat 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:
base tablecontrol and plan shape witness redden, so it is not over-broadoptimizecall inReadFromMergecreateChildrenPlans, the join runtime filter test foraddFilter, so both stayReadFromMergeguardRegression 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.