Skip to content

Plant the materialization gate in a nested set subquery's own plan - #115740

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-in-set-gate
Aug 22, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-materialized-cte-in-set-gate

Conversation

@groeneai

@groeneai groeneai commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fix LOGICAL_ERROR "Reading from materialized CTE 'X' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan" when a MATERIALIZED CTE is read from inside an IN subquery over a Distributed table. Closes #113184.

Description

Closes #113184. A MATERIALIZED CTE read from inside an IN subquery over a Distributed table failed with Code: 49. Reading from materialized CTE 'ct' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan. Reproducer in #113184:

WITH ct AS MATERIALIZED (SELECT 1 AS c),
     rs AS MATERIALIZED (SELECT * FROM dist_t WHERE c IN (SELECT c FROM ct))
SELECT count() FROM rs AS a, rs AS b;

Root cause. A set subquery is planned with forceMaterializeCTE because buildOrderedSetInplace may execute it as a standalone pipeline, with no outer processor to gate its CTE readers. But collectMaterializedCTEs declined the reference: inside a set subquery it has isMaterializedCTE() == false (the subquery child was detached by detachQueryTree) and hasPlanOrBuilt() == false. Nothing was collected, addBuildSubqueriesForMaterializedCTEsIfNeeded returned early, and the readers ran with nothing ordering them after the writer.

The change. The by-name carve-out is correct for a plan shipped to a remote shard, which must not be wrapped, but misfires on a plan executed in process. Accept the reference when force_materialize_cte is set, in both lambdas of the traversal. Such a reference carries no subquery, so push the CTE handle; the writer stays with whoever holds the subquery. The widened predicate also admits by-name references under callers that plan a tree standalone, so makePlansForCTEs now tests for a built plan before consuming the materialization claim.

Validation. The query above returns the expected 1. The test covers 9 shapes (PREWHERE, GLOBAL IN, GLOBAL JOIN, empty and populated middle tables) plus index-pruning and materialization assertions, and passes 50/50 under randomization. On the ordinary main-query path force_materialize_cte is false and EXPLAIN output is byte-identical to master.

A three-level CTE chain behind the same nested subquery still fails identically on unpatched master: a separate pre-existing defect, not addressed here.


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

A MATERIALIZED CTE read from inside a nested IN subquery aborted with
"Reading from materialized CTE 'X' before its materialization completed -
DelayedPortsProcessor gate is missing in the query plan" (LOGICAL_ERROR).

A set subquery is planned with forceMaterializeCTE precisely because
FutureSetFromSubquery::buildOrderedSetInplace may later execute it as a
standalone pipeline: that pipeline is completed into an EmptySink and run by a
bare CompletedPipelineExecutor, so no outer processor exists to gate its CTE
readers. But collectMaterializedCTEs declined the reference anyway. Inside a set
subquery the reference has isMaterializedCTE() == false, because the subquery
child was detached by detachQueryTree, and hasPlanOrBuilt() == false, because
the plan is not built yet. So no CTE was collected,
addBuildSubqueriesForMaterializedCTEsIfNeeded returned early, and the readers
ran with nothing ordering them after the writer.

The by-name carve-out is right for a plan shipped to a remote shard, which reads
the temp table by name and must not be wrapped. It misfires on a plan executed
in process, so accept the reference when force_materialize_cte is set. Both
lambdas of the traversal change together: they are the enter/leave pair of one
walk and the second decrements the level that orders materialization.

Accepting the reference then reaches the "CTE does not have query tree, but was
not planned yet" throw, since a by-name reference carries no subquery to plan.
The CTE handle alone is enough to build the gate, so push it and let whoever
holds the subquery remain the writer.

Measured on the reproducer: the abort is gone and the values are correct, the
plan shape and results on the ordinary main-query path are byte-identical
(force_materialize_cte is false there), and the shared-dependency diamond that a
broader variant of this change regressed stays clean over 30 runs.

