Skip to content

One parallel replicas implementation per query, and skip the query-tree analysis under plan-based - #127038

Merged
devcrafter merged 23 commits into
masterfrom
skip-query-tree-analysis-for-plan-based
Oct 31, 2026
Merged

devcrafter merged 23 commits into
masterfrom
skip-query-tree-analysis-for-plan-based

Conversation

@devcrafter

@devcrafter devcrafter commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Two related changes to who decides how a query reads with replicas.

One implementation per query. A subquery carries its own context, so its SETTINGS clause could
name the other implementation. The two split the work at different points, so a query mixing them does
not combine them - it loses parallel replicas for that subtree. With a query-based query and a
plan-based subquery, the subquery built a plain local read that the plan-based split never came to
distribute, because that split follows the query's own settings.

Such a query is now rejected with INCORRECT_QUERY: before the sets and the materialized CTEs are
planned, every subquery - a table expression, an IN set, a materialized CTE, a correlated subquery -
is checked against the implementation the query is planned with. The check applies only while the
query can read with parallel replicas (enable_parallel_replicas or automatic_parallel_replicas_mode)
and only on the initiator:

  • Without parallel replicas the setting has no effect, so a subquery or a view that sets it keeps
    working.
  • A follower reads the tasks the initiator hands out whatever its own value. That value can differ from
    the initiator's - the initiator ships only the settings it changed, so a follower's profile value
    wins - while the query it receives keeps a subquery's SETTINGS clause, so checking there would
    reject a query the initiator accepted.

The query-tree analysis is skipped under plan-based. findQueryForParallelReplicas answers which
query node the query-based implementation should execute with replicas, and clones the query tree with
dummy storages and builds a throwaway plan to do it. Plan-based picks the fragment while optimizing
the plan and has no use for the answer, so it no longer runs.

03215_analyzer_replace_with_dummy_tables is pinned to the query-based implementation: the walk over
an unresolved subtree that it guards is part of that analysis, and the CLUSTER_DOESNT_EXIST it
expects is the error the walk has to reach.

05433_pr_plan_based_subquery_with_other_mode checks that a subquery repeating the query's
implementation keeps its read step and the aggregation where the data is read, that a mixed query is
rejected (subquery in FROM, IN set, automatic mode), that it runs without parallel replicas, and
that setting the implementation for the whole query reaches its subqueries.

Related: #112351

Changelog category (leave one):

  • Improvement

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

A query that reads with parallel replicas now uses one implementation throughout: a subquery whose
SETTINGS set parallel_replicas_plan_based differently from the query is rejected, instead of
silently reading that subquery without parallel replicas.

🤖 Generated with Claude Code


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

Version info

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

`findQueryForParallelReplicas` clones the query tree with dummy tables and
builds a throwaway plan, whose only reader ignores it when
`parallel_replicas_plan_based` is set.

`03215_analyzer_replace_with_dummy_tables` gets rows and a zero per-replica row
threshold, so parallel replicas is planned and the expected cluster error is
raised on both implementations.

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

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a9bcaf3]

Summary: ✅


AI Review

Summary

The PR rejects mixed parallel-replica implementations within a query and skips redundant query-tree analysis for plan-based execution. The distributed-insert fix handles explicit subqueries, but the existing finding remains applicable to settings introduced by inlined views.

Findings

⚠️ Majors

  • [P2] Preserve the forced implementation when expanding views — src/Interpreters/InterpreterInsertQuery.cpp:898. This is a remaining case of the existing distributed-insert finding. removeSettingsFromQuery only visits the submitted AST. Later, QueryAnalyzer::inlineViewSubqueryIfNeeded loads a view's stored AST and applies its settings, restoring parallel_replicas_plan_based = 1 beneath the insert context forced to 0. The new validator then throws INCORRECT_QUERY before remote execution, although the user consistently selected implementation 1 and the setting is documented as having no effect on this insert path.

    With the table and replica settings from 05433, this reproduces the failure:

    CREATE VIEW v_05433 SQL SECURITY INVOKER AS
        SELECT x, y FROM t_05433
        SETTINGS parallel_replicas_plan_based = 1;
    CREATE TABLE dst_05433 (x UInt64) ENGINE = Memory;
    
    EXPLAIN PIPELINE
    INSERT INTO dst_05433
    SELECT x FROM t_05433
    WHERE x IN (SELECT x FROM v_05433 WHERE y < 5)
    SETTINGS analyzer_inline_views = 1,
             parallel_replicas_plan_based = 1,
             parallel_distributed_insert_select = 2;

    Ensure the forced query-based mode also applies to contexts created from stored view definitions before validation. Add this view case to the distributed-insert regression coverage.

