Skip to content

Materialize a chain of MATERIALIZED CTEs in dependency order inside a distributed read's IN set - #121688

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:matcte-gate-distributed-set-subquery-chain
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:matcte-gate-distributed-set-subquery-chain

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119469 (its CI found this)
Related: #121010
Related: #119986

Changelog category (leave one):

  • Improvement

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

MATERIALIZED CTEs (enable_materialized_cte = 1) are now materialized in dependency order when a distributed read's IN set 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 IN set subquery declares a chain of MATERIALIZED CTEs aborts with Logical error: 'Reading from materialized CTE 'c' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan'. Reproduces on v26.9.1.1629-stable. Found by AST fuzzer (amd_debug, targeted, old_compatibility) on the CI of #119469: https://github.com/ClickHouse/ClickHouse/actions/runs/35708578518/job/106693497358. Minimal form:

CREATE TABLE t (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY (id, v);
SELECT count() FROM remote('127.0.0.1', currentDatabase(), 't') WHERE v IN (
    WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)),
         d AS MATERIALIZED (SELECT x + 200 AS y FROM c)
    SELECT a.y FROM d AS a, d AS b);

The AST fuzzer on #123121 found two more routes, both fixed here: PREWHERE v IN (...) with v in no key, and a minmax skip index on v.

Root cause. With prefer_localhost_replica = 1 the 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. collectMaterializedCTEs admits such by-name references under forceMaterializeCTE(), 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 residual 33b4afbbc5702 deferred in its own commit message.

Fix. Record each materialized CTE's dependencies while the bodies are still in the tree (analyzer), then have collectMaterializedCTEs assign 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]

groeneai and others added 3 commits September 22, 2026 22:27
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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,
all six changed files and the sibling planner paths). 7 findings from the cold read, adjudicated below.

# Sev Finding Verdict Evidence / action
1 ⚠️ Phase 2 registers a dependency with a null subquery unconditionally, so a collector run with force_materialize_cte = false could reach the pre-existing LOGICAL_ERROR at CollectMaterializedCTE.cpp:215 instead of the bare-gate branch. Named sites: MutationsInterpreter.cpp:2201/2227 and the shard-local plan's own top-level pair (DistributedCreateLocalPlan.cpp:37). DISAGREE Refuted at both sites. MutationsInterpreter.cpp:2201: the tree is the one the subquery_planner just above planned with bodies present, so the inner CTE registers with a real subquery, and registerMaterializedCTE promotes null to non-null but never the reverse (:44-45). createLocalPlan: emplace_local_stream runs before Planner.cpp:3205 builds the IN-set plan, so no CTE has a plan yet; with force = false and by-name nodes the walk admits nothing and the function returns at :94-95, before phase 2.
2 ⚠️ StorageMerge.cpp:1033 collectMaterializedCTEsFromQueryTree has the same by-name blind spot: it walks only the outer tree, so a by-name reference contributes the CTE itself but never the CTEs its body reads, and that set is what stops a Merge child from claiming a CTE the outer plan owns. AGREE (fact), out of scope Not a regression: 04811_materialized_cte_merge_child_gate passes on the fixed binary. Different collector, feeding a strip rather than a plant, and outside this change's scope. Recorded here rather than raised, because I have no measured reachable payload for it.
3 💡 The new test sets enable_analyzer = 1, which is OBSOLETE and frozen at its only supported value (Settings.cpp:8529). AGREE (fact), noted Harmless (only 0 is rejected), and the convention it was copied from is still in master's own 05230 and about ten other recent tests. Worth a suite-wide sweep, not a change here.
4 💡 The description named the failing check but linked no clickable job. AGREE, fixed The actions/runs/.../job/... URL is now in ### Description.
5 💡 Changelog category was Not for changelog. AGREE, fixed Bug Fix stays excluded, and measured: enable_materialized_cte is declared EXPERIMENTAL and defaults to false (Settings.cpp:5718), so the surface is experimental-only even though the defect is live in v26.9.1.1629-stable. Not for changelog is for a defect that is master-only since the last branch cut, which this is not, so the category is Improvement and the entry is in improvement voice.
6 💡 The 46-line analyzer pass re-walks a tree collectMaterializedCTEs already walks with a depth counter, so the edges could be recorded inside the single file that consumes them, dropping a file, a traversal and an ordering constraint. AGREE (fact), noted Kept as written: the analyzer runs once per QueryAnalyzer::resolve, so it covers every query shape uniformly, and this variant carries the measurement (20/20 red to 0/20, plus the test-level base-vs-fix pair). Happy to move it if a reviewer prefers the smaller diff.
7 💡 dependencies holds strong pointers, so the self-edge guard also avoids a reference cycle, which is a stronger reason than ordering. AGREE (fact), noted A cycle is unreachable anyway: edges come from a tree walk with no visited set, so the graph is acyclic by construction.

