Skip to content

Keep WITH RECURSIVE recursive when the first UNION branch's WITH list is propagated - #118510

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-recursive-with-union-branch-propagation
Sep 12, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-recursive-with-union-branch-propagation

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #114908

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 WITH RECURSIVE losing its recursiveness in the second and later branches of a UNION, INTERSECT or EXCEPT. When a later branch had no WITH clause of its own, the first branch's WITH list was copied into it without the RECURSIVE marker, so WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3) SELECT sum(id) FROM src UNION ALL SELECT sum(id) FROM src was rejected with UNKNOWN_TABLE, and returned a wrong value for the copied branch when an enclosing CTE of the same name existed. CREATE VIEW also stored the copied branch without RECURSIVE.

Description

At pure defaults (enable_analyzer = 1, enable_global_with_statement = 1):

WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3)
SELECT sum(id) AS s FROM src
UNION ALL
SELECT sum(id) AS s FROM src;
-- Code: 60. UNKNOWN_TABLE: Unknown table expression identifier 'src'.

With an enclosing plain CTE of the same name there is no error: the non-recursive copy resolves src in its own body outward to that CTE, so the branch silently returns its seed row (1, 6 where both must be 6).

Root cause: enable_global_with_statement copies the first branch's WITH list into every later branch that has none, but recursive_with is a member of ASTSelectQuery, not of the cloned ASTExpressionList, so the copy arrived marked non-recursive. QueryTreeBuilder then built no recursive-CTE table for that branch, and the CTE's self-reference resolved as an ordinary table.

Fix: thread the first branch's recursive_with through the three ApplyWithGlobalVisitor::visit overloads and set it where the cloned list is installed, as wrapQueryIntoSelect in ParserPipeOperators.cpp already does; assigning only there keeps recursive_with implying with() != nullptr.

05111_recursive_cte_union_branch_propagation: 8 arms fail without this change, 7 controls and boundaries must not move; its view arm asserts the stored definition text, since the read-back value also depends on ApplyWithSubqueryVisitor, which ignores the flag. A later branch with its own WITH still receives no CTE from the first branch; its last two arms pin that. 05112_recursive_cte_union_branch_propagation_json_ast covers the INTERSECT/EXCEPT overload: such a node reaches the propagation only through dialect = clickhouse_json, since SQL text is rewritten into it afterwards.

Found while adjudicating a review comment on #114908; it reproduces on plain master without that PR: #114908 (comment)


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

Version info

  • Merged into: 26.9.1.1317 (included in 26.9 and later)

groeneai and others added 2 commits September 7, 2026 04:38
…'s WITH list

enable_global_with_statement copies the first branch's WITH list into every later
branch of a UNION, INTERSECT or EXCEPT that has no WITH of its own.
ASTSelectQuery::recursive_with, the flag recording that the list was written
WITH RECURSIVE, is a member of the SELECT rather than of the ASTExpressionList
being cloned, so cloning the list could not carry it and nothing else set it.
The later branch therefore held a recursive CTE while reporting
recursive_with == false.

QueryTreeBuilder marks a recursive CTE only under that flag, and it is the sole
producer of UnionNode::is_recursive_cte, whose only consumer builds the
recursive-CTE table. Without it the branch got no such table and the CTE's
self-reference resolved as an ordinary table. Absent, that gives UNKNOWN_TABLE
for

    WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3)
    SELECT sum(id) AS s FROM src UNION ALL SELECT sum(id) AS s FROM src;

and when an enclosing CTE of the same name existed it resolved to that one
instead, returning a wrong value for the copied branch with no error at all.
ASTSelectQuery::formatImpl emits RECURSIVE from the same flag, so a CREATE VIEW
over such a query stored the copied branch without RECURSIVE and the loss became
durable.

Thread the first branch's recursive_with through the three private visit
overloads and assign it where the cloned list is installed. That is the shape
ParserPipeOperators::wrapQueryIntoSelect already uses for the identical
clone-a-WITH-list-onto-another-ASTSelectQuery step, and keeping the assignment
inside the branch that installs a list upholds the invariant that recursive_with
is set only when with() is non-null.

ApplyWithAliasVisitor looks near-identical but needs no such change: it builds a
fresh list out of ASTWithAlias values only, never out of another SELECT's WITH,
so recursive_with == false is correct there. PR ClickHouse#105433 fixed the mirror case of
this invariant, a flag set with no list at all.

The new test asserts the stored view definition as text rather than reading the
view back, because the read-back value additionally depends on
ApplyWithSubqueryVisitor, which does not consult recursive_with at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
…results

The arms of 05111 asserted query results only, and the flag's effect on a
non-recursive list is invisible in results: QueryTreeBuilder acts on a WITH
element only when it is a UnionNode, and every control's CTE is a QueryNode.
Two wrong implementations therefore passed the whole file: one that sets the
flag unconditionally on the copy, and one that also sets it in the merge path,
marking a branch that has a WITH of its own. Both are user-visible, since a
plain query's stored view definition would then contain WITH RECURSIVE and
enable_analyzer = 0 would start throwing UNSUPPORTED_METHOD.