Missing context / blind spots
  • ⚠️ Runtime probes used the PR's earlier CI binary at 1a55f117ea48dff50929a0e66cc359b1251d16ff; a binary for current head a9bcaf3ccade600b54dfc03f30ab03db372f5abb was unavailable. Current-source tracing confirms the remaining gap: the latest change strips explicit nested AST settings, while this reproduction introduces the setting from view metadata afterward. Running the focused regression on the current head would close the runtime-validation gap.
Final Verdict

Status: ⚠️ Request changes. Complete forced-mode normalization for inlined views and add the focused regression test. Earlier resolved findings and the author's intentional eligibility policy do not require further changes.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 20, 2026
@devcrafter devcrafter added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-performance Pull request with some performance improvements labels Oct 20, 2026
It is unrelated to skipping the analysis: the expected error is raised either
way, before and after.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Oct 20, 2026
The walk this test guards is part of the analysis skipped here, so plan-based
has nothing to cover in it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
devcrafter added a commit that referenced this pull request Oct 20, 2026
It moved to #127038, which skips
the analysis the test covers.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter
devcrafter requested review from nickitat and a balanced review from Copilot October 20, 2026 22:23

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.

🟡 Changes recommended

Nested query-based subqueries can still need the skipped analysis, causing aggregation pushdown to be lost in mixed-setting queries.

1 open issue
What changed in this PR

Avoids unused query-tree analysis when planning parallel replicas through the query plan.

Changes:

  • Adds an early return for plan-based parallel replicas.
  • Pins the existing dummy-table regression test to query-based execution and explains why.
File Description
tests/​queries/​0_stateless/​03215_analyzer_replace_with_dummy_tables.sql Pins regression coverage to query-based execution.
src/​Planner/​findParallelReplicasQuery.cpp Skips candidate analysis in plan-based mode.

Review effort: Balanced

Comment on lines +495 to +496
if (context->getSettingsRef()[Setting::parallel_replicas_plan_based])
return nullptr;

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.

Checked this against a server built from the branch, and the plan does not change. For

SELECT sum(c) FROM (SELECT y, count() AS c FROM t GROUP BY y SETTINGS parallel_replicas_plan_based = 0)
SETTINGS parallel_replicas_plan_based = 1, parallel_replicas_local_plan = 0, ...

both master and this branch produce

Aggregating
└──MergingAggregated (memory-efficient)
   └──ReadFromRemoteParallelReplicas

so the grouped subquery is still selected and partial aggregates are still shipped - the subquery's
own planner runs the analysis for itself, with its own settings, rather than reading the root's
answer. Added 05433_pr_plan_based_subquery_with_other_mode for this shape: it asserts the result
and that the plan merges partial aggregates above a parallel replicas read, so a future change that
did move the aggregation onto the initiator would fail it.

Worth noting separately that mixing the two implementations within one query is not something we want
to support - one query should execute with one of them - so the intended direction is for the outer
setting to win, not for a subquery to opt back into the query-based path.

devcrafter and others added 2 commits October 21, 2026 11:55
Skipping the query-tree analysis must not leave such a subquery aggregating on
the initiator over rows read from replicas.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A subquery naming the other one in its own `SETTINGS` used to split a query
across both, and with a query-based outer query and a plan-based subquery it
lost parallel replicas entirely. `parallelReplicasArePlanBased` answers from the
query context for every planner.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter devcrafter changed the title Skip the query-tree parallel replicas analysis under plan-based parallel replicas One parallel replicas implementation per query, and skip the query-tree analysis under plan-based Oct 21, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Oct 21, 2026
@devcrafter devcrafter changed the title One parallel replicas implementation per query, and skip the query-tree analysis under plan-based Skip the query-tree parallel replicas analysis under plan-based parallel replicas Oct 21, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-improvement Pull request with some product improvements labels Oct 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a9bcaf3cc with master ca9786f6b (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.

Object file sizes

7 object files changed (+21.82 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/PlannerJoinTree.cpp.o 891.41 KiB 910.53 KiB +19.12 KiB (+2.15%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

10 translation units recompiled, 64 s compile time in total, 10 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.2 s (+5%) in total before that adjustment.

Job report

A subquery naming the other one in its own `SETTINGS` split a query across both,
and with a query-based query and a plan-based subquery it lost parallel
replicas entirely. The subquery is given the implementation the query is
planned with, next to where parallel replicas itself is propagated.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter devcrafter changed the title Skip the query-tree parallel replicas analysis under plan-based parallel replicas One parallel replicas implementation per query, and skip the query-tree analysis under plan-based Oct 21, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Oct 21, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
devcrafter and others added 3 commits October 24, 2026 21:32
…lysis-for-plan-based

# Conflicts:
#	tests/queries/0_stateless/03215_analyzer_replace_with_dummy_tables.sql
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Planner/Planner.cpp

/// Before the sets and the materialized CTEs are collected: they are planned by their own planners,
/// from the context each subquery carries.
checkParallelReplicasImplementationOfSubqueries(query_tree, query_context);

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.

[P2] Apply the multi-table opt-out before validating the mode

parallel_replicas_for_queries_with_multiple_tables = 0 promises that joined queries execute without parallel replicas, including when enable_parallel_replicas = 2. This call runs before disableParallelReplicasForMultipleTablesQueryIfNeeded, so the new validator still sees parallel replicas enabled and rejects a differing subquery mode before the opt-out can disable them.

For example:

SELECT a.x
FROM (SELECT 1 AS x SETTINGS parallel_replicas_plan_based = 1) AS a
CROSS JOIN numbers(1) AS b
SETTINGS enable_parallel_replicas = 2,
         automatic_parallel_replicas_mode = 0,
         max_parallel_replicas = 2,
         parallel_replicas_plan_based = 0,
         parallel_replicas_for_queries_with_multiple_tables = 0;

This should run locally and return 1, but the new check throws INCORRECT_QUERY. Apply the multi-table opt-out before this validation, while keeping validation ahead of the independent subquery planners, and add a focused stateless regression case.

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.

This is intended. A query whose subqueries name different parallel_replicas_plan_based values is rejected regardless of whether parallel replicas end up being used: the two implementations disable parallelization for different queries (and some settings are not effective for the plan-based one), so whether a given opt-out applies is itself implementation-dependent. Validating before those opt-outs keeps the rule simple and the same for both implementations: one query, one implementation.

Comment thread src/Planner/PlannerJoinTree.cpp Outdated
Comment on lines +1842 to +1843
if (!settings[Setting::allow_experimental_parallel_reading_from_replicas] && !settings[Setting::automatic_parallel_replicas_mode])
return;

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.

[P2] Skip mode validation when replica eligibility rules disable execution

The guard tests only the enable switches, so it rejects a mixed setting even when neither implementation can run. With the fixture from 05433, this query should execute locally and return 200000:

SELECT sum(c)
FROM (SELECT y, count() AS c FROM t_05433 GROUP BY y
      SETTINGS parallel_replicas_plan_based = 1)
SETTINGS enable_parallel_replicas = 1,
         automatic_parallel_replicas_mode = 0,
         max_parallel_replicas = 1,
         parallel_replicas_prefer_local_replica = 1,
         parallel_replicas_plan_based = 0;

Context::canUseTaskBasedParallelReplicasImpl returns false for both contexts because the replica limit is one and local preference is enabled; consequently both query-based planning and plan-based distribution are disabled. This new check nevertheless throws INCORRECT_QUERY, breaking queries whose subquery setting is inert. Base validation on effective task-based eligibility (while retaining support for automatic selection), and add a regression case for this local-execution configuration.

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.

Same as #127038 (comment): this is intended. Whether parallel replicas can effectively run (max_parallel_replicas, parallel_replicas_prefer_local_replica, parallel_replicas_mode) is decided differently by the two implementations, so the check does not depend on it. The only exception is the explicit switch: with parallel replicas disabled by enable_parallel_replicas / automatic_parallel_replicas_mode, the setting has no meaning and the query runs.

…mentation

Each arm is planned by its own planner from its own context, so the check
in `buildPlanForQueryNode` never compared an arm with the union's setting.

Related: #127038 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@devcrafter

Copy link
Copy Markdown
Member Author

@nickitat done in bd29a4a: a subquery setting a different parallel_replicas_plan_based now throws INCORRECT_QUERY.

@devcrafter
devcrafter requested a review from nickitat October 26, 2026 16:06
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@devcrafter
devcrafter requested a review from groeneai October 26, 2026 16:14

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I built the head (e4e1ae3b) and the same tree with the four src/Planner files reverted to the merge base, and ran both with the 05433 setup. 05433 fails on the base for the right reason (the mixed queries succeed) and passes on the head. 03215 passes on both.

Both points below come from the check reading only the query's own switches.

  1. A subquery that opts out is now rejected. With replicas on and the query-based implementation, SELECT count() FROM t_05433 WHERE x IN (SELECT x FROM t_05433 WHERE y < 5 SETTINGS enable_parallel_replicas = 0, parallel_replicas_plan_based = 1) throws INCORRECT_QUERY on the head. On the base it returns 1000 with ParallelReplicasUsedCount = 1: the outer read uses replicas and the set is read locally, as requested. A join and a FROM subquery that opt out the same way are rejected too, and so is the opposite direction. All of them run on the base. That subtree does not read with replicas, so under the rule the PR already applies to the query's own switch, its setting has no effect. The inline suggestion skips such contexts. With it, 05433 still passes, the mixed queries are still rejected, and a grandchild that turns replicas back on under a disabled subquery is still rejected too.

  2. On r4379584103: the bypass is real, and the base behaves the same (ParallelReplicasUsedCount = 0). But mixing implementations is not the cause. Take a subquery with enable_parallel_replicas = 2, parallel_replicas_plan_based = 1 under a query with replicas off. It reads locally even when the query's own parallel_replicas_plan_based is also 1. I measured this for a FROM subquery, an IN set and a UNION ALL arm. The query-based equivalent does read with replicas (1/1). So comparing nested switches and implementations, as suggested there, would reject only one of these shapes. Under plan-based, a subquery cannot turn replicas on. I think this case either needs its own rejection, or it can stay out of this PR, since the PR does not cause it.

Comment thread src/Planner/PlannerJoinTree.cpp Outdated
const bool plan_based = settings[Setting::parallel_replicas_plan_based];
auto check = [plan_based](const ContextPtr & context)
{
if (context->getSettingsRef()[Setting::parallel_replicas_plan_based] != plan_based)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A subquery with both switches off reads without replicas whatever this setting says, so it does not have to match (point 1 of the review).

Suggested change
if (context->getSettingsRef()[Setting::parallel_replicas_plan_based] != plan_based)
const auto & subquery_settings = context->getSettingsRef();
if (!subquery_settings[Setting::allow_experimental_parallel_reading_from_replicas] && !subquery_settings[Setting::automatic_parallel_replicas_mode])
return;
if (subquery_settings[Setting::parallel_replicas_plan_based] != plan_based)

Comment thread src/Planner/PlannerJoinTree.cpp Outdated
const bool plan_based = settings[Setting::parallel_replicas_plan_based];
auto check = [plan_based](const ContextPtr & context)
{
if (context->getSettingsRef()[Setting::parallel_replicas_plan_based] != plan_based)

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.

[P2] Honor the forced implementation for distributed inserts

With parallel_distributed_insert_select = 2, InterpreterInsertQuery::buildInsertSelectPipelineParallelReplicas pins parallel_replicas_plan_based to false and removes its top-level SETTINGS assignment, while preserving nested assignments. This check consequently rejects a query whose user settings consistently select implementation 1 throughout.

Using the replica setup from 05433, the PR's CI binary reproduces this before any remote execution:

CREATE TABLE dst (x UInt64) ENGINE = Memory;
EXPLAIN PIPELINE
INSERT INTO dst
SELECT x FROM t_05433
WHERE x IN
    (SELECT x FROM t_05433 WHERE y < 5
     SETTINGS parallel_replicas_plan_based = 1)
SETTINGS parallel_replicas_plan_based = 1,
         parallel_distributed_insert_select = 2;

It throws INCORRECT_QUERY, reporting child true versus query false. Setting both implementations to 0, or omitting the nested assignment, produces the distributed insert pipeline. This contradicts the setting's documented behavior that it has no effect on this insert path. Normalize the forced implementation across nested contexts on that path before validating, and cover this consistent-setting insert with a regression test.

groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 27, 2026
Since it runs in the parallel pool, the remote part of its killed `SELECT`
keeps sleeping and the hung check reports `Some queries hung`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127038&sha=9f841c9ae9a312abac66b6136e939dc248c3a7a3&name_0=PR
PR: ClickHouse#127038
Related: ClickHouse#127149

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
devcrafter and others added 6 commits October 28, 2026 22:35
Its `parallel_replicas_plan_based` has no effect. Also shorten the comments.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…n-based' into skip-query-tree-analysis-for-plan-based
…d `INSERT SELECT`

The path is query-based, so a subquery keeping the setting was rejected as plan-based.

Related: #127038 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@devcrafter
devcrafter added this pull request to the merge queue Oct 31, 2026
@devcrafter
devcrafter requested a review from groeneai October 31, 2026 21:24

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I re-ran my probes on the CI amd_debug binary of a9bcaf3c, and on the one of 1a55f117 (before 56ba3097f6) for the insert path.

  • A subquery that opts out (enable_parallel_replicas = 0 with the other parallel_replicas_plan_based) now runs in both directions, as an IN set, a JOIN and a FROM subquery. For IN and JOIN the outer read still uses replicas (ParallelReplicasUsedCount = 1).
  • Plain mixing is still rejected, and so is a grandchild that re-enables the other implementation under a disabled subquery. 05433 passes locally (3/3).
  • The distributed INSERT SELECT from r4385841383 throws INCORRECT_QUERY on 1a55f117, and on the head it is shipped to all three replicas (two plus the local plan with parallel_replicas_local_plan = 1) and writes the expected 1000 rows. That holds with the query and the IN subquery on different values too, and when the subquery reads a view whose definition sets either value.

LGTM.

Merged via the queue into master with commit 223e394 Oct 31, 2026
180 checks passed
@devcrafter
devcrafter deleted the skip-query-tree-analysis-for-plan-based branch October 31, 2026 21:52
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). 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.

5 participants