Skip to content

Plan based parallel replicas. Part 1 (aggregation) - #108504

Merged
devcrafter merged 56 commits into
masterfrom
parallel-replicas-exchange-plan
Jul 17, 2026
Merged

devcrafter merged 56 commits into
masterfrom
parallel-replicas-exchange-plan

Conversation

@devcrafter

@devcrafter devcrafter commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Add experimental plan-based parallel replicas execution for MergeTree queries.

devcrafter and others added 3 commits June 25, 2026 00:34
Add experimental setting `parallel_replicas_exchange_plan`. When enabled, the
planner builds a plain local plan (PR construction in `PlannerJoinTree` is
skipped) and a post-build phase `ClusterProxy::applyParallelReplicasSplit`
replaces the `ReadFromMergeTree` with a `UNION` of a local read and a remote
read of the fragment (`ReadFromParallelRemoteReplicasStep`), sharing one
`ParallelReplicasReadingCoordinator`. Applicability is decided on the plan.

Results are correct and `EXPLAIN` shows the union; remote-replica range
coordination for the shipped fragment is not wired yet (WIP).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pped fragments coordinate ranges

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a1d198]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID: 2678-3c21) FAIL cidb

AI Review

Summary

This PR introduces experimental plan-based parallel replicas by inserting a split marker into the query plan and lowering it into local and remote fragment execution. The core idea is reasonable, but the current implementation still drops several correctness and safety invariants from the existing task-based path: the aggregation rewrite is not gated for all supported modes, and the new remote step no longer preserves replica freshness checks, initiator read limits, or query scalars. I would block merge until those gaps are fixed or explicitly rejected.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp:68-106] The aggregation rewrite always lowers AggregatingStep below the split and merges states above it, but it does not keep the safety gates from tryMakeDistributedAggregation. Queries that use max_rows_to_group_by, aggregation-in-order (inOrder / explicitSortingRequired), or grouping sets cannot preserve the original global semantics once each replica aggregates independently and the coordinator only merges states. Suggested fix: reuse the same gate conditions as tryMakeDistributedAggregation and leave aggregation above the split for unsupported modes.
  • [src/Processors/QueryPlan/ReadFromParallelReplicas.cpp:205-219] The new plan-based remote step never calls setMainTable(storage_id). That skips getTablesStatus, so max_replica_delay_for_distributed_queries, missing-table checks, and read-only-table filtering are bypassed for plan-based parallel replicas. A lagging replica can still be selected and read a different part set than the coordinator/local branch. Suggested fix: carry StorageID into ReadFromParallelReplicasStep and call remote_query_executor->setMainTable(storage_id) before building the pipe.
  • [src/Processors/QueryPlan/ReadFromParallelReplicas.cpp:210-212] The remote executor is built with Scalars{} instead of the initiator's query scalars. Any fragment that moves an ExpressionStep below the split and relies on __getScalar, shardNum, or shardCount can now throw Scalar ... not found or evaluate with zeroed shard metadata on every replica. Suggested fix: thread the initiator scalars through ReadFromParallelReplicasStep the same way ReadFromParallelRemoteReplicasStep does.
  • [src/Processors/QueryPlan/ReadFromParallelReplicas.cpp:120-123] The new step comments out processor->setStorageLimits(storage_limits) and never stores storage_limits at all. Plan-based parallel replicas can therefore read past the initiator-side max_rows_to_read / max_bytes_to_read limits as long as each replica stays under its own leaf limit. Suggested fix: keep a storage_limits member in ReadFromParallelReplicasStep and apply it to every remote source before pipeline.init.

⚠️ Majors

  • [src/Core/Settings.cpp:7764-7765] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108504#discussion_r3475605777] parallel_replicas_plan_based always ships a QueryPlan packet, but the setting text never says that every server must also enable <process_query_plan_packet>true</process_query_plan_packet>. With the default server config, turning the feature on just fails at runtime with Reading of QueryPlan packet is disabled, and the error text still tells users to disable serialize_query_plan even when that setting is 0. I still consider this real because the feature contract currently omits a mandatory cluster-wide prerequisite.
  • [src/Processors/QueryPlan/ParallelReplicasLocalPlan.cpp:346-347] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108504#discussion_r3532471524] The local fragment path still throws away the cloned ReadFromMergeTree analysis and rebuilds parallel reading from nullptr, even though the cloned step already carries an analyzed_result_ptr. That changes the snapshot/range-selection point from the initiator's analyzed plan to execution time, so plan-based mode can observe a later part set than the task-based path under concurrent inserts or merges. I still consider this real because createLocalParallelReplicasReadingStep explicitly uses analyzed_result_ptr to preserve the analyzed ranges, and the plan-based helper is the only path that discards it.
