Skip to content

Fix materialized CTE read before materialization on EXPLAIN ANALYZE - #113683

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-querypipeline-complete-drops-gated-totals-extremes
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-querypipeline-complete-drops-gated-totals-extremes

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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 into CHANGELOG.md):

Fixed the LOGICAL_ERROR Reading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan when EXPLAIN ANALYZE runs a query that reads a materialized CTE behind an IN subquery together with extremes = 1 or GROUP BY ... WITH TOTALS.

Description

QueryPipelineBuilder::addPipelineBefore routes the totals and extremes streams through the DelayedPortsProcessor that gates a materialized CTE read, so they are gate output ports.

QueryPipeline::complete discarded them by attaching a NullSink. A NullSink has no outputs, so ExecutingGraph::initializeExecution seeds it and it runs first, and its prepare closes its input without ever pulling. That finishes a gate output; the gate finishes the pair and closes the paired input; the gated sub-pipeline is released. The CTE read then runs before MaterializingCTETransform has built it and the fail-fast check in ReadFromMemoryStorageStep throws, aborting the server in a build with assertions.

The two streams are now discarded with a DroppingTransform on the main output instead. It forwards the data stream 1:1 and drains totals/extremes, so it keeps data outputs and is not seeded. This is the mechanism 641fc75ea3f0d37 already established for the builder's own drop sites; extending it here leaves the file with no producer of an output-less discard node, so drop and the NullSink.h include are deleted. The helper returns immediately when neither port exists.

Reached from ordinary SQL, with only enable_materialized_cte gated. This does not close #110176 by itself, although it does fix that issue's reproducer: INSERT ... SELECT and an aggregating subquery reach the same error through dropTotalsAndExtremes, a separate site that #111194 addresses.

Validation: the four EXPLAIN ANALYZE shapes abort on unpatched master and pass with the change. Four mutants each redden the new test: reverting the helper call, discarding the aux ports with NullSink while keeping the transform, and corrupting a control or a witness reference line. Reintroducing a drop call no longer compiles. The test passes 100/100 runs (50 randomized, 50 not), and across 262 stateless cases using extremes, WITH TOTALS, EXPLAIN ANALYZE or materialized CTEs no case fails only with the change and no failure reason changes.

`QueryPipelineBuilder::addPipelineBefore` routes the totals and extremes streams through the
`DelayedPortsProcessor` that gates a materialized CTE read, so those streams are gate output
ports.

`QueryPipeline::complete` discarded them by attaching a `NullSink`. A `NullSink` has no
outputs, so `ExecutingGraph::initializeExecution` seeds it and it runs before anything else;
its `prepare` closes its input without ever pulling. That finishes a gate output, the gate
finishes the pair and closes the paired input, and the gated sub-pipeline is released. The
CTE read then runs before `MaterializingCTETransform` has built it and the fail-fast check in
`ReadFromMemoryStorageStep` throws:

    Reading from materialized CTE 'a' before its materialization completed -
    DelayedPortsProcessor gate is missing in the query plan

Discard the two streams with a `DroppingTransform` on the main output instead. The transform
forwards the data stream 1:1 and drains totals/extremes, so it keeps data outputs and is not
seeded. This is the mechanism 641fc75 already established for the builder's own drop
sites; extending it here removes the last producer of an output-less discard node in this file,
so `drop` and the `NullSink.h` include are no longer needed.

Reached from `EXPLAIN ANALYZE` over a materialized CTE read behind an IN-subquery with either
`extremes = 1` or `WITH TOTALS`. `INSERT ... SELECT` and an aggregating subquery reach the same
error through `QueryPipelineBuilder::dropTotalsAndExtremes`, which is a separate site and is
not changed here.

`complete(Chain)` shares the helper. It is reachable from SQL through a lightweight
`UPDATE`/`DELETE`, but every caller that reaches it drops totals and extremes earlier in
`InterpreterInsertQuery`, so it is always entered with both ports already null and the new test
does not cover it.
@groeneai

groeneai commented Aug 6, 2026

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