Also noticed, not raised: with the dependent CTE read only once, the same distributed shape fails
differently, Code: 60 Unknown table expression identifier '_materialized_cte_...'. Same
architectural origin (the shard AST names a materialized CTE by its temporary table name) but a
different code path (name resolution, not the gate). Still present after this change, so this
change neither causes nor hides it.

On test volume: 12 arms, but each is a distinct carrier of the invariant rather than a repeat, over
the in-place and runtime set routes, the serialized plan, a scalar subquery, a lightweight UPDATE,
and prefer_localhost_replica both ways. Both non-vacuity pins carry a negative control that was
measured to move (1 to 0, and 2 to 0).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260923-010900

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe46497]

Summary: ✅


AI Review

Summary

This PR records MATERIALIZED CTE-to-CTE dependencies before inlining and uses a topological pass in collectMaterializedCTEs so re-analyzed distributed-set subqueries still materialize chained CTEs in dependency order. After reading the full changed code, the existing review thread, and the surrounding planner/mutation paths, I did not find a new correctness or contract gap in the current diff.

Final Verdict

✅ No new blocker or major findings.

LLVM Coverage Report

Measured on commit fe46497.

Metric Baseline Current Δ
Lines 88.20% 88.10% -0.10%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 83/84 (98.81%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 23, 2026
@PedroTadim

Copy link
Copy Markdown
Member

cc @novikd

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7c4a75f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 2/6) CI harness, not this diff: the shard is red only on 4 confirmed regression(s) on the performance dashboard; the dashboard verdict gate reds unrelated PRs with a regression that does not reproduce when the same head is re-run #121090 (mine, open), with #121189 (mine, open)
Performance Comparison (arm_release, master_head, 4/6) same gate: 1 confirmed regression(s) on the performance dashboard #121090 (mine, open), with #121189 (mine, open)

The discriminator is in the shard reports: 1/6 of this same run reports 8 too long, 1 unstable
and is GREEN, so the criterion that failed 2/6 and 4/6 is the dashboard regression verdict
alone. 152 checks succeeded, 20 were skipped. Mergeable Check and PR are the praktika
aggregators reflecting the two reds above, not separate failures.

Session id: cron:our-pr-ci-monitor:20260923-163416

@antoniofilipovic antoniofilipovic self-assigned this Sep 24, 2026
Comment thread src/Planner/CollectMaterializedCTE.cpp Outdated
Comment on lines +96 to +116
/// 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");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just a hack. A proper solution is to use a topological sort here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@groeneai
groeneai requested a review from novikd September 25, 2026 23:57
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe464977c with master 06108f98a (stripped binary size, per-symbol sizes and ThinLTO time; 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

12 object files changed (+41.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/CollectMaterializedCTE.cpp.o 88.98 KiB 110.50 KiB +21.52 KiB (+24.19%)
src/CMakeFiles/dbms.dir/Analyzer/inlineMaterializedCTEIfNeeded.cpp.o 90.58 KiB 108.81 KiB +18.23 KiB (+20.13%)

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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 546 633 +16.0% <0.0001 aggregation: This query is a high-cardinality GROUP BY with no CTEs, so it never reaches the materialized-CTE planning code this PR changes. The +16.0% stays inside master's current range.
⚠️ 32 not_sure 716 811 +13.3% <0.0001 aggregation: This GROUP BY WatchID, ClientIP query has no CTEs and very noisy measurements on both sides. The +13.3% sits inside master's current range and cannot be traced to this diff.
⚠️ 33 not_sure 1138 1225 +7.6% <0.0001 aggregation: This query groups by URL and has no materialized CTEs, so the changed level-ordering code never runs. The +7.6% is inside master's current range.
⚠️ 34 not_sure 1147 1206 +5.2% <0.0001 aggregation: This is a URL GROUP BY with no CTEs, so this PR cannot affect it. The +5.2% is within master's current range.

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
  • StressHouse run: eff81329-ed75-4f9f-a329-08e1d8cb06d3
  • MIRAI run: befde10d-c58d-4a67-8c0c-b574f7a38add
  • PR check IDs:
    • clickbench_2671095_1790833971
    • clickbench_2671109_1790833971
    • clickbench_2671115_1790833971
    • tpch_adapted_1_official_2671126_1790833971
    • tpch_adapted_1_official_2671151_1790833971
    • tpch_adapted_1_official_2671165_1790833971

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

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.

This branch has not been deployed

No deployments
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-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants