Skip to content

Fix LOGICAL_ERROR for reused materialized CTE filtered by IN over another materialized CTE - #105041

Merged
alexey-milovidov merged 34 commits into
masterfrom
fix-mat-cte
Jun 6, 2026
Merged

alexey-milovidov merged 34 commits into
masterfrom
fix-mat-cte

Conversation

@novikd

@novikd novikd commented May 15, 2026 •

Copy link
Copy Markdown
Member

Motivation

Two related shapes of LOGICAL_ERROR: Reading from materialized CTE 'X' before it has been materialized triggered by enable_materialized_cte.

Issue #101940:

WITH
    ct AS MATERIALIZED (SELECT c FROM t LIMIT 10),
    rs AS MATERIALIZED (SELECT * FROM t WHERE c IN (SELECT c FROM ct))
SELECT count()
FROM rs AS a ANY LEFT JOIN rs AS b USING c
SETTINGS enable_materialized_cte = 1;

Issue #102320:

WITH a AS MATERIALIZED (SELECT number AS id FROM numbers(100))
SELECT id FROM a
WHERE id IN (
    SELECT id FROM test
    WHERE id IN (SELECT id FROM a GROUP BY id)
    GROUP BY id
)
GROUP BY id;

EXPLAIN on either query also threw — the bug fires during plan
optimization, not just at execution time.

Root cause

The Planner installs two layers of DelayedMaterializingCTEsStep:

  1. Outer steps at the top of the main plan, one per CTE dependency level,
    added by addBuildSubqueriesForMaterializedCTEsIfNeeded so the materialized
    CTEs run before the main pipeline at runtime.
  2. Safety-net steps inside every IN-subquery's plan, planted by
    forceMaterializeCTE so the synchronous inplace path
    (FutureSetFromSubquery::buildSetInplace / buildOrderedSetInplace,
    reached via KeyCondition::tryPrepareSetIndexForIn or
    VirtualColumnUtils::buildSetsForDAG) can materialize a referenced CTE
    during plan optimization.

makePlansForCTEs did the atomic claim, the optimize call, and the
std::move of materialized_cte->plan in one step, and
resolveMaterializingCTEs ran before addStepsToBuildSets. So in both bug
shapes 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:

  1. Split resolveMaterializingCTEs into two traversals. Pass 1
    (DelayedMaterializingCTEsStep::optimizePlans) just optimizes each CTE's
    pre-built plan; pass 2 (the existing addPlansForMaterializingCTEs walk)
    claims and attaches. makePlansForCTEs no longer optimizes, only claims
    and 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 is
    fixed because the safety-net inside rs.plan->optimize claims ct
    during pass 1, before main's pass 2 attempts the outer claim.

  2. Run addStepsToBuildSets before resolveMaterializingCTEs in
    QueryPlan::optimize.
    When the inplace path fires from
    addStepsToBuildSets on the main plan (LOGICAL_ERROR with materialized CTE #102320's shape, where the IN
    target is a MergeTree column and the PK pruning fires during the
    recursive outer_IN.plan->optimize), the safety-net inside the nested
    IN-subquery is now reached before the outer claim runs, again winning
    the race.

  3. Strip safety-net DelayedMaterializingCTEsStep chains from set plans
    in DelayedCreatingSetsStep::makePlansForSets.
    When a set plan is
    being attached for runtime construction (vs synchronous inplace
    execution), its safety-nets are redundant — at runtime the outer
    MaterializingCTEsStep materializes the CTE before the
    CreatingSetsStep's pipeline runs. Stripping the whole stacked chain
    prevents the recursive plan->optimize from claiming the CTE in the
    wrong scope when the safety-net chain has multiple levels (one per
    transitive CTE dependency). The strip handles CreatingSetStep wrapping
    the chain (added by FutureSetFromSubquery::build).

Test plan

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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 materialized shapes thrown by queries with enable_materialized_cte: (1) a reused materialized CTE filtered by IN (subquery) over another materialized CTE, and (2) a materialized CTE referenced both directly and inside a WHERE ... IN (...) filter that hits a MergeTree primary key through a nested IN-subquery. EXPLAIN on the same queries was affected too because the bugs fired during plan optimization. Closes #101940, closes #102320.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.454

novikd and others added 4 commits May 15, 2026 16:08
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]>
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46bf468]

Summary: ✅


AI Review

Summary

This PR rewires materialized CTE planning so IN-subquery set construction cannot read a CTE before its writer has run. The core SELECT path is much better covered now, but I found two remaining regressions in surrounding pipeline/set-plan surfaces that should be fixed before merge.

PR Metadata
  • 💡 Changelog category should be Bug Fix (user-visible misbehavior in an official stable release), not Critical Bug Fix, because the release-build user impact is a LOGICAL_ERROR exception rather than data loss/RBAC.
  • 💡 The Changelog entry is specific, but issue-closing text should not be part of the changelog entry. Move these to standalone PR-description lines:
    Closes: https://github.com/ClickHouse/ClickHouse/issues/101940
    Closes: https://github.com/ClickHouse/ClickHouse/issues/102320
Findings

