Skip to content

Keep parallel replicas for cluster engines with AutoPR enabled - #122306

Merged
nickitat merged 20 commits into
masterfrom
autopr-keep-cluster-engines
Oct 14, 2026
Merged

nickitat merged 20 commits into
masterfrom
autopr-keep-cluster-engines

Conversation

@nickitat

@nickitat nickitat commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Parallel replicas are kept enabled for cluster engines when automatic_parallel_replicas_mode is set. Also, from now on, with enable_parallel_replicas = 2 parallel replicas are forced and the automatic mode is not applied.


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

Version info

  • Merged into: 26.10.1.2338-master (included in 26.10 and later)

nickitat and others added 2 commits September 25, 2026 15:11
…replicas_mode`

With `automatic_parallel_replicas_mode` set, `buildContext` forced
`enable_parallel_replicas = 0` for the whole query. The automatic mode only
decides for `MergeTree` reads, but the forced value also stopped cluster
engines (`s3`, `url`, tables of a data lake catalog such as an `Iceberg`
table in a `DataLakeCatalog` database) from being replaced by their cluster
alternative, so such a query silently ran on a single node.

`canUseTaskBasedParallelReplicas` is already false while the automatic mode
is on, so `MergeTree` reads do not need the forced value. Keep
`enable_parallel_replicas` as is and let cluster engines check it through
the new `canUseTaskBasedParallelReplicasForClusterEngines`, which ignores the
automatic mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`canUseTaskBasedParallelReplicasImpl` took whether parallel replicas are enabled as an argument
because an earlier version of the fix passed a different value for cluster engines. Both callers
now pass the same expression, so express `canUseTaskBasedParallelReplicas` through
`canUseTaskBasedParallelReplicasForClusterEngines` instead.

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

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0bc9f29]

Summary: ✅


AI Review

Summary

This PR fixes the main semantic bug: cluster engines now keep their cluster-variant fan-out when automatic_parallel_replicas_mode is enabled, and force mode (enable_parallel_replicas = 2) now correctly suppresses the automatic heuristic. The remaining problem is that one user-facing branch of the change is still untested, and one earlier parallel-replicas compatibility gap is still present for the AutoPR path with enable_parallel_replicas = 1, so I would keep this in changes requested until the coverage is tightened and that remaining contract decision is addressed.

Missing context / blind spots
  • ⚠️ I could not execute the new stateless tests locally because this checkout has no built clickhouse binary. Running tests/queries/0_stateless/05175_autopr_keep_cluster_engines.sh and tests/queries/0_stateless/05260_autopr_force_mode_wins.sql against a local build would close that gap.
Findings

⚠️ Majors

  • [tests/queries/0_stateless/05260_autopr_force_mode_wins.sql:1] The only regression test for the new “force mode wins” contract is tagged no-old-analyzer, but this PR changes that contract partly in the old-analyzer path in src/Interpreters/InterpreterSelectQuery.cpp:611. A future regression there would merge without any test failure. Split the force-mode assertions into an untagged test, or add an old-analyzer variant that covers enable_parallel_replicas = 2 with automatic_parallel_replicas_mode = 1 and 2.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/122306#discussion_r4112183619] [src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:149] The planner still decides parallel_replicas_allow_in_with_subquery = 0 too late for cluster-engine reads: with enable_parallel_replicas = 1, automatic_parallel_replicas_mode = 1, a url / s3 / data-lake read can already be resolved to its *Cluster storage before the planner clears allow_experimental_parallel_reading_from_replicas, so the query still ships its IN (subquery) to followers. This PR newly exposes that mode-0 behavior under AutoPR because buildContext now keeps enable_parallel_replicas live; the added test only covers the enable_parallel_replicas = 2 branch.
Final Verdict

⚠️ Changes requested — the core fix looks right, but the old-analyzer force-mode path needs direct coverage, and the remaining AutoPR IN (subquery) compatibility gap is still real.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0bc9f29a9 with master 360bb0de6 (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

97 object files changed (-66.80 KiB total), 0 added.

Object file Master PR Δ
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorage.cpp.o 2.60 MiB 2.58 MiB -29.50 KiB (-1.11%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionURL.cpp.o 252.20 KiB 234.04 KiB -18.16 KiB (-7.20%)
src/CMakeFiles/dbms.dir/Databases/DataLake/DatabaseDataLake.cpp.o 1.66 MiB 1.64 MiB -17.40 KiB (-1.02%)

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

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

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

Translation unit Master PR Δ vs median
src/Formats/FormatFactory.cpp 32.9 s 49.2 s +14.3 s (+41%)

Job report

With `automatic_parallel_replicas_mode = 2` drawn, `clickhouse-test` also sets `enable_parallel_replicas = 1` with
`cluster_for_parallel_replicas = 'parallel_replicas'`. Now that cluster engines follow `enable_parallel_replicas`
under the automatic mode, every `s3`/`url`/data lake read in such a run became a cluster read over that cluster,
which contains a deliberately unreachable replica. `ConnectionPoolWithFailover` logs a warning for each failed try,
and those warnings failed about 40 tests on "having stderror". The results were correct.

These runs are meant to exercise the automatic mode, which only covers `MergeTree` reads, so keep cluster engines
out of them with `parallel_replicas_for_cluster_engines = 0`. That is what they covered before. Cluster engines
with parallel replicas stay covered by the ParallelReplicas job, which does not use this adjustment.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122306&sha=latest&name_0=PR
PR: #122306

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nickitat and others added 2 commits September 25, 2026 23:32
…n every mode

Cluster engines now use parallel replicas regardless of `automatic_parallel_replicas_mode`, but two checks were still
gated by predicates that are false under it: the `parallel_replicas_allow_in_with_subquery` check in the planner
(`canUseTaskBasedParallelReplicas`) and `DisableParallelReplicasPass` (`canUseParallelReplicasOnInitiator`). So an
`IN` subquery over `url` in force mode threw `SUPPORT_IS_DISABLED` in mode 0 but ran as a cluster read in modes 1
and 2. Gate both on `canUseTaskBasedParallelReplicasForClusterEngines`, so they behave the same in every mode.

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

# Conflicts:
#	src/Planner/Planner.cpp
Comment thread src/Planner/Planner.cpp Resolved
A replica matches `additional_table_filters` by the table name or alias in the query it receives. A cluster engine
ships the query text with the table expression renamed (`__table1`), so the replica silently read unfiltered data:
`SELECT sum(n) FROM url(...) AS t` with `additional_table_filters = {'t': 'n > 1'}` returned 6 instead of 5.

The planner check for this combination runs after the cluster read has been chosen, so it never prevented it: in mode
0 with `enable_parallel_replicas = 1` the result was already wrong, and with this PR modes 1 and 2 were affected too.
`serialize_query_plan` does not help either, as cluster engines ship the query text, not the plan.

Do not replace a cluster engine with its `*Cluster` variant while `additional_table_filters` is set
(`canReplaceClusterEngineWithClusterVariant`), and gate the planner check on the cluster-engine predicate, so force mode
without `serialize_query_plan` throws `SUPPORT_IS_DISABLED` in every mode.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
nickitat and others added 4 commits September 26, 2026 13:50
…hipped cluster reads

The `IN` subquery and `additional_table_filters` checks in the planner were gated on
`canUseTaskBasedParallelReplicasForClusterEngines`, which only says that parallel replicas are enabled. So under
`automatic_parallel_replicas_mode` they threw in force mode even when nothing was shipped to the replicas: for a
`url` read with `parallel_replicas_for_cluster_engines = 0`, or for a `MergeTree` read the automatic mode keeps local.

Apply them to `MergeTree` reads as before (`canUseTaskBasedParallelReplicas`), and to a query that actually reads a
cluster engine in every mode (`readsFromClusterEngine`).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…elReplicasEnabled`

