Skip to content

Fix coordination mode mismatch with a parameterized view subquery - #114916

Merged
nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-106039-parameterized-view-coordination-mode
Aug 26, 2026
Merged

nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-106039-parameterized-view-coordination-mode

Conversation

@groeneai

@groeneai groeneai commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #106039
Related: #113622

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

Fixed Coordination mode mismatch for stream <table>: got Default, expected WithOrder when a parameterized view is used as an IN-subquery of an ordered query with parallel replicas enabled. A parameterized view used this way no longer plans its inner read with parallel replicas coordination on a replica.

Description

SELECT ... FROM t WHERE id IN (SELECT id FROM pv(id = 'a')) AND id IN (SELECT id FROM pv(id = 'b')) ORDER BY id
with parallel replicas enabled aborted the server in debug and sanitizer builds, and threw in release.

Root cause. A parameterized view resolves as a TableFunctionNode, so its arguments land in
skip_children in Planner/CollectSets.cpp and the view call survives verbatim into the text sent
to the replicas. The initiator plans the outer read in order from the sort key and announces
WithOrder; each replica re-plans the view body, an unordered scan, and announces Default. Both
key on the bare table name, so the second announcement reaches the first's coordinator and throws.

PlannerJoinTree.cpp already guards a view planning its own read on a follower, but it compares
table_node against the chosen parallel_replicas_table, and both are null, so it concludes "this
is the chosen table" and leaves coordination enabled for the view.

A table expression that is not a TableNode is now treated as not chosen, which is always correct:
parallel_replicas_table is a const TableNode *, and both walks in findTableForParallelReplicas
bail out on a table function. The union-children comparison is skipped for the same reason. A view
referenced by name is a TableNode, so parallel_replicas_allow_view_over_mergetree = 1 is
unaffected.

Validation. The test pins the five settings the divergence depends on, three of which the runner
randomizes; each of the four that can vary was confirmed load-bearing by a negative control on the
unfixed binary. It fails 8 of 8 randomized runs on master with the reported error and passes 100 of
100 here. Expected rows are parallel-replicas-off ground truth, so each query also asserts
ParallelReplicasHandleAnnouncementMicroseconds > 0 to show coordination was reached. The in-tree
view, parameterized-view, trivial-view-pushdown and table-function tests are unchanged.

Version info

  • Merged into: 26.9.1.132 (included in 26.9 and later)

A parameterized view used as an IN-subquery resolves as a TableFunctionNode, so
Planner/CollectSets.cpp puts its arguments in skip_children and the view call survives
verbatim into the query text sent to the replicas. The initiator plans the outer read
in order from the sort key and announces WithOrder while each replica re-plans the view
body, an unordered scan, and announces Default. Both announcements key on the bare table
name, so the second one reaches the first's coordinator and getOrCreateCoordinator
raises "Coordination mode mismatch for stream <table>: got Default, expected WithOrder".

The follower guard in PlannerJoinTree.cpp exists to stop a nested planner from reading
with parallel replicas, but it compares table_node against the chosen
parallel_replicas_table and for a table function both are null, so the null-vs-null
comparison concludes the view is the chosen carrier. Treat a null table_node as not
chosen instead. That is always sound: parallel_replicas_table is a const TableNode *
and both walks in findTableForParallelReplicas bail out on a table function, so a table
function can never be the carrier. The union-children comparison just below matches null
against null for the same reason and is now skipped rather than re-enabling parallel
replicas for the view.

The regression test pins the five settings the divergence depends on, since the runner
randomizes all of them and each one alone stops the two reads from being planned in
different modes; each pin was confirmed load-bearing by forcing it back on a pre-fix
build. Because the expected rows are also what a query returns when parallel replicas
never engage, every query additionally asserts
ParallelReplicasHandleAnnouncementMicroseconds > 0, which is incremented in the same
function that raised the mismatch.

Closes: ClickHouse#106039
Resolves the adjacent-line conflict in PlannerJoinTree.cpp: master's
trivial-view-pushdown plumbing (effective_context / effective_storage /
effective_snapshot) is kept verbatim, and this branch's two changed lines
(the !table_node disjunct and the table_node-conditional table_union
lookup) are kept as they are independent statements in the same block.
system.query_log is a non-replicated MergeTree, so with
parallel_replicas_for_non_replicated_merge_tree = 1 it is eligible for
parallel replicas, and the session sets enable_parallel_replicas = 2,
which throws on a shape it does not support rather than falling back.
The verification query could therefore fail instead of measuring the
queries under test. All four in-tree precedents that read query_log for
parallel replicas profile events pin enable_parallel_replicas = 0.

The comment above the query no longer implies the assertion identifies
which replica announced: ParallelReplicasLocalPlan installs the same
announcement callback on the initiator, and the profile event is
incremented before the coordination mode check, so the initiator's own
local plan increments it too. The event shows coordination was reached;
the two-sided randomized run is what shows the repaired path.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, all findings resolved)

An independent model reviewed this change three times. Rounds 1 and 2 raised 6 findings; all
were accepted and addressed (five randomizer-controlled settings pinned with per-setting
negative controls, a liveness oracle added, the UNION-children comparison guarded, master
merged, the verification query taken off the parallel replicas path, the changelog claim
narrowed to what was measured).

Round 3 re-raised two of them. Both are answered by measurement rather than argument.

❌ A view body's own SETTINGS enable_parallel_replicas = 1 could re-enable coordination
after the guard clears it.
The mechanism is real up to the last step: the guard clears the
setting on a copied context, StorageView replans the stored inner query, QueryTreeBuilder
reapplies its SETTINGS, and Context::createCopy keeps the coordinator callbacks. The
consequence does not follow. Four arms on the fixed binary (no SETTINGS, = 1, = 2, and
the allow_experimental_parallel_reading_from_replicas alias) are all clean, while the same
SQL on the unfixed binary aborts with the reported error, so the arms do reach the defect. The
arms are self-evidencing: an OR arm that must return rows returned them in all four, a
system.tables probe showed each arm's SETTINGS clause survived into the stored query, and a
post-arm liveness query rules out a server that had died. No change made, since I could not
reproduce it - the same three lines are byte-identical on master today, reached through the
comparison this PR does not touch.

⚠️ The ParallelReplicasHandleAnnouncementMicroseconds > 0 assertion can be satisfied by the
initiator's own local plan.
Correct, and the test comment now says so. The suggested fix -
scope the assertion to secondary queries - was implemented and measured: it returns zero rows,
because the test cluster is eleven 127.0.0.x:9000 entries in one process, so no secondary
query_log rows exist at all. That form would pass by matching nothing, on both binaries, so
it is weaker than what ships. Follower involvement is instead established by the abort's
reachability: getOrCreateCoordinator throws only from RemoteQueryExecutor's announcement
path, and canUseParallelReplicasOnFollower() is false on an initiator by construction, so the
unfixed binary failing 8 of 8 randomized runs with that error is itself follower-side evidence.

