Repository navigation
Support materialized CTEs in recursive WITH - #123452
alexey-milovidov merged 13 commits into
Conversation
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]>
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
|
🕵 @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 |
|
Workflow [PR], commit [7acaccb] Summary: ✅
AI ReviewSummaryThis PR allows Final Verdict
LLVM Coverage ReportMeasured on commit 7acaccb.
Changed lines: Changed C/C++ lines covered: 69/69 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes13 object files changed (+32.41 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units26 translation units recompiled, 142 s compile time in total, 26 of them have a recent master baseline. |
Supersedes #107069 by @ArctypeZach, keeping the author's original commits. The original branch is in a fork and became
CONFLICTINGwithmaster. The conflict is resolved here (cte_name_to_query_nodenow maps toQueryTreeNodes, andcte_definitions_in_resolve_processis tracked alongsidectes_in_resolve_process). The resolution could not be pushed to the fork because mergingmasterbrings.github/workflowschanges, which needs a token with theworkflowscope.Related: #107069
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Allow
MATERIALIZEDcommon table expressions inside recursiveWITH. 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
MATERIALIZEDCTE insideWITH RECURSIVEis currently rejected(
UNSUPPORTED_METHOD,QueryTreeBuilder.cpp). But a plainSELECTCTE can never be the recursivemember — 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: rejectMATERIALIZEDonly for union-shaped (potentially recursive) CTEs, with aclearer message; allow it for plain
SELECTCTEs. 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.
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
26.10.1.1360-master(included in26.10and later)