An independent cold review plus a second-model pass reviewed this change against the resulting
code, with the reviewer forbidden from editing any source or test file. One major finding, one
nit. Verdicts and evidence below.

⚠️ A non-consuming sink at a complete call site can still release the gate (pre-existing; this change reduces it)

The second-model pass found that ArrowFlightServer.cpp:1245 hands an output-less NullSink to
QueryPipeline::complete(std::shared_ptr<ISink>). ExecutingGraph::initializeExecution seeds every
node whose direct_edges are empty, so that sink is seeded, its prepare closes its input, and
DroppingTransform then closes its own data input and, on its terminal path, the totals and
extremes inputs. The mechanism is real and I confirm it.

Verdict: correct mechanism, not a defect of this change, and not part of its contract.

  1. It is not caused by this change, and this change strictly improves it. On unpatched master the
    same call site seeded three output-less nodes: the caller's NullSink plus one per aux port
    from the deleted drop, and each of the latter two closed a DelayedPortsProcessor output
    directly. After this change exactly one remains, the caller's own sink, and the two direct
    aux releases are gone. git diff --name-only over this branch is three files and none of them
    is ArrowFlightServer.cpp, which is byte-identical to the merge base.
  2. It is outside this change's contract. The changelog establishes that complete must not
    discard totals or extremes with an output-less node, which it no longer does. Whether a caller
    may pass an output-less sink is a property of that call site; the fix is in
    ArrowFlightServer.cpp (the reviewer's own suggested remedy is to use a draining EmptySink
    there), a different file and a separate concern.
  3. It is not reachable in a default build or a default configuration. That file is entirely inside
    #if USE_ARROWFLIGHT, and the listener exists only when arrowflight_port is configured
    (programs/server/Server.cpp:4007); that key appears in neither programs/server/config.xml
    nor config.d/.

For completeness, the remaining in-tree producer of an output-less discard node,
Pipe::dropPort, reached from QueryPipelineBuilder::dropTotalsAndExtremes and
complete(Pipe), is measured disjoint from this change and is addressed by #111194; the two
together were measured to fix every carrier of this family. Also noticed while reviewing: the
NullSink at DelayedSource.cpp:105 is not a carrier, because it is created during
DelayedSource::work as a dynamic graph update rather than being present when the graph is
seeded. Neither is raised as a separate task.

💡 no-fasttest on the new test is not justified by a measured duration

Noted, not blocking. Of the four stateless tests using EXPLAIN ANALYZE only the new one carries
the tag; 04312_explain_analyze.sql runs EXPLAIN ANALYZE over numbers_mt(1000000) six times
untagged. The new test's largest input is numbers(10) and it was measured at 0.25 sec, against a
60 second Fast test budget. The tag can only hide a pass, never cause a failure, and coverage is
retained in every other stateless flavour, so it is left as is; dropping it is safe if a reviewer
prefers.

✅ Checked and found sound

  • Invariant carriers were enumerated independently before comparing against the plan, and the
    lists agree: both complete overloads, the deleted helper (compiler-verified, since
    reintroducing a call no longer builds), complete(IOutputFormat) as a non-carrier because it
    attaches a format that consumes the aux streams, and the unchanged gate itself, which is why
    the JOIN, CreatingSets and parallel-replicas users of DelayedPortsProcessor cannot be
    perturbed.
  • Test liveness: the pre-fix failure is a thrown LOGICAL_ERROR from ReadFromMemoryStorageStep,
    so each of the four witnesses reddens on a revert for its own stated reason, and the five result
    controls assert exact output. Neither extremes nor enable_materialized_cte is randomized by
    the test runner, so no randomization opt-out is needed.
  • A candidate major about header compatibility was developed and then refuted: connect uses the
    weaker assertCompatibleHeader, a divergent totals header is reachable only under ROLLUP or
    CUBE and is realigned by the very next plan step in both analyzers, and
    complete(IOutputFormat) already imposes the same equality today.

