Skip to content

Disable parallel replicas in every subquery of the filter-collection plan - #121273

Merged
nickitat merged 10 commits into
ClickHouse:masterfrom
groeneai:pr-local-plan-adopts-in-subquery-set
Nov 6, 2026
Merged

nickitat merged 10 commits into
ClickHouse:masterfrom
groeneai:pr-local-plan-adopts-in-subquery-set

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

With parallel_replicas_min_number_of_rows_per_replica, collecting the filters of a query no longer plans its IN subqueries with parallel replicas, which saves an extra index analysis of the subquery's read and an unused parallel replicas coordinator.

Description

Related: #71028 (class 3), builds on #121283. Failing jobs: Fast test of this PR, 04052 on #71028.

What breaks. With parallel_replicas_min_number_of_rows_per_replica > 0, WHERE key IN (SELECT key FROM t WHERE ...) over a parallel replicas MergeTree read index-analyzes the subquery's read twice (IndexAnalysisRounds 3 for two reads) and creates a second coordinator that never runs. With distributed_index_analysis that is one more mergeTreeAnalyzeIndexesUUID query, which 04052 counts.

Root cause. collectFiltersForAnalysis plans a clone of the query with dummy join tree tables and disabled parallel replicas only in its top context. An IN subquery keeps its real table and the original's context, so that planner planned it with parallel replicas (a row estimate, a coordinator, a local replica plan) that nothing executes since #121283.

The change. Copy the context of every QueryNode/UnionNode of the clone and disable parallel replicas there, as the replica plans and scalar subqueries already do; the original is untouched. A materialized CTE's subquery is skipped: the query executes the plan built for it. The earlier set adoption is removed (inert on top of #121283).

Scope. The same clone serves Distributed, view and cluster-engine reads: a collected set built in place for pruning (e.g. _path IN (...)) now runs its subquery without parallel replicas, same contents. Unchanged: a view whose stored query sets enable_parallel_replicas itself; under a throwing max_rows_to_read, a read whose own row estimate runs (a GLOBAL IN subquery's) is still analyzed twice, as #121269 does not memoize it; with parallel_replicas_plan_based = 1, 04052 still counts one extra (3 before, 2 after).

Validation. The new 05234 counts 3 index analyses and 2 coordinators per IN arm on master, 2 and 1 here (GLOBAL IN 3/3 to 2/2, control 2/1 on both); 04052 with parallel_replicas_min_number_of_rows_per_replica = 1 fails 3/3 on master and passes 50/50 randomized here. Results unchanged.


Workflow [PR]
Sync PR [sync-upstream/pr/121273]

Version info

  • Merged into: 26.11.1.1562-master (included in 26.11 and later)

…n is re-planned

With parallel_replicas_min_number_of_rows_per_replica above 0 an `IN` subquery was
planned, index-analyzed and executed twice. Measured on a 100,000-row MergeTree with
`SELECT sum(key) FROM t WHERE key IN (SELECT key FROM t WHERE key > 50000)`: read_rows
100,000 -> 150,000 (1.50x) and IndexAnalysisRounds 2 -> 3, with correct results. Under
distributed_index_analysis each extra analysis is also a cross-replica round trip,
which is what 04052_distributed_index_analysis_in_subquery_no_quadratic counts.

The chain. Above 0 the setting makes collectFiltersForAnalysis build a throwaway
StorageDummy plan purely to harvest filter DAGs for the row-count estimate. The
estimate's index analysis (selectRangesToRead -> KeyCondition::tryPrepareSetIndexForIn
-> buildOrderedSetInplace) fills the `IN` set behind that DAG, and the DAG reaches the
executed read as SelectQueryInfo::filter_actions_dag: ActionsDAG::clone copies
Node::column by pointer, so the executed read's filter surface holds the same,
already-filled set object. createLocalPlanForParallelReplicas then re-plans the local
replica's query from the query tree with a fresh PlannerContext and a fresh, empty set,
so the first KeyCondition built over the local plan's `key IN <empty set>` fills it a
second time. The outer read is spared because its analysis is transplanted; a read
nested under an `IN` is not.

Measurement decided which surface to collect from. Of the analyzed read's four
candidate filter surfaces only getQueryInfo().filter_actions_dag ever carries the
filled set, both with prewhere at its defaults and with optimize_move_to_prewhere and
query_plan_optimize_prewhere off; getFilterActionsDAG(), the prewhere actions and the
row-level filter are null in every configuration measured. The collector is therefore
called on that one surface instead of on all four.

