Skip to content

Do not use task-based parallel replicas for a recursive CTE or a correlated subquery enabled by a nested SETTINGS clause - #115916

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:no-parallel-replicas-for-recursive-cte
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:no-parallel-replicas-for-recursive-cte

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121105
Related: #84318
Related: #85773
Related: #64571

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

Fixed the logical errors UNION query ... is not recursive, a spurious TOO_DEEP_RECURSION and Duplicate announcement received for replica number N: task-based parallel replicas (parallel_replicas_mode = 'read_tasks') are no longer used for a WITH RECURSIVE query or for a correlated subquery, including when a nested SETTINGS clause enables them for the subquery alone.

Description

Two query shapes have no distributed form, yet were shipped to replicas.

A recursive CTE is evaluated on the initiator, where RecursiveCTESource rewrites the CTE's
self-reference in place. Shipping replaces it with a fresh TableNode while the UnionNode keeps its
recursive-CTE flag, so the source locates nothing: Logical error: 'UNION query ... is not recursive'
with a second reference site, a spurious TOO_DEEP_RECURSION otherwise.

A correlated subquery was meant to stay local, but DisableParallelReplicasPass::run decided
eligibility once, from the top-level context, while a nested SETTINGS clause applies to the
subquery's own context. With them off outside and on in the subquery, decorrelating on a
replica materializes the referenced read twice under one stream_id, so the coordinator throws
Duplicate announcement received for replica number N.

The pass now decides per node and leaves a follower's setting alone. A query that evaluates a
correlated subquery keeps its own subqueries local too: decorrelation may clone its input plan (with
correlated_subqueries_use_in_memory_buffer = 0, as a lowered compatibility sets), and a
parallel-replicas read step cannot be cloned, so on master a correlated subquery in WHERE over a
FROM subquery fails with Cannot clone ReadFromLocalReplica plan step. The setting goes into a copy
of the node's context, as the clones of a non-materialized CTE share one. Custom-key modes are
unchanged.

03034_recursive_cte_tree_merge_tree leaves the parallel-replicas blacklist.
05137_pr_disable_for_multiple_tables_execution relied on the old visit order for its kill-switch
control, which now reads a subquery the pass leaves alone.

Found by Stress test (arm_msan) and by the AST fuzzer in Stress test (arm_debug):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115619&sha=452c119a225d1107c28037a0c371d692306cd2de&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
https://github.com/ClickHouse/ClickHouse/actions/runs/35525939313/job/106154645706


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

A recursive CTE is evaluated on the initiator: RecursiveCTESource owns a pair
of temporary tables, rotates them between iterations and rewrites the CTE's
self-reference in place. That fixed-point loop has no distributed form, but
nothing prevented such a query from being shipped to replicas.

The self-reference is a temporary table named after the CTE
(QueryAnalyzer.cpp:6832). When the query is shipped, buildQueryTreeForShard
globalizes the join because that table is not MergeTree (:1069) and then
replaces the table expression with a fresh TableNode carrying the shipped
_data_* name (:925). The UnionNode keeps its recursive CTE flag, so
Planner.cpp:2169 still builds ReadFromRecursiveCTEStep, and the name based
lookup in RecursiveCTESource.cpp:82 finds nothing.

Two user visible symptoms, both fixed here:

  * "Logical error: 'UNION query ... is not recursive'" when the CTE has a
    second reference site, for example inside IN (SELECT ... FROM cte).
  * A spurious TOO_DEEP_RECURSION, or a query that does not terminate without
    a depth bound, for the single reference shape: the shipped self-reference
    reads a table that never advances.

Extend DisableParallelReplicasPass, which already keeps correlated subqueries
local, to also trip on a recursive CTE. Fixing the consumer's name lookup
instead would be wrong: without the flag the planner treats the union as an
ordinary one and reads the placeholder table, which is created empty and
populated only by RecursiveCTESource, so the query would silently return no
recursive rows.

Found by Stress test (arm_msan) on an unmutated query.
A recursive CTE is evaluated on the initiator: RecursiveCTESource owns a pair
of temporary tables, rotates them between iterations and rewrites the CTE's
self-reference in place. That fixed-point loop has no distributed form, but
nothing prevented such a query from being shipped to replicas.

The self-reference is a temporary table named after the CTE
(QueryAnalyzer.cpp:6832). When the query is shipped, buildQueryTreeForShard
globalizes the join because that table is not MergeTree (:1074) and then
replaces the table expression with a fresh TableNode carrying the shipped
_data_* name, minted at :581. The UnionNode keeps its recursive CTE flag, so
Planner.cpp:2169 still builds ReadFromRecursiveCTEStep, and the name based
lookup in RecursiveCTESource.cpp:82 finds nothing.

Two user visible symptoms, both fixed here:

  * "Logical error: 'UNION query ... is not recursive'" when the CTE has a
    second reference site, for example inside IN (SELECT ... FROM cte).
  * A spurious TOO_DEEP_RECURSION, or a query that does not terminate without
    a depth bound, for the single reference shape: the shipped self-reference
    reads a table that never advances.

Extend DisableParallelReplicasPass, which already keeps correlated subqueries
local, to also trip on a recursive CTE. Fixing the consumer's name lookup
instead would be wrong: without the flag the planner treats the union as an
ordinary one and reads the placeholder table, which is created empty and
populated only by RecursiveCTESource, so the query would silently return no
recursive rows.

The pass used to return early when the top level context could not use
parallel replicas, but a nested SETTINGS clause gives a subquery its own
context, and the planner reads that node's context when it decides to ship
(PlannerJoinTree.cpp:2615). A recursive CTE inside such a subquery was
therefore never visited and still aborted. Decide eligibility per node
instead, which also keeps the setting untouched on a follower.

03034_recursive_cte_tree_merge_tree was blacklisted for parallel replicas
because of this defect and passes now, so remove it from the list. The two
remaining entries in that group stay: 03075_... does not exist in this tree,
and 03154_... is tagged shard while the job reading the list passes
--no-shard.

Found by Stress test (arm_msan) on an unmutated query.
The nested SETTINGS arm is the regression case for the per-node gate: before
that change the pass returned early on the top level context and never visited
a recursive CTE living inside a subquery that enables parallel replicas on its
own. That arm asserted only its result row, so it would keep passing if the
inner SETTINGS ever stopped engaging parallel replicas.

Give it the same ParallelReplicasQueryCount pair the top level placement
already has. The counter is incremented once, in the replica reading
coordinator's destructor, so a non-zero value means the query built such a
coordinator. Both queries are asserted after they succeed, which distinguishes
"ran on the initiator" from "did not run".

The control aggregates over the parts rather than answering from part counters,
which never reach the coordinator and would leave the control unable to fail.
The projection over system.query_log counted every matching row, so it
returned more than the four expected lines whenever a measured query was
executed more than once against the same database. Two paths do that: the
stress profile enables the server-side AST fuzzer for any query and a
re-execution inherits log_comment, and clickhouse-test retries a test up
to three times while stress's --database mode keeps one database for the
whole run.

Pin ast_fuzzer_runs on each measured query so it is executed exactly once,
and aggregate the projection with argMax over event_time_microseconds so a
repeated run reports the latest attempt instead of accumulating rows.

Measured on a server configured with the stress profile
(ast_fuzzer_runs = 5, ast_fuzzer_any_query = true): running the test three
times against one database returned 4, 8 and 12 projection rows before this
change and 4, 4, 4 after it.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Four review rounds, each an independent cold read plus a second-model pass. Findings that
survived adjudication were fixed; the ones I disagreed with are recorded below with the code that
refutes them.

❌ Fixed during review

Round Finding Resolution
r1 The pass returned early on the top-level context, so a recursive CTE inside a subquery whose own SETTINGS enables parallel replicas was never visited. Reproduced: that placement still threw is not recursive. Eligibility is now decided per node. Confirmed by reading the settings back from system.query_log rather than inferring them from the query text, with a non-recursive positive control that does ship.
r1 03034_recursive_cte_tree_merge_tree sat in parallel_replicas_blacklist.txt because of this defect. Entry removed, gated on an A/B: the test fails on master, is reported NOT_FAILED ("remove it from the list") with the fix and the entry still present, and passes once removed. The two remaining entries in that group were each re-checked and correctly stay.
r2 The nested-SETTINGS arm asserted only its result row, so it would keep passing if the inner settings ever stopped engaging parallel replicas. Added a matched locality pair for that placement. ParallelReplicasQueryCount has exactly one increment site, in ParallelReplicasReadingCoordinator's destructor, so it cannot be lit by an unrelated path.
r3 The locality projection counted every matching row, so it returned more than the four expected lines when a measured query ran twice against one database. Projection aggregates per log_comment with argMax over event_time_microseconds, and each measured query pins ast_fuzzer_runs. Reproduced deterministically: the old form returned 4, 8 and 12 rows across three runs, the new one 4, 4, 4.
r4 The Related: links sat inside the leading HTML comment, so they neither rendered nor created a cross-reference. Moved into the visible body. Measured both ways on two earlier pull requests: one with the link inside the comment produces no cross-reference on the target, one with it outside does.

