Skip to content

Fix materialized CTE self-reference in set operation - #110428

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-self-name-set-operation
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-self-name-set-operation

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110176

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

Fixes two errors when a materialized CTE is named identically to a base table it reads inside its own body: a LOGICAL_ERROR (Reading from materialized CTE before its materialization completed - DelayedPortsProcessor gate is missing) when the body is a set operation, e.g. WITH test1 AS MATERIALIZED ((SELECT i FROM test1) EXCEPT ALL (SELECT i FROM test1)) SELECT 4 AS i WHERE i IN (test1), and TOO_DEEP_SUBQUERIES when the CTE is referenced twice, e.g. WITH test1 AS MATERIALIZED (SELECT i FROM test1) SELECT count() FROM test1, test1 AS t2.

Description

Found by the AST fuzzer (STID 2467-2c2d), still live on master. A distinct, non-EXPLAIN ANALYZE manifestation of the DelayedPortsProcessor gate is missing site.

A materialized CTE named the same as a base table it reads inside its own body must bind that self-reference to the base table (recursive CTEs are not supported here), exactly like a non-materialized CTE. The guard in tryResolveIdentifierFromCTE tests the node stored in scope.cte_name_to_query_node against ctes_in_resolve_process, so only that node works as a guard.

The guard has three call sites, and two were passing the wrong node or none at all:

  1. The expression path in resolveExpressionNode inserted the freshly cloned TableNode placeholder, which the guard never looks up. With a set-operation body the guard did not fire on the second branch, so FROM test1 there bound to the still-unmaterialized CTE and the plan read its StorageMemory with no DelayedPortsProcessor gate, tripping the fail-fast in ReadFromMemoryStorageStep.

  2. The reused-reference branch of resolveQueryJoinTreeNode (taken when another reference already created the storage) resolves this clone's own unresolved copy of the body but inserted nothing. A body reference bound back to the CTE, re-entered the same branch and recursed until TOO_DEEP_SUBQUERIES. Reaching it needs two consumers, not a set operation, which is why the first version of the test did not cover it; found by the AI reviewer on this PR.

Both now insert the cte_name_to_query_node node. The scope walk that finds it was duplicated per site and is now findCTENodeInScopes, so the three sites cannot drift apart again.

Verified against the non-materialized CTE as an oracle, plus a plan assertion that the CTE really is materialized. Genuine recursive CTEs are still rejected. No performance impact: this only changes which node a set insert/erase uses during name resolution.


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

groeneai and others added 2 commits July 14, 2026 17:57
A materialized CTE named identically to a base table it reads inside its
own body must bind that self-reference to the base table (recursive CTEs
are not supported here). The self-reference guard in QueryAnalyzer checks
the node stored in cte_name_to_query_node, but the materialized-CTE
expression path inserted the TableNode placeholder/clone into
ctes_in_resolve_process, which the guard never sees. When the CTE body is
a set operation, a later branch then self-referenced the still
unmaterialized CTE, producing a read with no DelayedPortsProcessor gate
and a LOGICAL_ERROR (STID 2467-2c2d). Insert the cte_name_to_query_node
node instead, matching the sibling resolveQueryJoinTreeNode path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE test1 (i Int64, j Int64) ENGINE=Memory; INSERT INTO test1 SELECT number,number FROM numbers(100); SET enable_materialized_cte=1; WITH test1 AS MATERIALIZED ((SELECT i FROM test1) EXCEPT ALL (SELECT i FROM test1)) SELECT 4 AS i WHERE i IN (test1); aborts the server on the first run (single-threaded, no EXPLAIN ANALYZE).
b Root cause explained? A materialized CTE named the same as a base table it reads in its body must self-bind to the base table (recursive CTEs unsupported). The guard in tryResolveIdentifierFromCTE checks the node in scope.cte_name_to_query_node against ctes_in_resolve_process, but the materialized-CTE expression path inserted the cloned TableNode placeholder (which the guard never looks up). With a set-operation body the guard didn't fire on the second branch, so FROM test1 bound to the unmaterialized CTE → a StorageMemory read with no DelayedPortsProcessor gate → fail-fast at ReadFromMemoryStorageStep.cpp:87.
c Fix matches root cause? Yes. Insert the cte_name_to_query_node node (the exact node the guard checks, found by walking scopes) into ctes_in_resolve_process instead of the placeholder clone — mirroring the already-correct sibling path in resolveQueryJoinTreeNode.
d Test intent preserved / new tests added? New regression test 04545_materialized_cte_self_name_in_set_operation added, covering EXCEPT ALL / UNION ALL / INTERSECT bodies, the original 2-column DISTINCT fuzzer shape, and a correctness assertion (materialized result == non-materialized result = 200).
e Both directions demonstrated? Yes. Pristine binary (Build ID 46AED3AC): test aborts with DelayedPortsProcessor gate is missing. Patched binary (Build ID 45C2EE32, merged master): test passes with correct results.
f Fix is general across code paths? Yes. The sibling materialized-CTE path (resolveQueryJoinTreeNode) already guards the cte_name_to_query_node node correctly; this makes the expression path (resolveExpressionNode) consistent with it. The non-materialized CTE path also inserts the original map node.
g Fix generalizes across inputs? Verified across set-operation kinds (UNION ALL, EXCEPT ALL, INTERSECT), single- vs multi-column IN, with/without DISTINCT, and the correctness path (result matches non-materialized). Chained q->b->a WITH TOTALS and non-shadowing CTEs remain correct.
h Backward compatible? Yes. Pure name-resolution correctness fix; no setting, format, or default change. It only makes self-referencing set-operation CTE bodies bind to the base table (as they already do for non-materialized CTEs and single-branch materialized bodies).
i Invariants and contracts preserved? Yes. Restores the ctes_in_resolve_process guard invariant (a CTE cannot resolve to itself while its own body is being resolved) for the materialized set-operation path. Existing materialized-CTE stateless tests (03801/03821/04042/04057/04227/04228/04259/04295/04148 and the rest of the materialized_cte suite) verified to still produce correct output.