⚠️ Majors

  • [src/Processors/QueryPlan/CreatingSetsStep.cpp:244] removeAllDelayedMaterializingCTEsStep is applied for every DelayedCreatingSetsStep caller, but only the SELECT planner guarantees an outer DelayedMaterializingCTEsStep will replace the stripped safety net. Mutation plans built by MutationsInterpreter::buildSubqueryPlansForSetsAndAdd use forceMaterializeCTE inside the set subquery but do not add an outer materialized-CTE wrapper, so an ALTER TABLE ... WHERE x IN (WITH c AS MATERIALIZED (...) SELECT ... FROM c) shape can lose its only CTE writer/gate and hit the new is_built fail-fast.
    Suggested fix: strip safety nets only when the caller provides an enclosing CTE materialization step, or add equivalent materialized-CTE wrapping for mutation/non-SELECT callers before DelayedCreatingSetsStep.
  • [src/QueryPipeline/QueryPipelineBuilder.cpp:808] DroppingTransform uses the main data header for totals/extremes inputs. The previous dropTotals path used each aux port's own header, and Pipe::addTransform intentionally allows totals to differ from the data header because TotalsHavingTransform can produce finalized totals while data remains not finalized. In that valid shape, connect will throw while trying to discard totals.
    Suggested fix: let DroppingTransform take separate data/totals/extremes input headers, using pipe.getTotalsPort()->getSharedHeader() and pipe.getExtremesPort()->getSharedHeader() for aux inputs while keeping only data outputs.
Tests
  • ⚠️ Add a focused mutation regression with enable_materialized_cte = 1, an ALTER TABLE ... UPDATE or DELETE condition using IN (WITH c AS MATERIALIZED (...) SELECT ... FROM c), and mutations_sync = 2.
  • ⚠️ Add coverage that discarding totals/extremes works when the aux header differs from the main data header, either as a small processor test for DroppingTransform or a SQL query that reaches addCreatingSetsTransform/addMaterializingCTETransform with such totals.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: preserve materialized-CTE safety nets for non-SELECT set-plan callers, fix DroppingTransform aux-port headers, add the focused regressions above, and adjust the changelog metadata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 15, 2026
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]>
@novikd
novikd marked this pull request as ready for review May 15, 2026 15:10
@EmeraldShift

Copy link
Copy Markdown
Contributor

@alexey-milovidov

This comment was marked as resolved.

alexey-milovidov and others added 11 commits May 17, 2026 21:08
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]>
@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels May 18, 2026
@novikd

novikd commented May 18, 2026

Copy link
Copy Markdown
Member Author

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

@novikd

novikd commented May 19, 2026

Copy link
Copy Markdown
Member Author

Bugfix validation check was broken in #104081.

Details
  What actually happened on master (no-fix build)

  From bugfix_validation_functional_tests/job.log:

  - 14:19:09 — clickhouse-test … --jobs 9 -- 04227_… 04228_… starts
  - 14:20:15 — Hung check failed: server is not responding
  - 14:20:24 — Unable to locate any ClickHouse server process. It must have crashed or 
  exited prematurely!
  - 14:20:24 — Stopping tests, terminating all processes...
  - workers raise Terminated: 15 and exit before writing any [ FAIL ] line
  - 14:20:29 — Failed to reproduce the bug

  The LOGICAL_ERROR aborted the server (debug build), as evidenced by the artifact
  core.QueryCompPipeEx.1592-275296.zst.enc (core dump from the QueryCompletedPipelineEx…
  thread, 15-char comm truncation).

  Why the validation misreads it

  ci/jobs/scripts/functional_tests_results.py:13-15 defines:

  HUNG_SIGN         = "Found hung queries in processlist"
  SERVER_DIED_SIGN  = "Server died, terminating all processes"
  SERVER_DIED_SIGN2 = "Server does not respond to health check"

  None of these match what clickhouse-test actually emits today on the global-hung-check
  / server-crash path (tests/clickhouse-test:1117, 4898, 4903):

  ┌────────────────────────┬─────────────────────────────────────────────────────────┐
  │    Parser looks for    │             clickhouse-test actually emits              │
  ├────────────────────────┼─────────────────────────────────────────────────────────┤
  │ "Found hung queries in │ "Hung check failed: server is not responding"           │
  │  processlist"          │                                                         │
  ├────────────────────────┼─────────────────────────────────────────────────────────┤
  │ "Server died,          │                                                         │
  │ terminating all        │ "Stopping tests, terminating all processes..."          │
  │ processes"             │                                                         │
  ├────────────────────────┼─────────────────────────────────────────────────────────┤
  │ "Server does not       │ only in the per-test cleanup path                       │
  │ respond to health      │ (clickhouse-test:3444), which never runs here because   │
  │ check"                 │ workers were SIGTERM'd first                            │
  └────────────────────────┴─────────────────────────────────────────────────────────┘

@alexey-milovidov

Copy link
Copy Markdown
Member

The test is flaky.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 9, 2026
@groeneai groeneai mentioned this pull request Jul 1, 2026
1 task done
thiagohora added a commit to comet-ml/opik that referenced this pull request Aug 4, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rialized CTE filtered by IN over another materialized CTE
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rialized CTE filtered by IN over another materialized CTE
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 16, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

8 participants