Skip to content

Fix a view returning only the seed row when a recursive CTE is shadowed by a same-named plain CTE - #120089

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:recursive-cte-view-shadowed-by-plain-cte
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:recursive-cte-view-shadowed-by-plain-cte

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 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 a VIEW returning only the seed row of a WITH RECURSIVE CTE when a nested subquery declares a plain CTE of the same name. CREATE VIEW stores the definition with CTE references expanded into copies of their bodies, and a copy taken from a WITH RECURSIVE list 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:

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

SELECT id FROM v;  -- 10, not 10, 20, 30

Root cause: ApplyWithSubqueryVisitor rewrites a CTE reference into a clone of the element's body tagged cte_name, recording nothing about the list being WITH 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 rows WHERE id < 3 discards; unshadowed, to the real CTE, which gives the right rows through one extra join, so used_number_of_joins of a view now matches live (05058 goes from 2 to 1).

Fix: mark the substituted ASTSubquery as coming from a WITH RECURSIVE list and turn that into setIsRecursiveCTE where a CTE's UnionNode is built. No setting, no stored-text change; same shape as #118510. The copy of a MATERIALIZED element stays unmarked, so a stored materialized recursive CTE is still refused, and cte_name is length-prefixed in the tree hash so the flag cannot collide with a longer name.

05213_recursive_cte_in_view_shadowed_by_plain_cte reads live and view side by side; five arms fail without the fix. Two pin reads that now match live: enable_global_with_statement = 0 returns rows instead of UNKNOWN_TABLE, as a stored plain CTE does, and a shadowed non-UNION ALL body is refused (UNSUPPORTED_METHOD).

readJSON accepted a bodyless {"type":"Subquery","cte_name":"src"}, which then read children[0] out of bounds (experimental enable_json_ast_dialect only). It now requires exactly one child, as 8e6d703 did for the empty-cte_name branch.

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 fails Code: 47, as plain t(x) does.


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


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

…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
passes and the gate; 3 fix rounds). The final pass, on the tree published here, returned none.

# Sev Finding Verdict Evidence / action
1 ❌ ASTSubquery::readJSON accepts a cte_name subquery with no body, and the query tree builder indexes children[0] unconditionally in both expression and table position (QueryTreeBuilder.cpp:745, :985) AGREE, fixed @ 3d1e9738318d5 Reproduced from the clickhouse_json dialect: a debug build aborts in vector::operator[], a release build reads out of bounds. Pre-existing and independent of the new field, but it is the sibling branch of the guard this PR adds, so it is fixed here: that branch now requires exactly one child, with a reacting arm in 04350 (the branch point prints src, this branch raises BAD_ARGUMENTS). Four round trips confirm nothing writeJSON emits is rejected
2 ⚠️ The 04350 recursive_with arms inject the field into already-serialized JSON, so writeJSON and the tree hash update have no oracle DISAGREE The negative arm reacts (it fails on the branch-point binary, which ignores the unknown field). No SQL path can hand writeJSON a marked node: the flag is set only by ApplyWithSubqueryVisitor, and parseQueryToJSON serializes a freshly parsed AST. Both statements exist to satisfy gtest_tree_hash_completeness.cpp's stated contract, so the only test that could distinguish them is a hand-built-AST gtest
3 ⚠️ The PR body claimed the WITH RECURSIVE t(x) Code: 47 defect was pinned by an arm; no such arm exists AGREE, fixed in the body Verified: every view in the new test uses src AS. The claim is removed rather than an arm added for a pre-existing defect with a different root cause
4 ⚠️ ASTSubquery.h claimed "only a marked node becomes a recursive CTE in the query tree" AGREE, fixed @ 86416e68acaaa False as written. Counting the setters: QueryTreeBuilder.cpp:212 and :257 mark from the new field, but :374 marks every UnionNode child of a WITH RECURSIVE list directly, and those are built from an unmarked ASTSubquery, since no parser sets the field. The comment is rescoped to substituted copies; preprocessed token streams are identical, so the object code is unchanged
5 💡 Two in-tree statements this change falsifies: the ASTSubquery JSON field catalog in 04054, and a sentence in 05111 saying the visitor "does not consult recursive_with at all" AGREE, fixed @ 3d1e9738318d5 Both corrected, the 05111 read-back measured on both binaries first rather than inferred
6 ⚠️ The replacement 05111 comment then asserted a read-back value (1, not 6) as current behaviour AGREE, fixed @ 41808d979ef08 True on this branch, but not on #114908, where 02cce1ce285b stops expanding an enclosing plain CTE into the recursive members of a nested same-named WITH RECURSIVE and that fixture reads back 6. A test comment should not pin a value another open PR changes, so it now names the dependency the textual assertion is avoiding. The test's SQL, assertion and reference are untouched

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding.

Two things I decided rather than hid, each with a measurement attached:

  1. setIsRecursiveCTE is set at both union builders, and the one at buildSelectIntersectExceptQuery cannot
    be reached by any results-or-error-code oracle: a self-referencing INTERSECT/EXCEPT recursive CTE is
    refused whether or not the copy is marked, and a non-self-referencing one makes the mark inert. The same holds
    for the mark set at the IN substitution site, since expression position discards it. I kept both, because
    the WITH-list path marks every UnionNode child of a recursive list and I would rather not have the FROM path
    mark a smaller set for no stated reason. Removing either is a one-line change with no measured behaviour
    delta, so say the word if you prefer that.
  2. A recursive CTE as the right argument of IN still diverges: UNKNOWN_TABLE live, rows from a stored
    definition. I left it alone because there is no live behaviour for a stored definition to converge on, and
    pinned both sides in a test arm instead of changing them. If you want that carried, I will do it as its own
    PR.

Session id: cron:clickhouse-review-slot-11:20260914-214100

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

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [133dfbf]

Summary: ✅


AI Review

Summary

This PR preserves the recursive identity of CTE bodies copied into stored VIEW definitions, so a nested plain CTE with the same name no longer makes the view return only the seed row. It also rejects bodyless named ASTSubquery nodes during JSON deserialization and updates regression coverage and the expected join count. No actionable findings remain on head 133dfbf39d61ad0445d720da407e1ebe6b9d87cd.

Missing context / blind spots
  • ⚠️ No local build or test execution was available. At review time, the current head's Fast test had passed, while builds and functional bugfix validation were still incomplete. Completed results for the added 05213 regression test, the modified 04350 JSON validation test, and 05058 would close this runtime validation gap. See the current-head CI report.
Final Verdict

Status: ✅ Approve. No code changes requested; merge remains subject to the required CI checks completing successfully.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 133dfbf39d61ad0445d720da407e1ebe6b9d87cd was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 41808d9

Every failure below has an owner: a fixing PR (mine 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
Stateless tests (amd_debug, parallel) / 05182_join_order_conflict_detector_cast_null_propagation flaky, and not reachable from this diff: clickhouse-test randomizes auto_statistics_types, and any subset that leaves basic out gets the optimizer its own estimate, which costs the join the other way and leaves both reassociation arms not reassociating #120084 (external, open)
Mergeable Check, PR (rollup statuses) derived, they mirror the single red job above and carry nothing independent #120084 (external, open)

The only other red on commit 41808d97 is the Finish Workflow of workflow run 94515067620, the duplicate PR run cancelled three minutes after publish when the can be tested label landed; its 171 sibling check-runs are cancelled, and the live run 94515041141 closed Finish Workflow green at 02:07:11Z. CH Inc sync is green. Both Bugfix validation (functional tests, *) jobs passed: the 05111_recursive_cte_union_branch_propagation and 04054_ast_json_serialization rows CIDB records inside them are the master-side failures that check exists to observe, which is why it is green.

Session id: cron:our-pr-ci-monitor:20260915-023038

groeneai and others added 5 commits October 14, 2026 12:19
…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]>

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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant