Repository navigation
Plan based parallel replicas. Part 2 - #111063
Conversation
…zation pass The planner builds a plain local plan under parallel_replicas_plan_based (no split, no ReadFromLocalReplica even for views/unions); applyParallelReplicas inserts a split above every eligible MergeTree read and lifts/combines/distributes them. Views over UNION are parallelized without parallel_replicas_allow_view_over_mergetree. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [194871b] Summary: ✅
AI ReviewSummaryThis PR moves Findings
Final VerdictNeeds changes before merge: the plan-based path still ignores the explicit materialized-view opt-out and changes a pre-existing setting contract. |
…matically force_index_by_date / force_primary_key over a view under parallel_replicas_plan_based no longer throw a false-positive INDEX_NOT_USED, without enabling parallel_replicas_filter_pushdown (the filter is pushed into the reading step by standard plan optimization before the split). Complements #109409, which fixes the query-tree path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…y aggregation fragments count(DISTINCT ...) with count_distinct_optimization becomes a keys-only partial aggregation. When shipped to replicas as a serialized plan fragment, its chunks lacked AggregatedChunkInfo (RemoteSource only auto-detects it from an AggregateFunction column), so MergingAggregated aborted with a logical error. ReadFromParallelReplicas now sets add_agg_info when the fragment ends in a partial AggregatingStep. Fixes the distributed-plan CI lane crash in 04538. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…istinct test Drop the redundant query_plan null check; the count-distinct regression test does not need serialize_query_plan or parallel_replicas_local_plan. Tighten comments. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
…n and duplicate-table handling insertParallelReplicasSplit reused findReadingSteps (the view-expansion helper), which skips a root UnionStep (so a top-level UNION ALL distributed only the first branch) and bypassed the duplicate-StorageID guard (so a same-table union was combined into one coordinator's fragment). Replace it with a pass-local collector that descends every union (including the root) and rejects unions that read the same table more than once (left local). Add regression tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Implements “plan-based” parallel replicas as a plan-level optimization: the planner now builds a normal local plan first, then QueryPlanOptimizations::applyParallelReplicas inserts/lifts ParallelReplicasSplitStep markers and rewrites them into local/remote execution (including handling of views and UNION ALL), plus adds regression coverage for key edge cases.
Changes:
- Move parallel-replicas boundary selection from planner-time special planning to a plan optimization that inserts split markers above eligible
MergeTreereads and can lift/merge them throughUNION/aggregation. - Fix distributed execution for shipped partial-aggregation fragments by ensuring remote chunks carry
AggregatedChunkInfowhen needed. - Add/adjust stateless query tests for root
UNION ALL, view-expandedUNION ALL, same-tableUNION ALLrejection, view predicate pushdown withforce_*settings, and count-distinct aggregation serialization.
Reviewed changes
Copilot reviewed 22 out of 22 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/queries/0_stateless/04615_pr_plan_based_same_table_union.sql | New regression test ensuring same-table UNION ALL is not shipped as one distributed fragment. |
| tests/queries/0_stateless/04615_pr_plan_based_same_table_union.reference | Expected outputs for the same-table UNION ALL regression test. |
| tests/queries/0_stateless/04614_pr_plan_based_top_level_union.sql | New regression test verifying distribution descends into a root UNION ALL. |
| tests/queries/0_stateless/04614_pr_plan_based_top_level_union.reference | Expected outputs for the root UNION ALL regression test. |
| tests/queries/0_stateless/04605_pr_plan_based_count_distinct_serialized.sql | New regression test for shipped partial aggregation / count(DISTINCT ...) serialization correctness. |
| tests/queries/0_stateless/04605_pr_plan_based_count_distinct_serialized.reference | Expected outputs for count-distinct regression test. |
| tests/queries/0_stateless/04604_pr_plan_based_force_index_view.sql | New regression test for view predicate pushdown with force_index_by_date / force_primary_key under plan-based PR. |
| tests/queries/0_stateless/04604_pr_plan_based_force_index_view.reference | Expected outputs for force-index-over-view regression test. |
| tests/queries/0_stateless/04603_pr_plan_based_view_no_view_flag.sql | New regression test confirming views with UNION ALL parallelize without parallel_replicas_allow_view_over_mergetree. |
| tests/queries/0_stateless/04603_pr_plan_based_view_no_view_flag.reference | Expected outputs for view-with-union/no-flag regression test. |
| tests/queries/0_stateless/04546_pr_plan_based_remote_only.sql | Update expected plan-shape assertions to reflect “plain local plan then optimize” behavior. |
| tests/queries/0_stateless/04546_pr_plan_based_remote_only.reference | Updated expected outputs for plan-shape changes. |
| tests/queries/0_stateless/04545_pr_view_union_local_reads.sql | Update plan-shape assertions for view-expanded UNION under plan-based PR flow. |
| tests/queries/0_stateless/04545_pr_view_union_local_reads.reference | Updated expected outputs for plan-shape changes. |
| tests/queries/0_stateless/04511_pr_view_union_all.sql | Update plan-shape assertions for view UNION ALL under plan-based PR flow. |
| tests/queries/0_stateless/04511_pr_view_union_all.reference | Updated expected outputs for plan-shape changes. |
| src/Storages/StorageView.cpp | Keep parallel replicas enabled for view inner queries in plan-based mode to allow later plan optimization to distribute reads. |
| src/Processors/QueryPlan/ReadFromParallelReplicas.cpp | Enable AggregatedChunkInfo for shipped fragments rooted at partial AggregatingStep to support merging. |
| src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp | Add plan-wide read collection and a new insertion phase to place split markers above eligible reads; add logic to lift splits above UnionStep. |
| src/Planner/PlannerJoinTree.cpp | Remove planner-time insertion of split step for parallel replicas under the new plan-based approach. |
| src/Planner/Planner.cpp | Skip the old parallel-replicas planning path when parallel_replicas_plan_based is enabled. |
| src/Core/Settings.cpp | Update parallel_replicas_plan_based setting description to match the new “optimize after planning” behavior. |
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
…lan-based-analysis
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
| if (typeid_cast<UnionStep *>(node->step.get())) | ||
| { | ||
| std::vector<QueryPlan::Node *> reads; | ||
| for (auto * child : node->children) |
There was a problem hiding this comment.
collectReadsToDistribute now treats any plain ReadFromMergeTree as eligible after wrapper storages have already expanded. That means the plan-based path can no longer tell that a read came from a MaterializedView, so it bypasses the old storage-level gate in parallelReplicasEnabledForStorage (src/Planner/PlannerJoinTree.cpp:1312-1346) and will parallelize even refreshable MVs that were explicitly rejected there.
That is not just a setting mismatch. StorageMaterializedView::readImpl first chooses and locks the current target table (src/Storages/StorageMaterializedView.cpp:406-413), and refreshable MVs rely on RefreshTask::getAndLockTargetTable to retry dropped targets and SYNC REPLICA before a SELECT (src/Storages/MaterializedView/RefreshTask.cpp:1555-1647). Once the optimizer rewrites the target-table ReadFromMergeTree directly, the remote fragment skips that wrapper contract entirely, so a refreshable MV can read a stale or disappearing target during refresh exchange. The same loss of wrapper identity also ignores parallel_replicas_allow_materialized_views = 0.
Please carry the original storage eligibility into the plan-based pass before wrapping a read, or keep MaterializedView / refreshable-MV reads out of collectReadsToDistribute until their wrapper semantics are preserved.
There was a problem hiding this comment.
This is still present in the current head. collectReadsToDistribute only re-checks refreshable-MV swap targets and parallel_replicas_for_non_replicated_merge_tree (src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:243-255), but it never re-applies the existing parallel_replicas_allow_materialized_views gate that still lives in parallelReplicasEnabledForStorage (src/Planner/PlannerJoinTree.cpp:1329-1337).
So in plan-based mode a query like SELECT count() FROM mv_pr_repl SETTINGS parallel_replicas_allow_materialized_views = 0 still reaches the target ReadFromMergeTree and gets split/distributed, and the new 04617_pr_plan_based_materialized_view.sql comments/tests now codify that target-only behavior (tests/queries/0_stateless/04617_pr_plan_based_materialized_view.sql:1-7,55-70). The refreshable-MV part is fixed, but the explicit materialized-view opt-out is still ignored.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
| /// keeps lifting through the code below (e.g. to a partial aggregation above the union) and the whole | ||
| /// union ships as one fragment. Branches are left untouched if not all of them are split markers | ||
| /// (e.g. a mixed view over MergeTree + non-MergeTree), so those distribute per branch instead. | ||
| void liftSplitsAboveUnion(QueryPlan::Node * node) |
There was a problem hiding this comment.
What we can do more
- Probably, multiplex parallel replicas for partial UNION as well; e.g.
UNION (SPLIT(A), SPLIT(B), C)->UNION(SPLIT(UNION(A, B)), C) - For partial union check for Aggregating on top. e.g.
Aggregating(UNION(SPLIT(UNION(A, B)), C))->MergeAggregated(UNION(SPLIT(AggregatingState(UNION(A, B))), AggregatingState(C))
…rrect in plan-based PR Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Put the row policy on the definer's own table so no user reads a table with foreign-only policies; the invoker branch's table stays policy-free. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
The flaky check runs the test concurrently; a global USER with a fixed name
collided (ACCESS_ENTITY_ALREADY_EXISTS). Name it user_${CLICKHOUSE_DATABASE}.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
The user + DEFINER view is incompatible with the multi-node Replicated test database (the non-replicated user is absent on some nodes, so the view's DDL does not resolve). Also run everything in one client session for consistency. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
FINAL is incompatible with parallel-replica reading; classic parallel replicas disables PR for a query with FINAL. Do the same in the plan-based pass instead of distributing the FINAL read, which aborted (fuzzer added FINAL to a union branch). Left a TODO for granular per-read handling. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lan-based-analysis
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 133/140 (95.00%) · Uncovered code |
04606 asserts that a shard of a `Distributed` table which merges the partially
aggregated results of its parallel replicas hands the initiator the two-level
buckets in ascending bucket id order, so the initiator's memory-efficient merge
does not merge and output the same bucket twice. It measures that as
`count() - uniqExact(x)` over 200000 groups, which has to be `0`.
Upstream computes the aggregation in a subquery. On this branch the same query
kills the server before it reaches the assertion:
Logical error: 'Chunk should have AggregatedChunkInfo in
MergingAggregatedTransform.' (MergingAggregatedTransform.cpp:239)
Logical error: 'Chunk should have AggregatedChunkInfo/ChunkInfoWithAllocatedBytes
in GroupingAggregatedTransform.' (MergingAggregatedMemoryEfficientTransform.cpp:369)
on run 1, against a pristine 26.7 tip with none of this branch applied. The
outer query consumes only `x`, so `sum(y)` is pruned from the shard-side
fragment and its header carries no aggregate state column.
`ReadFromParallelReplicas.cpp:197` hard-codes `add_agg_info = false`, and the
only other way that flag is set is the auto-detection in `RemoteSource`'s
constructor (`RemoteSource.cpp:29-33`), which looks for a
`DataTypeAggregateFunction` column in the header. So no `AggregatedChunkInfo` is
attached and the merge throws. Master fixed that in #111063
(`36966297cd1696a`), merged five days after this branch was cut.
The test is healthy upstream: 12348 runs and 0 failures on master over the last
30 days. It is this branch that cannot run the shape, not the test that is
flaky.
Upstream itself wrote the test this way first. `7a902aec5b1f6` introduced it
writing the result into a `Memory` table, with the comment "at the moment such a
query cannot be used as a subquery", and `bcd47d843620` converted it to a
subquery only once master had the fix: "it failed with `Chunk should have
AggregatedChunkInfo in MergingAggregatedTransform`. That is fixed in master,
which is merged here, so the query is a subquery again and the table is gone."
This commit reverts that one transformation and keeps the rest of it, including
the drop hygiene.
The coverage is unchanged. 200000 keys keep the buckets of the two-level result
being converted by a thread pool, which is what returns them in an arbitrary
order, and `enable_producing_buckets_out_of_order_in_aggregation = 0` keeps the
producer from reporting them as delayed. The reference stays `0`.
Co-Authored-By: Claude Opus 5 <[email protected]>
Part 2 of plan-based parallel replicas (follows #108504).
Under
parallel_replicas_plan_based, the planner now builds a plain, normal local plan everywhere — noParallelReplicasSplitStep, and noReadFromLocalReplica/ReadFromRemoteParallelReplicas, even for views and unions. Distribution is applied afterwards as a plan-level optimization:QueryPlanOptimizations::applyParallelReplicasinserts aParallelReplicasSplitStepabove every eligibleMergeTreeread, lifts the markers up through expression / filter / aggregation steps (combining sibling markers above aUnionStepso the whole union ships as one fragment), and rewrites them into aUNIONof a local read and a remote parallel-replicas read of the shipped fragment. The split step takes its context from theReadFromMergeTreeit sits above.As a result, queries over a view whose underlying query is a
UNIONare parallelized without enablingparallel_replicas_allow_view_over_mergetree— that flag is only relevant to the query-tree-level path, which plan-based mode no longer uses.Related: #108504
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Plan-based parallel replicas (
parallel_replicas_plan_based): the local/remote boundary is now chosen by a plan-level optimization over a normal query plan, and queries over views with aUNIONare parallelized withoutparallel_replicas_allow_view_over_mergetree.🤖 Generated with Claude Code