`enable_parallel_replicas` now stays on under `automatic_parallel_replicas_mode` for cluster engines, so code that read
the setting directly to ask "are parallel replicas enabled in any mode" started to see it on where it used to see it
off. `StorageDistributed::getClusterQueriedNodes` multiplied the number of nodes by `max_parallel_replicas`, so a
single-node `remote()` / `Distributed` query looked like a multi-node one: `01812_optimize_skip_unused_shards_single_node`
threw `UNABLE_TO_SKIP_UNUSED_SHARDS` and `05077_limit_after_plan_deserialize_type_complexity` took the multi-node path.

Add `Context::isParallelReplicasEnabled`, which treats `read_tasks` under the automatic mode as disabled (what the
setting used to mean there), and use it in `getClusterQueriedNodes`, the two trivial count paths, the propagation to
subqueries for `parallel_replicas_for_queries_with_multiple_tables` and the sampling-key path.

Also fold the conditions shared by the three cluster engine sites (`cluster_for_parallel_replicas`,
`parallel_replicas_for_cluster_engines`, not a distributed context) into `canReplaceClusterEngineWithClusterVariant`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122306&sha=latest&name_0=PR
PR: #122306

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A query with a `JOIN` never replaces a cluster engine by its `*Cluster` variant, so the `JOIN USING` key resolved
from an alias nested in the SELECT list is never shipped with it, in any `automatic_parallel_replicas_mode`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
…ueries

