Repository navigation
Do not use task-based parallel replicas for a recursive CTE or a correlated subquery enabled by a nested SETTINGS clause - #115916
Conversation
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.
Internal second-model review (click to expand)Four review rounds, each an independent cold read plus a second-model pass. Findings that ❌ Fixed during review
💡 Noted, not blocking
Session id: cron:clickhouse-review-slot-48:20260822-131100 |
Pre-PR validation gate (click to expand)
Also fixed, found while validating: the simpler single-reference shape did not throw but failed Validation: 50 runs with randomized settings and 50 with randomization disabled, all green. All Session id: cron:clickhouse-impl-slot-6:20260822-100700 |
|
Workflow [PR], commit [8aecfbb] Summary: ❌
|
|
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 |
| /// 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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units10 translation units recompiled, 31 s compile time in total, 10 of them have a recent master baseline. |
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.
|
Fixed the old-analyzer red on the new test in
The file now pins the analyzer once at the top, which is what the other 25 recursive-CTE tests do. Verified with one binary against several servers, changing only the test file: the previous file One further note, on the internal review finding that in-place |
CI finish ledger - a615811Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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 The failing frame is The old-analyzer regression fixed in Session id: cron:our-pr-ci-monitor:20260823-070000 |
…s-for-recursive-cte
…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.
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]>
|
@groeneai Would it simplify the implementation if parallel replicas could be enabled/disabled ony in root query? |
|
Partly. A root-only rule would remove the parts that exist because a nested
The blockers stay. Both bugs reproduce on today's master (
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, |
…s-for-recursive-cte
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]>
|
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. |
Closes: #121105
Related: #84318
Related: #85773
Related: #64571
Changelog category (leave one):
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 spuriousTOO_DEEP_RECURSIONandDuplicate announcement received for replica number N: task-based parallel replicas (parallel_replicas_mode = 'read_tasks') are no longer used for aWITH RECURSIVEquery or for a correlated subquery, including when a nestedSETTINGSclause 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
RecursiveCTESourcerewrites the CTE'sself-reference in place. Shipping replaces it with a fresh
TableNodewhile theUnionNodekeeps itsrecursive-CTE flag, so the source locates nothing:
Logical error: 'UNION query ... is not recursive'with a second reference site, a spurious
TOO_DEEP_RECURSIONotherwise.A correlated subquery was meant to stay local, but
DisableParallelReplicasPass::rundecidedeligibility once, from the top-level context, while a nested
SETTINGSclause applies to thesubquery'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 throwsDuplicate 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 loweredcompatibilitysets), and aparallel-replicas read step cannot be cloned, so on master a correlated subquery in
WHEREover aFROMsubquery fails withCannot clone ReadFromLocalReplica plan step. The setting goes into a copyof the node's context, as the clones of a non-materialized CTE share one. Custom-key modes are
unchanged.
03034_recursive_cte_tree_merge_treeleaves the parallel-replicas blacklist.05137_pr_disable_for_multiple_tables_executionrelied on the old visit order for its kill-switchcontrol, which now reads a subquery the pass leaves alone.
Found by
Stress test (arm_msan)and by the AST fuzzer inStress 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]