⚠️ Disagreed, with evidence

  • Recursive CTEs remain enabled for custom-key parallel replicas, and automatic parallel
    replicas can still engage inside a recursive CTE
    . Both describe master, not a change here.
    canUseTaskBasedParallelReplicas() requires parallel_replicas_mode == READ_TASKS and
    automatic_parallel_replicas_mode == 0; master gated run() on that predicate and this branch
    gates the write on the same predicate, so in those modes both revisions leave the setting
    untouched and behave identically. The correlated-subquery half of the pass shares that gate, so
    the changelog entry's "the same way they are already disabled for correlated subqueries" holds
    exactly. For the automatic mode the outcome is additionally unreachable: considerEnablingParallelReplicas
    requires every step to support dataflow-statistics collection and ReadFromRecursiveCTEStep does
    not, while the inner replan runs through a builder that clears the mode before re-running the
    query-tree passes. The suggested remedy would suppress the automatic heuristic for a whole
    subtree, which is outside this fix.
  • Two earlier arms were dropped rather than kept as decoration, because measurement showed they
    could not fail: an EXPLAIN-token count that reads 0 on master only because the query aborts
    first, and a count()-based control that never reaches the reading coordinator.

💡 Noted, not blocking

  • The pass now walks every analyzer query tree instead of returning immediately. Only the
    traversal widened; the write is still gated per node. Any top-level gate would reintroduce the
    r1 blind spot.
  • getDescription() changes, and it is visible in EXPLAIN QUERY TREE dump_passes = 1. No
    reference file pins the old string.
  • Dropping the top-level early return closes the same blind spot for correlated subqueries, which
    is stated in the description.

Session id: cron:clickhouse-review-slot-48:20260822-131100

@clickhouse-gh clickhouse-gh Bot closed this Aug 22, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on pristine master b16561cc816c. A WITH RECURSIVE query with a second reference site inside IN (SELECT ... FROM cte) plus allow_experimental_parallel_reading_from_replicas = 1, max_parallel_replicas = 3, cluster_for_parallel_replicas = 'parallel_replicas', parallel_replicas_for_non_replicated_merge_tree = 1 throws Logical error: 'UNION query d is not recursive' at RecursiveCTESource.cpp:84, the same frame as the CI report. Also reproduced with those settings on an inner subquery instead of the top query.
b Root cause explained? Yes. The self-reference is a temporary table named after the CTE (QueryAnalyzer.cpp:6832). Shipping globalizes the join because that table is not MergeTree (buildQueryTreeForShard.cpp:1074) and then replaces the table expression with a fresh TableNode holding the shipped _data_* name, minted at :581. The UnionNode keeps its recursive-CTE flag, so Planner.cpp:2169 still builds ReadFromRecursiveCTEStep and the name lookup at RecursiveCTESource.cpp:82 finds nothing.
c Fix matches root cause? Yes. It removes the decision to ship a query whose shape cannot be shipped, extending the existing DisableParallelReplicasPass that already keeps correlated subqueries local. It does not widen or downgrade the guard at RecursiveCTESource.cpp:84.
d Test intent preserved / new tests added? Yes. No test removed or weakened. New 05033_recursive_cte_parallel_replicas asserts the returned rows, not merely absence of an abort; it also asserts locality via ParallelReplicasQueryCount (0 for the recursive query, non-zero for a plain one), for the settings placed on the top-level query and on an inner subquery alike and that a plain query over the same table still uses parallel replicas. 03034_recursive_cte_tree_merge_tree was blacklisted for parallel replicas because of this defect and is re-enabled.
e Both directions demonstrated? Yes, with two distinct binaries whose Build IDs were asserted against SELECT lower(buildId()) on each running server. Base 9f6a4fa9: the new test exits 32 with two is not recursive lines, and 03034 fails with TOO_DEEP_RECURSION. Fix 002d5b2f: both pass.
f Fix is general across code paths? Yes. Both entry points into shipping were checked; findParallelReplicasQuery.cpp is downstream of the setting the pass writes, so the pass alone suffices, measured rather than assumed. Eligibility is decided per node, so a subquery whose own SETTINGS clause enables parallel replicas is covered even when the top-level query is ineligible; the follower path stays untouched because the same predicate is false there. The plain Distributed / remote() analogue was probed on the base binary and returns correct rows with no abort, so there is no second bug shape there.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the dimensions that apply. Covered one versus two reference sites, aliased self-join, IN-subquery reference, scalar subquery in the outer WHERE, a nested recursive CTE, settings at the top level and on an inner subquery, plain MergeTree and Distributed. Type wrappers are N/A: the predicate is UnionNode::hasRecursiveCTETable(), a node property, not a type property.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no changed default, no serialization or format change, so no SettingsChangesHistory.cpp entry. Behaviour changes only for queries that today either throw or fail to terminate. It is a performance change for those queries, stated in the description.
i Invariants and contracts preserved? Yes. The pass writes an existing setting on nodes that could otherwise use parallel replicas, so no node is written that the previous code would have refused; the early return moved from once per query to once per node. No new locking, allocation or error path, and nothing persisted.