Final Verdict

Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 25, 2026
const bool original_step_was_final
= aggregating_step->getFinal(); /// Save whether the original AggregatingStep was final or partial

/// Convert Aggregation step to partial aggregation

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 rewrites every AggregatingStep above the split into partial aggregation below the split plus MergingAggregatedStep, but it does not carry the safety gates that make that rewrite semantics-preserving. Modes such as max_rows_to_group_by with group_by_overflow_mode = 'any', aggregation-in-order (inOrder / explicitSortingRequired), and grouping sets cannot simply be applied independently on each replica and then merged as if the coordinator had seen one global stream. Once the split is lowered, replicas can apply overflow/order logic locally and the merge can return different keys or ordering than the non-parallel query. Please either reject/skip this rewrite for unsupported aggregation modes, at least matching the guards in tryMakeDistributedAggregation, or leave the aggregation above the split.

devcrafter and others added 10 commits July 3, 2026 23:15
…lly catch N x duplication

Wrap the correctness queries with SYSTEM ENABLE/DISABLE FAILPOINT
slowdown_parallel_replicas_local_plan_read so the remote replicas emit rows before the
local read completes, turning the previously flaky "each replica reads everything" bug
into a deterministic failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
connection_pool_with_failover,
query_plan);

remote_query_executor->setLogger(log);

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.

❌ The old parallel-replicas remote step immediately calls setMainTable(storage_id) here; this new path never does. Without a main_table, ConnectionEstablisher skips getTablesStatus, so max_replica_delay_for_distributed_queries and missing/read-only table checks are bypassed for plan-based parallel replicas. A lagging replica can still be picked and read an older part set than the coordinator/local branch. Please carry StorageID into this step and call remote_query_executor->setMainTable(storage_id) before building the pipe.

// for (const auto & processor : pipe.getProcessors())
// processor->setStorageLimits(storage_limits);

pipeline.init(std::move(pipe));

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 new source no longer propagates storage_limits to its RemoteSources. The existing ReadFromParallelRemoteReplicasStep::initializePipeline path calls processor->setStorageLimits(storage_limits) for every remote pipe, and RemoteSource::setStorageLimits is what preserves the initiator-side max_rows_to_read / max_bytes_to_read checks while stripping leaf-only limits. Dropping that wiring means plan-based parallel replicas can read past the query's global read limits as long as each replica stays under its own leaf limit. Please thread storage_limits through ReadFromParallelReplicasStep and set them on the created processors before pipeline.init.

Plan-based parallel replicas requires the analyzer, so under the old-analyzer CI
config the split/remote read do not engage and the EXPLAIN checks fail. Force the
analyzer in the tests so they are deterministic in every config.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108504&sha=7ae799f7c6a6d4f16ac05617039d076db4ce7e0a&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%202%2F3%29
PR: #108504

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@devcrafter
devcrafter enabled auto-merge July 16, 2026 12:10
@devcrafter

devcrafter commented Jul 16, 2026 •

Copy link
Copy Markdown
Member Author

@clickhouse-gh The comments you have are valid, but they will be addressed separately. This PR introduces only the first part of the experimental feature. The fixes will land with consequent pull requests.

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

Adds an experimental “plan-based” parallel replicas execution mode for MergeTree queries, where the planner produces a normal local plan and a later optimization phase inserts/moves a split marker and replaces it with a local+remote execution plan (including shipping a serialized plan fragment to replicas).

Changes:

  • Introduces ParallelReplicasSplitStep and a new optimization (applyParallelReplicas) that transforms plans into local+remote parallel-replicas execution (including aggregation handling).
  • Adds a new distributed read step (ReadFromParallelReplicasStep) and extends query-plan serialization to support parallel-replicas reads and safe “skip/drain” deserialization.
  • Adds multiple stateless regression tests covering remote-only mode, UNION ALL/view branching fragments, constant folding consistency across replicas, and split header correctness.

Reviewed changes