Read the flag itself instead, via countSubstrings(explain, 'WITH RECURSIVE')
over EXPLAIN SYNTAX: 0 markers for a non-recursive source, and 1 when the later
branch owns its WITH, bracketing the 2 the existing arm asserts for a
propagated recursive list. A build carrying both wrong implementations at once
fails on exactly those two cells.

Drop the "inside a subquery" arm: the shadowed-CTE arm has the identical
SELECT * FROM ( ... UNION ALL ... ) shape and covers the same dispatch.

State the shadowed arm's mechanism correctly: the pre-fix value was 1. The copy
is not recursive, so src inside its own body resolves outward to the enclosing
CTE, whose 99 fails id < 3, leaving the branch its seed row alone.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold, then by an independent second model, over two review rounds and one fix round.

❌ Controls could not observe the flag. Every negative control asserted only query results, and a
non-recursive list marked recursive changes no result (QueryTreeBuilder only acts on a WITH
element that is a union), so a constant recursive_with = true would have passed the whole file.
Fixed by two EXPLAIN SYNTAX marker oracles: 0 markers for a non-recursive source, exactly 1
when the later branch owns its WITH, against 2 for the propagated recursive case. A build
carrying both wrong implementations at once now fails on exactly those two cells and nothing else.

⚠️ A test comment named the wrong mechanism for the silent-wrong-result case. The copy is not
recursive, so src inside its body resolves outward to the enclosing CTE, whose 99 fails
id < 3; the branch is left with its seed row and returns 1. Comment and PR description corrected.

⚠️ Views stored before this fix are not repaired by it. The second round raised that as a
compatibility gap and asked for load-time normalization. I disagree, for a reason this PR's own test
pins: on such a definition the copied branch already carries a plain WITH, byte-identical to one a
user wrote, so the only available rule is "mark an existing list recursive", which is precisely the
second mutant the new marker oracle kills (1 becomes 2). It is user-visible too: a plain query's
stored definition would gain WITH RECURSIVE, and enable_analyzer = 0 would start throwing. Only
the same-name-shadowed shape can persist at all, because CREATE VIEW over the unshadowed shape
fails at creation; such a view returns the wrong value on master today and keeps doing so until it is
recreated. The changelog entry states that CREATE VIEW stored the copied branch without
RECURSIVE, which is the fact an affected reader needs. Repairing the read-back value belongs to
ApplyWithSubqueryVisitor, which does not consult this flag at all on master.

💡 One redundant arm was removed (the plain-subquery shape is covered by the shadowed one), so the
added oracles keep the test's size matched to a two-line change. The INTERSECT/EXCEPT arms
exercise the ASTSelectQuery overload rather than the intersect/except one, because
SelectIntersectExceptQueryVisitor runs after this visitor; that overload is threaded for
consistency. The ASTSelectWithUnionQuery overload, reached by a parenthesized nested union in a
later branch, is covered by a measured probe rather than a shipped arm, for the same volume reason.

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f227fd4]

Summary: ✅


AI Review

Summary

This PR preserves recursive_with when ApplyWithGlobalVisitor clones the first branch's WITH list into later UNION/INTERSECT/EXCEPT branches, and the added regressions now check both the result-changing bug and the cases where the RECURSIVE marker must or must not survive propagation. I did not find a remaining correctness, compatibility, or test-coverage issue in the current patch.

Final Verdict

✅ No remaining findings.

LLVM Coverage Report

Measured on commit f227fd4.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.20% +0.10%

Changed lines: Changed C/C++ lines covered: 25/31 (80.65%) · Uncovered code