Also fixed, found while validating: the simpler single-reference shape did not throw but failed
to terminate, surfacing as a spurious TOO_DEEP_RECURSION with a depth bound set. Same root
cause, same fix.

Validation: 50 runs with randomized settings and 50 with randomization disabled, all green. All
26 recursive-CTE stateless tests plus 03229_query_condition_cache_recursive_cte pass. The
correlated-subquery and parallel-replicas suites were A/B'd against pristine master under an
identical harness: every failure reproduces on master, and the apparent differences pass on both
binaries when run in isolation.

Session id: cron:clickhouse-impl-slot-6:20260822-100700

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8aecfbb]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05033_recursive_cte_parallel_replicas FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @yakov-olkhovskiy, could you review this? A recursive CTE is evaluated on the initiator, so shipping it renames the CTE's self-reference and the source can no longer find it, which surfaces as a logical error or as a spurious TOO_DEEP_RECURSION. This extends DisableParallelReplicasPass to trip on a recursive CTE, deciding eligibility per node so a subquery with its own SETTINGS is covered too.

/// It is also false on a follower, which must keep reading its assigned ranges.
static void disable(const ContextMutablePtr & node_context)
{
if (!node_context->canUseParallelReplicasOnInitiator())

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.

canUseParallelReplicasOnInitiator() is READ_TASKS-only (Context.cpp:8697-8717), so this early return leaves parallel_replicas_mode = CUSTOM_KEY_* untouched. That mode is still taken in PlannerJoinTree.cpp:2533-2553, and executeQueryWithParallelReplicasCustomKey fans the query out with a per-replica filter (ClusterProxy/executeQuery.cpp:505-529).

For a recursive CTE that means the fixed-point still runs on partitioned replica-local data instead of on the initiator, which can silently miss rows as soon as the recursion crosses the custom-key split. If the invariant here is "recursive CTEs have no distributed form", the guard needs to disable all parallel-replica modes for these nodes, or reject the custom-key path explicitly before the planner reaches it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The premise is right, the scope claim is not, so I am leaving this one alone. Custom-key mode is
untouched by this PR, and it behaves identically before and after.

canUseParallelReplicasOnInitiator() is indeed READ_TASKS-only, but master gated on the very same
predicate one level up: it returned from run() on context->canUseParallelReplicasOnInitiator()
before visiting anything. Under a custom-key mode master never entered the visitor at all; this PR
enters it and then declines to write the setting. Either way the setting is left as the user set it,
so the two revisions are behaviourally identical here.

I did measure the underlying concern rather than argue it. With parallel_replicas_mode = 'custom_key_sampling', parallel_replicas_custom_key = 'k' and a 3-replica single-shard cluster, a
recursive CTE over a MergeTree table returned 15 / 44 where the correct answer is 6 / 15, so the
fixed point does run on partitioned replica-local data as you describe. It returned the same wrong
15 / 44 on pristine master, with a positive control confirming the fixture genuinely engages the
custom-key path (a plain query on the same table plans ReadFromRemote). So this is a pre-existing
defect, not something this PR introduces or widens.

I am not widening the guard to cover it here, for two reasons. disable() is shared with the
correlated-subquery branch, so broadening it would silently change that feature's behaviour under
custom key as well. And the in-tree policy for these modes is explicit at src/Analyzer/Resolve/QueryAnalyzer.cpp:5623,
which deliberately leaves custom-key modes to ship full SQL and fail loudly rather than being
special-cased. Changing that is a separate decision from fixing the LOGICAL_ERROR this PR is about.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1b4505d17 with master a017407d3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5a33e4237; 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.

Compile time of recompiled translation units

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

Job report

DisableParallelReplicasPass tracked "a blocker was seen" in a single flag that,
once set, stayed set for the rest of the traversal. Every scope visited after the
first blocker therefore had parallel replicas disabled, including scopes in a
different branch of a union, which Planner::buildPlanForUnionNode plans
independently. Eligibility depended on the DFS order rather than on whether a
node's own subtree contains a recursive CTE or a correlated subquery.

Replace the flag with a scope stack. A scope is disabled when a blocker is on the
path from the root to it, or inside its own subtree; a blocker in a sibling
branch no longer affects it.

The subtree half is load-bearing: a recursive CTE can be declared in an outer
scope and referenced from a sibling of the union node, so restricting the veto to
the blocker and its ancestors alone lets the reads it drives ship, which is the
TOO_DEEP_RECURSION and LOGICAL_ERROR this pass exists to prevent.

Reported on ClickHouse#115916.
The test carried `enable_analyzer = 1` in each of its 17 per-query SETTINGS
clauses and no session-level pin. On the old-analyzer lane the server profile
sets `allow_experimental_analyzer = 0` (tests/config/users.d/analyzer.xml), so
for the two queries whose outer SELECT has no SETTINGS clause of its own the
nested value disagreed with the top level and
executeQuery.cpp:1128 rejected the query with

  Code: 80 Setting 'enable_analyzer' is changed in the subquery.
  Top level value: false. (INCORRECT_QUERY)

deterministically (3 of 3 reruns), at query 14.

Replace the per-query clauses with one `SET enable_analyzer = 1` at the top of
the file, matching the 25 other recursive-CTE tests. No coverage is lost on
that lane: recursive CTEs are analyzer-only (03311_recursive_cte_old_analyzer_error
pins the `UNSUPPORTED_METHOD` rejection) and DisableParallelReplicasPass runs in
the query-tree pass manager, so the old analyzer cannot reach any assertion in
this file. With the pin the test passes there rather than being skipped.

Verified on one binary against four servers: the pre-fix file still returns
Code 80 against an old-analyzer server while the new file passes and matches the
reference; the new file also matches on a default-analyzer server. Both negative
controls stay live with the new file - it still aborts pristine master with
'UNION query d is not recursive', and still differs at exactly the
sibling-branch line against the superseded sticky-flag build. 50 randomized plus
50 non-randomized runs pass under the test runner on both server profiles.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the old-analyzer red on the new test in a615811.

05033 set enable_analyzer = 1 in each of its 17 per-query SETTINGS clauses and never at the
session level. The old analyzer lane installs tests/config/users.d/analyzer.xml
(allow_experimental_analyzer = 0), and validateAnalyzerSettings
(src/Interpreters/executeQuery.cpp:1096-1138) rejects a nested value that disagrees with the top
level, so the two queries whose outer SELECT carries no SETTINGS clause of its own failed with
Code: 80 INCORRECT_QUERY (deterministic, 3 of 3 reruns, at line 88).

The file now pins the analyzer once at the top, which is what the other 25 recursive-CTE tests do.
No coverage is lost on that lane: recursive CTEs are analyzer-only
(03311_recursive_cte_old_analyzer_error pins the UNSUPPORTED_METHOD rejection) and
DisableParallelReplicasPass runs in the query-tree pass manager, so the old analyzer never reaches
an assertion in this file. With the pin the test passes there instead of erroring.

Verified with one binary against several servers, changing only the test file: the previous file
still returns Code: 80 against an old-analyzer server where the new file passes and matches the
reference, and the new file also matches on a default-analyzer server. Both negative controls stay
live: the new file still aborts pristine master with UNION query d is not recursive, and still
differs at exactly the sibling-branch line against the superseded sticky-flag build. 50 randomized
and 50 non-randomized runs pass under the test runner on both server profiles.

One further note, on the internal review finding that in-place disable() could leak through a
shared non-materialized CTE and take parallel replicas away from an independent sibling. The
mechanism is real - QueryNode::cloneImpl and UnionNode::cloneImpl do pass the original context
pointer through - but it does not produce that effect here. A shared CTE read from two plain
branches with no recursive CTE anywhere, so the pass marks nothing, already reports zero remote
read steps, and the reported control 1 / shared 0 pair is byte-identical on pristine master. The
sensitivity control in the same file (one plain branch reading a CTE) reports one, so the zero is a
pre-existing property of shipping a CTE read through a UNION rather than an effect of this pass.
Testing the isolation claim directly, with a recursive branch beside a sibling that shares nothing,
gives one remote step on this branch and on master, and zero only on the superseded sticky-flag
build, which is what the sibling arm of 05033 pins. So I have not changed the source for it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a615811

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Shard number is greater than shard count (STID 5066-457d) pre-existing trunk defect, not caused by this PR #113589 (ours, open)

Notes on the one red, measured rather than assumed:

The fuzzer mutated a query from this PR's own new test file, so the shape looks PR-specific. It
is not. Breadth on the signature text over 30 days is 58 rows across 48 distinct pull requests
plus 7 hits on master, with onset 2026-08-03, i.e. 19 days before this pull request was created
on 2026-08-22.

The failing frame is prepareClusterForParallelReplicas at
src/Interpreters/ClusterProxy/executeQuery.cpp:788, reached because the fuzzed query wraps the
recursive CTE in view(...) with its own nested SETTINGS cluster_for_parallel_replicas, over
remote() and remoteSecure() which ship a _shard_num = 2 scalar while that cluster has
shard_count = 1. #113589 rewrites exactly that function and its admission sites to bind the
shard scope to the cluster that produced it, which is the mechanism its description names.

The old-analyzer regression fixed in a615811 is confirmed green at this head: the
old analyzer stateless lane reports OK for 05033_recursive_cte_parallel_replicas, alongside
250 passing runs across five flaky-check lanes.

Session id: cron:our-pr-ci-monitor:20260823-070000

@devcrafter devcrafter self-assigned this Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 4, 2026
…parallel replicas

DisableParallelReplicasPass already kept a correlated subquery off the replicas, but
run() decided eligibility once, from the top-level context. Every subquery owns its own
context and the query tree builder applies a nested SETTINGS clause to that one, so with
enable_parallel_replicas = 0 outside and = 1 on the subquery the pass returned before its
visitor ran, the subquery was distributed, decorrelation on a replica cloned the referenced
read, both reads shared a stream_id, and the coordinator threw
"Duplicate announcement received for replica number N".

This branch already fixes that by deciding per node. What it lacked was coverage for the
correlated blocker in that placement: 05033 pins outer-off/inner-on for the recursive-CTE
blocker only, and 05211's subquery-SETTINGS case is green on master because its outer query
has parallel replicas on.

05233 covers the plain-SQL path (QueryTreePassManager), with an uncorrelated control proving
a nested SETTINGS clause still enables parallel replicas and an availability control proving
they work at all in this configuration. The 05211 case covers the mergeTreeAnalyzeIndexes
path, which is the shape the AST fuzzer reached. report() takes the settings string as an
optional fifth argument so the existing cases are unchanged.

The EXPLAIN oracle used elsewhere is vacuous here: an outer EXPLAIN does not render an
IN-subquery's plan, so it counts zero remote reads for the uncorrelated control as well.
Both files therefore assert on system.text_log coordinator creation, keyed by query_id, and
report the query result alongside the count so a query that failed outright cannot pass as
"no coordinators".

Verified on one tree with two binaries differing only in this pass: unfixed gives
"Duplicate announcement received for replica number 0" and aborts, fixed gives 100/100 green
over 50 randomized runs per test at parallel_replicas_local_plan 0 and 1.
Cut the clauses that narrate the fix from the three multi-line blocks in DisableParallelReplicasPass, keeping only the properties of pre-existing entities (Planner plans union branches independently, a recursive CTE source is initiator-local, canUseParallelReplicasOnInitiator is false on a follower). 11 added comment lines -> 8.
@groeneai groeneai changed the title Do not use parallel replicas for queries with a recursive CTE Do not use task-based parallel replicas for a recursive CTE or a correlated subquery enabled by a nested SETTINGS clause Sep 21, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Sep 21, 2026
A query that evaluates a correlated subquery was disabled because a blocker sits in its subtree,
but a subquery in its FROM is its own scope with its own context, and the scoped veto left that
context alone. The planner then read the FROM subquery with parallel replicas, and decorrelation,
which clones its input plan when `correlated_subqueries_use_in_memory_buffer = 0` (what a lowered
`compatibility` gives) or `correlated_subqueries_default_join_kind = 'left'`, failed with
`Cannot clone ReadFromLocalReplica plan step` (NOT_IMPLEMENTED). On master the same query in the
SELECT clause returned its rows, because the sticky flag set by the projection also covered the
FROM subquery visited after it.

Such a query is now a blocker itself, so its whole subtree stays local. Measured on a 3-replica
parallel_replicas cluster, PR head 3ff84bf vs this change vs master 31d10e5:
- correlated subquery in SELECT over a FROM subquery: NOT_IMPLEMENTED / rows / rows
- the same with the FROM subquery enabling parallel replicas on its own: NOT_IMPLEMENTED / rows / rows
- correlated subquery in WHERE (FROM is visited first): NOT_IMPLEMENTED / rows / NOT_IMPLEMENTED
- outer query without parallel replicas, FROM subquery with them: NOT_IMPLEMENTED / rows / NOT_IMPLEMENTED
A sibling branch of a union that holds such a query still reads with parallel replicas, in either
branch order.

The setting is now written into a copy of the node's context. The clones of a non-materialized
CTE share one context, so writing in place through the clone read by a recursive CTE also turned
parallel replicas off for a clone read by a sibling union branch: `WITH RECURSIVE shared AS
(SELECT ... SETTINGS enable_parallel_replicas = 1), d AS (... FROM shared ...) SELECT * FROM
(SELECT ... FROM d UNION ALL SELECT ... FROM shared)` planned 0 parallel-replicas reads before
and 1 now (master: 1); the same query with no recursive CTE plans 3 on all binaries. Reassigning
a node's context after it is built follows `evaluateScalarSubqueryIfNeeded`.

`05137_pr_disable_for_multiple_tables_execution` used the old visit order as the control of its
kill-switch probe: a FROM subquery read before the correlated `EXISTS` kept parallel replicas, so
its `FINAL` read was refused. That subquery is now local and the query runs; the probe moves to a
FROM subquery joined with a subquery that evaluates the correlated `EXISTS`, which the pass leaves
alone, so the refusal control stays live.

`05211` gains the control its outer-off arm lacked: the same subquery `SETTINGS` on an
uncorrelated predicate subquery create a coordinator, and stop creating one when the subquery
does not enable parallel replicas.

Reported by the AI review on ClickHouse#115916 (discussion_r4354610844).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@devcrafter

devcrafter commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

@groeneai Would it simplify the implementation if parallel replicas could be enabled/disabled ony in root query?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Partly. A root-only rule would remove the parts that exist because a nested SETTINGS can enable parallel replicas under a root that has them off:

  • the per-node canUseParallelReplicasOnInitiator() check in disable(); master's single early return in run() would be enough again (Correlated subquery with subquery-scoped parallel replicas throws LOGICAL_ERROR #121105 is exactly root off, subquery on);
  • the Context::createCopy in disable(): I only saw the CTE-clone leak it prevents with a CTE that enables parallel replicas in its own SETTINGS;
  • the nested-SETTINGS arms of 05233, 05211 and 05033.

The blockers stay. Both bugs reproduce on today's master (44cf9c04) with parallel replicas set only on the top-level query:

  • the first query of 05033: Logical error: 'UNION query d is not recursive';
  • a correlated subquery in WHERE over a FROM subquery, with correlated_subqueries_use_in_memory_buffer = 0: Cannot clone ReadFromLocalReplica plan step.

The larger simplification does not depend on that rule: keep the whole query local when it contains a blocker anywhere. That drops the scope stack, evaluatesCorrelatedSubquery and the context copy, so the pass becomes one search for a blocker followed by disabling every scope. The cost is that a subquery or UNION branch without a blocker also loses parallel replicas (master kept one only when it was visited before the blocker). If you prefer that, I'll switch the PR to it.

Master's style check requires every test that reads system.text_log to
filter on event_time (a full scan of the CI server's text_log exceeds the
test profile's max_rows_to_read). Use the same predicate master's 05211
already carries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The red Fast test / 05033_recursive_cte_parallel_replicas line at 8aecfbb (expected 10, got 0, the sum() over a subquery that enables parallel replicas in its own SETTINGS) is a wrong result on master, not caused by this PR. Fixing PR: #131618.

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated subquery with subquery-scoped parallel replicas throws LOGICAL_ERROR

3 participants