Repository navigation
Disable parallel replicas in every subquery of the filter-collection plan - #121273
Conversation
…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.
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:
Severity: ❌ blocker / Four properties in the wrong-results class were re-derived independently in the final round rather than Session id: cron:clickhouse-review-slot-48:20260921-050600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260921-035600 |
|
Workflow [PR], commit [892524a] Summary: ✅
AI ReviewSummaryThe 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 Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 22 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - f01f35fEvery 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
155 checks succeeded and 18 were skipped; Session id: cron:our-pr-ci-monitor:20260921-103829 |
|
No, and on top of each other #121283 undoes this one. Measured each PR's own change (
The estimate fills its own copy of the set (#121283 (comment)), and only this PR's re-planned local plan adopts it. In 05237,
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 |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai, pls fix tests |
|
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 (
#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 |
|
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). |
…s-in-subquery-set
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]>
…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]>
Internal second-model review (click to expand)
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261105-220200 |
|
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. Measured: |
`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]>
| /// 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) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
Changelog category (leave one):
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 itsINsubqueries 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 (IndexAnalysisRounds3 for two reads) and creates a second coordinator that never runs. Withdistributed_index_analysisthat is one moremergeTreeAnalyzeIndexesUUIDquery, which 04052 counts.Root cause.
collectFiltersForAnalysisplans a clone of the query with dummy join tree tables and disabled parallel replicas only in its top context. AnINsubquery 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/UnionNodeof 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 setsenable_parallel_replicasitself; under a throwingmax_rows_to_read, a read whose own row estimate runs (aGLOBAL INsubquery's) is still analyzed twice, as #121269 does not memoize it; withparallel_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
INarm on master, 2 and 1 here (GLOBAL IN3/3 to 2/2, control 2/1 on both); 04052 withparallel_replicas_min_number_of_rows_per_replica = 1fails 3/3 on master and passes 50/50 randomized here. Results unchanged.Workflow [PR]
Sync PR [sync-upstream/pr/121273]
Version info
26.11.1.1562-master(included in26.11and later)