Skip to content

Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE - #121010

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-gate-shared-by-two-ctes
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-gate-shared-by-two-ctes

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120985
Related: #119715
Related: #119489

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed the LOGICAL_ERROR Reading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan raised when an IN or other set subquery defines a MATERIALIZED CTE that two other MATERIALIZED CTEs of that subquery read (for example a UNION ALL whose branches each chain two MATERIALIZED CTEs), in a lightweight UPDATE/DELETE or a SELECT, 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.

inlineMaterializedCTEIfNeeded merges duplicate MATERIALIZED CTEs across UNION branches by name and body hash. In the reported query the branches' c are identical and collapse to one CTE while the two differing d bodies stay two, so one inner CTE is read by two distinct outer CTEs.

SelectQueryOptions::subquery() copies force_materialize_cte through, so inside a set subquery the nested planner that builds each CTE's own plan also planted a DelayedMaterializingCTEsStep for c, once inside each d's plan. Claiming a CTE is a single atomic exchange, and resolveMaterializingCTEs optimizes 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 no DelayedPortsProcessor. The two CTE plans then run as sibling side pipelines, and the ungated MemorySource for c is 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 EXPLAIN are unchanged.

The UNION ALL is not essential: the same defect reproduces with a single-branch diamond, as UPDATE and as SELECT. 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:38 is the single-branch chained control that already passes.


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

Version info

  • Backported to: 26.9.18.8, 26.8.27.6

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 💡 enable_materialized_cte carries the EXPERIMENTAL tier, so the changelog category should be Experimental Feature instead of Bug Fix (src/Core/Settings.cpp:5714) DISAGREE The tier is right, the inference is not. In the pull request template Experimental Feature sits between New Feature and Improvement: it is the category for shipping an experimental feature, not for fixing a bug in one, so selecting it would file this under new features in CHANGELOG.md. Every recent fix for this exact message uses Bug Fix (user-visible misbehavior in an official stable release): #119715 (also labelled pr-bugfix), #119489 (merged 2026-09-12), #115740 (merged 2026-08-22). Category kept.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-11:20260919-100500

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%. tests/clickhouse-test 05230_... on pristine HEAD: [ FAIL ] server died 32, Logical error: 'Reading from materialized CTE 'c' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan'. Four shapes, 20/20 each.
b Root cause explained? Yes. Identical c bodies merge across the UNION branches while the differing d bodies stay two, so one inner CTE has two outer readers. subquery() copies force_materialize_cte, so each d's own plan also planted a gate for c; the single atomic claim plus pass-1-before-pass-2 ordering leaves the loser and the enclosing dominating gate as zero-CTE steps that insert no DelayedPortsProcessor, and the sibling side pipelines race. Premise measured: EXPLAIN shows 3 writer steps.
c Fix matches root cause? Yes. Removes the dominated duplicate gate at the site that creates it. No widened bound, no defensive check, no test tag, no change to DelayedPortsProcessor (that is #119715, and the run that found this was a run of #119715). The fail-fast check in ReadFromMemoryStorageStep is untouched.
d Test intent preserved / new tests added? No existing test weakened and no reference updated. New regression test with anti-vacuity writer-step pins, a negative control and discriminating data oracles.
e Both directions demonstrated? Yes, same rig and runner with only the binary swapped: FAIL on fc93c094..., [ OK ] on 3ca6429f.... Pristine HEAD is also the mutation arm, since it differs from the shipped tree by exactly one semantic line.
f Fix is general across code paths? Yes. Fixed at the source, not guarded at the throw site. All five forceMaterializeCTE() callers and all four force_materialize_cte readers inspected; their pinning tests run (scalar subqueries, per-shard external tables, index analysis, set subqueries, mutations).
g Fix generalizes across inputs (params/datatypes/wrappers)? The invariant is plan topology, so carriers are plan-level rather than type wrappers. Covered: both statement types (UPDATE, SELECT), both topologies (UNION ALL of chained CTEs, and a diamond with no UNION), and the inlining boundary.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialized-plan format change, so no SettingsChangesHistory.cpp entry; 04043 (serialize query plan) passes.
i Invariants and contracts preserved? Yes, and made explicit: gates for a materialized CTE are planted only by the plan that collected it, where a deeper level yields a dominating gate. The test's EXPLAIN writer-step pins assert both gate levels survive. The "does not have query tree, but was not planned yet" throw is unreachable from the change (the nested collect returns empty, so the nested plant loop never runs).

Suites on the final binary: materialized-CTE family 38/39, lightweight_update 6/6, broad cte lwu patch_part materialized_cte sweep 254/261, new test 50/50 with randomization and 50/50 without, check_style.py clean apart from an infra-only leg, clang-tidy-22 rc=0. Every non-green line fails identically on the pristine-HEAD binary (the one materialized-CTE case is a one-line port-literal diff from the local cluster rig); no reference file was updated.

Session id: cron:clickhouse-impl-slot-6:20260919-091000

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5150fe3]

Summary: ✅


AI Review

Summary

This PR stops nested materialized-CTE planning from re-planting dominated DelayedMaterializingCTEsSteps when force_materialize_cte is already active on the enclosing plan, and adds a focused stateless regression for the previously missing "one shared materialized CTE read by two sibling materialized CTEs inside a set subquery" shape. I re-read the current planner/runtime paths that claim, strip, and execute these CTE plans (Planner, DelayedCreatingSetsStep, MutationsInterpreter, scalar-subquery evaluation, and merge-child stripping) against the current diff and did not find a remaining correctness issue or a missing contract check that warrants a review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 5150fe3.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.60% -0.10%

Changed lines: Changed C/C++ lines covered: 5/6 (83.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@groeneai
groeneai requested review from novikd and vdimir September 19, 2026 10:56
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5150fe392 with master eb604efc0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 95f5e92cb; 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

117 object files changed (+44.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.12 MiB 2.14 MiB +22.75 KiB (+1.05%)
src/CMakeFiles/dbms.dir/Core/Settings.cpp.o 3.53 MiB 3.55 MiB +17.52 KiB (+0.48%)

716 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

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 46a8c1e Sep 19, 2026
176 of 349 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #121010 to 26.9: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
alexey-milovidov pushed a commit that referenced this pull request Oct 13, 2026
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]>
robot-ch-test-poll added a commit that referenced this pull request Oct 13, 2026
Cherry pick #121010 to 26.8: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
…CTEs of a set subquery read one shared CTE
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 13, 2026
Backport #121010 to 26.8: Fix missing materialized-CTE gate when two CTEs of a set subquery read one shared CTE
@novikd novikd added pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR v26.8-must-backport labels Nov 13, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
@novikd novikd removed the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 23, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 23, 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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

8 participants