Session id: cron:clickhouse-review-slot-8:20260806-130200

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 3/3 on unpatched master: EXPLAIN ANALYZE processors=1 WITH a AS MATERIALIZED (SELECT number AS id FROM numbers(10)) SELECT id FROM a WHERE id IN (SELECT id FROM a) SETTINGS extremes=1 with enable_analyzer=1, enable_materialized_cte=1. clickhouse local writes the fatal to the log, so the run needs -- --logger.log=<path> --logger.level=error and the log is grepped for the message.
b Root cause explained? QueryPipelineBuilder::addPipelineBefore routes totals and extremes through the DelayedPortsProcessor that gates the materialized CTE read, so they are gate output ports. QueryPipeline::complete discarded them with a NullSink, which has no outputs, so ExecutingGraph::initializeExecution seeds it and it runs first; its prepare closes its input without pulling. That finishes a gate output, the gate finishes the pair and closes the paired input, the gated sub-pipeline is released, and MemorySource::generate runs with the CTE unbuilt.
c Fix matches root cause? Yes. It removes the property that causes the defect (a discard node with no outputs) at the site that creates it, rather than guarding the gate that detects it or relaxing the fail-fast check. DroppingTransform exists for exactly this purpose and 641fc75ea3f0d37 already applied it to the builder's own drop sites.
d Test intent preserved / new tests added? New stateless test 04815_materialized_cte_explain_analyze_aux_ports: four EXPLAIN ANALYZE witnesses plus five controls asserting results are unchanged. No existing test is modified or weakened. EXPLAIN ANALYZE is wrapped in viewExplain because its own output carries timings; measured that FORMAT Null does not suppress that output (15 lines, a different md5 on each of 3 runs), while the viewExplain form emits 1 line with the same md5 on all 3.
e Both directions demonstrated? Yes. Through clickhouse-test, the new test is FAIL (server died, log carries the target LOGICAL_ERROR twice) on a server running the pristine master binary and OK on the patched one, with SELECT lower(buildId()) asserted equal to readelf -n on each server before the verdict. Per-carrier: all four shapes are rc=134 on base and rc=0 on the fix.
f Fix is general across code paths? All four drop call sites in the file are the two pairs being replaced, so drop itself and the NullSink.h include are deleted; the deletion is compiler-verified (reintroducing a call gives use of undeclared identifier 'drop'). Both complete overloads route through the new helper. QueryPipelineBuilder::dropTotalsAndExtremes is a separate site, left to #111194. Pipe.cpp's remaining NullSink uses are not on a gate output.
g Fix generalizes across inputs? Measured on both arms: totals only, extremes only, both, neither, WITH CUBE, WITH ROLLUP WITH TOTALS, LIMIT 0, LIMIT 1, an empty CTE, a single-row CTE, Nullable, and LowCardinality+Array. Every carrier aborts on base and passes with the change; the two non-carriers (no aux port, empty CTE) are byte-identical on both arms.
h Backward compatible? Yes. No setting, no default, no serialization or on-disk format is touched, so no SettingsChangesHistory.cpp entry is owed. The change is confined to how a pipeline discards two streams it was already discarding.
i Invariants and contracts preserved? The helper is only reached after each overload's if (!pulling()) throw, and pulling() is output != nullptr, so its chassert(output) cannot fire. It republishes output as the transform's data output, keeping the pipeline pulling with exactly one output port, which is what num_streams_ = 1 matches. DroppingTransform::prepare closes the aux inputs on its all_outputs_done path, so an early-finishing consumer cannot stall upstream, and no arm hung. Over the 256 stateless test stems whose name contains materialized_cte or whose body matches extremes = 1, WITH TOTALS, EXPLAIN ANALYZE or viewExplain (262 test cases after the runner expands three .j2 templates), the failure set and every failure reason are unchanged against unpatched master: 0 only-in-fix, 0 reason changes.

Session id: cron:clickhouse-impl-slot-40:20260806-104800

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @davenger, could you review this? QueryPipeline::complete discarded the totals and extremes streams with a NullSink, which has no outputs, so ExecutingGraph::initializeExecution seeded it and it closed a DelayedPortsProcessor output before the main inputs finished, releasing a gated materialized-CTE read and raising a logical error; the two streams now go through a DroppingTransform on the main output, which keeps data outputs and is not seeded.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@PedroTadim