createRemotePlanForParallelReplicas and createRemotePlanFragmentForParallelReplicas are
deliberately left alone: those plans are serialized and shipped, an in-memory Set
cannot travel, and each replica must build its own.

The external-table guard sits in the new collector rather than in reuseBuiltSets or
collectBuiltSets because the difference is in the consumer, not in the mechanism. The
existing collectBuiltSets deliberately shares GLOBAL IN sets: its only consumer is the
automatic-parallel-replicas probe plan, which is never executed, and 03800's query_6
measures that behaviour. This consumer is executed, so it declines any set whose fill is
entangled with an external table. That is a conservative boundary rather than a defect
being fixed: on this path buildQueryTreeForShard materializes a GLOBAL IN subquery into
the temporary table before the local plan exists and replaces the subquery with a read of
that table, so the re-planned set is keyed on the table and cannot match an offered set
anyway. The hash collision the predicate rules out is real - the collected GLOBAL IN set's
hash is byte-identical to a plain IN's over the same subquery text, because the set is
registered before that substitution - and refusing it keeps reuseBuiltSets,
collectBuiltSets and the probe path byte-for-byte unchanged.

Pruning is preserved rather than degraded. Both in-place build paths fill the set's
elements, so an adopted set reports hasExplicitSetElements() and the local plan's own
KeyCondition still uses the index instead of falling back to a set-less condition.

At the default 0 there is no pre-pass, the filter surface is null, nothing is collected
and reuseBuiltSets returns at its first statement, so those plans are unchanged. No
setting is added, changed or re-defaulted.

This closes the parallel_replicas_min_number_of_rows_per_replica trigger. It does not
close the parallel_replicas_plan_based = 1 trigger of ClickHouse#118275: that path splits one
plan into fragments rather than re-planning it, it doubles both analyses rather than
one, and 04052 under it behaves identically before and after this change.

Related: ClickHouse#118275
Drop the fix narration at the local-plan reuse site and the header's caller cross-reference; keep the GLOBAL IN temp-table property and the external-table contract.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 21, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex), over 3 review rounds and 2 fix rounds:
2 gate findings plus 4 from my own cold reads. Every row was fixed before this PR was published, and
the final round returned 0 findings from both the gate and my own read.

