Repository navigation
Support materialized CTEs in recursive WITH - #107069
ArctypeZach wants to merge 12 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)
|
Workflow [PR], commit [fedd96c] Summary: ✅
AI ReviewSummaryThe PR relaxes Missing context / blind spots
Final Verdict✅ No new inline findings for the current code. One older bot thread about the LLVM Coverage ReportMeasured on commit fedd96c.
Changed lines: Changed C/C++ lines covered: 68/68 (100.00%) · Uncovered code |
|
Dear @ArctypeZach, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message. |
|
@rschu1ze, please review. |
`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.
|
🕵 Merged The test did not exercise materialization at all
With the setting on,
|
| shape | materializations |
|---|---|
helper referenced only from the recursive member (this PR's test case 1, IN) |
0 |
helper referenced only from the recursive member (this PR's test case 2, JOIN) |
0 |
| helper referenced from the anchor (non-recursive) member | 1 |
| helper referenced from the outer query as a table | 1 |
So in exactly the pattern the description showcases, nothing is materialized: the subquery is re-planned and re-executed on every recursion step. Two independent confirmations:
- Cost scales linearly with recursion depth. With a helper that scans
numbers(30000000): depth 3 → 1.20 s, depth 9 → 3.58 s (≈ one full scan per step). - The snapshot is not stable. With
h AS MATERIALIZED (SELECT rand64() AS r FROM numbers(3))referenced only from the recursive member,uniqExactover the values seen across steps grows as1 + 3 × (steps − 1)(7 at depth 3, 25 at depth 9) instead of staying at 3 — each step sees fresh random rows.
EXPLAIN QUERY TREE shows why: in that shape the reference stays an ordinary inlined CTE subquery —
QUERY id: 20, alias: __table6, is_subquery: 1, is_cte: 1, is_materialized: 1, cte_name: h
— whereas when it is also referenced from the anchor or the outer query it is converted into a materialized-CTE TableNode (temporary_table_name: _materialized_cte_h_…, with a MATERIALIZED CTE SUBQUERY child), and then every recursive step correctly reads the snapshot. The conversion in QueryAnalyzer::tryResolveIdentifierFromCTE does not fire for a reference that only occurs inside the recursive member, so the existing machinery is never engaged and there are no per-step savings.
Why this matters
Master's blanket UNSUPPORTED_METHOD is fail-closed. Relaxing it as-is means a user writing AS MATERIALIZED inside WITH RECURSIVE gets the keyword silently ignored for the most natural pattern: no performance benefit, and — observably, with any non-deterministic expression — a different snapshot per iteration. That is a semantic guarantee quietly not honoured rather than an error.
I did not change the analyzer: making the recursive-member-only reference resolve to a materialized-CTE TableNode is a design decision I do not want to make unilaterally on someone else's PR. Two options as I see them:
- Make it work: extend the materialized-CTE conversion so a reference occurring only inside a recursive member is materialized before the recursion starts. The rest already works — once the CTE is materialized up front, the per-step interpreters observe
hasPlanOrBuilt()and read the snapshot (verified with the anchor-reference shape). - Keep the guard honest: only allow
MATERIALIZEDwhere the snapshot semantics actually hold, and keep throwing otherwise, so nothing is silently ignored.
@rschu1ze @alexey-milovidov @ArctypeZach — which way should this go? The branch is merged with master, tests strengthened and pushed, so it is ready for CI either way.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+31.87 KiB total), 0 added.
716 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 units25 translation units recompiled, 129 s compile time in total, 25 of them have a recent master baseline. |
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: ClickHouse#107069 Related: ClickHouse#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]>
|
Thanks for digging into this, @alexey-milovidov. The observation is right and I went with option 1, but one correction to the mechanism, because it changes where the fix has to live. What actually happens
The inlined subquery keeps Fix (1221527)
Nothing else is needed. The outer planner collects the CTE through the recursive union, hoists a The two AST fuzzer failures were caused by this PR
One more review itemThe builder-level check rejected every union-shaped All of the above is from reading the code; I do not have a local build right now, so CI is the verification. |
| candidates.push_back(table_node); /// first encountered = canonical (deterministic) | ||
| else if (canonical->getMaterializedCTE() != table_node->getMaterializedCTE()) | ||
| { | ||
| canonical->getMaterializedCTE()->is_referenced_from_recursive_cte_member |
There was a problem hiding this comment.
This operation is not needed, because CTE is already reused and will be materialized (not inlined)
There was a problem hiding this comment.
Agreed, removed in the latest commit. A merge target was already counted once when it became the canonical and is counted again after the adoption, so it is retained by the use count alone; the flag only matters for a CTE whose single reference site is inside a recursive member, where no merge happens.
| union_node_typed.getCTEName(), | ||
| scope.scope_node->formatASTForErrorMessage()); | ||
|
|
||
| table_node->getMaterializedCTE()->is_referenced_from_recursive_cte_member = true; |
There was a problem hiding this comment.
You don't check in which branch the materialized CTE is used. It does not make sense to materialize if it is only used in the init branch.
There was a problem hiding this comment.
The branch is checked by the loop bound: for (size_t i = 1; ...) skips queries_nodes[0], which is the non-recursive term (auto & non_recursive_query = queries_nodes[0] above; RecursiveCTESource runs [0] once and [1..] on every step). A MATERIALIZED helper referenced only from the init branch is never flagged, so it keeps a use count of one and inlineMaterializedCTEIfNeeded inlines it as before. The flag is set only when a reference site is under a recursive member, where inlining would re-execute the subquery on every step.
I agree it was easy to miss with the guard sitting between the loop header and the assignment. The guard has since moved into the widening pass, the comment above the loop now says explicitly that queries_nodes[0] is skipped, and the test pins the anchor-only shape: the EXPLAIN count of MaterializingCTE steps is 0 there and 1 for the recursive-member shape.
| /// Union-shaped CTEs are speculatively marked recursive here; whether a CTE actually | ||
| /// references itself is only known after analysis. The recursive evaluation cannot | ||
| /// itself be materialized, so `MATERIALIZED` on a self-referencing CTE is rejected in | ||
| /// `QueryAnalyzer::resolveUnion`. Helper CTEs that do not reference themselves may be | ||
| /// `MATERIALIZED`: they are materialized once and every recursive step reads the | ||
| /// snapshot instead of re-evaluating the subquery per step. |
| /// Set by `QueryAnalyzer::resolveUnion` when a reference site of this CTE lies inside a recursive | ||
| /// member of a recursive CTE. `RecursiveCTESource` re-plans and re-executes the recursive members | ||
| /// once per recursion step, so such a CTE must keep its snapshot even when it has a single static | ||
| /// reference site (see `inlineMaterializedCTEIfNeeded`). |
There was a problem hiding this comment.
Shortened to one line.
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: ClickHouse#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]>
|
@novikd hey, could you please take another look when you have a moment? All four points from your review are addressed and replied to inline, and CI is green. |
…ialized-with # Conflicts: # src/Analyzer/Resolve/QueryAnalyzer.cpp # src/Parsers/ParserWithElement.cpp
|
🕵 This is superseded by #123452, which keeps your original commits and adds a merge of the current |
Conflicts in `QueryTreeBuilder.cpp` and `ParserWithElement.cpp` resolved in favor of master: master now carries the reviewed version of "Support materialized CTEs in recursive WITH" (ClickHouse#107069), which checks the `MATERIALIZED` restriction in `QueryAnalyzer::resolveUnion` once self-reference is known. The duplicate test `05213_materialized_cte_in_recursive_with` carried by this branch is removed in favor of master's `04327_materialized_cte_in_recursive_with`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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).
Workflow [PR]
Sync PR [sync-upstream/pr/107069]