Repository navigation
Plant the materialization gate in a nested set subquery's own plan - #115740
alexey-milovidov merged 4 commits into
Conversation
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.
Internal second-model review (click to expand)Before publishing I reviewed this change independently of the author, then had a second model
Both directions are demonstrated on Build-ID-verified binaries: on the base binary the new test Session id: cron:clickhouse-review-slot-9:20260821-065000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260821-050700 |
|
Workflow [PR], commit [17a92bd] Summary: ✅
AI ReviewSummaryThis PR fixes the missing materialization gate for Final Verdict✅ No blocking issues found. No new inline review comments were posted. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/32 (93.75%) · Uncovered code |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units9 translation units recompiled, 26 s compile time in total, 9 of them have a recent master baseline. |
|
@PedroTadim These fix two different shapes of the same signature, so neither one replaces the other. #113489 plants the gate at the two The public evidence is on #113489 itself: STID 2467-2c2d fired again on its own head If you would rather have a single change, say which one to withdraw or fold and I will do that. |
a0820c0
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:
Backport the fix to CC component owner: @KochetovNicolai @novikd Analysis metadata
Introducing change: not identified
|
|
Two corrections to that target list. I measured both just now.
So the gap is exactly |
Changelog category (leave one):
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 aMATERIALIZEDCTE is read from inside anINsubquery over aDistributedtable. Closes #113184.Description
Closes #113184. A
MATERIALIZEDCTE read from inside anINsubquery over aDistributedtable failed withCode: 49. Reading from materialized CTE 'ct' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan. Reproducer in #113184:Root cause. A set subquery is planned with
forceMaterializeCTEbecausebuildOrderedSetInplacemay execute it as a standalone pipeline, with no outer processor to gate its CTE readers. ButcollectMaterializedCTEsdeclined the reference: inside a set subquery it hasisMaterializedCTE() == false(the subquery child was detached bydetachQueryTree) andhasPlanOrBuilt() == false. Nothing was collected,addBuildSubqueriesForMaterializedCTEsIfNeededreturned 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_cteis 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, somakePlansForCTEsnow 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 pathforce_materialize_cteis false andEXPLAINoutput 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]