Skip to content

Plan based parallel replicas. Part 2 - #111063

Merged
devcrafter merged 26 commits into
masterfrom
parallel-replicas-plan-based-analysis
Jul 27, 2026
Merged

devcrafter merged 26 commits into
masterfrom
parallel-replicas-plan-based-analysis

Conversation

@devcrafter

Copy link
Copy Markdown
Member

Part 2 of plan-based parallel replicas (follows #108504).

Under parallel_replicas_plan_based, the planner now builds a plain, normal local plan everywhere — no ParallelReplicasSplitStep, and no ReadFromLocalReplica / ReadFromRemoteParallelReplicas, even for views and unions. Distribution is applied afterwards as a plan-level optimization: QueryPlanOptimizations::applyParallelReplicas inserts a ParallelReplicasSplitStep above every eligible MergeTree read, lifts the markers up through expression / filter / aggregation steps (combining sibling markers above a UnionStep so the whole union ships as one fragment), and rewrites them into a UNION of a local read and a remote parallel-replicas read of the shipped fragment. The split step takes its context from the ReadFromMergeTree it sits above.

As a result, queries over a view whose underlying query is a UNION are parallelized without enabling parallel_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):

  • Experimental Feature

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 a UNION are parallelized without parallel_replicas_allow_view_over_mergetree.

🤖 Generated with Claude Code

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [194871b]

Summary: ✅


AI Review

Summary

This PR moves parallel_replicas_plan_based onto a post-planning optimization pass and fixes the earlier union/local-fragment issues well enough that I did not find a second new problem to add. One important contract drift still remains, though: after wrapper storages have already expanded away, the new collector no longer preserves the explicit parallel_replicas_allow_materialized_views opt-out, so plan-based mode still parallelizes regular materialized views even when the query disables them.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:243-256 collectReadsToDistribute now treats any wrapper-expanded ReadFromMergeTree as eligible as long as the target is replicated (or parallel_replicas_for_non_replicated_merge_tree is on). That bypasses the existing parallel_replicas_allow_materialized_views gate from parallelReplicasEnabledForStorage in src/Planner/PlannerJoinTree.cpp:1329-1337, so SELECT ... FROM mv SETTINGS parallel_replicas_plan_based = 1, parallel_replicas_allow_materialized_views = 0 still ships the target-table read. The new 04617 test comments also describe that target-only behavior, which means the regression is now codified instead of prevented. Suggested fix: carry the original storage eligibility/materialized-view origin into the plan-based pass and reject wrapper-expanded MV reads when that setting is off, instead of re-deriving eligibility only from ReadFromMergeTree.
Final Verdict

Needs changes before merge: the plan-based path still ignores the explicit materialized-view opt-out and changes a pre-existing setting contract.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 20, 2026
@devcrafter
devcrafter marked this pull request as draft July 20, 2026 18:13
devcrafter and others added 5 commits July 20, 2026 22:22
…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]>
…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]>

Copilot AI left a comment

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.

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 MergeTree reads and can lift/merge them through UNION/aggregation.
  • Fix distributed execution for shipped partial-aggregation fragments by ensuring remote chunks carry AggregatedChunkInfo when needed.
  • Add/adjust stateless query tests for root UNION ALL, view-expanded UNION ALL, same-table UNION ALL rejection, view predicate pushdown with force_* 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.

@devcrafter
devcrafter requested a review from Copilot July 22, 2026 12:41
@devcrafter
devcrafter marked this pull request as ready for review July 22, 2026 12:42

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 23 out of 23 changed files in this pull request and generated 2 comments.

devcrafter and others added 2 commits July 22, 2026 15:04
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)

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

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

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.

What we can do more

  1. Probably, multiplex parallel replicas for partial UNION as well; e.g. UNION (SPLIT(A), SPLIT(B), C) -> UNION(SPLIT(UNION(A, B)), C)
  2. 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))

devcrafter and others added 3 commits July 24, 2026 22:10
…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]>
devcrafter and others added 7 commits July 25, 2026 22:25
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]>
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]>
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]>
Comment thread src/Core/Settings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 133/140 (95.00%) · Uncovered code

Full report · Diff report

@devcrafter
devcrafter added this pull request to the merge queue Jul 27, 2026
Merged via the queue into master with commit 30e2edb Jul 27, 2026
178 checks passed
@devcrafter
devcrafter deleted the parallel-replicas-plan-based-analysis branch July 27, 2026 16:05
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
PedroTadim pushed a commit that referenced this pull request Sep 29, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature 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