Skip to content

Support materialized CTEs in recursive WITH - #123452

Merged
alexey-milovidov merged 13 commits into
masterfrom
continue-pr-107069-materialized-cte-recursive-with
Oct 3, 2026
Merged

alexey-milovidov merged 13 commits into
masterfrom
continue-pr-107069-materialized-cte-recursive-with

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Supersedes #107069 by @ArctypeZach, keeping the author's original commits. The original branch is in a fork and became CONFLICTING with master. The conflict is resolved here (cte_name_to_query_node now maps to QueryTreeNodes, and cte_definitions_in_resolve_process is tracked alongside ctes_in_resolve_process). The resolution could not be pushed to the fork because merging master brings .github/workflows changes, which needs a token with the workflow scope.

Related: #107069

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Allow MATERIALIZED common table expressions inside recursive WITH. A materialized helper CTE is evaluated once and every recursive step reads the snapshot, instead of the subquery being re-evaluated on each iteration. The recursive CTE itself still cannot be materialized.


Problem. Any MATERIALIZED CTE inside WITH RECURSIVE is currently rejected
(UNSUPPORTED_METHOD, QueryTreeBuilder.cpp). But a plain SELECT CTE can never be the recursive
member — only union-shaped CTEs are (speculatively) marked recursive — so the blanket rejection
unnecessarily forbids the most useful pattern for recursive queries over large tables: materializing a
filtered search space once and iterating over the snapshot.

Without it, a helper CTE referenced from a recursive member is re-planned and re-executed on every
recursion step
(each step builds a fresh interpreter). Measured on a graph-search workload: a
12M-row region-filter subquery referenced inside the recursive member was re-evaluated ~450 times,
costing 5.3B rows read for a query whose useful working set was a few million rows.

Change.

  • QueryTreeBuilder: reject MATERIALIZED only for union-shaped (potentially recursive) CTEs, with a
    clearer message; allow it for plain SELECT CTEs. The existing materialized-CTE machinery
    (future-table built once before the main plan; per-step inner planners skip already-built CTEs via
    hasPlanOrBuilt()) handles the rest with no executor changes.

Usage.

WITH RECURSIVE corridor AS MATERIALIZED
(
    SELECT u, v, w FROM edges WHERE <expensive spatial/region filter>
),
search AS
(
    SELECT ... UNION ALL SELECT ... FROM search JOIN corridor ON ...
)
SELECT ... FROM search;

Tests. 04327_materialized_cte_in_recursive_with: materialized helper feeding a recursive member
(scalar IN and JOIN forms), and the negative case (materializing the recursive CTE itself still throws).
Full recursive-CTE stateless suite passes.

Part of the keyed-recursion work tracked in #107067 (PR 2 of 3).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1360-master (included in 26.10 and later)

ArctypeZach and others added 13 commits June 10, 2026 15:56
Previously any MATERIALIZED CTE inside WITH RECURSIVE was rejected. Only the
recursive CTE itself (union-shaped, speculatively marked recursive) cannot be
materialized; plain SELECT helper CTEs can never be recursive, so allow them.
They materialize once via the existing future-table machinery and every
recursive step reads the snapshot instead of re-evaluating the subquery per
step, which is the natural way to pre-filter a search space for a recursive
traversal (e.g. a road-graph corridor for a shortest-path search).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
(cherry picked from commit 83b1529)
`enable_materialized_cte` is `false` by default, so without setting it the test
only checked that the queries are accepted - `AS MATERIALIZED` was a no-op and
nothing was materialized.

Set `enable_materialized_cte = 1` and add two cases:
- a materialized helper referenced from the non-recursive (anchor) member is
  evaluated once, so a non-deterministic subquery contributes exactly as many
  distinct values as it has rows across all recursion steps;
- a materialized CTE reading the recursive CTE.
A `MATERIALIZED` helper CTE referenced only from the recursive member of a
recursive CTE was converted to a materialized `TableNode` by the analyzer,
but `inlineMaterializedCTEIfNeeded` inlined it again because it keeps only
CTEs with at least two static reference sites. The recursive member is one
site, yet `RecursiveCTESource` re-plans and re-executes it once per step,
so the helper was re-evaluated on every step and `MATERIALIZED` was a
silent no-op in exactly the shape this PR advertises.

Flag such CTEs in `QueryAnalyzer::resolveUnion`, once the CTE is known to
be recursive, and treat the flag as reuse in the inlining pass. The
snapshot is taken before the recursion starts, while the working table is
still empty, so a materialized CTE that reads the recursive CTE from
inside a recursive member is rejected with `UNSUPPORTED_METHOD` instead of
snapshotting an empty table.