A three-level CTE chain behind the same nested subquery still aborts. That shape
fails identically on unpatched master, so it is a separate pre-existing defect
and is deliberately out of scope here.
makePlansForCTEs consumed the is_materialization_planned claim before testing
whether the CTE actually carries a plan, so it could emit a ClaimedCTE holding a
null plan. The attach site in addPlansForMaterializingCTEs dereferences that plan
raw. Test the plan first, so a plan-less entry neither enters the claimed list nor
burns the flag the real writer tests. optimizePlans already tolerates a plan-less
CTE this way.

Reachable now that the collect predicate also admits a by-name reference under
force_materialize_cte: MutationsInterpreter, StorageMergeTreeAnalyzeIndexes and
buildQueryTreeForShard each plan a tree standalone without calling
collectMaterializedCTEs.

Also make the index-pruning arm of the regression test assert something. It
explained a three-row table at default granularity, so the reference recorded
Granules: 1/1, which is "nothing was pruned" and passed either way. It now uses
the nested-IN-over-Distributed shape over 16 granules and requires the selected
granule count to be strictly below the total plus the PrimaryKey condition line,
with a companion arm showing both counters drop to zero when the set-index path is
off. index_granularity and prefer_localhost_replica are pinned because a
randomized value of either collapses the plan back to a state where the assertion
is vacuous.
`DelayedMaterializingCTEsStep::optimizePlans` claimed `is_plan_optimized` and only then
tested `cte->plan`, the opposite order from the `is_materialization_planned` claim in
`makePlansForCTEs` twenty lines below.

Two steps can hold the same `MaterializedCTE`, and `resolveMaterializingCTEs` pass 1 walks
every such step before pass 2 attaches any plan. A plan-less entry reached in pass 1
therefore burned the flag for a handle whose plan a different holder populates afterwards,
and that plan was attached having never been optimized. The plan-less state on this path is
one this change newly creates: before it, `collectMaterializedCTEs` declined the reference
and every entry pushed by the planner already carried a plan.
The arm was vacuous twice over. It named the CTE once, so
`inlineMaterializedCTEIfNeeded` inlined it and no materialized CTE survived to be gated: an
`EXPLAIN` of that arm contains zero `MaterializingCTEs` steps, against one for a reused CTE.
And its `ANY LEFT JOIN` keeps every left row, so `count()` was 3 whether the right side
contributed rows or nothing at all, which the empty-CTE variant confirms.

Name the CTE twice so it stays materialized, and assert a value fed by the joined right-hand
side plus an `EXPLAIN` line showing a materialized CTE is read. Both halves discriminate:
emptying the CTE turns `3 1` into `3 0`, and reverting the arm to one reference turns the
`EXPLAIN` assertion from 1 to 0.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 21, 2026
@groeneai

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

Before publishing I reviewed this change independently of the author, then had a second model
re-review it cold. Four rounds; every finding below is either fixed or refuted with evidence.

# Finding Verdict
❌ DelayedMaterializingCTEsStep::optimizePlans consumed the is_plan_optimized claim before testing whether the CTE had a plan. Two steps can hold the same CTE and pass 1 of resolveMaterializingCTEs walks all of them before pass 2 attaches anything, so a plan-less entry burned the flag for a handle whose plan a later holder populates, and that plan was attached having never been optimized. Fixed in a4174ce. The null test now precedes the claim, matching makePlansForCTEs.
❌ The GLOBAL JOIN arm asserted nothing, twice over. It named the CTE once, so the analyzer inlined it and no materialized CTE survived to be gated; and count() over an ANY LEFT JOIN returns 3 whether the right side contributes rows or nothing. Fixed in 17a92bd. The CTE is named twice so it stays materialized, the oracle is a value fed by the joined right-hand side, and a second arm asserts a materializing step is in the plan. Both halves control-proven: emptying the CTE turns 3 1 into 3 0, reverting to one reference turns the plan assertion from 1 to 0.
❌ The EXPLAIN indexes = 1 arm expected Granules: 1/1, which cannot demonstrate pruning: one granule available, one selected. Fixed in an earlier round. The arm now requires the selected count to be strictly below the total with index_granularity pinned, plus a companion arm requiring both counters to fall to zero when the set-index path is off. Verified by three separate corruptions, each turning it red.
❌ An earlier draft claimed the two 600 s test timeouts were caused by the change. Fixed. Both tests pass on both binaries in one run on one server directory (0.98 s / 1.03 s and 2.18 s / 2.09 s); the claim was removed rather than re-explained.
⚠️ Row (f) of the validation gate implied the GLOBAL IN and GLOBAL JOIN arms exercise the widened predicate. Corrected against measurement, in the weaker direction. A log probe shows those arms reach buildQueryTreeForShard's force site but enter the widened branch 0 times across ten variants, while the nested-IN arm enters it twice. They are kept as coverage of the neighbouring writer, and row (f) now says so.
⚠️ Four tests were reported as flaky or environmental across earlier rounds. Not the code. The review server lacked process_query_plan_packet, which CI installs. With the CI configuration the failure set collapses to 04041_materialized_cte_parallel_replicas alone, which needs a real parallel-replicas cluster and whose EXPLAIN diff is byte-identical on both binaries.
💡 Whether SelectQueryOptions::subquery() leaks the force flag into shard-local plans. Refuted. It does copy the flag, but no shard-local plan path sets it: DistributedCreateLocalPlan, ParallelReplicasLocalPlan, StorageMerge and StorageBuffer each build a fresh options object with the default. The by-name carve-out for shipped plans is byte-for-byte in force, and 04036_materialized_cte_distributed_race passes on both binaries.
💡 Whether the test needs a no-parallel-replicas tag. Refuted twice with citations. Not added.

Both directions are demonstrated on Build-ID-verified binaries: on the base binary the new test
kills the server with the LOGICAL_ERROR this change removes; on the fixed binary it passes, and
50/50 under randomized settings.

