Skip to content

Fix crash reading from materialized CTE before materialization - #101305

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/cte-materialization-race-condition
Apr 8, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix/cte-materialization-race-condition

Conversation

@groeneai

@groeneai groeneai commented Mar 31, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed crash with "Logical error: Reading from materialized CTE before materialization" when a scalar subquery references a chain of dependent materialized CTEs.

What this PR does

When enable_materialized_cte = 1 and a scalar subquery references a materialized CTE that depends on another CTE, the server crashes with:

Logical error: 'Reading from materialized CTE 'y' before it has been materialized (materialization was planned: false)'

Minimal reproducer:

SET enable_materialized_cte = 1;
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(5)),
     w AS MATERIALIZED (SELECT * FROM y WHERE a > 0)
SELECT count() FROM y WHERE a != (SELECT min(a) FROM w);

Root cause: evaluateScalarSubqueryIfNeeded() (QueryAnalyzer phase) evaluates scalar subqueries by building and executing a pipeline inline. The sub-planner is created with is_subquery=true, causing collectMaterializedCTEs() to return empty — so no CTE materialization steps are included. The pipeline then reads from CTE StorageMemory tables that haven't been populated.

Fix (3 parts):

  1. evaluateScalarSubqueryIfNeeded: Add forceMaterializeCTE() to the sub-planner options, ensuring CTE materialization steps are included when the scalar subquery's pipeline is executed. This matches the existing pattern in addBuildSubqueriesForSetsStepIfNeeded for set subqueries referencing CTEs.

  2. Planner: Flatten nested DelayedMaterializingCTEsStep nodes into a single step with all CTEs ordered from deepest dependency level to shallowest.

  3. MaterializingCTEsStep::updatePipeline: Chain CTE pipelines sequentially via addPipelineBefore instead of unitePipelines, ensuring deeper CTEs (that others depend on) complete materialization before shallower CTEs start reading.

Closes #100628

🤖 Generated with Claude Code

Version info

  • Merged into: 26.4.1.631

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260331-061500)

a) Deterministic repro? ✅ Yes. The following crashes 100% of the time without the fix:

SET enable_materialized_cte = 1;
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(5)),
     w AS MATERIALIZED (SELECT * FROM y WHERE a > 0)
SELECT count() FROM y WHERE a != (SELECT min(a) FROM w)

Even EXPLAIN PLAN optimize=0 crashes — confirming the issue is in the QueryAnalyzer phase, not pipeline execution.

b) Root cause explained? ✅ evaluateScalarSubqueryIfNeeded() evaluates scalar subqueries during query analysis by building and executing a pipeline inline. The sub-planner uses is_subquery=true, which makes collectMaterializedCTEs() return empty. No CTE materialization steps are included in the sub-plan. When the pipeline executes, MemorySource::generate() reads from CTE StorageMemory that hasn't been populated → is_built=false → LOGICAL_ERROR crash.

c) Fix matches root cause? ✅ Adding forceMaterializeCTE() directly addresses the missing CTE materialization steps. The pipeline chaining fix ensures correct dependency ordering. Both address the identified mechanism.

d) Test intent preserved / new tests? ✅ New regression test 04076_materialized_cte_dependency_ordering covers: 2-CTE chain with scalar subquery, 3-level chain, multiple scalar subqueries, simple CTE dependency. All 4 cases produce correct results.

e) Both directions demonstrated? ✅ Without fix: crashes on first execution (100% rate). With fix: 50/50 passes including 20/20 via test runner.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It fixes a crash where evaluateScalarSubqueryIfNeeded executes a pipeline reading from materialized CTE StorageMemory tables before they're populated. The fix adds forceMaterializeCTE() in the scalar subquery evaluation (matching the existing pattern for set subqueries), and flattens + sequentially chains CTE materialization pipelines in MaterializingCTEsStep.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Mar 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6c89ecb]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness issue where scalar subquery evaluation could read from materialized CTE storage before required CTE materialization was planned/executed. The change (forceMaterializeCTE in evaluateScalarSubqueryIfNeeded) is consistent with existing planner patterns for set subqueries, and the added stateless regression test covers dependent chains and repeated references. I did not find blocker or major issues in the code or tests.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 31, 2026
@novikd novikd self-assigned this Mar 31, 2026
Comment thread src/Planner/Planner.cpp Outdated
Comment on lines +1618 to +1626
all_ctes.push_back(materialized_cte);
}
}

if (!all_ctes.empty())
{
auto delayed_step = std::make_unique<DelayedMaterializingCTEsStep>(
query_plan.getCurrentHeader(),
std::move(ctes));
std::move(all_ctes));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Changes in this file seem unrelated

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You're right — removed. The existing nested DelayedMaterializingCTEsStep architecture already handles CTE dependency ordering correctly: post-order resolution in resolveMaterializingCTEs ensures deeper-level steps resolve before outer ones, and addPipelineBefore enforces the correct execution sequence. The crash was entirely in the scalar subquery evaluation path (evaluateScalarSubqueryIfNeeded), not in the pipeline-level CTE orchestration. Reverted.

Comment on lines +9 to +28
-- Case 1: scalar subquery referencing a CTE that depends on another CTE
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(5)),
w AS MATERIALIZED (SELECT * FROM y WHERE a > 0)
SELECT count() FROM y WHERE a != (SELECT min(a) FROM w);

-- Case 2: 3-level CTE chain with scalar subquery
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(10)),
w AS MATERIALIZED (SELECT * FROM y WHERE a > 2),
z AS MATERIALIZED (SELECT * FROM w WHERE a < 8)
SELECT count() FROM z WHERE a != (SELECT min(a) FROM y);

-- Case 3: multiple scalar subqueries referencing different CTEs
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(5)),
w AS MATERIALIZED (SELECT * FROM y WHERE a > 0)
SELECT (SELECT min(a) FROM w), (SELECT max(a) FROM y), count() FROM y;

-- Case 4: simple CTE dependency without scalar subquery (should still work)
WITH y AS MATERIALIZED (SELECT number AS a FROM numbers(5)),
w AS MATERIALIZED (SELECT * FROM y WHERE a > 0)
SELECT count() FROM w;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai Add tests when a materialized CTE is used multiple times within a single query

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added 3 multi-reference test cases (Cases 5-7):

  • Case 5: Same CTE referenced 4 times via scalar subqueries (count(), sum(), min()) and FROM
  • Case 6: Two dependent CTEs, both referenced multiple times — scalar subqueries from both y and w
  • Case 7: CTE used in a self-join (y AS y1 INNER JOIN y AS y2) plus scalar subquery

All 7 cases pass 50/50 with full randomization.

Scalar subqueries referencing materialized CTEs crash during
QueryAnalyzer's evaluateScalarSubqueryIfNeeded() because the sub-planner
uses is_subquery=true, causing collectMaterializedCTEs() to return empty.
The pipeline then reads from unpopulated CTE StorageMemory tables.

Fix: call forceMaterializeCTE() on the sub-planner options, following
the same pattern used for set subqueries in
addBuildSubqueriesForSetsStepIfNeeded.

Add regression tests covering: dependent CTE chains with scalar
subqueries, 3-level chains, multiple scalar subqueries, self-joins,
and CTEs referenced multiple times within a single query.
@groeneai
groeneai force-pushed the fix/cte-materialization-race-condition branch from 5e6bccd to cba98e9 Compare March 31, 2026 16:58
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@groeneai

groeneai commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Done — branch updated to include the SimSIMD fix (#101239) and latest master. Fresh CI should run now.

…1239)

Update branch as requested by @alexey-milovidov to resolve arm_msan
stress test failures.
@groeneai

groeneai commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator Author

Done — merged latest master (includes the SimSIMD SVE MSan fix from #101239) into the branch. CI should re-run with the fix included.

@EmeraldShift

Copy link
Copy Markdown
Contributor

Hi @novikd -- I think I ran into something similar to this in #101940. Do you expect this PR to be merged soon? When is the soonest I can expect the fix to be backported to 26.3 and available in an official build? Thanks!

@EmeraldShift

Copy link
Copy Markdown
Contributor

Actually, after looking at this PR more carefully, it looks like it will not cover the bug reported inhttps://github.com//issues/101940: this happens in evaluateScalarSubqueryIfNeeded, while that crash happens in buildOrderedSetInplace. The two issues are related, but I guess that they don't overlap in code.

I wonder if a more all-encompassing fix for this shape of error is to make MemorySource itself handle the unmaterialized case correctly: when MemorySource::generate() encounters is_built == false, instead of throwing, it should execute the CTE's materialization pipeline inline to populate the table, then proceed normally. Maybe this is tricky w/ makePlansForCTEs moving the plans away?

@novikd

novikd commented Apr 7, 2026

Copy link
Copy Markdown
Member

#101940 is a completely different issue; it won't be fixed in this PR.
#100628 is related to query analysis, and #101940 is related to query planning.

@clickhouse-gh

clickhouse-gh Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 100.00% (6/6) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 8, 2026
Merged via the queue into ClickHouse:master with commit 8747665 Apr 8, 2026
161 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to release branches 26.3, but no backport label was found.

Why: The enable_materialized_cte setting was introduced in 26.3 (SettingsChangesHistory.cpp shows it in both 26.3 and 26.4). The LOGICAL_ERROR crash affects users who enable this feature. Only 26.3 needs backporting since the feature doesn't exist in earlier branches.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 17, 2026
A scalar subquery is planned with SelectQueryOptions(is_subquery = true),
which makes collectMaterializedCTEs return nothing. No materialization
step is added to that plan, so at run time the pipeline reads a
materialized CTE's table while it is still empty:

  Reading from materialized CTE '<name>' before it has been materialized

Unlike the in-place set builds handled earlier on this branch, this one
fails during execution rather than planning - the stack ends in
MemorySource::generate under PipelineExecutor, not under index analysis.

Set subqueries already call forceMaterializeCTE for exactly this reason;
scalar subqueries need the same. This is the fix upstream shipped as
ClickHouse#101305, which this branch predates.

Found by running the second production query from the incident, the
volo-vaults portfolio snapshot: fifteen materialized CTEs where
`candidate_snapshot` is read through `(SELECT checkpoint FROM snapshot)`.
It now returns rows; before this commit it raised LOGICAL_ERROR on both
the patched and unpatched binaries, so this is a gap in coverage rather
than a regression.

Verified against an unpatched binary of the same build type: the seven
CTE shapes and every earlier review case are unchanged, primary-key,
ordinary-IN and projection pruning still report 1/100 granules,
force_primary_key and text-index results are unaffected, and the cetus
query returns the same rows as before.

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

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Reading from materialized CTE 'A' before it has been materialized (materialization was planned: B) (STID: 2467-2c2d)

7 participants