Repository navigation
Fix LOGICAL_ERROR for reused materialized CTE filtered by IN over another materialized CTE - #105041
Conversation
The optimization step is moved one level up, into a dedicated first traversal of resolveMaterializingCTEs introduced in the next commit. This lets the recursive buildSetInplace / buildOrderedSetInplace path win the inner safety-net DelayedMaterializingCTEsStep's claim before the outer step attempts its own claim. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The first traversal optimizes every materialized CTE's pre-built plan and reports whether any DelayedMaterializingCTEsStep exists in the tree. The second traversal -- skipped entirely when the first saw none -- replaces DelayedMaterializingCTEsStep nodes with MaterializingCTEsStep, attaching plans for any CTEs not already claimed inplace. Why this fixes the LOGICAL_ERROR -------------------------------- Today makePlansForCTEs did three things atomically: it exchange'd is_materialization_planned, it called materialized_cte->plan->optimize, and it std::moved the plan into the synthesized MaterializingCTEsStep. The outer DelayedMaterializingCTEsStep[ct] in the main plan won the exchange before descending into [rs]; by the time rs.plan->optimize fired buildSetInplace via KeyCondition or VirtualColumnUtils, the inner safety-net DelayedMaterializingCTEsStep inside the IN-subquery's plan found ct.is_materialization_planned already true and degraded to a pass-through. The synchronously executed pipeline read ct.storage with is_built == false and threw. With two traversals, the optimize calls happen first across the entire tree, so the recursive buildSetInplace path gets to run makePlansForCTEs on the inner safety-net step before the outer step's claim is attempted. The outer step then sees the CTE already claimed and degrades to a harmless pass-through. For queries with no materialized CTEs at all (the common case), the first traversal walks the tree without doing any work, reports no DelayedMaterializingCTEsStep, and returns -- keeping the total work at one walk just like before. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…er CTE Covers the LOGICAL_ERROR path that fired when the outer DelayedMaterializingCTEsStep claimed the inner CTE before buildSetInplace had a chance to materialize it synchronously for primary-key / virtual-column analysis. Three query shapes: ANY LEFT JOIN on PK, cross-join on PK, ANY LEFT JOIN with the IN filter on a non-PK column (exercising the VirtualColumnUtils path). EXPLAIN is also checked because the bug fired during plan optimization -- the test only asserts that EXPLAIN produced at least one row so the reference file is not pinned to a specific plan shape. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… Expressions The two-traversal refactor in resolveMaterializingCTEs shifts the timing of `materialized_cte->plan->optimize` such that mergeExpressions now successfully collapses two adjacent ExpressionSteps in the materialized CTE's local Union branch (Project names + Change column names | Projection + Change column names to column identifiers). Functional results are unchanged (count() = 3 twice). The merged ExpressionStep performs identical work in a single transform. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [46bf468] Summary: ✅
AI ReviewSummaryThis PR rewires materialized CTE planning so PR Metadata
Findings
Tests
Final VerdictStatus: Minimum required actions: preserve materialized-CTE safety nets for non-SELECT set-plan callers, fix |
After the two-traversal split, makePlansForCTEs no longer calls plan->optimize -- that happens in DelayedMaterializingCTEsStep::optimizePlans during the first traversal. Drop the now-unused QueryPlanOptimizationSettings argument from the public method and from the local addPlansForMaterializingCTEs helper. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Just for posterity -- other (probably bad) attempts to fix this by me: |
This comment was marked as resolved.
This comment was marked as resolved.
A small utility to splice out a top-level `DelayedMaterializingCTEsStep` from a plan, replacing it with its single original child. Used by the upcoming change to `DelayedCreatingSetsStep::makePlansForSets` to strip the safety-net materialization step from set plans being attached for runtime execution. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When a set's plan is being attached for runtime construction (via DelayedCreatingSetsStep → CreatingSetsStep), the safety-net DelayedMaterializingCTEsStep planted by forceMaterializeCTE is no longer needed: at runtime the outer MaterializingCTEsStep in the main plan materializes the CTE before the CreatingSetsStep's pipeline runs. The strip is non-recursive on purpose. Nested set subquery plans (reached via DelayedCreatingSetsStep inside this plan) may still be consumed by buildSetInplace / buildOrderedSetInplace during the subsequent plan->optimize() and need their safety-nets to claim. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous order claimed materialized-CTE plans at the outer level during resolveMaterializingCTEs before addStepsToBuildSets had a chance to trigger synchronous buildSetInplace / buildOrderedSetInplace via the recursive plan->optimize. When that synchronous inplace path then ran on a deeply nested IN-subquery filtered by a MergeTree primary key, the safety-net DelayedMaterializingCTEsStep inside the inplace pipeline saw the CTE's plan already moved out and degraded to a pass-through, producing LOGICAL_ERROR while reading the still-empty StorageMemory. Swapping the order lets the inplace path claim the CTE via the safety-net first; resolveMaterializingCTEs then materializes only the CTEs that the inplace path did not already handle, with main's outer step degrading to a pass-through in those cases. Closes #102320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…sted IN Issue #102320: the CTE `a` is referenced once at top level and once inside a WHERE id IN (... WHERE id IN (...)) chain that hits a MergeTree primary key. The PK pruning on the outer IN-subquery triggers buildOrderedSetInplace for the inner IN-subquery, which used to read an empty StorageMemory because main's resolveMaterializingCTEs had already claimed the CTE before addStepsToBuildSets fired the inplace path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… CreatingSetStep wrapper Two fixes for cases the initial single-step strip missed: 1. `addBuildSubqueriesForMaterializedCTEsIfNeeded` stacks one `DelayedMaterializingCTEsStep` per CTE dependency level on top of a plan. An IN-subquery that transitively references a chain of CTEs gets multiple safety-net steps stacked, so stripping just the topmost one leaves the next one in place. The remaining safety-net claims its CTE in the wrong scope when the recursive `plan->optimize` below runs `resolveMaterializingCTEs`, attaching that CTE's plan inside the set subquery's `CreatingSetsStep` instead of at the outer `MaterializingCTEsStep` in the main plan. The fix loops while the top of the chain is `DelayedMaterializingCTEsStep`. 2. `DelayedCreatingSetsStep::makePlansForSets` calls `FutureSetFromSubquery::build` first, which wraps the source plan with `CreatingSetStep`. That makes the plan root a `CreatingSetStep` with the safety-net chain as its child, not at the root itself. The helper now peeks past one non-Delayed wrapper to reach the chain. Without (1), the third query in `03821_materialized_cte_with_sets` (`WITH b AS MATERIALIZED (SELECT uid FROM a, a), a AS MATERIALIZED ... SELECT count() FROM (SELECT * FROM b WHERE uid in b) ... LEFT SEMI JOIN a ...`) regressed because the main IN-subquery's safety-net stack was `Delayed[a] → Delayed[b] → body`: stripping only the top left `Delayed[b]` in place, and the recursive `plan->optimize` then claimed `b` inside the IN-subquery's `CreatingSetsStep`, leaving the join's right side reading `a.storage` before the outer step had a chance to materialize it. Without (2), the helper was a no-op for any plan reached via `makePlansForSets` (since `build` always wraps with `CreatingSetStep`), which is the only call site for it. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lets DelayedMaterializingCTEsStep::optimizePlans dedup the plan->optimize(...) call across multiple DelayedMaterializingCTEsStep instances that share the same MaterializedCTE pointer (e.g. UNION branches plus the UNION-level step). Logically parallel to the existing is_materialization_planned flag, but for the optimize stage rather than the claim/move stage. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Before this commit, `DelayedMaterializingCTEsStep::optimizePlans` (pass 1 of `resolveMaterializingCTEs`) called `cte->plan->optimize(...)` once per Delayed step that referenced the CTE. For shapes where multiple Delayed steps share one `MaterializedCTE` pointer -- e.g. UNION/INTERSECT/EXCEPT branches plus the UNION-level step, all planted by `addBuildSubqueriesForMaterializedCTEsIfNeeded` -- the same plan was optimized N times. Optimize is idempotent, so this was a CPU regression rather than a correctness bug, but it scales with the number of UNION branches and the optimization itself walks the CTE plan tree (and recursively triggers no-op `buildSetInplace` calls on already-built sets). Claim `is_plan_optimized` atomically before invoking optimize, mirroring the existing `is_materialization_planned` claim in `makePlansForCTEs`. Addresses review comment on PR #105041: #105041 (comment) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…al shape The dedup commit (3a0728b + 6c08747) reduces redundant plan->optimize(...) invocations across DelayedMaterializingCTEsStep instances that share a MaterializedCTE pointer. With the dedup in place, mergeExpressions no longer fires the second time during pass 1 of resolveMaterializingCTEs and the two adjacent ExpressionSteps in the local Union branch stay unmerged -- matching the pre-PR shape this test originally expected. Reverts the cosmetic update introduced in 5b2a827 (which adjusted the reference for the merged shape that pass-1's redundant optimize calls used to produce). Functional results (count() = 3 twice) are unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Per the project rule "When mentioning logical errors, say 'exception' instead of 'crash', because they don't crash the server in the release build." Pure comment edit, no behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
The fix seems to be working; the only thing is that Bugfix validation (functional tests) is somehow broken (it seems it does not handle LOGICAL_ERROR without this fix properly). |
|
Bugfix validation check was broken in #104081. Details |
|
The test is flaky. |
Reusing a materialized CTE from IN subqueries — the shape trace_final has in SELECT_FEEDBACK_SCORES_STATS, where it feeds three id IN (SELECT ...) filters — intermittently raises LOGICAL_ERROR "Reading from materialized CTE before it has been materialized" on ClickHouse 26.3 and 26.4, surfacing as a 500 from the stats endpoints. That is a known upstream bug, not a problem with this query: ClickHouse/ClickHouse#101940, fixed on master by ClickHouse/ClickHouse#105041 (pr-critical-bugfix). Upstream reports 26.3 and 26.4 affected, master and 26.5 clean; the 26.3 cherry-pick is still unmerged, so the version testcontainers pins (26.3.16.16) and the version staging and prod run (26.3.16.10001) both carry it. config-test.yml had the flag on so CI would cover the materialized plan. With it on, the shape reproduces: 18 ClickHouse errors -> 6 failed invocations in 4 of 10 local runs, and CI logged 12 errors that surefire's rerunFailingTestsCount=3 absorbed as 4 flakes, reporting the group green. Turning it off in tests removes that masked failure; the same 18 invocations now pass with no MATERIALIZED emitted at all. Both config comment blocks stay identical per convention, and rule 7 of the experimental-ClickHouse rule now says to check whether an experimental construct's fix actually reached the pinned branch before enabling it in tests. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rialized CTE filtered by IN over another materialized CTE
…rialized CTE filtered by IN over another materialized CTE
Two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. The set is built while the inner CTE is still unmaterialized, which raises Reading from materialized CTE '<name>' before it has been materialized On the debug build this branch ships, that aborts the server: production saw a user-data cluster restart five times in eleven minutes from exactly this query shape. On a release build the same query surfaces the error instead of killing the process, but it still cannot run. The test is committed as an executable reproducer and is expected to FAIL until the bug is fixed. No fix is included: an attempt to gate the standalone IN-set pipeline was measured against an unpatched binary of the same build type and changed no outcome on any of seven shapes, and a second attempt that materialized the CTEs in place regressed two shapes with "CTE is already built". Both were dropped rather than shipped. Upstream work on this family, none of it on this branch: ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489; ClickHouse#119714 is still open. This branch predates 26.4, so none of them apply cleanly. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis turns `x IN (subquery)` into a set built in place, executing that subquery during optimization. When the subquery reads another materialized CTE, that CTE's table is still empty at this point - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, the LOGICAL_ERROR aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Skip primary-key index analysis while optimizing CTE bodies in makePlansForCTEs. Nothing is lost: pipeline construction performs index analysis again, so the CTE's own reads still prune by primary key (verified with EXPLAIN indexes=1: 12 granules pruned to 1), and the main query's index analysis is untouched. Measured against an unpatched binary of the same build type over seven CTE shapes: the two failing shapes now pass, the other five are unchanged. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis turns `x IN (subquery)` into a set built in place, executing that subquery during optimization. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Two passes reach that code while planning a CTE body, so both are deferred: primary-key condition analysis and projection selection (optimizeUseNormalProjections -> selectRangesToRead -> buildIndexes also ends in buildOrderedSetInplace). Deferring only the first leaves the projection path live. The new defer_source_step_filter_analysis flag suppresses the call to applyFilters, not the collection of filters that precedes it in optimizePrimaryKeyConditionAndLimit. Dropping the whole pass would lose the predicates: a reused CTE over `WHERE id = 10` degraded from 1/100 to 100/100 granules with the primary key condition reported as `true`, and force_primary_key started failing with INDEX_NOT_USED. The held-back analysis runs once the CTE's plan is fully optimized and its dependencies are queued ahead of it, so the sets it builds read filled tables. Measured against an unpatched binary of the same build type: the two failing CTE shapes now pass, five other shapes are unchanged, pruning and force_primary_key behave as before the change, and the production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis turns `x IN (subquery)` into a set built in place, executing that subquery during optimization. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Plan CTE bodies with index analysis and projection selection held back, then replay a full optimization pass once the plan is complete and its dependencies are queued ahead of it, so the sets built then read filled tables. Both passes have to be deferred: optimizeUseNormalProjections reaches buildOrderedSetInplace through selectRangesToRead just as primary-key analysis does. Replaying rather than simply skipping matters. Filters are collected by optimizePrimaryKeyConditionAndLimit and acted on by applyFilters; dropping the pass outright lost the predicates, degrading a reused CTE over `WHERE id = 10` from 1/100 to 100/100 granules and failing force_primary_key. Text index function rewriting runs after index analysis and was silently skipped, so a CTE over a text index with a preprocessor returned no rows at all - a wrong result, not an error. applyFilters is now idempotent, since the replay pass walks steps the first pass already analyzed. Measured against an unpatched binary of the same build type: the two failing CTE shapes now pass, five other shapes are unchanged, primary-key pruning, force_primary_key, projection pruning and text-index results all match the unpatched binary, and the production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Known gap: force_optimize_projection still reports PROJECTION_NOT_USED for a materialized CTE referenced more than once, because the replay pass sees indexes already built. Unforced projection use is unaffected and prunes as before; a single-reference CTE and ordinary queries are unaffected. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis and PREWHERE optimization build `x IN (subquery)` sets in place, executing that subquery during optimization. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Suppress just those in-place set builds while a CTE body is planned, via a scoped guard checked in FutureSetFromSubquery::buildSetInplace and buildOrderedSetInplace. Callers already treat a null set as "this atom cannot be used for pruning" and carry on, so nothing else changes: every optimization pass still runs, filters are still collected and applied, text index functions are still rewritten, and projections are still selected. Disabling the passes instead was tried and rejected. Skipping primary-key analysis loses the predicates it collects, degrading a reused CTE over `WHERE id = 10` from 1/100 to 100/100 granules and failing force_primary_key. Skipping projection selection makes force_optimize_projection throw PROJECTION_NOT_USED. Skipping index analysis also skips the text index rewriting that runs after it, which returned no rows at all for a CTE over a text index with a preprocessor - a wrong result rather than an error. Replaying the passes afterwards conjoined each collected filter with itself. Measured against an unpatched binary of the same build type: the two failing CTE shapes now pass, five other shapes are unchanged, and primary-key pruning, force_primary_key, projection pruning, force_optimize_projection and text-index results all match the unpatched binary exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis and PREWHERE optimization build `x IN (subquery)` sets in place, executing that subquery during optimization. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Suppress those two in-place builds while a CTE body is planned, via a scoped guard. The two sites need different treatment: - FutureSetFromSubquery::buildOrderedSetInplace returns a set, and index analysis already treats a null result as "this atom cannot prune", so the guard returns null there. - The PREWHERE path is guarded at its call site in ReadFromMergeTree instead, next to the existing condition that skips it for the same underlying reason. buildSetInplace itself must not be short-circuited: VirtualColumnUtils builds a set and then immediately executes the filter expression, so returning early would leave a not-ready set and raise LOGICAL_ERROR on `_part`, `_partition_id` or Merge `_table`. Every optimization pass still runs: filters are collected and applied, text index functions are rewritten, projections are selected, and an IN subquery that does not read a materialized CTE is still built during index analysis and still prunes. Disabling passes instead was tried and rejected. Skipping primary-key analysis loses the predicates it collects, degrading a reused CTE over `WHERE id = 10` from 1/100 to 100/100 granules and failing force_primary_key. Skipping projection selection makes force_optimize_projection throw PROJECTION_NOT_USED. Skipping index analysis also skips the text index rewriting that runs after it, which returned no rows for a CTE over a text index with a preprocessor - a wrong result rather than an error. Replaying the passes afterwards conjoined each collected filter with itself. Measured against an unpatched binary of the same build type: the two failing CTE shapes now pass; five other shapes, primary-key pruning, force_primary_key, projection pruning, force_optimize_projection, text-index results and virtual-column filters all match it exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis builds `x IN (subquery)` sets in place, executing that subquery. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. While planning a CTE body, skip the in-place build only for sets whose own plan reads a CTE that is not built yet. buildOrderedSetInplace returns null there, which its callers already treat as "this atom cannot prune". PREWHERE takes a separate route into set building via buildSetsForDAGExcludingGlobalIn, so ReadFromMergeTree skips that call under the same condition and leaves those sets to CreatingSetsStep. The narrowing is what makes this safe, and several blunter versions were measured and rejected: - Suppressing every in-place set build inside a CTE body costs pruning for subqueries that read no CTE at all: `id IN (SELECT number FROM numbers(10, 1))` fell from 1/100 to 100/100 granules with the condition reported as `true`, and force_primary_key threw INDEX_NOT_USED. - Suppressing FutureSetFromSubquery::buildSetInplace is wrong regardless of narrowing: VirtualColumnUtils::buildFilterExpression evaluates the filter immediately after building its sets, so a skipped set surfaces as "Not-ready Set is passed as the second argument for function 'in'" on _part, _partition_id and Merge's _table. - Disabling the optimization passes instead loses the filters optimizePrimaryKeyConditionAndLimit collects, breaks force_optimize_projection, and skips the text index rewriting that runs after index analysis - which returned no rows at all for a CTE over a text index with a preprocessor, a wrong result rather than an error. Measured against an unpatched binary of the same build type: the two failing CTE shapes now pass, five other shapes are unchanged, and primary-key pruning, force_primary_key, projection pruning, force_optimize_projection, text-index results and virtual-column filters all match the unpatched binary exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis builds `x IN (subquery)` sets in place, executing that subquery. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Sets reach that code through four entry points, and each needs its own treatment while a CTE body is planned: - buildOrderedSetInplace, from index analysis: skip only when the set's own plan reads a CTE that is not built yet. Callers already treat a null set as "this atom cannot prune". Skipping unconditionally would cost pruning for subqueries reading no CTE at all - `id IN (SELECT number FROM numbers(10, 1))` fell to 100/100 granules and force_primary_key threw INDEX_NOT_USED. - applyFilters and updatePrewhereInfo, which build PREWHERE and row-level filter sets synchronously: skip the call. The race they guard against cannot occur here, since a CTE's plan runs on its own before any reader, so CreatingSetsStep can build them. - filterPartsByVirtualColumns: the predicate is evaluated immediately, so its sets cannot be left unbuilt - suppressing them surfaced as "Not-ready Set is passed as the second argument for function 'in'" on _part, _partition_id and Merge's _table. Skip the whole pruning step instead; every part stays a candidate and correctness is unaffected. Disabling optimization passes was tried first and rejected: it loses the filters optimizePrimaryKeyConditionAndLimit collects, breaks force_optimize_projection, and skips the text index rewriting that runs after index analysis, which returned no rows for a CTE over a text index with a preprocessor - a wrong result rather than an error. Measured against an unpatched binary of the same build type: four previously failing CTE shapes now pass, five others are unchanged, and primary-key pruning, force_primary_key, projection pruning, force_optimize_projection, text-index results and virtual-column filters all match the unpatched binary exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis and virtual column pruning build `x IN (subquery)` sets in place, executing that subquery. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Sets reach that code through several entry points. Each is now suppressed only when the predicate it is building actually reads a CTE that is not built yet, which the new dagReadsUnbuiltMaterializedCTE answers for a DAG and readsUnbuiltMaterializedCTE for a single set: - buildOrderedSetInplace, from index analysis: return null, which callers already treat as "this atom cannot prune". - applyFilters and updatePrewhereInfo, which build PREWHERE and row-level filter sets synchronously: skip the call and leave them to CreatingSetsStep. The race they guard against cannot occur here, since a CTE's plan runs on its own before any reader. - filterPartsByVirtualColumns and ReadFromMerge::getSelectedTables, which evaluate their predicate immediately: skip the whole pruning step, since leaving a set unbuilt surfaces as "Not-ready Set is passed as the second argument for function 'in'". Every part or table stays a candidate and the predicate is applied again when the query runs. Narrowing each guard to a real dependency is what keeps the rest intact. Suppressing unconditionally was measured and rejected twice: for ordered sets it cost pruning for subqueries reading no CTE at all, dropping `id IN (SELECT number FROM numbers(10, 1))` to 100/100 granules and failing force_primary_key; for virtual columns it stopped a plain `_partition_id = '10'` from pruning, turning one part into all of them and tripping max_rows_to_read. Disabling optimization passes was also tried and rejected: it loses the filters optimizePrimaryKeyConditionAndLimit collects, breaks force_optimize_projection, and skips the text index rewriting that runs after index analysis, which returned no rows for a CTE over a text index with a preprocessor - a wrong result rather than an error. Measured against an unpatched binary of the same build type: six previously failing CTE shapes now pass, five others are unchanged, and primary-key pruning, force_primary_key, projection pruning, force_optimize_projection, text-index results, virtual-column pruning plans and Merge-table filtering all match the unpatched binary exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Optimizing a query plan is not free of side effects: index analysis and virtual column pruning build `x IN (subquery)` sets in place, executing that subquery. When the subquery reads another materialized CTE, that CTE's table is still empty - its plan has only been scheduled, not run - and the read raises Reading from materialized CTE '<name>' before it has been materialized The shape that triggers it: two CTEs are both MATERIALIZED, the outer one's body reads the inner one, and the outer one is itself pulled into an IN-set. On the debug build this branch ships, that aborts the server; a production user-data cluster restarted five times in eleven minutes from exactly this query. Sets reach that code through several entry points. Each is suppressed only when the predicate it is about to build actually reads a CTE that is not built yet, which the new dagReadsUnbuiltMaterializedCTE answers for a DAG and readsUnbuiltMaterializedCTE for a single set: - buildOrderedSetInplace, from index analysis: return null, which callers already treat as "this atom cannot prune". - applyFilters and updatePrewhereInfo, which build PREWHERE and row-level filter sets synchronously: skip the call and leave them to CreatingSetsStep. The race they guard against cannot occur here, since a CTE's plan runs on its own before any reader. - filterPartsByVirtualColumns and ReadFromMerge::getSelectedTables, which evaluate their predicate immediately: skip the whole pruning step, since leaving a set unbuilt surfaces as "Not-ready Set is passed as the second argument for function 'in'". Every part or table stays a candidate and the predicate is applied again when the query runs. Where the check goes matters as much as the check itself. Both pruning steps first split out the sub-predicate they can evaluate, so the dependency is tested on that split DAG, not on the whole filter: a condition on an ordinary column never reaches them, and testing it there disabled pruning for the virtual column half of `_partition_id = '10' AND v IN (SELECT v FROM inner_cte)`, turning one part into all of them and tripping max_rows_to_read. Suppressing unconditionally was measured and rejected in the same way: for ordered sets it dropped `id IN (SELECT number FROM numbers(10, 1))` to 100/100 granules and failed force_primary_key; for virtual columns it stopped a plain `_partition_id = '10'` from pruning. Disabling optimization passes was also tried and rejected: it loses the filters optimizePrimaryKeyConditionAndLimit collects, breaks force_optimize_projection, and skips the text index rewriting that runs after index analysis, which returned no rows for a CTE over a text index with a preprocessor - a wrong result rather than an error. Measured against an unpatched binary of the same build type: six previously failing CTE shapes now pass, five others are unchanged, and primary-key pruning, force_primary_key, projection pruning, force_optimize_projection, text-index results, virtual-column pruning plans and Merge-table filtering all match the unpatched binary exactly. The production query behind the incident returns the same rows as the workaround of dropping one MATERIALIZED keyword. Upstream fixes for this family - ClickHouse#101305 (26.4), ClickHouse#105041 (26.6), ClickHouse#113489 - are all absent from this branch, which predates 26.4. ClickHouse#119714 is still open. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Motivation
Two related shapes of
LOGICAL_ERROR: Reading from materialized CTE 'X' before it has been materializedtriggered byenable_materialized_cte.Issue #101940:
Issue #102320:
EXPLAINon either query also threw — the bug fires during planoptimization, not just at execution time.
Root cause
The Planner installs two layers of
DelayedMaterializingCTEsStep:added by
addBuildSubqueriesForMaterializedCTEsIfNeededso the materializedCTEs run before the main pipeline at runtime.
forceMaterializeCTEso the synchronous inplace path(
FutureSetFromSubquery::buildSetInplace/buildOrderedSetInplace,reached via
KeyCondition::tryPrepareSetIndexForInorVirtualColumnUtils::buildSetsForDAG) can materialize a referenced CTEduring plan optimization.
makePlansForCTEsdid the atomic claim, theoptimizecall, and thestd::moveofmaterialized_cte->planin one step, andresolveMaterializingCTEsran beforeaddStepsToBuildSets. So in both bugshapes the outer step claimed the CTE and moved its plan out before the
inner safety-net inside the inplace pipeline could win the race —
the safety-net pass-throughs read an empty
StorageMemory.Fix
Three coordinated changes:
Split
resolveMaterializingCTEsinto two traversals. Pass 1(
DelayedMaterializingCTEsStep::optimizePlans) just optimizes each CTE'spre-built plan; pass 2 (the existing
addPlansForMaterializingCTEswalk)claims and attaches.
makePlansForCTEsno longer optimizes, only claimsand
std::moves. With this alone, the failing query from SEGV / LOGICAL_ERROR when materialized CTE is used in IN subquery of another materialized CTE referenced in a join #101940 isfixed because the safety-net inside
rs.plan->optimizeclaimsctduring pass 1, before main's pass 2 attempts the outer claim.
Run
addStepsToBuildSetsbeforeresolveMaterializingCTEsinQueryPlan::optimize. When the inplace path fires fromaddStepsToBuildSetson the main plan (LOGICAL_ERROR with materialized CTE #102320's shape, where the INtarget is a MergeTree column and the PK pruning fires during the
recursive
outer_IN.plan->optimize), the safety-net inside the nestedIN-subquery is now reached before the outer claim runs, again winning
the race.
Strip safety-net
DelayedMaterializingCTEsStepchains from set plansin
DelayedCreatingSetsStep::makePlansForSets. When a set plan isbeing attached for runtime construction (vs synchronous inplace
execution), its safety-nets are redundant — at runtime the outer
MaterializingCTEsStepmaterializes the CTE before theCreatingSetsStep's pipeline runs. Stripping the whole stacked chainprevents the recursive
plan->optimizefrom claiming the CTE in thewrong scope when the safety-net chain has multiple levels (one per
transitive CTE dependency). The strip handles
CreatingSetStepwrappingthe chain (added by
FutureSetFromSubquery::build).Test plan
04227_materialized_cte_reused_with_in_subquery.sqlcovers SEGV / LOGICAL_ERROR when materialized CTE is used in IN subquery of another materialized CTE referenced in a join #101940 inANY-LEFT-JOIN-on-PK, cross-join, non-PK IN (
VirtualColumnUtilspath),and EXPLAIN.
04228_materialized_cte_nested_in_subquery_pk.sqlcovers LOGICAL_ERROR with materialized CTE #102320 (CTEreferenced through a PK-pruned nested IN).
0380*/0392*/0400*/04036_…distributed_race/04041_…parallel_replicas/ etc.).04041_materialized_cte_parallel_replicas.referenceis updated: withthe new traversal timing,
mergeExpressionsnow merges two adjacentExpressionSteps in the CTE's local Union branch into one. Functionalresults unchanged.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed two
LOGICAL_ERROR: Reading from materialized CTE 'X' before it has been materializedshapes thrown by queries withenable_materialized_cte: (1) a reused materialized CTE filtered byIN (subquery)over another materialized CTE, and (2) a materialized CTE referenced both directly and inside aWHERE ... IN (...)filter that hits a MergeTree primary key through a nested IN-subquery.EXPLAINon the same queries was affected too because the bugs fired during plan optimization. Closes #101940, closes #102320.Documentation entry for user-facing changes
Version info
26.6.1.454