Repository navigation
Fix materialized-CTE gate torn down by an always-false ignore filter in lightweight mutations - #119715
Conversation
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]>
|
Workflow [PR], commit [5fb7b70] Summary: ✅
AI ReviewSummaryThis PR changes Final Verdict✅ No remaining findings from this review. LLVM Coverage ReportMeasured on commit 5fb7b70.
Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline. |
…d-cte-gate-ignore
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]>
|
🕵 Status after merging master into the branch:
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 @groeneai, investigate #120985 and provide a fix in a separate pull request. If a fix is already in progress, please link it there.
|
`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]>
…d-cte-gate-ignore
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]>
…d-cte-gate-ignore
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]>
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]>
…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]>
Closes: #119714
Related: #119489
Related: #116914
Related: #117311
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the
LOGICAL_ERRORReading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query planraised by a lightweightUPDATEorDELETEwhose predicate passes anINsubquery that defines aMATERIALIZEDCTE to a function such asignore, 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:
What breaks. The gate is not missing - the message misattributes it. An instrumented build shows
collectMaterializedCTEsreturning the CTE, theDelayedMaterializingCTEsStepplanted byMutationsInterpreter::buildSubqueryPlansForSetsAndAdd, andDelayedMaterializingCTEsStep::makePlansForCTEsclaiming it, so the CTE writer is attached.FilterTransformtreats a condition that is a constantignore(...)as always false and doesinput.close(); output.finish()the moment its output is needed. That teardown reaches the stackedMaterializingCTEsStepandCreatingSetsStepgates as a finished output, andDelayedPortsProcessor::preparereacted to any output update - finished ones included - by starting the inputs that have no output port, i.e. its side pipelines. TheIN-subquery source plan started that way still holds the CTE'sMemorySourcereaders, whose safety-net gateDelayedCreatingSetsStep::makePlansForSetshas 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
SELECTcounterpart is unaffected becauseoptimizePrewhere->ReadFromMergeTree::updatePrewhereInfo->buildSetsForDAGExcludingGlobalInbuilds the set in place while the source plan still has its safety net, so the CTE is materialized there. A mutation plan is built withoptimize_plan = falseand 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
MaterializingCTEsStepandCreatingSetsStepuseaddPipelineBefore, and for both the side pipeline exists solely to feed the main one.Validation.
05210_lightweight_update_materialized_cte_in_ignorecovers theUPDATE, theAND-with-a-second-INshape, the lightweightDELETE, and two positive controls; it returnsCode: 49on an unpatched26.9.1.1274build and passes after the change, as do theUNION ALLandINNER JOIN ... ONreuse variants.05182_lightweight_update_materialized_cte_in_subqueryand 33 of the 39materialized_cte/lightweight_updatetests pass; the other 6 needZooKeeperor 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
26.10.1.1450-master(included in26.10and later)