# Sev Finding Verdict Evidence / action
1 ⚠️ The GLOBAL IN arm of the new test does not exercise the external-table exclusion its comment claimed to cover (05234_pr_local_plan_adopts_in_subquery_set.sql) AGREE, fixed buildQueryTreeForShard substitutes a temporary TableNode before the local plan is built and the tree hash mixes in node type, so the re-planned set can never match the offered one; the arm's stated purpose is corrected to what it does check, and the only discriminating shape costs one extra index-analysis round, never a wrong result.
2 💡 The commit message and the new collector's comment presented that exclusion as preventing replicas from reading an empty temporary table AGREE, fixed On this path the temporary table is filled eagerly before the local plan exists and the one setExternalTable caller runs after adoption, so both now describe a conservative boundary instead.
3 💡 The report oracle (IndexAnalysisRounds = 2) is also the value a run with parallel replicas disengaged produces AGREE, fixed The report SELECT now also asserts ProfileEvents['ParallelReplicasUsedCount'] > 0, as 02950_parallel_replicas_used_count does, verified under a call-site mutation to be an engagement assertion and not a second detector.
4 ⚠️ The regression sweep was keyed on filenames and default settings, so it missed the only pre-existing test in this change's trigger shape AGREE, fixed 03232_pr_not_ready_set is that test; it runs 5/5 on both sides and its A/B shows this change also closes it there (IndexAnalysisRounds 3 to 2, read_rows about halved), recorded as no regression on the destructive in-place path rather than as coverage of the counting property, with no line added to the diff.
5 💡 The no-prewhere arm's comment claimed the filter reaches the read through another surface AGREE, fixed The probe shows only SelectQueryInfo::filter_actions_dag ever carries the filled set, identically with prewhere on and off; the arm stays (its before-value is 3 and the mutation reddens it independently) and its comment now states what it checks.
6 💡 A second unrun test, 04327_pr_view_union_empty_branch, also pins the setting above 0 DROPPED on my own measurement Its six IN ( are all tuple INs, which build a FutureSetFromTuple the collector skips, so it is not in the trigger shape; run anyway because it was free, 2/2 on both sides.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings on hunks unchanged by a fix round are auto-dropped.

Four properties in the wrong-results class were re-derived independently in the final round rather than
inherited: adoption matches on the content-derived FutureSet::getHash() and only ever replaces a set
that is not yet created; Set's hash table is built unconditionally by insertFromBlock and the
collected set carries explicit elements, so runtime FunctionIn and index pruning are both preserved;
the new block sits before the right_branch_selected guard because a set is keyed by subquery content
while an AnalysisResult is bound to one table expression; and the adoption runs in the only window
where the re-planned plan's sets are still reachable, confirmed by the probe rather than by reading.

Session id: cron:clickhouse-review-slot-48:20260921-050600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 04052_distributed_index_analysis_in_subquery_no_quadratic --no-random-settings --client-option parallel_replicas_min_number_of_rows_per_replica=1 is 3/3 FAIL on master and 50/50 PASS here, and the new test's counter is 3 before and 2 after on every single run, so this is not a rate.
b Root cause explained? Above 0 the setting makes the planner build a throwaway StorageDummy plan for the row-count estimate, whose index analysis fills the IN set behind the filter DAG that then reaches the executed read as SelectQueryInfo::filter_actions_dag, while the local replica's plan is re-planned with a fresh PreparedSets, so its KeyCondition fills the set a second time.
c Fix matches root cause? Yes: the already-filled set is handed to the re-planned build through the existing reuseBuiltSets, the remedy shape recorded at CreatingSetsStep.cpp:382-388, with no widened bound, no no-random-* tag, no settings clamp, no defensive check and 04052's reference untouched.
d Test intent preserved / new tests added? 04052 is unmodified and its BETWEEN 3 AND 4 bound still holds; the new 05234_pr_local_plan_adopts_in_subquery_set adds three IndexAnalysisRounds arms plus a GLOBAL IN result arm, each also asserting ParallelReplicasUsedCount > 0 so a future disengagement of this path reddens the test instead of passing on a count of 2 that plain local execution also produces.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: reverting only src/ reddens the new test at estimate 3 and estimate_no_prewhere 3 while the control stays at 2 and every sum stays 3749925000, and reverting only the call site reproduces exactly that with the engagement column still 1, so the counters and not the engagement assertion are what detect the defect.
f General across code paths? createLocalPlanForParallelReplicas is the single re-planning site and buildQueryPlanForParallelReplicas reaches it, so one edit fixes both variants; the two remote-plan builders are deliberately excluded because those plans are serialized and shipped and an in-memory Set cannot travel, and applyParallelReplicas does not call the changed function at all, which I measured.
g Generalizes across inputs? The unit adopted is a whole Set keyed by the subquery's tree hash, so column type wrappers are not a dimension, and the dimensions that are real were measured: prewhere on and off (both arms reddening), IN vs GLOBAL IN, the setting at 0 vs 1, parallel_replicas_plan_based 0 vs 1, plus an indexHint-wrapped IN, which is covered because appendSetsFromActionsDAG recurses into FunctionIndexHint::getActions().
h Backward compatible? Yes, and nothing to record: no setting is added, changed or re-defaulted, so there is no SettingsChangesHistory.cpp entry, and at the default 0 the filter surface is null, nothing is collected and reuseBuiltSets returns at its first statement.
i Invariants and contracts preserved? The invariant is that a re-planned build may adopt a set an earlier build filled, except where that fill also feeds an external table; that predicate is a conservative boundary rather than a defect being fixed, since on this path buildQueryTreeForShard materializes the subquery into the temporary table before the local plan exists and keys the re-planned set on that table, so it could not match an offered set anyway; pruning is preserved because the collected set reports hasExplicitSetElements() == true, and storage, tuple and correlated sets are excluded by the typeid_cast and the isCreated() check.

Session id: cron:clickhouse-impl-slot-7:20260921-035600

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [892524a]

Summary: ✅


AI Review

Summary

The PR disables parallel replicas in filter-collection subqueries while preserving the contexts of materialized CTEs whose shared plans execute later. No unresolved findings remain. Comparing exact base 5fad0b44 with head 892524a4, the new regression confirms one fewer index analysis and coordinator in each affected arm, unchanged results, and preserved parallel execution for the materialized CTE. The head output matches the reference exactly. The previous CTE finding is fixed and its review thread is resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
Comment thread src/Planner/Utils.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 892524a4e with master 679267cc9 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 22 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 - f01f35f

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
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 the master_head gate reds a shard on a dashboard confirmed_regression that the shard's own report does not sustain: the same query is called slower on 108 true-master runs over 53 master commits in the last 7 days, and on dozens of unrelated PRs #121090 (mine, open)

155 checks succeeded and 18 were skipped; Mergeable Check and PR are aggregate rollups over the one failure above, not separate results.

Session id: cron:our-pr-ci-monitor:20260921-103829

@nickitat nickitat self-assigned this Sep 22, 2026
@nickitat

nickitat commented Oct 8, 2026

Copy link
Copy Markdown
Member

@groeneai, does it supersede #121283 ?

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

No, and on top of each other #121283 undoes this one. Measured each PR's own change (f01f35f5 and 8d6d483c, both on a78f42ee) and both together, on one 3-replica rig with --no-random-settings:

test this PR #121283 both
05237_parallel_replicas_input_table_function (from #121283) FAIL, all three input() cases Code: 477 OK OK
04052_distributed_index_analysis_in_subquery_no_quadratic, parallel_replicas_min_number_of_rows_per_replica = 1 OK FAIL, the CI diff (1 -> 2) FAIL
05234_pr_local_plan_adopts_in_subquery_set (from this PR) OK FAIL, 3 index analysis rounds instead of 2 FAIL

The estimate fills its own copy of the set (#121283 (comment)), and only this PR's re-planned local plan adopts it. In 05237, input() is read the second time elsewhere (from the 477 stack traces; lines at 16222351):

  • GLOBAL IN: executeSubqueryNode at buildQueryTreeForShard.cpp:1020 fills the temporary table by running the subquery again, before the local plan exists. Removing the GLOBAL IN branch (patch in the Utils.cpp review thread) does not change that: 05237 fails the same way.
  • automatic_parallel_replicas_mode = 2: the probe plan of considerEnablingParallelReplicas runs its own row estimate, which builds the set again.

With both, #121283's decline means the estimate never fills the set this PR adopts, so the result is that of #121283 alone.

Two ways to end up with one fix: (a) extend this PR so the GLOBAL IN temporary-table fill and the automatic-mode probe also reuse the estimate's set, and drop #121283; (b) keep both, with #121283 declining only when the subquery cannot run twice (input()), so that elsewhere the estimate still runs and this PR adopts its set. Which do you prefer?

@nickitat

nickitat commented Nov 5, 2026

Copy link
Copy Markdown
Member

@groeneai, pls fix tests

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

The Fast test failure is deterministic. I have not pushed a test-only fix, because it would go red again as soon as #121283 merges. Measured on this branch (fa7e1106), 05234's estimate arm, IndexAnalysisRounds / read_rows:

build max_rows_to_read = 0 max_rows_to_read = 20000000
master 3 / 150000 5 / 150000
master + #121273 2 / 100000 4 / 100000
master + #121283 3 / 100000 3 / 100000
master + both 3 / 100000 3 / 100000

#121283 already removes the second execution of the subquery. Should I (a) close this PR once #121283 is merged, or (b) rework it on top of #121283 to remove that remaining analysis (a different change)?

@nickitat

nickitat commented Nov 5, 2026

Copy link
Copy Markdown
Member

The Fast test failure is deterministic. I have not pushed a test-only fix, because it would go red again as soon as #121283 merges. Measured on this branch (fa7e1106), 05234's estimate arm, IndexAnalysisRounds / read_rows:
build max_rows_to_read = 0 max_rows_to_read = 20000000
master 3 / 150000 5 / 150000
master + #121273 2 / 100000 4 / 100000
master + #121283 3 / 100000 3 / 100000
master + both 3 / 100000 3 / 100000

* Why it is red now: the CI test profile sets `max_rows_to_read: 20000000` (`tests/config/users.d/limits.yaml`), and since [Do not enforce read row limits in the parallel-replicas row estimate #121269](https://github.com/ClickHouse/ClickHouse/pull/121269) the row estimate then goes through `selectRangesToReadForEstimation()`, which is not memoized, so the local plan analyzes both reads again (2 -> 4). Pinning `max_rows_to_read = 0` in the test fixes that part.

* Why that is not enough: [Fix `input()` read twice when the parallel-replicas row estimate builds an IN set #121283](https://github.com/ClickHouse/ClickHouse/pull/121283) skips the estimate whenever `filter_actions_dag` holds a set that is not built yet, and this PR collects built sets from that same DAG, so on top of [Fix `input()` read twice when the parallel-replicas row estimate builds an IN set #121283](https://github.com/ClickHouse/ClickHouse/pull/121283) it has nothing to adopt (identical numbers above). With both, `05234` gives 3, and `04052` with `parallel_replicas_min_number_of_rows_per_replica = 1` still counts the `greater(key, ...)` analysis twice. That remaining round is the IN subquery's read: analyzed for its own row estimate when it is planned for parallel replicas, then again in the re-planned local replica plan.

#121283 already removes the second execution of the subquery. Should I (a) close this PR once #121283 is merged, or (b) rework it on top of #121283 to remove that remaining analysis (a different change)?

I guess (b), because we don't want extra analysis regardless

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged, (b). I will rework this PR on top of #121283 so the IN subquery read is not analyzed a second time in the re-planned local replica plan, and follow up here with the updated PR (or my findings).

groeneai and others added 2 commits November 5, 2026 22:04
On top of ClickHouse#121283 the parallel-replicas row estimate declines when its
filter references a set that is not built yet, which is the filter whose
built sets appendBuiltSetsFromActionsDAG collected for reuseBuiltSets in
createLocalPlanForParallelReplicas. Nothing is ever collected there any
more, so the adoption is dead code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 5, 2026 22:12
…plan

With parallel_replicas_min_number_of_rows_per_replica > 0,
collectFiltersForAnalysis plans a clone of the query in which only the
join-tree tables are replaced by dummies, and it disabled parallel replicas
only in the clone's top context. An IN subquery keeps its real table and
shares its context with the original tree, so that throwaway planner planned
the subquery with parallel replicas: a row estimate (one index analysis of
the subquery's read), a coordinator and a local replica plan, none of which
is ever executed since ClickHouse#121283 made the outer estimate decline on an unbuilt
set. The real execution then analyzes the subquery read again.

Copy the context of every QueryNode/UnionNode of the clone and disable
parallel replicas there, the way the local replica plan, the remote plan and
scalar subqueries already do. Copies are assigned to the clone's nodes only,
so the original query tree keeps its settings.

Related: ClickHouse#71028
Related: ClickHouse#118275

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imate

Renames 05234_pr_local_plan_adopts_in_subquery_set, whose subject (the
local plan adopting the estimate's IN set) is gone, and checks
IndexAnalysisRounds and ParallelReplicasQueryCount per query with
parallel_replicas_min_number_of_rows_per_replica on: with and without a
read row limit (the CI profile sets max_rows_to_read = 20000000), with
prewhere off, for a GLOBAL IN, and a control with the row estimate off.
Without the previous commit the three IN arms give 3 analyses and 2
coordinators instead of 2 and 1, and the GLOBAL IN arm 3 and 3
instead of 2 and 2; the control stays at 2 and 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not re-execute an IN subquery when the parallel replicas local plan is re-planned Disable parallel replicas in every subquery of the filter-collection plan Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
⚠️ The test did not assert that the unused parallel replicas coordinator is gone AGREE, fixed: 05234 also checks ParallelReplicasQueryCount
💡 The GLOBAL IN arm depended on the profile's max_rows_to_read AGREE, fixed: pinned like the first arm

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the new 05234 counts 3 index analyses per IN arm on master (with #121283) and 2 here in every run; 04052 with parallel_replicas_min_number_of_rows_per_replica = 1 fails 3/3 on master, byte-identical to CI, and passes here.
b Root cause explained? collectFiltersForAnalysis disabled parallel replicas only in the top context of its clone, so an IN subquery (real table, context shared with the original tree) was planned with parallel replicas: a row estimate (one index analysis), a coordinator and a local plan that nothing executes since #121283.
c Fix matches root cause? Yes: the switch now reaches every QueryNode/UnionNode of the clone, copy then assign, the walk the replica plans and scalar subqueries already use; no tag, clamp or widened bound, 04052 untouched.
d Test intent preserved / new tests added? 04052 is unmodified; 05234 is renamed to its new subject and checks IndexAnalysisRounds with and without a read row limit, with prewhere off, for GLOBAL IN, and a control, each row also asserting parallel replicas were used and how many coordinators were created.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: without the fix commit 05234 fails 3/3 (four arms off by one in analyses and in coordinators, control unchanged); with it 5/5 plus 50/50 randomized, and 04052 50/50 randomized under the trigger.
f Fix is general across code paths? collectFiltersForAnalysis is the only planner of this clone; the full traversal covers FROM subqueries, union arms, correlated subqueries and materialized CTEs; the local/remote replica plans and scalar subqueries already have the same walk.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured IN, GLOBAL IN, mixed, prewhere on/off, max_rows_to_read 0 and 20000000, a view inside the subquery, parallel_replicas_plan_based 0/1; type wrappers are not a dimension of which context plans a subquery; results unchanged everywhere.
h Backward compatible? (maintainer-approved exception only) Yes: planning only, no setting or format change; with the default parallel_replicas_min_number_of_rows_per_replica = 0 on plain MergeTree the function returns before this code.
i Invariants and contracts preserved? No (sub)query of the clone is planned with parallel replicas, and the original tree's contexts are never mutated (copies go to the clone's nodes only); a view whose stored query sets enable_parallel_replicas itself is outside this, as for the existing walks.

Session id: cron:clickhouse-impl-slot-7:20261105-220200

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Reworked as (b), on top of #121283 (master merged into the branch for it): 5ef47ae

A correction to my previous comment: the extra analysis did not come from the re-planned local replica plan. collectFiltersForAnalysis disabled parallel replicas only in the top context of its clone, so an IN subquery (real table, the original's context) was planned there with parallel replicas: a row estimate with one index analysis, plus a coordinator that nothing executes since #121283. The fix disables parallel replicas in every QueryNode/UnionNode of the clone. The earlier set adoption is removed, as it is inert on top of #121283.

Measured: 05234 (renamed to 05234_parallel_replicas_in_subquery_read_analyzed_once, max_rows_to_read 0 and 20000000 arms) counts 3 index analyses and 2 coordinators per IN arm on master, 2 and 1 here. 04052 with parallel_replicas_min_number_of_rows_per_replica = 1 fails 3/3 on master and passes 50/50 randomized here.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Nov 6, 2026
Comment thread src/Planner/Planner.cpp Resolved
`collectFiltersForAnalysis` builds its throwaway plan with the
`DelayedMaterializingCTEsStep` machinery, so planning a materialized CTE
there stores the CTE plan in the `MaterializedCTE` handle the clone
shares with the original tree. The real query then sees
`hasPlanOrBuilt()` and executes that plan. With parallel replicas
disabled in every subquery of the clone, that plan read the CTE without
parallel replicas: a two-reference `MATERIALIZED` CTE inside an `IN`
under a view lost its coordinator (0 instead of 1).

Skip a materialized CTE's subquery in the walk, so its plan is built
with the original contexts exactly as before. The other subqueries
still get parallel replicas disabled.

05234 gains that shape as an arm: 1/1/1 (index analyses, parallel
replicas used, coordinators) on master and with this commit, 1/0/0
without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/Planner.cpp
/// Disable parallel replicas to collect filters, in every (sub)query: each one is planned with its own context,
/// which the clone still shares with the original tree, and an `IN` subquery keeps its real tables.
/// A materialized CTE keeps its contexts: the plan built for it here is stored in the handle the query shares and executes.
auto not_materialized_cte = [](const QueryTreeNodePtr & parent, const QueryTreeNodePtr & child)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A materialized CTE's subquery is skipped: the query executes the plan built for it.

Can you elaborate on that? Do we skip them because the plan will be executed and we don't want to override the settings it will be executed with?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Yes. The plan built for a materialized CTE here is not a throwaway one: addBuildSubqueriesForMaterializedCTEsIfNeeded stores it in MaterializedCTE::plan (CollectMaterializedCTE.cpp:195), the clone shares that handle (TableNode::cloneImpl copies the pointer, TableNode.cpp:253), and the real query sees hasPlanOrBuilt() (CollectMaterializedCTE.cpp:159) and executes that plan instead of planning the CTE again. materialize_ctes = false below only skips the materialization, not the plan assignment.

So disabling parallel replicas in the CTE's context would run the real CTE read without them: on 7f21213 (no skip) the two-reference CTE in 05234's materialized_cte arm got 0 coordinators, against 1 on master and on this head. With the skip the CTE is still planned once, with the settings it executes with, as on master.

@nickitat
nickitat added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 9ecf1e8 Nov 6, 2026
186 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements 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.

4 participants