Skip to content

Do not start reading in multi-output transforms before an output asks for data - #125043

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:processors-request-input-only-on-output-demand
Oct 16, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:processors-request-input-only-on-output-demand

Conversation

@groeneai

@groeneai groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119715

Changelog category (leave one):

  • Improvement

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

Negative and fractional LIMIT/OFFSET, GROUPING SETS and window functions with PARTITION BY now wait until a downstream step asks for data before reading their input, so a lightweight UPDATE or DELETE whose ignore(...) predicate holds an IN subquery over a MATERIALIZED CTE no longer fails with a logical error.

Description

Found by the AST fuzzer (STID 2467-34d3) on 2 unrelated PRs: report 1, report 2.

Repro on master (t: MergeTree with block number/offset columns, rows 0, 1, 2 in one part):

SET enable_materialized_cte = 1, enable_lightweight_update = 1, max_threads = 3;
UPDATE t SET v = 1 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 GROUP BY a.x LIMIT -2));
-- Logical error: 'Reading from materialized CTE 'c' before its materialization completed ...'

Cause: the constant ignore(...) filter tears the mutation pipeline down before it runs, which closes c's writer unrun and the never-started IN-set plan from its end. A multi-output processor in that plan sees its outputs finish one at a time; six of them answered the first one by requesting input, although no output was ever needed, so a reader of c ran.

Change: each of the six requests its inputs for the first time only once an unfinished output asks for data (IProcessor::isAnyOutputNeeded), the rule #119715 applied to DelayedPortsProcessor; after that it behaves as before. In normal execution that first request is caused by a consumer asking for data, so only a processor nobody asked is affected. Open #114550 adds a stricter per-call guard to ScatterByPartitionTransform that subsumes this one.

Validation: new test 05355_lightweight_update_materialized_cte_set_teardown, one statement per processor; each aborts on master and passes with the change. 50 randomized runs pass. The processors' unit tests and 819 related stateless tests (materialized-view fan-out incl. 03652_threads_count_insert, distributed broadcast/shuffle, windows, grouping sets, negative/fractional limits) give the same results with and without the change.


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

Version info

  • Merged into: 26.11.1.43-master (included in 26.11 and later)

groeneai and others added 2 commits October 10, 2026 07:38
…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]>
Drop the over-general second sentence of the isAnyOutputPushable doc comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Oct 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own review of the same head (4 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 Copy/Scatter no longer prefetch one input chunk while every output holds data AGREE, noted a consumer's pull re-prepares the processor, so this is the ISimpleTransform protocol; the Performance Comparison check of this PR measures it
2 💡 DelayedPortsProcessor keeps its own inline "any output needed" check (#119715) AGREE, noted it runs before anything is pushed, where it equals the new helper; left unchanged

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261010-074200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Each of the 7 teardown statements of the new test aborts 3/3 on master (debug, clickhouse local, one part, max_threads = 3); the exact fuzzer query aborts 3/3 too.
b Root cause explained? Yes. The constant ignore(...) filter tears the mutation down before it runs; the never-started IN-set plan is closed from its end, and six multi-output processors answered the first finished output by requesting input, so a reader of the unwritten MATERIALIZED CTE ran.
c Fix matches root cause? Yes. The six processors now request input only while an unfinished output can take a chunk (the ISimpleTransform rule); the reader's check and the gates are unchanged.
d Test intent preserved / new tests added? Yes. New 05355_lightweight_update_materialized_cte_set_teardown: one statement per processor plus two statements that still need the same sets. No existing test changed.
e Both directions demonstrated? Yes. Master and a build with the six guards reverted: all 7 statements abort, and the test aborts the server under clickhouse-test. With the change: 7/7 OK 3/3, 50/50 randomized runs OK.
f Fix is general across code paths? Yes. All processors with more than one output were checked; these six were the only ones requesting input without output demand. Reverting any one guard brings back exactly its statement.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. 2- and 3-stream inputs, GROUP BY and UNION ALL, 1 -> N fan-outs, UPDATE and DELETE, Nullable keys from the fuzzer query; the guard depends on port state only.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. 716 related tests (limits, grouping sets, windows, runtime filters, MV fan-out, broadcast/shuffle joins) give identical results with and without the change.
i Invariants and contracts preserved? Yes. prepare returns PortFull only when no output can take data (its documented meaning); input demand comes back on the next prepare with a pushable output; the all-outputs-finished branch still closes the inputs first.

Session id: cron:clickhouse-impl-slot-4:20261010-045900

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [956a755]

Summary: ✅


AI Review

Summary

This PR makes the first input request in Copy, ScatterByPartition, negative/fractional LIMIT/OFFSET, and the related multi-output processors wait for actual downstream demand, which matches the existing demand-driven processor contract and addresses the teardown path behind the MATERIALIZED CTE LOGICAL_ERROR. I reviewed the diff, the touched processor state machines, and the prior discussion, and I did not find a correctness, concurrency, or protocol regression in the current patch.

Final Verdict

✅ No blocking or major issues found. I did not post any new inline review comments.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 10, 2026
@groeneai
groeneai requested review from davenger and nihalzp October 10, 2026 08:34
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 10, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai how related to #123121 this PR is?

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 956a755d4 with master 18b5a991f (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

They are independent. Both involve a MATERIALIZED CTE read inside an IN set, but they are different bugs at different layers, share no files, and can be merged in either order.

  • Materialize a reused MATERIALIZED CTE before a parallel replicas read with a local plan sends it to the replicas #123121 fixes UNKNOWN_TABLE on the other replicas with parallel replicas and parallel_replicas_local_plan = 1 (05182, 05230, and 05210 in the ParallelReplicas jobs): the query sent to the replicas reads the CTE's temporary table before it is written. Its only behavior change is one call in executeQueryWithParallelReplicas.
  • This PR fixes the AST fuzzer LOGICAL_ERROR "Reading from materialized CTE ... before its materialization completed" (STID 2467-34d3) on fuzzer mutations of the 05210 query. A constant ignore(...) tears the lightweight mutation pipeline down before it runs, and six multi-output transforms then request input although none of their outputs can take data, so a CTE reader runs while its writer never started.

Neither covers the other: this PR's test aborts in clickhouse local on current master (d741c98), where #123121's change is never reached, and this PR adds no ordering between the CTE writer and the replicas' query. The only link is that this PR's test is tagged no-parallel-replicas because of #112642, which #123121 closes.

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]>
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-improvement Pull request with some product improvements 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.

4 participants