💡 Noted, not changed: the comment above the SET block says the runner varies all five pinned
settings; it varies three (enable_analyzer is chosen per job, and
parallel_replicas_min_number_of_rows_per_replica already defaults to 0). Four of the five
have negative controls. The description above states the measured numbers.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes. The 04241 AND query with enable_parallel_replicas=1, max_parallel_replicas=3, parallel_replicas_for_non_replicated_merge_tree=1 aborts on every run of a master debug build. No randomization, no stress harness, and optimize_aggregation_in_order is not required.
b Root cause explained Yes. A parameterized view resolves as a TableFunctionNode, so the view call survives into the text sent to the replicas; the initiator announces WithOrder for the outer in-order read while each replica announces Default for the view body, both keyed on the bare table name. The follower guard in PlannerJoinTree.cpp that exists to prevent this compares two null pointers and so concludes the view is the chosen table.
c Fix matches root cause Yes. Two conditions added to that existing guard (the chosen-table test and the union-children test below it), at the layer that already owns the decision. Not a coordinator-side tolerance patch (that approach was closed unmerged in #106043), no new setting, no widened bound.
d Test intent preserved, new test added Yes. No existing test removed or weakened. New stateless test 04907_parallel_replicas_parameterized_view_in_subquery, parallel-safe (no no-parallel tag, no global objects), asserting query results rather than log text. It pins the five settings the divergence depends on, three of which the test runner randomizes; each of the four that can vary was proven load-bearing by forcing it back to its neutering value on a master build. It asserts ParallelReplicasHandleAnnouncementMicroseconds > 0 per query so it cannot pass by silently skipping parallel replicas. That event is incremented for the initiator's own local plan too, so it shows coordination was reached rather than identifying which replica announced; the two-sided randomized run in (e) is what shows the repaired path. The verification query itself pins enable_parallel_replicas = 0, matching the four in-tree precedents, so the oracle cannot become the failure it measures.
e Demonstrated in both directions Yes. Under clickhouse-test: [ FAIL ] on a master build with Coordination mode mismatch ... got Default, expected WithOrder at getOrCreateCoordinator, [ OK ] with this change. Under full randomization the master build fails 8 of 8 runs, all carrying that signature, and this change passes 100 of 100. Every arm verified against its build id. The expected result rows were generated with parallel replicas OFF on the master build, so they encode ground truth rather than patched output.
f General across code paths Yes. The guard is the single decision site. Every other kind of table expression reaching it was checked: plain table functions including merge(), named views under parallel_replicas_allow_view_over_mergetree = 1, materialized views under parallel_replicas_allow_materialized_views = 1, the parallel_replicas_table_union sub-branch, parallel_replicas_plan_based = 1 and serialize_query_plan = 1. All measured unchanged.
g Generalizes across inputs Yes. The discriminator is the node type of the table expression, not a value, so the coverage is across table-expression kinds and both boolean states of the two relevant settings rather than a type-wrapper matrix. The empty-table case is covered by the existing 04078_pr_view_over_empty_mergetree.
h Backward compatible Yes. No setting default, serialization format or protocol change, so no SettingsChangesHistory.cpp entry. The change only declines parallel replicas for a read that could never have been the chosen carrier, so no query that coordinates today stops doing so.
i Invariants and contracts preserved Yes. The guard's own contract, that a table expression which is not the chosen carrier must not coordinate, is restored rather than altered; the body it gates is untouched. No lifetime, locking or concurrency surface is involved.

Also checked, all re-measured after merging current master rather than inherited from an earlier
build: 50 runs under default randomization and 50 with --no-random-settings, all green. The in-tree
view and parameterized-view parallel-replicas tests were run serially on a master build and on this
change, with identical results, including all 14 that use
parallel_replicas_allow_view_over_mergetree. The merge touches the line the trivial-view-pushdown
optimization added, so that feature's own 22 04*_trivial_view_pushdown* tests were run on the
merged tree as well: 22 of 22 pass.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b40bd4]

Summary: ✅


AI Review

Summary

This PR closes the common follower-side parameterized-view mismatch by forcing nested table-function reads off the parallel-replicas path and by preserving the copied context for pipeline lifetime. I found one remaining correctness gap: a parameterized view whose stored SELECT has its own SETTINGS enable_parallel_replicas ... can re-enable parallel replicas inside the inner view planner, so the same coordination-mode mismatch is still reachable.

Findings

❌ Blockers

  • [src/Planner/PlannerJoinTree.cpp:2466] Clearing allow_experimental_parallel_reading_from_replicas on the parent read context is not enough when the view body itself contains SETTINGS enable_parallel_replicas (or the alias). StorageView::read reparses the stored query, QueryTreeBuilder::buildSelectExpression reapplies those settings to the inner QueryNode context, and buildPlannerContext then plans the inner table as the new parallel-replicas carrier. That reopens the same Coordination mode mismatch failure this PR is supposed to fix.
    Suggested fix: strip enable_parallel_replicas and allow_experimental_parallel_reading_from_replicas from the inner view query on the follower path, or override them after the inner query tree is built. Add a regression case with CREATE VIEW ... AS SELECT ... SETTINGS enable_parallel_replicas = 2.
Final Verdict

⚠️ Request changes

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @novikd, could you review this? A parameterized view resolves as a TableFunctionNode, so the parallel replicas follower guard compared two null pointers, concluded the view was the chosen table, and left coordination enabled for the view's inner read, which then announced Default against the outer WithOrder on the same stream key.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 15, 2026
Admitting a null table_node routes a table function into the arm that reads with a
Context::createCopy. That copy was only kept alive until read() returned, while source
processors deriving from WithContext store a weak_ptr and resolve it lazily from a
pipeline thread: StorageURLSource's initialize lambda then threw "Context has expired"
(LOGICAL_ERROR) on urlCluster reads, which broke 02221_parallel_replicas_bug in Fast
test.

Hand the copy to QueryPlanResourceHolder::interpreter_context, which exists for this
case and outlives the pipeline. The same createCopy / setSetting / read / addInterpreterContext
sequence is already used in resolveStorages.cpp for the identical reason.

Verified on the failing test's own content with the build ids asserted: pre-PR master is
clean, the previous head aborts, and this build is clean with output byte-identical to
pre-PR master. 04907 still reproduces its committed reference.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test failure on the previous head (02221_parallel_replicas_bug, Context has expired).

Root cause was in this PR. Admitting a null table_node also admits the case where both sides
of the old comparison are null, so a table function now enters the arm that reads with a
Context::createCopy. That copy only lived until read() returned, while source processors
deriving from WithContext keep a weak_ptr and resolve it lazily on a pipeline thread, so
StorageURLSource's initialize lambda threw on urlCluster reads.

The copy is now handed to QueryPlanResourceHolder::interpreter_context, which outlives the
pipeline. resolveStorages.cpp already does the same createCopy / setSetting / read /
addInterpreterContext sequence for the identical reason.

Verified on the failing test's own content, with build ids asserted on each server: pre-PR master
is clean, the previous head aborts, this build is clean and its output is byte-identical to pre-PR
master. 04907 still reproduces its committed reference.

@@ -2462,6 +2465,9 @@ JoinTreeQueryPlan buildQueryPlanForTableExpression(TableExpressionNodePtr table_
auto mutable_context = Context::createCopy(effective_context);
mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If the parameterized view body itself carries SETTINGS enable_parallel_replicas = 1/2 (or the allow_experimental_parallel_reading_from_replicas alias), this one-shot override does not actually stick. StorageView::read reparses the stored SELECT, QueryTreeBuilder::buildSelectExpression reapplies the view body's SETTINGS into the inner QueryNode context, and buildPlannerContext then uses that re-enabled context when it chooses the inner parallel_replicas_table. At that point the follower is back to planning a coordinated inner read, so the same Coordination mode mismatch path is still reachable for a view like CREATE VIEW pv AS SELECT ... SETTINGS enable_parallel_replicas = 2.

I think this needs to strip those two setting names from the inner view query on the follower path (similar to the blacklist in InterpreterCreateQuery.cpp for MV POPULATE), or otherwise override them after the inner query tree is built. A focused regression case with a parameterized view that sets enable_parallel_replicas in its body would catch it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The reparse-and-reapply part is right: I probed it directly with a getSetting('allow_experimental_parallel_reading_from_replicas') column inside the view body, and it returns 2 on the fixed binary, so the body's clause does reach the inner query node and the guard's cleared copy does not.

The abort does not follow from it. Four arms, one server restart each, build id asserted per arm, on a pristine-master binary (pinned c8dacba9, these lines reverted) and on the current head 0b40bd4:

view body base head
none mismatch, got Default expected WithOrder clean
enable_parallel_replicas = 1 mismatch clean
enable_parallel_replicas = 2 mismatch clean
allow_experimental_parallel_reading_from_replicas = 1 mismatch clean

Base aborts in all four, so the arms reach the defect; head is clean in all four, with the positive-output rows present and a post-arm liveness check passing. Both directions reproduce on an independent re-run.

What decides it is which context is threaded into StorageView::read, not the inner query node's context: StorageMergeTree::read takes enable_parallel_reading from its local_context (StorageMergeTree.cpp:385), and the follower gate reads the planner's query context (PlannerJoinTree.cpp:2443). In the = 2 arm the followers running the outer query text show plain default reading with zero ReadPoolParallelReplicas lines, so they no longer announce for that table; the only coordinated pool left is the initiator-side remote subquery.

I re-ran this rather than reusing the earlier measurement because 0b40bd4 changed context handling on this exact path.

So no change here. A regression case for the body-SETTINGS shape would be a real oracle (base does abort on it), but it exercises the same one-line guard that 04907_parallel_replicas_parameterized_view_in_subquery already covers, so I would rather not add a second arm for it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0b40bd499 with master b04769724 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 693.40 MiB 690.38 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 24 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 0b40bd4

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-6673) trunk bug in set skip-index deserialization, not reachable from this diff (this PR touches PlannerJoinTree.cpp + one stateless test) #112484 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable)

