Repository navigation
Keep WITH RECURSIVE recursive when the first UNION branch's WITH list is propagated - #118510
Conversation
…'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.
Internal second-model reviewReviewed 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
💡 One redundant arm was removed (the plain-subquery shape is covered by the shadowed one), so the |
|
Workflow [PR], commit [f227fd4] Summary: ✅
AI ReviewSummaryThis PR preserves Final Verdict✅ No remaining findings. LLVM Coverage ReportMeasured on commit f227fd4.
Changed lines: Changed C/C++ lines covered: 25/31 (80.65%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260907-054100 |
|
cc @vdimir @novikd, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 21 s compile time in total, 9 of them have a recent master baseline. |
…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]>
Related: #114908
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
WITH RECURSIVElosing its recursiveness in the second and later branches of aUNION,INTERSECTorEXCEPT. When a later branch had noWITHclause of its own, the first branch'sWITHlist was copied into it without theRECURSIVEmarker, soWITH 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 srcwas rejected withUNKNOWN_TABLE, and returned a wrong value for the copied branch when an enclosing CTE of the same name existed.CREATE VIEWalso stored the copied branch withoutRECURSIVE.Description
At pure defaults (
enable_analyzer = 1,enable_global_with_statement = 1):With an enclosing plain CTE of the same name there is no error: the non-recursive copy resolves
srcin its own body outward to that CTE, so the branch silently returns its seed row (1, 6where both must be6).Root cause:
enable_global_with_statementcopies the first branch'sWITHlist into every later branch that has none, butrecursive_withis a member ofASTSelectQuery, not of the clonedASTExpressionList, so the copy arrived marked non-recursive.QueryTreeBuilderthen 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_withthrough the threeApplyWithGlobalVisitor::visitoverloads and set it where the cloned list is installed, aswrapQueryIntoSelectinParserPipeOperators.cppalready does; assigning only there keepsrecursive_withimplyingwith() != 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 onApplyWithSubqueryVisitor, which ignores the flag. A later branch with its ownWITHstill receives no CTE from the first branch; its last two arms pin that.05112_recursive_cte_union_branch_propagation_json_astcovers theINTERSECT/EXCEPToverload: such a node reaches the propagation only throughdialect = 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
26.9.1.1317(included in26.9and later)