Repository navigation
Materialize a chain of MATERIALIZED CTEs in dependency order inside a distributed read's IN set - #121688
Materialize a chain of MATERIALIZED CTEs in dependency order inside a distributed read's IN set#121688groeneai wants to merge 4 commits into
Conversation
…uted-set-subquery-chain
A distributed read whose uncorrelated IN set subquery declares a chain of MATERIALIZED CTEs aborted with "Reading from materialized CTE 'c' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan". Found by AST fuzzer (amd_debug, targeted, old_compatibility) on the CI of ClickHouse#119469, which had mutated master's own 05230 regression test. With prefer_localhost_replica = 1 the local shard is served by a second plan built from an AST (createLocalPlan), where a materialized CTE serialises to a bare temporary table name and the WITH list is already cleared, so the shard AST names the CTE with no body. Re-analysis recovers the same MaterializedCTE through extractCTE with no subquery child. collectMaterializedCTEs admits such by-name references under forceMaterializeCTE(), but it cannot see what those bodies read, so it levels the two readers at 0 and never sees the shared CTE they both read. Index analysis then reaches buildOrderedSetInplace, which takes the destructive path on a non-clonable plan, claims the readers and relocates their pre-built plans under that truncated gate. Those plans carry no gate for the shared CTE, by the deliberate design of 5150fe3 (gates for a materialized CTE belong to the plan that collected it), so both readers run with is_built == false and throw in the same millisecond. This is the residual that 33b4afb deferred in its own commit message. Record each materialized CTE's dependencies where they are still visible, on the shared MaterializedCTE in the analyzer, and let collectMaterializedCTEs expand a by-name reference into those dependencies one level deeper in a post-walk phase. The merge rule keeps the deepest level and promotes a null subquery to a non-null one, which is what separates a CTE that is both referenced directly and reached as a dependency into two steps instead of one concurrent step. addBuildSubqueriesForMaterializedCTEsIfNeeded then plants the nested steps it already knows how to plant, and the optimizer side is untouched. Edges are recorded only for CTEs that survive inlining: a CTE referenced once is inlined, so at run time it has no temporary table, no writer and nothing to order, and an edge to one would register a dependency that no planner ever plans. Recording runs as its own traversal after mergeDuplicateMaterializedCTEs has canonicalised the pointers, because that pass redirects them on leave. Phase 2 is a bounded worklist that throws on a cycle rather than collapsing to one level, since a flat step unites writer pipelines as concurrent siblings, which is the defect itself. enable_materialized_cte is an Experimental-tier setting that is disabled by default, so no supported configuration reaches this and it is not a changelog-visible bug fix. Co-Authored-By: Claude Opus 5 <[email protected]>
Delete the comments that narrate the new code's own design (function doc, lambda-symmetry note, self-edge rationale) and condense the surviving property comments to one or two lines each.
Internal second-model review: adjudication log (click to expand)One independent cold read of the resulting code plus a second-model pass (engine: codex, 0 findings,
Also noticed, not raised: with the dependent CTE read only once, the same distributed shape fails On test volume: 12 arms, but each is a distinct carrier of the invariant rather than a repeat, over Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260923-010900 |
|
Workflow [PR], commit [fe46497] Summary: ✅
AI ReviewSummaryThis PR records Final Verdict✅ No new blocker or major findings. LLVM Coverage ReportMeasured on commit fe46497.
Changed lines: Changed C/C++ lines covered: 83/84 (98.81%) · Uncovered code |
|
cc @novikd |
CI finish ledger - 7c4a75fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The discriminator is in the shard reports: 1/6 of this same run reports Session id: cron:our-pr-ci-monitor:20260923-163416 |
| /// A by-name reference carries no body, so the CTEs that body reads are invisible to the walk above. | ||
| for (size_t iteration = 0;; ++iteration) | ||
| { | ||
| std::vector<std::pair<MaterializedCTEPtr, size_t>> known; | ||
| known.reserve(materialized_ctes.size()); | ||
| for (const auto & [cte, entry] : materialized_ctes) | ||
| known.emplace_back(cte, entry.level); | ||
|
|
||
| bool level_changed = false; | ||
| for (const auto & [cte, cte_level] : known) | ||
| for (const auto & dependency : cte->dependencies) | ||
| level_changed |= registerMaterializedCTE(materialized_ctes, dependency, nullptr, cte_level + 1); | ||
|
|
||
| if (!level_changed) | ||
| break; | ||
|
|
||
| /// A level rising past one round per CTE implies a dependency cycle, which no ordering satisfies. | ||
| if (iteration >= materialized_ctes.size()) | ||
| throw Exception(ErrorCodes::LOGICAL_ERROR, | ||
| "Dependencies of materialized CTEs form a cycle, their materialization cannot be ordered"); | ||
| } |
There was a problem hiding this comment.
This is just a hack. A proper solution is to use a topological sort here
There was a problem hiding this comment.
Done in fe46497: the loop is replaced by a topological sort (Kahn's algorithm) over MaterializedCTE::dependencies. A CTE is processed only after every CTE that reads it, so its level is final when it is passed to its dependencies, and a cycle shows up as CTEs that never become ready. I also added a test case with a diamond on a three-CTE chain, the only shape in the test that needs more than one propagation hop; it aborts on master and passes with this change.
Replace the fixpoint iteration that deepened the levels of the CTEs a by-name reference reads with Kahn's algorithm over `MaterializedCTE::dependencies`: a CTE is processed only after every CTE that reads it, so its level is final when it is passed on to its own dependencies, and a cycle shows up as CTEs that never become ready. The result is the same longest-path level assignment, computed in one pass. Add a test arm with a diamond on a three-CTE chain, the first shape that needs the levels propagated through more than one dependency hop. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes12 object files changed (+41.59 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, 152 s compile time in total, 25 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes how MATERIALIZED CTEs are ordered during planning: it records which CTEs each CTE reads and assigns levels in dependency order. No query in ClickBench or TPC-H uses materialized CTEs, so no query in either benchmark runs the changed code. The four flagged ClickBench queries (Q16, Q32, Q33, Q34) are aggregation-heavy GROUP BY queries. They were slower by +16.0%, +13.3%, +7.6% and +5.2%, but every result is inside master's current range, so they stay as not_sure. The matching CPU rise, combined with two of the PR's runs sharing a host, points to the test environment rather than this diff, and I found no reason to contest any of these calls. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Dear @antoniofilipovic, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #119469 (its CI found this)
Related: #121010
Related: #119986
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
MATERIALIZEDCTEs (enable_materialized_cte = 1) are now materialized in dependency order when a distributed read'sINset subquery declares a chain of them, so a reader no longer starts before the CTE it reads has been written.Description
A distributed read whose uncorrelated
INset subquery declares a chain ofMATERIALIZEDCTEs aborts withLogical error: 'Reading from materialized CTE 'c' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan'. Reproduces onv26.9.1.1629-stable. Found byAST fuzzer (amd_debug, targeted, old_compatibility)on the CI of #119469: https://github.com/ClickHouse/ClickHouse/actions/runs/35708578518/job/106693497358. Minimal form:The AST fuzzer on #123121 found two more routes, both fixed here:
PREWHERE v IN (...)withvin no key, and a minmax skip index onv.Root cause. With
prefer_localhost_replica = 1the local shard is served by a second plan built from an AST, in which a materialized CTE appears as a bare temporary table name with no body.collectMaterializedCTEsadmits such by-name references underforceMaterializeCTE(), but it cannot see what those bodies read, so it levels both readers at 0 and never sees the shared CTE they read. Index analysis then claims the readers in place and relocates their pre-built plans under that truncated gate; those plans read the shared CTE and carry no gate for it, so both readers throw. This is the residual33b4afbbc5702deferred in its own commit message.Fix. Record each materialized CTE's dependencies while the bodies are still in the tree (analyzer), then have
collectMaterializedCTEsassign the levels by a topological sort of those dependencies, so the CTEs a by-name reference reads land below it. The optimizer side is unchanged.#121010 and #119986 are both present in the failing tree and do not address this; the branch already contains both.
Workflow [PR]
Sync PR [sync-upstream/pr/121688]