Make the test observable for the recursive-member-only shape: count the
`MaterializingCTE` plan steps and check that a `rand64()` helper
contributes exactly as many distinct values as it has rows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The first reference to a materialized CTE resolves its subquery and throws
`UNSUPPORTED_METHOD` if the subquery is correlated. A subsequent reference
re-resolves its own clone of the subquery in the scope of that reference
site, where an identifier may bind to an outer column even though it did
not at the first site, and that path had no such check. The correlated
clone was then planned with a `PLACEHOLDER` action and execution failed
with a logical error.

Found by the AST fuzzer on this PR with a helper referenced from both the
anchor and the recursive member: in the anchor the identifier resolved to
a constant alias, in the recursive member to a column of the recursive CTE.
Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107069&sha=645044925ee410e7d30df49aa3f7b76ee7379a0f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: #107069
Related: #105501

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… to be recursive

The check in `QueryTreeBuilder` fired for every union-shaped `WITH`
element of a recursive `WITH`, so a helper CTE written as a `UNION` that
never references itself was rejected as "the recursive CTE itself", even
with `enable_materialized_cte = 0` where `MATERIALIZED` is only a hint.
Whether a CTE references itself is only known after analysis, so move the
check to `QueryAnalyzer::resolveUnion`, next to the other checks that run
once the CTE is confirmed to be recursive.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The guard for a materialized CTE that reads the recursive CTE's working
table ran only once the CTE was confirmed recursive, after type widening.
When widening re-resolved the recursive member, the second reference to
the materialized CTE found the storage created by the first pass with the
old column types and failed with `TYPE_MISMATCH` before the guard was
reached. Check right after each member is resolved instead, so the
intended `UNSUPPORTED_METHOD` is reported.
Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107069&sha=68398b08ec1ea1c8cbd5b2d66f1a570d3d07cc47&name_0=PR&name_1=Fast%20test
PR: #107069

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…chor-only case

Propagating `is_referenced_from_recursive_cte_member` to the canonical CTE
before adoption was dead code: a merge target is counted at least twice,
so it is retained by the use count alone. Shorten the comments on the flag
and drop the one in `QueryTreeBuilder`. State next to the flagging loop
that the non-recursive member is skipped, and add a test showing that a
helper referenced only from the anchor stays inlined.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…reference

The `WITH` reference still said that a single-use materialized CTE is
always inlined and that `MATERIALIZED` is not supported together with
`RECURSIVE`. Describe the new behaviour: a helper referenced from a
recursive member is kept and evaluated once before the recursion, and only
the recursive CTE itself cannot be materialized.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…rence site

The first reference to a materialized CTE resolved its body with the CTE
hidden through `ctes_in_resolve_process`, so that inside the body the
CTE's own name refers to a table of that name. A subsequent reference
re-resolves its own clone of the body without hiding the name, so the
clone bound the name to the CTE itself and recursed through the reference
resolution instead of reading the table. Hoist the lookup of the CTE map
node and hide the name in both branches.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ialized-with

# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
#	src/Parsers/ParserWithElement.cpp
…ialized-with

# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
@alexey-milovidov alexey-milovidov added pr-improvement Pull request with some product improvements comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). can be tested Allows running workflows for external contributors labels Oct 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @novikd, your four review threads on #107069 were addressed by the author in that PR before this one superseded it, and the code here includes those changes: the redundant flag set in inlineMaterializedCTEIfNeeded.cpp was removed, the comments in QueryTreeBuilder.cpp and MaterializedCTE.h were removed or shortened, and the recursive-member loop in QueryAnalyzer::resolveUnion starts at i = 1, so a materialized CTE that is referenced only from the non-recursive member (queries_nodes[0]) is still inlined. The test checks this case with EXPLAIN.

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7acaccb]

Summary: ✅


AI Review

Summary

This PR allows MATERIALIZED helper CTEs inside WITH RECURSIVE, keeps helpers referenced from recursive members materialized across recursive steps instead of inlining them, rejects the unsafe case where such a helper would snapshot the recursive working table, and updates both documentation and stateless coverage around the new behavior. I do not see a remaining correctness, safety, or contract issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7acaccb.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 69/69 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7acaccb4b with master a200f3b9a (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.

Object file sizes

13 object files changed (+32.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.49 MiB 1.52 MiB +30.21 KiB (+1.97%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit 26adb30 Oct 3, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the continue-pr-107069-materialized-cte-recursive-with branch October 3, 2026 00:19
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-improvement Pull request with some product improvements 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