The propagation for `parallel_replicas_for_queries_with_multiple_tables = 0` asks whether the outer planner turned
parallel replicas off, which is the value of `enable_parallel_replicas`, not `isParallelReplicasEnabled`. The latter is
false under `automatic_parallel_replicas_mode` and made the block clear `enable_parallel_replicas` in the contexts of
subqueries for no reason. It did not change which storage a subquery reads, as storages are resolved before planning,
but it is the wrong question. Also cover cluster engine reads in a subquery and a CTE in 05175.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
nickitat and others added 4 commits September 27, 2026 12:01
The `IN` subquery and `additional_table_filters` checks applied to any query in mode 0 (`canUseTaskBasedParallelReplicas`
is true there whatever the query reads), but under `automatic_parallel_replicas_mode` only to a query reading a cluster
engine. So in force mode the same query threw `SUPPORT_IS_DISABLED` in mode 0 and was executed in modes 1 and 2. Gate
both checks on `canUseTaskBasedParallelReplicasForClusterEngines` alone, which keeps mode 0 as it is and makes modes 1
and 2 behave the same, and drop `readsFromClusterEngine`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`enable_parallel_replicas = 2` asks for parallel replicas and an exception when they cannot be used, while
`automatic_parallel_replicas_mode` asks a heuristic to decide. The automatic mode used to win, so forcing had no effect
on `MergeTree` reads. Now forcing wins: `Context::getAutomaticParallelReplicasMode` returns 0 when parallel replicas
are forced, and every reader of the mode goes through it (`canUseTaskBasedParallelReplicas`,
`isParallelReplicasEnabled`, the optimization settings deciding whether the automatic mode runs, and both analyzers).
It cannot be done only in `buildContext`, as a query's `SETTINGS` clause is re-applied to the contexts of its query nodes.

Under the automatic mode `enable_parallel_replicas` is therefore 1, and the planner checks and
`DisableParallelReplicasPass` only turn parallel replicas off, which changes nothing observable there. So they go back to
their original gates, and the behavior stays the same in every mode: forced, the checks throw in modes 0, 1 and 2 alike.

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

# Conflicts:
#	src/Databases/DataLake/DatabaseDataLake.cpp
The lookup is already scoped to the test database, which is unique per run; the time window follows
`02950_parallel_replicas_used_count` and also covers a manual run against a fixed database.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
bool canUseTaskBasedParallelReplicasForClusterEngines() const;
/// Whether a cluster engine (`s3`, `url`, a table of a data lake catalog, ...) may be replaced by its `*Cluster`
/// variant over `cluster_for_parallel_replicas`, which ships the query text to the replicas.
bool canReplaceClusterEngineWithClusterVariant() const;

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.

The name is arguably sub-optimal )

&& query_settings[Setting::parallel_replicas_for_cluster_engines]
&& context_->canUseTaskBasedParallelReplicas()
&& !context_->isDistributed();
const auto can_use_parallel_replicas = context_->canReplaceClusterEngineWithClusterVariant();

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.

The same check, but now it doesn't look at the autopr mode at all.

Comment on lines +9140 to +9142
/// A replica matches `additional_table_filters` by the table name or alias in the query it receives, and the shipped
/// query renames the table expression (`__table1`), so the replica would silently read unfiltered data.
/// `serialize_query_plan` does not help here: cluster engines ship the query text, not the plan.

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.

Filed as #122544

Comment thread src/Interpreters/Context.cpp Resolved
@nickitat
nickitat marked this pull request as ready for review September 29, 2026 14:23
@nickitat
nickitat requested a review from devcrafter September 29, 2026 14:23
@devcrafter devcrafter self-assigned this Sep 29, 2026
…-engines

# Conflicts:
#	src/Interpreters/InterpreterSelectQueryAnalyzer.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR changes how parallel replicas are switched on and off: forcing them with enable_parallel_replicas = 2 now overrides the automatic mode, and cluster engines get a new eligibility check. With default settings none of this runs on single-node ClickBench MergeTree queries, and the TPC-H benchmark flagged nothing. Q33 (-8.4%) and Q34 (-7.9%) fall inside master's normal range, have noisy histories and do not run the changed code, so both are downgraded to not sure. Q20 (-45.0%, with CPU time nearly halved) is too large to override and stays an improvement, but the diff does not explain it; check the PR's merge base for other changes before crediting this PR.

clickbench

🟢 1 improved · ⚠️ 2 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 222 122 -45.0% <0.0001 cpu: At -45.0% with CPU time nearly halved, this change is large enough that the verdict is locked. The diff only changes parallel-replicas gating, which a default single-node query does not reach, so treat the cause as unconfirmed.
⚠️ 33 not_sure 1127 1032 -8.4% <0.0001 cpu: At -8.4%, the PR median sits inside master's normal range and this query has a noisy history. The parallel-replicas gating changes do not touch a single-node read.
⚠️ 34 not_sure 1123 1034 -7.9% <0.0001 cpu: At -7.9%, the PR median is inside master's normal range and the history is noisy. This mirrors Q33, and nothing in the diff runs on this query's path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 09a12a82-db85-4a75-8a18-f7ccaeb95338
  • MIRAI run: 10a5f0e0-6d40-4b97-b1ef-a7cb618838ab
  • PR check IDs:
    • clickbench_45922_1791928355
    • clickbench_46072_1791928364
    • clickbench_46181_1791928371
    • tpch_adapted_1_official_46306_1791928390
    • tpch_adapted_1_official_46443_1791928423
    • tpch_adapted_1_official_46550_1791928430

…-engines

# Conflicts:
#	tests/clickhouse-test

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.

🔵 Needs a closer look

Distributed query-planning behavior spans analyzer contexts, cluster engines, and replica execution and warrants final human validation.

0 open findings

What changed in this PR

Preserves parallel-replica fan-out for cluster engines while AutoPR controls only MergeTree reads.

Changes:

  • Centralizes parallel-replica eligibility in Context.
  • Makes forced mode override AutoPR consistently.
  • Adds regression coverage and stabilizes randomized tests.
File Description
src/​Interpreters/​Context.h Declares centralized eligibility helpers.
src/​Interpreters/​Context.cpp Implements AutoPR and cluster-engine rules.
src/​Interpreters/​InterpreterSelectQueryAnalyzer.cpp Retains cluster-engine parallel replicas under AutoPR.
src/​Interpreters/​InterpreterSelectQuery.cpp Honors forced mode with the legacy analyzer.
src/​TableFunctions/​TableFunctionURL.cpp Uses centralized cluster replacement eligibility.
src/​TableFunctions/​TableFunctionObjectStorage.cpp Applies shared eligibility to object storage.
src/​Databases/​DataLake/​DatabaseDataLake.cpp Applies shared eligibility to data-lake tables.
src/​Storages/​StorageDistributed.cpp Corrects active replica counting.
src/​Storages/​MergeTree/​MergeTreeDataSelectExecutor.cpp Corrects sampling-mode eligibility.
src/​Planner/​PlannerJoinTree.cpp Corrects trivial-count handling.
src/​Processors/​QueryPlan/​Optimizations/​QueryPlanOptimizationSettings.cpp Uses effective AutoPR mode.
src/​Core/​Settings.cpp Documents forced-mode behavior.
tests/​clickhouse-test Disables unsafe cluster fan-out during randomization.
tests/​queries/​0_stateless/​05175_autopr_keep_cluster_engines.sh Tests cluster-engine behavior and exclusions.
tests/​queries/​0_stateless/​05175_autopr_keep_cluster_engines.reference Records expected plans and errors.
tests/​queries/​0_stateless/​05260_autopr_force_mode_wins.sql Tests forced-mode precedence.
tests/​queries/​0_stateless/​05260_autopr_force_mode_wins.reference Records replica-usage expectations.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@devcrafter devcrafter left a comment

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.

Let's mention in the change log the change on behavior when enable_parallel_replicas = 2

…e impl

Replace it with a private `canUseTaskBasedParallelReplicasImpl(bool ignore_automatic_parallel_replicas)`,
so `canUseTaskBasedParallelReplicas` no longer reads as being defined through a cluster-engine check.
The flag is set only by `canReplaceClusterEngineWithClusterVariant`.

Review: #122306 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nickitat
nickitat enabled auto-merge October 12, 2026 12:28
@nickitat
nickitat added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 2c2ff37 Oct 14, 2026
350 of 351 checks passed
@nickitat
nickitat deleted the autopr-keep-cluster-engines branch October 14, 2026 00:00
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
Master no longer converts a url or s3 read to its cluster variant when
additional_table_filters is set (Context::canReplaceClusterEngineWithClusterVariant,
since ClickHouse#122306), so that line read through a plain url and passed without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-bugfix Pull request with bugfix, not backported by default 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