Session id: cron:clickhouse-worker-slot-0:20260714-172500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review this? It fixes a materialized-CTE self-reference name-resolution bug (STID 2467-2c2d, still live on master): when a materialized CTE is named the same as a base table it reads and its body is a set operation, the ctes_in_resolve_process guard was fed the cloned TableNode placeholder instead of the cte_name_to_query_node node the guard checks, so a later set-op branch self-bound to the unmaterialized CTE and read its StorageMemory with no DelayedPortsProcessor gate. Fix inserts the map node (matching the sibling resolveQueryJoinTreeNode path).

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8a99f4e]

Summary: ✅


AI Review

Summary

The change fixes materialized CTE self-binding in expression-level set operations. The earlier two-consumer finding is also fixed in the current code. Test 04545_materialized_cte_self_name_in_set_operation passes with output matching its reference on the fast-test binary for head 8a99f4ead61c4a47b884b24f44324c7b850d94c8. One acknowledged scope-shadowing defect remains; no new inline findings were identified.

Findings

❌ Blockers

  • src/Analyzer/Resolve/QueryAnalyzer.cpp:6171: The guard can hide a different CTE definition. [dismissed by author -- https://github.com/Fix materialized CTE self-reference in set operation #110428#discussion_r3669894934] The author deferred this as pre-existing, but the current name-only lookup still selects an inner, already-hidden definition when resolution actually selected an outer materialized CTE. The outer definition remains visible inside its own body, causing valid queries to recurse until TOO_DEEP_SUBQUERIES. The equivalent lookup at lines 7146–7156 has the same problem.

    With a Memory table t(i UInt64) containing 1 and 2, this fails with code 162 on the current head:

    WITH t AS MATERIALIZED (SELECT i FROM t)
    SELECT count()
    FROM (WITH t AS (SELECT i FROM t) SELECT i FROM t)
    SETTINGS enable_materialized_cte = 1;

    Replacing AS MATERIALIZED with AS returns 2. An expression-level variant and two shadowed consumers also fail with code 162; their inlined oracles return 1 and 4. Preserve the selected definition's identity through cloning and guard that definition at every materialized reference site. If deliberately deferred, link a public tracking issue for these shadowing cases; the discussion currently names an internal task without an issue link. Keep this point in the summary only, respecting the author's scope decision.

Missing context / blind spots
  • ⚠️ Full CI and functional bugfix validation for the latest head are still running or pending. The focused local checks used that head's published fast-test binary; completed CI reports would close the remaining validation gap.
Final Verdict

⚠️ Request changes. Fix and cover the shadowing case, or link an issue explicitly tracking the deferred defect. The previously resolved two-consumer thread should remain resolved; no duplicate inline comment or thread reply is warranted.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cd7050b

CI fully finished on this HEAD (Finish Workflow + Mergeable Check pass; only CH Inc sync pending, which is exempt). CIDB shows ZERO FAIL/ERROR test rows at this commit.

Check / test Reason Owner / fixing PR
(none) — —
Sync — CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260714-233000

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
groeneai added 5 commits July 29, 2026 01:52
The self-reference guard has three call sites: the expression path in
resolveExpressionNode and, in resolveQueryJoinTreeNode, the first-reference
branch (which creates the storage) and the reused-reference branch (which
resolves this clone's own copy of the body and reuses the existing storage).
Only the first two inserted the CTE into ctes_in_resolve_process.

The reused-reference branch resolves an unresolved body, so it needs the guard
too. Without it, a body reference such as `FROM test1` inside a CTE named
`test1` binds back to the CTE instead of the base table. Because the shared
storage is already initialized, that nested clone takes the same branch again
and recurses until TOO_DEEP_SUBQUERIES, so a query with two consumers of one
self-named materialized CTE failed outright:

    WITH test1 AS MATERIALIZED ((SELECT i FROM test1) UNION ALL (SELECT i FROM test1))
    SELECT count() FROM test1, test1 AS t2;

A set operation in the body is not required to reach the branch - two
consumers are enough. A single consumer never reaches it, which is why the
existing test did not cover this.

The scope walk that finds the cte_name_to_query_node entry was duplicated at
each site; it is now findCTENodeInScopes, so the three sites cannot drift
apart again.

Reported by the AI reviewer on ClickHouse#110428.
The two-consumer counts are compared against a non-materialized CTE, so on
their own they would also pass if the CTE were inlined instead of materialized.
Assert the `MaterializingCTE` plan step is present first; with
`enable_materialized_cte = 0` that assertion yields 0, so it discriminates.

Also call the failure an exception rather than a crash - it is a thrown
`LOGICAL_ERROR`, handled normally in release builds - and wrap the diagnostic
names in inline code blocks.
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 42/43 (97.67%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 630aa25

Every failure below has an owner: a fixing PR (ours 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_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the per-table concurrency throttle the test asserts is keyed on query id, and secondary parallel-replicas reads are sent without one, so the holder query competes against itself (3/3 reruns, deterministic) #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-120000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

The same invariant is broken at two more sites, and the four sites cannot be split across two PRs

This PR fixes the materialized-CTE self-reference guard at resolveExpressionNode (:3219) and at the reused-reference branch of resolveQueryJoinTreeNode (:5906). While preparing a separate change for the shadowing route, I measured that the same invariant is broken at two further points, and that no partition of the four sites into two pull requests is both complete and conflict-free. I am not pushing anything here; this is the measurement, so you can decide the shape.

The invariant. tryResolveIdentifierFromCTE (:1321) tests ctes_in_resolve_process.contains(cte_query_node_it->second) -- the map's own node. So whatever arms the guard must insert that exact node. 905908415072c3e established this and added cte_copy_to_original_map for it; the QUERY/UNION arm at :5817 still does it correctly via try_get_original_cte_node. The materialized path re-derives the node by walking scopes by name from the referencing scope (:5848-5857), so a same-named CTE in a descendant scope is the nearest match and the outer entry is never inserted.

Four carrier classes, measured on four debug binaries. Each arm asserts SELECT lower(buildId()) equals its readelf -n build id before any verdict, and every case is paired with its non-materialized oracle (AS instead of AS MATERIALIZED).

carrier example this PR name-walk replaced by node lookup at :5848 + map widening both
IN (cte), set-operation body this PR's own 04545 first query fixed LOGICAL_ERROR, gate missing fixed
two references FROM c AS l JOIN c AS r fixed Code: 162 fixed
descendant re-declaration, first reference WITH t AS MATERIALIZED (SELECT i FROM t) SELECT count() FROM (WITH t AS (SELECT i FROM t) SELECT i FROM t) Code: 162 fixed fixed
both at once two references and a descendant re-declaration Code: 162 Code: 162 fixed

The last row is the one that matters: five independent shapes of it (JOIN of two shadowed subqueries; one plain reference joined with a shadowed one, both orders; two scalar subqueries; a comma join plus a shadowed IN) return Code: 162 on both this PR and a change that fixes only :5848, and return the oracle value only when :5848 and :5906 are both keyed on the map node. So those two sites are jointly load-bearing, not alternatives.

Why it cannot be two PRs. :5848 is 11 lines that this PR rewrites into findCTENodeInScopes(cte_name, scope) and the other change deletes in favour of try_get_original_cte_node(join_tree_node) -- two different intents on one block. git merge-tree --write-tree --merge-base=cd6fd72e2b29fa60 returns a content conflict in QueryAnalyzer.cpp in both directions, and it still conflicts after removing every overlapping line except :5848 itself. A pull request based on a feature branch gets no CI, so stacking is not an option either.

The complete fix is the four sites keyed uniformly on the map node: :3219 (this PR), :5848 (name walk to try_get_original_cte_node), :5906 (this PR), plus widening cte_copy_to_original_map's producer at :4208 so a materialized CTE's TableNode clone is registered -- a materialized CTE arrives at initializeQueryJoinTreeNode as a TableNode and currently falls into the arm that registers nothing. That widening is not cosmetic: without it the key is always null, the guard arms for no materialized CTE at all, and three cases that pass today start failing -- strictly worse than the bug. The map's only existing consumer is read in the QUERY/UNION arm, which a TableNode cannot enter, so the widening is additive.

Two options, both of which touch this PR, so the call is yours:

  1. Extend this PR to all four sites, keyed uniformly. Its title and description already describe this invariant, and its 04545 test stays valid; three shapes would be added.
  2. Keep this PR as it is and replace it later with a single change covering all four. Higher friction, and the shadowing and combined carriers stay broken meanwhile.

I have a validated 31-case matrix (carriers, non-materialized oracles, seven controls, a materialization assertion, and a check that WITH RECURSIVE ... AS MATERIALIZED is still rejected), plus two mutation arms proving each edit is independently load-bearing. Happy to produce either shape.

Everything above is behind enable_materialized_cte, which is experimental and off by default. Nothing here is a regression of this PR: the two extra sites are broken on master today.

Session id: cron:clickhouse-plan-slot-1:20260805-071502

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
…e-self-name-set-operation

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8a99f4ead with master f30d7ec4f (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

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

Job report

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-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants