Repository navigation
Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE - #121010
Conversation
…d one shared CTE A set subquery that declares a MATERIALIZED CTE read by two other MATERIALIZED CTEs of the same subquery lost the materialization gate for the shared CTE, so a reader was dispatched before its writer finished: Reading from materialized CTE 'c' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan. (LOGICAL_ERROR) inlineMaterializedCTEIfNeeded merges duplicate MATERIALIZED CTEs across UNION branches by name and body hash. In the reported query the two branches' `c` are identical and collapse to one MaterializedCTE, while the two `d` bodies differ (x + 1048577 vs x + 200) and stay two, so one inner CTE ends up read by two distinct outer CTEs. SelectQueryOptions::subquery() copies force_materialize_cte through, so inside a set subquery the nested Planner that builds a CTE's own plan also passed the is_subquery && !force_materialize_cte guard in collectMaterializedCTEs and planted a DelayedMaterializingCTEsStep for `c` - once inside each `d`'s plan. Claiming a CTE is a single atomic exchange in makePlansForCTEs, and resolveMaterializingCTEs runs its recursive optimizePlans pass before the claims in this tree, so the first nested gate wins. The second nested gate and the enclosing plan's dominating level-1 gate then both find `c` already claimed and degenerate to a MaterializingCTEsStep holding zero CTEs, which updatePipeline returns unchanged, so no DelayedPortsProcessor is inserted at all. The two CTE plans run as sibling side pipelines of one step, and the ungated MemorySource for `c` is dispatched while its writer, now buried inside the other CTE's plan, is still running. A CTE's plan is attached below its own gate, so it can only dominate that CTE's readers. Gates for the CTEs its body reads belong to the plan that collected them, which places an inner CTE at a deeper level and therefore plants a gate above the outer CTE's. The nested gate was a dominated duplicate, so the fix is to stop propagating force_materialize_cte into the nested CTE planner, making the force path behave exactly like the already-correct non-force path (a plain top-level SELECT passes force = false today, which is why the non-force path never showed this). Writer-step counts in EXPLAIN are unchanged, confirming only dominated duplicates were removed and no materialization work moved. The UNION ALL is not essential. What is required is two multiply-referenced outer CTEs reading one shared inner CTE, plus more than one reading stream, so the same defect reproduces with a single-branch diamond and as a plain SELECT as well as a lightweight UPDATE. The new test covers all four shapes; each failed 20 of 20 runs before this change. It also pins the number of MaterializingCTE writer steps so a future planner change that inlines the CTEs cannot make the cases vacuous, with a control asserting the count drops to zero without the MATERIALIZED keyword, and asserts post-UPDATE data rather than only the absence of a throw. 05182_lightweight_update_materialized_cte_in_subquery:38 is the single-branch chained case that already passes and is left untouched. Closes: ClickHouse#120985 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20260919-100500 |
Pre-PR validation gate (click to expand)
Suites on the final binary: materialized-CTE family 38/39, Session id: cron:clickhouse-impl-slot-6:20260919-091000 |
|
Workflow [PR], commit [5150fe3] Summary: ✅
AI ReviewSummaryThis PR stops nested materialized-CTE planning from re-planting dominated Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 5150fe3.
Changed lines: Changed C/C++ lines covered: 5/6 (83.33%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes117 object files changed (+44.38 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 units2006 translation units recompiled, 12076 s compile time in total, 2006 of them have a recent master baseline. |
46a8c1e
Backport #121010 to 26.9: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
Resolve the cherry-pick of #121010 to 26.8. On master, #119489 moved `addBuildSubqueriesForMaterializedCTEsIfNeeded` from `src/Planner/Planner.cpp` into `src/Planner/CollectMaterializedCTE.cpp`. That PR is not on 26.8, so the hunk did not apply. On 26.8 the function is still in `Planner.cpp`, and its body is identical to the one #121010 patched. The resolution adds the same three lines there, before `Planner cte_planner(...)`, and leaves `CollectMaterializedCTE.cpp` as it is on 26.8. #119489 also adds the materialized-CTE gate for lightweight `UPDATE` and `DELETE` set subqueries, which the two `UPDATE` cases of `05230_materialized_cte_shared_by_two_ctes_in_set_subquery` depend on. Without it they still fail on 26.8, so those two cases are removed from the test here. The `SELECT` cases are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #121010 to 26.8: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
…CTEs of a set subquery read one shared CTE
Backport #121010 to 26.8: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
Closes: #120985
Related: #119715
Related: #119489
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the
LOGICAL_ERRORReading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query planraised when anINor other set subquery defines aMATERIALIZEDCTE that two otherMATERIALIZEDCTEs of that subquery read (for example aUNION ALLwhose branches each chain twoMATERIALIZEDCTEs), in a lightweightUPDATE/DELETEor aSELECT, on a table read with more than one stream.Description
Found by the AST fuzzer of
Stress test (arm_tsan)on #119715: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119715&sha=b3e2df76469ad562af7bf032eeffea9deb5f61d1&name_0=PR&name_1=Stress%20test%20(arm_tsan). Not caused by that pull request: the reporter reproduced it on master with a control binary and filed it separately.inlineMaterializedCTEIfNeededmerges duplicateMATERIALIZEDCTEs acrossUNIONbranches by name and body hash. In the reported query the branches'care identical and collapse to one CTE while the two differingdbodies stay two, so one inner CTE is read by two distinct outer CTEs.SelectQueryOptions::subquery()copiesforce_materialize_ctethrough, so inside a set subquery the nested planner that builds each CTE's own plan also planted aDelayedMaterializingCTEsStepforc, once inside eachd's plan. Claiming a CTE is a single atomic exchange, andresolveMaterializingCTEsoptimizes CTE plans before claiming in this tree, so the first nested gate wins; the second and the enclosing plan's dominating gate degenerate to zero-CTE steps that insert noDelayedPortsProcessor. The two CTE plans then run as sibling side pipelines, and the ungatedMemorySourceforcis dispatched while its writer still runs.A CTE's plan sits below its own gate, so it dominates only that CTE's readers; gates for the CTEs it reads belong to the plan that collected them, at a deeper level and therefore above. The nested gate was a dominated duplicate, and not creating it makes the force path match the already-correct non-force path. Writer-step counts in
EXPLAINare unchanged.The
UNION ALLis not essential: the same defect reproduces with a single-branch diamond, asUPDATEand asSELECT. All four shapes fail 20/20 before the change. The new test covers them and pins the writer-step counts against silent inlining;05182_lightweight_update_materialized_cte_in_subquery:38is the single-branch chained control that already passes.Workflow [PR]
Sync PR [sync-upstream/pr/121010]
Version info
26.9.18.8,26.8.27.6