Repository navigation
Fix crash reading from materialized CTE before materialization - #101305
alexey-milovidov merged 6 commits into
Conversation
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 b) Root cause explained? ✅ c) Fix matches root cause? ✅ Adding d) Test intent preserved / new tests? ✅ New regression test e) Both directions demonstrated? ✅ Without fix: crashes on first execution (100% rate). With fix: 50/50 passes including 20/20 via test runner. |
|
cc @novikd @KochetovNicolai — could you review this? It fixes a crash where |
|
Workflow [PR], commit [6c89ecb] Summary: ✅ AI ReviewSummaryThis 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 ( ClickHouse Rules
Final Verdict
|
| 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)); |
There was a problem hiding this comment.
Changes in this file seem unrelated
There was a problem hiding this comment.
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.
| -- 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; |
There was a problem hiding this comment.
@groeneai Add tests when a materialized CTE is used multiple times within a single query
There was a problem hiding this comment.
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
yandw - 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.
5e6bccd to
cba98e9
Compare
|
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. |
|
@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.
|
Done — merged latest master (includes the SimSIMD SVE MSan fix from #101239) into the branch. CI should re-run with the fix included. |
|
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 I wonder if a more all-encompassing fix for this shape of error is to make |
LLVM Coverage Report
Changed lines: 100.00% (6/6) · Uncovered code |
|
Hi — this PR may need backporting to release branches 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 |
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]>
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]>
Changelog category (leave one):
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 = 1and a scalar subquery references a materialized CTE that depends on another CTE, the server crashes with:Minimal reproducer:
Root cause:
evaluateScalarSubqueryIfNeeded()(QueryAnalyzer phase) evaluates scalar subqueries by building and executing a pipeline inline. The sub-planner is created withis_subquery=true, causingcollectMaterializedCTEs()to return empty — so no CTE materialization steps are included. The pipeline then reads from CTEStorageMemorytables that haven't been populated.Fix (3 parts):
evaluateScalarSubqueryIfNeeded: AddforceMaterializeCTE()to the sub-planner options, ensuring CTE materialization steps are included when the scalar subquery's pipeline is executed. This matches the existing pattern inaddBuildSubqueriesForSetsStepIfNeededfor set subqueries referencing CTEs.Planner: Flatten nestedDelayedMaterializingCTEsStepnodes into a single step with all CTEs ordered from deepest dependency level to shallowest.MaterializingCTEsStep::updatePipeline: Chain CTE pipelines sequentially viaaddPipelineBeforeinstead ofunitePipelines, ensuring deeper CTEs (that others depend on) complete materialization before shallower CTEs start reading.Closes #100628
🤖 Generated with Claude Code
Version info
26.4.1.631