Copy link
Copy Markdown
Member

cc @novikd

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [605a434]

Summary: ⏳

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d) FAIL cidb

AI Review

Summary

This PR replaces the output-less aux-port discard in QueryPipeline::complete with a DroppingTransform, so EXPLAIN ANALYZE no longer seeds a childless NullSink on delayed materialized-CTE totals/extremes streams and release the gated CTE reader too early. I reviewed the current diff, the surrounding pipeline and scheduler code, the existing PR discussion, and the current PR head state; I did not find any actionable correctness, safety, performance, or metadata issues that warrant a new inline comment. The targeted regression coverage is aligned with the changed contract, and the current CI report for PR #113683 is all green.

Final Verdict

✅ No actionable findings in the current diff.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 605a434d3 with master a96691076 (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
Binary Master PR Δ
programs/clickhouse-stripped 689.52 MiB 686.50 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@novikd

novikd commented Aug 7, 2026

Copy link
Copy Markdown
Member

@PedroTadim This is again a duplicate with a wrong solution. There is a current attempt to fix #111194.

@novikd novikd closed this Aug 7, 2026
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fine to close this one, and I will fold the change into #111194 while addressing your review comment there.

One measured point for that work, because it changes what "check all the usages" has to include. There are two independent childless-NullSink drop helpers in src/QueryPipeline/, and they share no code:

  • Pipe.cpp:406 dropPort, behind Pipe::dropTotals (:421) and Pipe::dropExtremes (:426). This is what QueryPipelineBuilder::dropTotalsAndExtremes (QueryPipelineBuilder.cpp:203) calls and what Fix materialized CTE "gate is missing" error with WITH TOTALS #111194 changes. 17 call sites in src/: 13 in QueryPipelineBuilder.cpp, 2 unqualified in Pipe::addChains (Pipe.cpp:654), 2 in QueryPipeline::complete(Pipe) (QueryPipeline.cpp:563).
  • QueryPipeline.cpp:505 drop, file-static, reached only from QueryPipeline::complete(ISink) (:524) and complete(Chain) (:539).

EXPLAIN ANALYZE goes through the second one: InterpreterExplainQuery.cpp:1293 completes the pipeline with an EmptySink. So covering Pipe::dropTotals/dropExtremes exhaustively, including a new Pipe::dropTotalsAndExtremes, still does not reach that site.

Measured on a debug build of #111194's head 2e3feec2 applied to 25d677a4, against pristine master and against this branch. gate counts DelayedPortsProcessor gate is missing in the server log:

query master #111194 this branch
EXPLAIN ANALYZE + extremes=1 rc=134 gate=2 rc=134 gate=2 rc=0
EXPLAIN ANALYZE + WITH TOTALS rc=134 gate=2 rc=134 gate=2 rc=0
both rc=134 gate=2 rc=134 gate=2 rc=0
+ ORDER BY id LIMIT 1 rc=134 gate=2 rc=134 gate=2 rc=0
INSERT ... SELECT + extremes=1 rc=134 gate=2 rc=0 rc=134 gate=2
SELECT count() FROM (... WITH TOTALS) rc=134 gate=2 rc=0 rc=134 gate=2

The last two rows are the control: they are #111194's own scope, so that column is genuinely carrying #111194. The first four are 3/3 deterministic, and a plain SELECT with extremes=1 returns its rows normally on all three.

Repro for the first row:

SET enable_analyzer = 1;
SET enable_materialized_cte = 1;
EXPLAIN ANALYZE processors = 1
WITH a AS MATERIALIZED (SELECT number AS id FROM numbers(10))
SELECT id FROM a WHERE id IN (SELECT id FROM a)
SETTINGS extremes = 1;

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
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 groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error Reading from materialized CTE before its materialization completed under EXPLAIN ANALYZE with chained materialized CTEs and WITH TOTALS

3 participants