Session id: cron:clickhouse-review-slot-9:20260821-065000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. WITH ct AS MATERIALIZED (SELECT 1 AS c), rs AS MATERIALIZED (SELECT * FROM dist_t WHERE c IN (SELECT c FROM ct)) SELECT count() FROM rs AS a, rs AS b; with enable_materialized_cte = 1 on a single server with test_shard_localhost. Aborts every run on unpatched master (the #113184 reproducer); 8 further shapes reproduce identically.
b Root cause explained? Yes. A set subquery is planned with forceMaterializeCTE because buildOrderedSetInplace may run it as a standalone pipeline (completed into an EmptySink, executed by a bare CompletedPipelineExecutor), so nothing above it can gate its CTE readers. But collectMaterializedCTEs declined the reference: inside a set subquery it has isMaterializedCTE() == false (the subquery child was detached by detachQueryTree) and hasPlanOrBuilt() == false (the plan is not built yet). Nothing was collected, addBuildSubqueriesForMaterializedCTEsIfNeeded returned early, no DelayedPortsProcessor was planted, and the reader hit the is_built invariant check in MemorySource::generate.
c Fix matches root cause? Yes. The gate is planted at the layer that decides which CTE references get one, not guarded at the abort site. The by-name carve-out stays intact for a plan shipped to a remote shard; it is bypassed only when force_materialize_cte marks a plan that may run standalone. A previous read-time point fix in this family (#101305) was incomplete, which is why this one is in the planner.
d Test intent preserved / new tests added? New test 05026_materialized_cte_nested_set_subquery_gate covering 9 shapes plus an EXPLAIN indexes = 1 arm that requires the selected granule count to be strictly below the total and names the PrimaryKey condition line, so a silently disabled optimization cannot pass unnoticed. That arm was verified live rather than assumed: three separate corruptions (turning the set-index path off, dropping the index_granularity pin, reading the shard remotely) each turn it red, and a companion arm asserts both counters drop to zero when the index path is off. The GLOBAL JOIN arm names the CTE twice so it is not inlined, and asserts a value fed by the joined right-hand side plus an EXPLAIN line proving a materialized CTE is read; both halves are control-proven, emptying the CTE turns 3 1 into 3 0 and reverting the arm to one reference turns the EXPLAIN assertion from 1 to 0. Parallel-safe, no no-parallel tag, SQL-based. No existing test was modified or weakened.
e Both directions demonstrated? Yes, on Build-ID-verified binaries, both arms on one server config with no skipped tests. Base 2241cad252eb: running the new test kills the server, ClickHouse server died during test '05026_materialized_cte_nested_set_subquery_gate', stack frame 5 ReadFromMemoryStorageStep.cpp:87 in MemorySource::generate(). Fix b1b7b556399a: the same test is [ OK ] and 50/50 green under randomized settings. A strict probe for the abort signature reads 0 on both arms of the 32-test materialized_cte suite and 1 on the base-arm control where the server died, so it is proven able to discriminate. With the server configured as CI configures it (process_query_plan_packet on, the full cluster set defined) that suite leaves an identical failure set on both binaries apart from the new test: only 04041_materialized_cte_parallel_replicas, whose EXPLAIN diff is byte-identical on base and fix and needs a real parallel-replicas cluster. Earlier rounds reported 04227_pr_materialized_cte_set_subquery and three others as flaky or environmental; with that config they pass on both, so the failure set is now a single pre-existing test.
f Fix is general across code paths? Yes. All 5 writers of force_materialize_cte were enumerated and exercised: Planner.cpp set subqueries (the defect), buildQueryTreeForShard's executeSubqueryNode (GLOBAL IN and GLOBAL JOIN arms; a log probe at that call site counts 1 to 2 hits per arm), evaluateScalarSubqueryIfNeeded, MutationsInterpreter, StorageMergeTreeAnalyzeIndexes (granule-pruning arm). The same probe on the widened predicate shows the GLOBAL arms reach that writer without entering the widened branch, which only the set-subquery shapes do (2 hits) - so the GLOBAL arms cover the neighbouring writer rather than this change, and are kept for that. Both lambdas of the traversal change together, since they are the enter/leave pair of one walk and the second decrements the level that orders materialization.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered the reachable axes for this defect: empty and populated middle tables, local and Distributed sources, WHERE and PREWHERE, IN and GLOBAL IN and GLOBAL JOIN, CTE declared before and after its reader, use_index_for_in_with_subqueries 0 and 1, prefer_localhost_replica 0 and 1, max_threads 1 and 8, and 2 to 4 CTE references. The condition is on a plan-level flag rather than on column types, so type wrappers are not an axis here.
h Backward compatible? Yes. No new setting, no default change, no serialization or format change, so no SettingsChangesHistory.cpp entry is needed. The change only widens which references get a gate on plans that would otherwise abort. EXPLAIN and results on the ordinary main-query path are byte-identical to master.
i Invariants and contracts preserved? Yes. The invariant is the one ClickHouse states itself: a materialized-CTE reader may only run after the writer sets is_built, enforced by a DelayedPortsProcessor. This change makes a plan that may run standalone satisfy it. Single-writer ownership is preserved: the accepted by-name reference pushes only the CTE handle and never claims the writer role, so whoever holds the subquery remains the writer. Level numbering is preserved because both lambdas change together. The "every claimed entry carries a plan" invariant that the attach site relies on is now enforced rather than merely observed: makePlansForCTEs tests the plan before consuming the claim, so a plan-less CTE neither enters the claimed list nor burns the flag its real writer tests. That ordering matters, since skipping after the claim would suppress the writer, so optimizePlans tests its plan before claiming too: a handle whose plan a later holder populates is then still optimized by that holder instead of having its claim burned by the first step to see it plan-less. A shared-dependency diamond with reused siblings is clean over 30 runs, verified against a positive control that fails 30/30, and the per-shard by-name path is covered by 04036_materialized_cte_distributed_race passing on both binaries.

Session id: cron:clickhouse-impl-slot-5:20260821-050700

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [17a92bd]

Summary: ✅


AI Review

Summary

This PR fixes the missing materialization gate for MATERIALIZED CTE reads from detached IN subquery plans by carrying the CTE handle through force_materialize_cte standalone planners and by skipping plan-less delayed-step claims until a real writer plan exists. I did not find a correctness, compatibility, or test-coverage issue in the current diff that warrants an inline review comment; the added regression test exercises the reported shape and the PR's current CI is all green.

Final Verdict

✅ No blocking issues found. No new inline review comments were posted.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @davenger, could you review this? A materialized CTE read from inside an IN subquery over a Distributed table aborted with a logical error: the set subquery is planned with forceMaterializeCTE because it may run as a standalone pipeline, but collectMaterializedCTEs declined the by-name reference (no subquery, no built plan), so no gate was planted and the readers ran unordered with the writer.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai you are already fixing this issue here #113489

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 17a92bdd2 with master 36af905ab (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
Binary Master PR Δ
programs/clickhouse-stripped 704.41 MiB 701.39 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim These fix two different shapes of the same signature, so neither one replaces the other.

#113489 plants the gate at the two PreparedSets in-place sites (buildSetInplace / buildOrderedSetInplace), and its helper only covers a CTE that still holds its subquery plan (if (!cte->plan) continue;). This PR fixes a case one layer up: the by-name carve-out in CollectMaterializedCTE.cpp declines the CTE reference inside a set subquery even when the enclosing plan has force_materialize_cte = 1, so no gate is planted for that subquery at all and #113489's helper has no reader to cover there (its walk measured read_ctes=0, would_add=0).

The public evidence is on #113489 itself: STID 2467-2c2d fired again on its own head 216fe8b2 in AST fuzzer (amd_debug, targeted, old_compatibility) on 2026-08-19, report. Locally I measured the arms on three binaries (pristine master, #113489's head, this PR's candidate): the nested-IN-over-Distributed arm aborts on master and on #113489 and is green only with this change, while the arm #113489 fixes is green on both. Applied together they build and both arms pass.

If you would rather have a single change, say which one to withdraw or fold and I will do that.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into ClickHouse:master with commit a0820c0 Aug 22, 2026
184 of 186 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- needs a server with the standard test_shard_localhost cluster
SET enable_analyzer = 1, enable_materialized_cte = 1;

CREATE TABLE t_gate (c Int32) ENGINE = MergeTree ORDER BY c;
INSERT INTO t_gate SELECT number + 1 FROM numbers(3);
CREATE TABLE dist_gate AS t_gate ENGINE = Distributed(test_shard_localhost, currentDatabase(), t_gate);

WITH ct AS MATERIALIZED (SELECT 1 AS c),
     rs AS MATERIALIZED (SELECT * FROM dist_gate WHERE c IN (SELECT c FROM ct))
SELECT count() FROM rs AS a, rs AS b;

-- 26.7.5.10 / 26.6.3.62 / 26.5.7.64 / 26.3.21.7:
--   Code: 49. DB::Exception: CTE 'ct' does not have query tree, but was not planned yet. (LOGICAL_ERROR)
-- master (post-#115740): 1
-- Same shape over the local table t_gate instead of dist_gate returns correctly on every build.

Results:

  • Culprit PR: not pinned — introduced in the 26.2–26.3 window (details in Analysis metadata)
  • Reproduces on: 26.7, 26.6, 26.5, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 unknown
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3.

CC component owner: @KochetovNicolai @novikd

Analysis metadata

comp-query-analyzer · Severity P2 · Finding phase_d_pr115740

  • Verified against master build 1562fec97aea (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 25.8
Introducing change: not identified
  • Secondary components: comp-query-execution, comp-testing

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Two corrections to that target list. I measured both just now.

26.5 is retired: it is absent from the active release set (26.3, 26.6, 26.7, 26.8, taken from the open PRs labelled release), it has no open PRs based on it, and its last merges were on 2026-08-27. No label can reach it.

26.8 already carries the fix. It was cut 2026-08-24T08:20Z, after this PR merged (2026-08-22T18:08Z), so it inherited a0820c0ba3b4 at the cut with no cherry-pick: compare/26.8...a0820c0ba3b4 is behind with ahead_by = 0. For 26.3, 26.6 and 26.7 the same comparison is diverged, which matches the reproducer.

So the gap is exactly 26.3, 26.6, 26.7, and one label covers all three: could a maintainer apply v26.3-must-backport? It marks the oldest release to reach and expands to it plus every newer active branch, and 26.8 is skipped there by cherry_pick.py::pre_check, which returns early when the merge commit is already an ancestor of the branch head.

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants