Skip to content

Fix materialized-CTE gate torn down by an always-false ignore filter in lightweight mutations - #119715

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-lwu-materialized-cte-gate-ignore
Oct 3, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-lwu-materialized-cte-gate-ignore

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

Closes: #119714
Related: #119489
Related: #116914
Related: #117311

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 into CHANGELOG.md):

Fixed the LOGICAL_ERROR Reading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan raised by a lightweight UPDATE or DELETE whose predicate passes an IN subquery that defines a MATERIALIZED CTE to a function such as ignore, on a table read with more than one stream.

Description

Found by the AST fuzzer of the stress test on master: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=d65d51174b052223d9055573b011bdc817aafdb5&name_0=MasterCI&name_1=Stress%20test%20%28arm_asan_ubsan%29

Reproducer - three rows in three parts, default settings:

SET enable_analyzer = 1;
SET enable_materialized_cte = 1;
SET enable_lightweight_update = 1;

CREATE TABLE t (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (0, 0);
INSERT INTO t VALUES (1, 1);
INSERT INTO t VALUES (2, 2);

UPDATE t SET v = 250 WHERE ignore(id IN (WITH c AS MATERIALIZED (SELECT number * 2 AS x FROM numbers(3)) SELECT a.x FROM c AS a, c AS b));

What breaks. The gate is not missing - the message misattributes it. An instrumented build shows collectMaterializedCTEs returning the CTE, the DelayedMaterializingCTEsStep planted by MutationsInterpreter::buildSubqueryPlansForSetsAndAdd, and DelayedMaterializingCTEsStep::makePlansForCTEs claiming it, so the CTE writer is attached.

FilterTransform treats a condition that is a constant ignore(...) as always false and does input.close(); output.finish() the moment its output is needed. That teardown reaches the stacked MaterializingCTEsStep and CreatingSetsStep gates as a finished output, and DelayedPortsProcessor::prepare reacted to any output update - finished ones included - by starting the inputs that have no output port, i.e. its side pipelines. The IN-subquery source plan started that way still holds the CTE's MemorySource readers, whose safety-net gate DelayedCreatingSetsStep::makePlansForSets has already stripped on the premise that the outer gate dominates them, and the executor can dispatch those readers before the pairs are finished - while the CTE writer gated above is torn down the same way and never runs.

More than one reading stream is needed for it to surface: with a single part the teardown arrives as one all-outputs-finished event, no reader is ever scheduled and the same situation passes silently.

The SELECT counterpart is unaffected because optimizePrewhere -> ReadFromMergeTree::updatePrewhereInfo -> buildSetsForDAGExcludingGlobalIn builds the set in place while the source plan still has its safety net, so the CTE is materialized there. A mutation plan is built with optimize_plan = false and never reaches that path, so it depends entirely on the outer gate.

The change. Start a gate's side pipelines only once an output actually asks for data, which for a stacked gate happens only after the outer gate's own delayed pipelines are done. Nothing needs them when every output is already gone, so leaving them unstarted is the correct behaviour for a collapsing pipeline. Only MaterializingCTEsStep and CreatingSetsStep use addPipelineBefore, and for both the side pipeline exists solely to feed the main one.

Validation. 05210_lightweight_update_materialized_cte_in_ignore covers the UPDATE, the AND-with-a-second-IN shape, the lightweight DELETE, and two positive controls; it returns Code: 49 on an unpatched 26.9.1.1274 build and passes after the change, as do the UNION ALL and INNER JOIN ... ON reuse variants. 05182_lightweight_update_materialized_cte_in_subquery and 33 of the 39 materialized_cte / lightweight_update tests pass; the other 6 need ZooKeeper or a cluster and fail identically on an unpatched binary with the same server config, which is how they were ruled out.

Two other seams were tried first and measured not to fix this, in case they come up in review: restricting makePlansForSets's safety-net strip to the CTEs the outer plan gates (the CTE is gated, so the strip still happens), and keying the guard above on "some output is not finished" instead of "some output is needed" (with several streams the teardown is gradual, so live outputs remain and the wake still fires).


Workflow [PR]
Sync PR [sync-upstream/pr/119715]

Version info

  • Merged into: 26.10.1.1450-master (included in 26.10 and later)

A lightweight `UPDATE` or `DELETE` whose predicate hands an `IN` subquery that
defines a reused `MATERIALIZED` CTE to `ignore` failed with

    Logical error: Reading from materialized CTE 'c' before its materialization
    completed - DelayedPortsProcessor gate is missing in the query plan

on a table read with more than one stream.

The gate is not actually missing: the mutation plan plants the
`DelayedMaterializingCTEsStep` and `makePlansForCTEs` claims the CTE, so the
writer is attached. What happens instead is that `FilterTransform` treats a
condition that is a constant `ignore(...)` as always false and closes its input
the moment its output is needed. That teardown travels down into the stacked
`MaterializingCTEsStep` and `CreatingSetsStep` gates as a finished output, and
`DelayedPortsProcessor::prepare` reacted to any output update - finished ones
included - by starting the inputs that have no output, i.e. its side pipelines.
The `IN`-subquery source plan started that way still has its `MemorySource`
readers of the CTE, and the executor can dispatch them before the pairs are
finished, while the CTE writer gated above is being torn down the same way and
never runs. A single reading stream hid this because the teardown then reaches
the gate as one all-outputs-finished event.

Start those pipelines only once an output actually asks for data, which for a
stacked gate happens only after the outer gate's own delayed pipelines are
done. Nothing needs them when every output is already gone.

Found by the AST fuzzer of the stress test on master:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=d65d51174b052223d9055573b011bdc817aafdb5&name_0=MasterCI&name_1=Stress%20test%20%28arm_asan_ubsan%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5fb7b70]

Summary: ✅


AI Review

Summary

This PR changes DelayedPortsProcessor so the side pipelines planted by addPipelineBefore start only after some output actually requests data, which prevents a torn-down outer gate from prematurely starting the IN-subquery readers behind a MATERIALIZED CTE during lightweight UPDATE / DELETE. I re-read the current diff, the prior review thread, and the current green CI report; the updated test now pins the stream multiplicity at the DelayedPorts gate itself, so I do not see remaining correctness or coverage issues in the patched shape.

Final Verdict

✅ No remaining findings from this review.

LLVM Coverage Report

Measured on commit 5fb7b70.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5fb7b70cf with master bfc1f5928 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits September 19, 2026 06:45
The test only checked the final row values, so a planner change that inlines the
reused `MATERIALIZED` CTE, or a read-path change that collapses the three-part
table back to a single stream, would keep every assertion passing while no longer
exercising the gate this fixes.

Pin both properties explicitly:

* the reused CTE really materializes - an `EXPLAIN` of the `IN` subquery must
  contain a `MaterializingCTE` step;
* the table is read from three separate parts, and the mutation itself really
  read more than one of them - `ProfileEvents['SelectedParts']` of the `UPDATE`
  is read back from `system.query_log`. With a single reading stream no reader
  of the set's source plan is ever scheduled and the bug is invisible.

`max_threads` is pinned so the stream count does not depend on the randomized
settings of the CI runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status after merging master into the branch:

Stress test (arm_tsan) hit the same error class this pull request is about, but a different shape - a UNION ALL of two branches, each with chained MATERIALIZED CTEs (d reading c), and no ignore anywhere:

UPDATE t SET v = 100 WHERE v IN (
    WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)),
         d AS MATERIALIZED (SELECT x + 1048577 AS y FROM c)
    SELECT DISTINCT a.y FROM d AS a, d AS b
    UNION ALL
    WITH c AS MATERIALIZED (SELECT number AS x FROM numbers(3)),
         d AS MATERIALIZED (SELECT x + 200 AS y FROM c)
    SELECT a.y FROM d AS a, d AS b);

I minimised it to three rows in three parts and proved it is not caused by this pull request with a control binary: master 6f5373e9a821dd593866f044d5244c807d8873fb (26.10.1.119, build_arm_release from CI, without this patch) fails identically. That is consistent with the change here, which only removes a premature setNeeded of the side pipelines when no output needs data at all - it can never make a reader run earlier than its writer. Filed separately as #120985.

@groeneai, investigate #120985 and provide a fix in a separate pull request. If a fix is already in progress, please link it there.

Upgrade check (amd_release) failed with Logical error: Virtual row has different type for A. Expected B, got C (STID 1637-309b). That was a fleet-wide burst on 2026-09-11 .. 2026-09-14 hitting over a hundred unrelated pull requests and master itself, with no occurrence since 2026-09-14; merging master clears it.

`max` over the mutation's `system.query_log` entries instead of the last one, and
skip the test where the pin cannot hold: a `Replicated` database enqueues the
`UPDATE` as a replicated DDL, so the initiator's entry carries no `SelectedParts`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits September 25, 2026 12:11
Address review: `ProfileEvents['SelectedParts']` counts parts selected for
reading, not read streams, so a `ReadFromMergeTree` change collapsing three
parts into one stream would keep the pin green. Count the mutation's own
`MergeTreeSelect` source processors in `system.processors_profile_log`
instead - one per reading stream.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Counting `MergeTreeSelect` sources does not prove multiple streams reach the
gate, since `ReadFromMergeTree` may resize its pipe afterwards. Read the
fan-out of the `MaterializingCTEs` step's own `DelayedPorts` processor from
`system.processors_profile_log` instead: `parent_ids` has one entry per
connected output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 10, 2026
The previous guard made the six multi-output transforms request input only
while an unfinished output could take a chunk (`canPush`), which also removed
their existing prefetch while every output holds data. That is a behaviour
change outside the teardown this PR fixes, and CI measured it on the INSERT
fan-out to materialized views, where `CopyTransform` feeds every view:
`03652_threads_count_insert` got 5 instead of 7 peak threads, and
`test_materialized_views_cascaded_multiple` saw its views run in another
order (`42,0` instead of `42,2` with `max_threads = 1`). The master unit test
`ScatterByPartition.DoesNotPullAnotherChunkWhileOneIsPending`, which encodes
that prefetch, failed as well.

The teardown only needs the start to be gated: a processor that no output
ever asked for must not wake its sources. So each of the six now requests its
inputs for the first time only once an unfinished output `isNeeded()`, the
rule ClickHouse#119715 applied to `DelayedPortsProcessor` (`are_inputs_initialized`),
and behaves exactly as on master afterwards. In normal execution the first
`prepare()` of such a processor is caused by a consumer calling `setNeeded()`
on one of its outputs, so nothing changes there; in the teardown the outputs
only finish, so the inputs are never requested and the CTE readers in the
never-started `IN`-set plan do not run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 16, 2026
…ake data

A lightweight UPDATE/DELETE whose predicate is a constant `ignore(...)`
tears its pipeline down before it runs: `FilterTransform` closes on its
first `prepare`, and the stacked `DelayedCreatingSets` and
`MaterializingCTEs` gates finish all their pairs, which closes the
writer of a MATERIALIZED CTE unrun and closes the never-started `IN`-set
plan from its end. The close reaches a multi-output processor one output
at a time. `NegativeLimitTransform`, `NegativeOffsetTransform`,
`FractionalLimitTransform`, `FractionalOffsetTransform`, `CopyTransform`
and `ScatterByPartitionTransform` answered the first finished output by
calling `setNeeded()` on their inputs although none of their outputs had
ever been needed, so a `MemorySource` reading the CTE ran before the
close caught up and threw "Reading from materialized CTE ... before its
materialization completed" (STID 2467-34d3, AST fuzzer, a mutation of
05210_lightweight_update_materialized_cte_in_ignore).

These six now follow the rule every single-output transform follows
(`ISimpleTransform::prepare`): request input only while an unfinished
output can take a chunk, otherwise withdraw the demand and return
`PortFull`. The predicate lives in `IProcessor::isAnyOutputPushable`.
ClickHouse#119715 applied the same rule to `DelayedPortsProcessor`. While some
output can take data the code path is unchanged.

The new test has one teardown statement per processor; each aborts on
master, and reverting any single guard brings back only its statement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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

2 participants