Repository navigation
Fix a view returning only the seed row when a recursive CTE is shadowed by a same-named plain CTE - #120089
Fix a view returning only the seed row when a recursive CTE is shadowed by a same-named plain CTE#120089groeneai wants to merge 9 commits into
Conversation
…med plain CTE CREATE VIEW stores the definition after ApplyWithSubqueryVisitor has rewritten each CTE reference into a clone of the element's body tagged with cte_name. The visitor never consulted ASTSelectQuery::recursive_with, so a copy taken from a WITH RECURSIVE list carried no record of having come from one. UnionNode::is_recursive_cte is set in exactly one place, QueryTreeBuilder over the WITH children of a query whose recursive_with is set, and it is the sole trigger for QueryAnalyzer creating the temporary table named getCTEName() and injecting it into each recursive branch's scope. That injection is what binds a self-reference. A FROM-position subquery carrying cte_name never received the flag, so the copy's recursive member was bound by ordinary name lookup: unshadowed it happened to find the real recursive CTE and re-derived the same set, while shadowed by a same-named plain CTE it found the plain one, whose rows had already been transformed, so the recursive member's filter discarded all of them and only the seed survived. CREATE VIEW v AS WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM src WHERE id < 3) SELECT id FROM (WITH src AS (SELECT id * 10 AS id FROM src) SELECT id FROM src); returned 10 where the same text run live returns 10, 20, 30, in the creating session and after every reload, and silently: ASTSubquery prints only its cte_name, so the stored text is unmangled and SHOW CREATE VIEW gives no hint. ASTSubquery now records that it replaced a reference to an element of a WITH RECURSIVE list, both substitution sites set it, and QueryTreeBuilder turns it into setIsRecursiveCTE where a UnionNode is built for a CTE. Putting the setter there rather than at the call sites keeps the "only when a UnionNode was built" test single-sourced: a single-branch element still collapses to a QueryNode and stays unmarked, exactly as on the WITH-list path, so a non-recursive sibling in a recursive list is unaffected. The tree hash update is guarded, because appendColumnNameImpl derives __subquery_<hash> from that hash for unnamed subqueries and an unconditional update would rename generated columns across unrelated queries. No new AST node, so dependency extraction sees nothing new; no setting; no change to any stored definition's text. Expression (IN) position is marked but deliberately not consumed. A recursive CTE cannot be an IN argument in a live query at all, since expression resolution clears is_cte before resolveUnion and the self-reference then falls through to the catalog, so there is no live behaviour for a stored definition to converge on. The reported IN shape is carried by the table-expression change anyway, because the recursive body lands in the shadowing element's FROM. The remaining live/view divergence there is pre-existing and is pinned unchanged. Reading a stored definition with enable_global_with_statement = 0 now returns rows where it used to fail with UNKNOWN_TABLE. That is what a stored plain CTE has always done, since the definition holds the expanded bodies and no longer needs an enclosing-scope lookup; the recursive case was the outlier, and an arm pins it beside its plain-CTE counterpart. 05213_recursive_cte_in_view_shadowed_by_plain_cte reads the live query and the view side by side in every arm. Five arms fail without this change: the reported repro, a UNION-bodied shadowing CTE, the IN-consumed shadowing CTE, two nesting levels, and the enable_global_with_statement = 0 read. Three controls must not move. 04350 gains the AST-JSON pair: recursive_with beside a cte_name round trips, recursive_with without one is rejected.
readJSON's non-empty-cte_name branch accepted zero children, but both query tree
builders index children[0] unconditionally when they meet a subquery in
expression position (QueryTreeBuilder.cpp:744) or in table position (:985). So
{"type":"Subquery","cte_name":"src"} aborted a debug build in
vector::operator[] and read out of bounds in a release one. The payload is
reachable because the clickhouse_json dialect executes a hand-written AST.
The invariant is the one the empty-cte_name branch already enforces: an
ASTSubquery carries exactly one child, its body. A cte_name changes only how the
node prints, to a bare identifier, never whether it has a body, so the two
branches now agree. Nothing writeJSON can emit is rejected: ParserSubquery, both
of the visitor's clones, UnionNode::toASTImpl and QueryNode::toASTImpl all
produce the child.
It ships with the recursive_with guard instead of separately because it is the
sibling branch of the same if/else, holds for the same downstream reason, and
04350's declared subject is exactly this class: a bodyless src prints as src and
then crashes.
Two in-tree statements this branch falsifies are corrected as well. 04054's
ASTSubquery JSON field catalog now lists recursive_with. 05111's note on why it
asserts the stored view definition as text no longer says the expansion side
ignores recursive_with, since it no longer does; the read-back that note declined
to assert is still wrong, for a cause this branch does not address. On a read the
enclosing plain src is substituted into the recursive member's own
self-reference, so the view returns 1 where the same text run live returns 6,
measured identical on the branch point and on this branch.
The field's comment claimed that only a marked node becomes a recursive CTE in the query tree. That is a universal claim and it is false. QueryTreeBuilder marks every UnionNode child of a WITH RECURSIVE list directly, and those nodes come from an ASTSubquery that nothing marks: no parser writes this field, only the visitor's two substitution sites and readJSON do. So the ordinary recursive CTE is recursive with the flag unset. What the flag governs is narrower, and is what the comment now says: a body the visitor copied into a CTE reference arrives at the builder in FROM position, detached from the WITH list that made it recursive, so the copy needs its own record of that. The WITH-list path is named as the case where the flag stays unset, so the sentence cannot be read as covering it. The readJSON guard's comment said both query-tree builders index children[0] unconditionally. There is one builder; the two indexings are its expression and table positions. Comments only. Preprocessed token streams of both files are identical to the previous commit, so the object code is unchanged and the round's test results stand as measured.
The comment explaining why 05111 asserts the stored view definition as text rather than by reading the view back also asserted the read-back value: that the view returns 1 and not 6. That is true on this branch and at its branch point, but it is not true everywhere the comment will live. PR ClickHouse#114908 carries commit 02cce1c, which stops expanding an enclosing plain CTE into the recursive members of a nested same-named WITH RECURSIVE. On that head the same view reads back 6, so the parenthetical becomes false the day ClickHouse#114908 merges, and nothing in this test would flag it. The value was also the wrong thing to state. What justifies asserting the definition as text is that the read-back depends on a second subsystem at all, not what that subsystem currently answers. The comment now names the dependency, which holds both before and after ClickHouse#114908. The test's SQL, its countSubstrings assertion and its reference file are unchanged.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 14 findings adjudicated across my own cold
Severity: ❌ blocker / Two things I decided rather than hid, each with a measurement attached:
Session id: cron:clickhouse-review-slot-11:20260914-214100 |
|
Workflow [PR], commit [133dfbf] Summary: ✅
AI ReviewSummaryThis PR preserves the recursive identity of CTE bodies copied into stored Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested; merge remains subject to the required CI checks completing successfully. |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 41808d9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The only other red on commit Session id: cron:our-pr-ci-monitor:20260915-023038 |
…shadowed-by-plain-cte Resolve the conflict in ApplyWithSubqueryVisitor.cpp with master's max_expanded_ast_elements budget: both substitution sites now take the copy from ExpandedASTBudget::replace and mark it with cte_name and recursive_with. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The old analyzer is gone on master: `enable_analyzer = 0` no longer selects it, so the query this arm expected to be refused now runs and succeeds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now refuses MATERIALIZED on a recursive CTE itself. A substituted copy does not carry MATERIALIZED, so marking the copy of a materialized element let it bind its own self-reference and skip that refusal: CREATE VIEW over WITH RECURSIVE src AS MATERIALIZED (...) was accepted and the view silently read the CTE unmaterialized, while the same query run directly is refused. Such a copy is now left unmarked and resolves by name as before, so the stored query is refused exactly as the live one. For a materialized element that does not reference itself the mark was inert, so nothing else changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new recursive_with byte followed an unframed cte_name, so a recursive copy named x hashed the same as a non-recursive one named x followed by byte 0x01 with the same body. Frame the name as ASTWithAlias frames the alias, and hash recursive_with inside the named branch, since it is never set without cte_name. Unnamed subqueries, whose column name derives from this hash, are unaffected. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The view's copy of a recursive element is now itself the recursive CTE, so reading `r` through the materialized view plans the same single join as the query sent without the view. Before, the copy was a plain `UNION ALL` whose second branch joined the real recursive CTE, one physical join more than the live query, and 05058's reference recorded that extra join as `2`. Measured on master `d245b78661ac` against this branch, `join_algorithm = 'hash'`: the query alone, as a SELECT and as an INSERT SELECT report 1 on both; a plain view of the scalar, a plain view of just `SELECT n FROM r` (no scalar, no materialized view) and the materialized view over 4 and 16 blocks report 2 on master and 1 here. EXPLAIN PLAN of the plain view on master is `Union(ReadFromSystemOne, Join(ReadFromRecursiveCTEStep, dim))`, here a single `ReadFromRecursiveCTEStep`, as live. The test still pins the deduplication: with `isCountedByAnEarlierBuild` forced to false it reports 20 joins (5 iterations x 4 blocks), and 80 over 16 blocks. That also shows the scalar runs once per block and not once more outside them, so the old comment's explanation of `2` is dropped with it. Co-Authored-By: Claude Opus 5.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 a
VIEWreturning only the seed row of aWITH RECURSIVECTE when a nested subquery declares a plain CTE of the same name.CREATE VIEWstores the definition with CTE references expanded into copies of their bodies, and a copy taken from aWITH RECURSIVElist carried no record of that, so its self-reference bound to the same-named plain CTE instead of to itself and only the seed row survived.Description
At defaults, no table involved:
Root cause:
ApplyWithSubqueryVisitorrewrites a CTE reference into a clone of the element's body taggedcte_name, recording nothing about the list beingWITH RECURSIVE.UnionNode::is_recursive_cte, the sole trigger for the table that binds a self-reference (QueryAnalyzer::resolveUnion), was set only for WITH children of a recursive list, so the copy's self-reference bound by name: shadowed, to the plain CTE, whose rowsWHERE id < 3discards; unshadowed, to the real CTE, which gives the right rows through one extra join, soused_number_of_joinsof a view now matches live (05058goes from 2 to 1).Fix: mark the substituted
ASTSubqueryas coming from aWITH RECURSIVElist and turn that intosetIsRecursiveCTEwhere a CTE'sUnionNodeis built. No setting, no stored-text change; same shape as #118510. The copy of aMATERIALIZEDelement stays unmarked, so a stored materialized recursive CTE is still refused, andcte_nameis length-prefixed in the tree hash so the flag cannot collide with a longer name.05213_recursive_cte_in_view_shadowed_by_plain_ctereads live and view side by side; five arms fail without the fix. Two pin reads that now match live:enable_global_with_statement = 0returns rows instead ofUNKNOWN_TABLE, as a stored plain CTE does, and a shadowed non-UNION ALLbody is refused (UNSUPPORTED_METHOD).readJSONaccepted a bodyless{"type":"Subquery","cte_name":"src"}, which then readchildren[0]out of bounds (experimentalenable_json_ast_dialectonly). It now requires exactly one child, as 8e6d703 did for the empty-cte_namebranch.Not addressed: a recursive CTE as
IN's right argument still diverges live (UNKNOWN_TABLE) versus stored;WITH RECURSIVE t(x) AS (...)in a view still failsCode: 47, as plaint(x)does.Workflow [PR]
Sync PR [sync-upstream/pr/120089]
Workflow [PR]
Sync PR [sync-upstream/pr/120089]