Copilot reviewed 40 out of 40 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04546_pr_plan_based_remote_only.sql Regression test for remote-only plan-based parallel replicas execution.
tests/queries/0_stateless/04546_pr_plan_based_remote_only.reference Expected output for remote-only regression test.
tests/queries/0_stateless/04545_pr_view_union_local_reads.sql Regression test for coordinating all UNION ALL branches in local fragment builder.
tests/queries/0_stateless/04545_pr_view_union_local_reads.reference Expected output for UNION-local-reads regression test.
tests/queries/0_stateless/04538_pr_plan_based_constants.sql Ensures query-level constants are consistent across replicas via shipped plan fragment.
tests/queries/0_stateless/04538_pr_plan_based_constants.reference Expected output for constants regression test.
tests/queries/0_stateless/04511_pr_view_union_all.sql Regression test for shipping branching fragments (UNION ALL) and required cloning support.
tests/queries/0_stateless/04511_pr_view_union_all.reference Expected output for branching-fragment regression test.
tests/queries/0_stateless/04507_pr_plan_based_split_header.sql Regression test for split-step header updates when pushed above header-changing steps.
tests/queries/0_stateless/04507_pr_plan_based_split_header.reference Expected output for split-header regression test.
tests/queries/0_stateless/04409_pr_plan_based.sql Base plan-based parallel replicas correctness + EXPLAIN shape assertions.
tests/queries/0_stateless/04409_pr_plan_based.reference Expected output for base plan-based test.
src/Server/TCPHandler.cpp Adds “skip/drain” query plan deserialization path to avoid building runnable plans when skipping/unexpected.
src/QueryPipeline/RemoteQueryExecutor.h Exposes getThrottler for reuse.
src/QueryPipeline/RemoteQueryExecutor.cpp Adds getThrottler and gates parallel-replicas usage on query-plan serialization version support.
src/Processors/QueryPlan/Serialization.h Adds skipping flag to step deserialization context.
src/Processors/QueryPlan/Serialization.cpp Plumbs skip_data through query-plan deserialization into step deserialization context.
src/Processors/QueryPlan/ReadFromParallelReplicas.h New plan step to execute a shipped plan fragment across parallel replicas.
src/Processors/QueryPlan/ReadFromParallelReplicas.cpp Implements remote-parallel-replicas read via RemoteQueryExecutor and coordinator callbacks.
src/Processors/QueryPlan/ReadFromMergeTree.h Adds a serialization-only marker to encode “parallel replicas read” intent into shipped plans.
src/Processors/QueryPlan/ReadFromMergeTree.cpp Serializes parallel-replicas flag; supports lightweight placeholder on skip/drain; rebuilds reads in parallel mode on replicas.
src/Processors/QueryPlan/QueryPlanVisitor.h Adjusts logging include/behavior for visitor debug logging.
src/Processors/QueryPlan/QueryPlan.h Extends deserialize with skip_data; adds cloneSubtree for branching fragments.
src/Processors/QueryPlan/QueryPlan.cpp Implements cloneSubtree using structural cloning.
src/Processors/QueryPlan/ParallelReplicasSplitStep.h New marker step to represent local/remote split boundary in query plans.
src/Processors/QueryPlan/ParallelReplicasSplitStep.cpp Implements pass-through behavior when executed without transformation.
src/Processors/QueryPlan/ParallelReplicasLocalPlan.h Adds helpers to build local/remote plan fragments from a shipped fragment.
src/Processors/QueryPlan/ParallelReplicasLocalPlan.cpp Implements fragment-specific local/remote plan construction and correct read collection under UNION roots.
src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h Adds enable_parallel_replicas optimization flag.
src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp Enables parallel replicas optimization only when initiator-capable + plan-based setting is on.
src/Processors/QueryPlan/Optimizations/optimizeTree.cpp Invokes applyParallelReplicas during second pass; disables it in certain subplans.
src/Processors/QueryPlan/Optimizations/applyParallelReplicas.cpp New optimization: moves split marker upward; rewrites aggregation; converts split into distributed plan.
src/Planner/PlannerJoinTree.cpp Adds plan-based split marker insertion path in planner (instead of old PR plan construction).
src/Planner/Planner.cpp Adds includes/setting plumbing related to plan-based mode.
src/Interpreters/ClusterProxy/executeQuery.h Declares createParallelReplicasPlan for plan-fragment → PR execution plan conversion.
src/Interpreters/ClusterProxy/executeQuery.cpp Implements createParallelReplicasPlan (local+remote union or remote-only), and refactors throttler helper usage.
src/Core/SettingsChangesHistory.cpp Registers new setting in settings history.
src/Core/Settings.cpp Introduces parallel_replicas_plan_based setting definition and description.
src/Core/ProtocolDefines.h Bumps query-plan serialization version and defines minimum version for PR-flag support.
src/Client/Connection.h Exposes server query-plan serialization version on connections.

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.00% 86.00% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 402/422 (95.26%) · Uncovered code

Full report · Diff report

@devcrafter
devcrafter added this pull request to the merge queue Jul 17, 2026
Merged via the queue into master with commit 7348f2f Jul 17, 2026
176 of 178 checks passed
@devcrafter
devcrafter deleted the parallel-replicas-exchange-plan branch July 17, 2026 08:05
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Plan-based parallel replicas requires the analyzer, so under the old-analyzer CI
config the split/remote read do not engage and the EXPLAIN checks fail. Force the
analyzer in the tests so they are deterministic in every config.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108504&sha=7ae799f7c6a6d4f16ac05617039d076db4ce7e0a&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%202%2F3%29
PR: ClickHouse#108504

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…s-exchange-plan

Plan based parallel replicas. Part 1 (aggregation)
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.

5 participants