Full report · Diff report

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

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on the pristine build, no randomization and no DDL: WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3) SELECT sum(id) AS s FROM src UNION ALL SELECT sum(id) AS s FROM src; gives Code: 60 UNKNOWN_TABLE ... In scope SELECT id + 1 FROM src WHERE id < 3. Not a rate.
b Root cause explained? enable_global_with_statement copies the first branch's WITH list into every later branch that has none of its own. recursive_with is a member of ASTSelectQuery, not of the ASTExpressionList being cloned, so the copy arrived marked non-recursive. QueryTreeBuilder only marks a recursive CTE under that flag, so the branch got no recursive-CTE table and the CTE's self-reference resolved as an ordinary table: absent, or the enclosing CTE of the same name instead. The formatter emits RECURSIVE from the same flag, which is how the loss reached stored CREATE VIEW text.
c Fix matches root cause? Yes. The propagation step that loses the information is the step corrected: the flag is captured beside the list it describes and assigned where the clone is installed. No widened bound, no reduced dataset, no no-random-* tag, no downstream guard, no defensive check.
d Test intent preserved / new tests added? New 05111_recursive_cte_union_branch_propagation: 8 arms that fail without this change plus 7 negative/boundary controls that must not move and did not. Two of the controls are EXPLAIN SYNTAX marker oracles, which observe the flag where it changes no query result: a build that instead marks the copy recursive unconditionally, and one that also marks a branch owning its own WITH, fail on exactly those two cells while every other arm stays green. No existing test was weakened, retagged or relaxed.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (318ea303... pristine, c309d91a... fixed), with the server's buildId() asserted against readelf -n before every verdict. Each arm was run separately against both binaries; as a test, [ OK ] on the fixed server and [ FAIL ] return code: 60 on the pristine one.
f Fix is general across code paths? The invariant is a list written WITH RECURSIVE has recursive_with == true, and that implies with() != nullptr. setExpression(Expression::WITH, ...) is the only way to install a list (there is no refWith()), so the install sites enumerate exhaustively; every one of them was reviewed, this one is fixed and the rest are already correct. ApplyWithAliasVisitor builds its list only from ASTWithAlias values, so false is right there; ParserInsertQuery cannot produce a recursive WITH (Keyword::RECURSIVE is consumed at one place only); QueryNode already guards with is_recursive_with && hasWith(); ParserPipeOperators already threads the flag and is the model for this change. Two of the three visit overloads are exercised by parsed SQL: ASTSelectQuery by every arm, ASTSelectWithUnionQuery by a nested-union probe. The ASTSelectIntersectExceptQuery overload is threaded for consistency and is reachable only for an AST that already contains that node, since SelectIntersectExceptQueryVisitor runs after this visitor (executeQuery.cpp:2787 vs :2791), which is why INTERSECT/EXCEPT arms go through the ASTSelectQuery overload here. Fixed at the source, not guarded at the symptom.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: this is a parser flag on a query node, not a value property. The input dimension that does apply is query shape, and it is enumerated in the test and probes: UNION ALL / INTERSECT / EXCEPT, two and three branches, top level and inside a subquery, shadowed and unshadowed by an enclosing CTE, CTE with and without a column alias list, scalar-alias-only WITH RECURSIVE, a WITH RECURSIVE CTE that does not reference itself, nested union and nested intersect in a later branch, enable_global_with_statement on and off, and both analyzers.
h Backward compatible? Yes. No setting, default or serialized format changes, so no SettingsChangesHistory.cpp entry is required. The behaviour change is confined to queries that are rejected or silently wrong today; the seven control and boundary arms are the guard that nothing which works today moves.
i Invariants and contracts preserved? The assignment sits inside the else branch that has just installed a list, so recursive_with implying with() != nullptr holds by construction on every path, including early returns. That matches ParserPipeOperators and the in-tree enforcement that makes flag-without-list a BAD_ARGUMENTS throw in ASTSelectQuery::readJSON. AddDefaultDatabaseVisitor dereferences select.with() unconditionally when the flag is set and stays safe for that reason; the stored-view arm exercises it. No concurrency or durability contract is in scope: this is a single-threaded AST rewrite in executeQuery before planning.

Session id: cron:clickhouse-impl-self-slot-57:20260907-054100

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd, could you review this? enable_global_with_statement clones the first UNION branch's WITH list into every later branch that has none, but recursive_with lives on ASTSelectQuery rather than on the cloned ASTExpressionList, so the copy arrived without RECURSIVE: that branch then got no recursive-CTE table and the CTE's self-reference resolved as an ordinary table, giving UNKNOWN_TABLE, or a silently wrong value when an enclosing CTE of the same name existed.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f227fd4de with master 794800200 (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.

Compile time of recompiled translation units

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

Job report

…alect

Threading recursive_with through ApplyWithGlobalVisitor touches three visit
overloads, and the one taking ASTSelectIntersectExceptQuery had no shipped arm.
SQL text always reaches the propagation as a flat ASTSelectWithUnionQuery,
because SelectIntersectExceptQueryVisitor, the sole producer of that node, runs
after the propagation in executeQuery. The node is present beforehand only when
the AST is deserialized from JSON, where readJSON accepts it as a query operand,
so dialect = clickhouse_json is the only way to reach that propagation target.

The new arms build such an AST out of parseQueryToJSON output. Under the
analyzer, both branches must sum the recursive CTE's ids: without the flag on the
copy the operand fails with UNKNOWN_TABLE on the CTE's self-reference. Results
alone cannot see a flag set where it should not be, because a non-recursive CTE
that is marked recursive returns the same rows, so the last two arms read the
copied flag through the old analyzer instead: it refuses a recursive WITH
outright, so the recursive AST is rejected there while the non-recursive one
keeps running.

Both wrong implementations of that overload pass the whole of 05111 and fail
05112: one that drops the flag, and one that forwards it unconditionally.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 8, 2026

@alexey-milovidov alexey-milovidov 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.

Amazing!

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 5c0934a Sep 12, 2026
175 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.

3 participants