The stack confirms the owner: the abort is raised in
SerializationNullable::deserializeBinaryBulkWithMultipleStreams, called from
MergeTreeIndexGranuleSet::deserializeBinary -> MergeTreeIndexReader::read ->
MergeTreeDataSelectExecutor::filterMarksUsingIndex. That is the set skip-index read path
#112484 addresses. Breadth over 30 days is 390 rows across 256 distinct PRs with 27 master
rows, so it is not specific to this branch.

@nickitat nickitat self-assigned this Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@nickitat
nickitat enabled auto-merge August 25, 2026 21:05
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This is a narrow null-safety fix in the parallel-replicas planner: it guards against a null table_node when a parameterized view is used as an IN-subquery and extends the read context's lifetime for the pipeline. ClickBench runs single-node and does not use parameterized views or parallel replicas, so neither flagged query executes the changed path. Both Q18 (+5.5%) and Q33 (+6.0%) are already non-directional (not_sure) and read as run-to-run variance rather than a real PR effect; Q33's delta also falls within master's current variance band.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1034 1091 +5.5% 0.0063 This PR only fixes the parallel-replicas planner path for parameterized views used as IN-subqueries; ClickBench runs single-node and never executes it, so the +5.5% is run-to-run variance, not a PR effect.
⚠️ 33 not_sure 1196 1268 +6.0% <0.0001 The change touches only the parallel-replicas parameterized-view code path, which this single-node ClickBench query does not exercise, so the +6.0% is unrelated to this PR. The delta also sits inside master's current variance band.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5db63325-0e9b-4ea8-8894-87fbcccfe7ba
  • MIRAI run: c595567c-71f9-46a7-93ab-f86a2d1bf70c
  • PR check IDs:
    • clickbench_381717_1787698697
    • clickbench_381728_1787698697
    • clickbench_381736_1787698697
    • tpch_adapted_1_official_381747_1787698697
    • tpch_adapted_1_official_381755_1787698697
    • tpch_adapted_1_official_381787_1787698697

@nickitat
nickitat added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit 5dd9252 Aug 26, 2026
359 of 360 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
On master `enable_analyzer` is frozen at 1, `parallel_replicas_only_with_analyzer`
is obsolete and the old-analyzer CI jobs are gone, so the pins that kept the arms
meaningful there, and the separate settings block the EXPLAIN arm needed, no
longer do anything. All arms now share one settings block.

The table is no longer partitioned by the per-row `DateTime`, which created 100
single-row partitions.

Measured with the real runner after merging master: the test fails on a build
with both this fix and the ClickHouse#114916 follower guard reverted (the server dies on
"Coordinator for parallel reading from replicas is not initialized"), and passes
with either change alone and with both. The single-partition table gives the
same results as the old one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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: Coordination mode mismatch for stream A: got B, expected C (STID: 6117-68e9)

4 participants