Repository navigation
Fix materialized CTE "gate is missing" error with WITH TOTALS - #111194
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-2:20260721-081200 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 4 findings across a full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-2:20260721-081200 |
|
cc @novikd @yariks5s — could you review this? It extends the |
|
Workflow [PR], commit [23920b4] Summary: ✅
AI ReviewSummaryThis PR replaces childless totals/extremes discards with Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 106/109 (97.25%) · Uncovered code |
CI finish ledger - c35d59bCI fully finished (Finish Workflow pass; 0 checks queued/in-progress; CH Inc sync pass). Every failure below has an owner. None is caused by this PR's diff (a
Session id: cron:our-pr-ci-monitor:20260721-190000 |
|
Correction and fixing-PR link for the My ledger reason was wrong. I called that row benign ("caught client-side exceptions, Two fixing PRs, for the two separate defects:
|
| /// may read a materialized CTE: a childless `NullSink` is seeded by | ||
| /// `ExecutingGraph::initializeExecution`, which would pull the reader before its | ||
| /// `DelayedPortsProcessor` gate opens (STID 2467-2c2d). | ||
| void dropTotalsAndExtremesViaTransform(); |
There was a problem hiding this comment.
@groeneai Better reimplement dropTotalsAndExtremes via dropTotalsAndExtremesViaDroppingTransform (no need to add a new method to the interface). Also, take a look at the dropTotals and dropExtremes functions.
There was a problem hiding this comment.
Done in 2e3feec - dropTotalsAndExtremes itself now drops via the DroppingTransform, the extra public method is gone, and the two call sites are back to plain dropTotalsAndExtremes(). Net effect on the interface is a 7-line deletion in the header.
That also widened the fix for free: InsertDependenciesBuilder.cpp:673 is the third dropTotalsAndExtremes caller and is now covered without touching it, and addCreatingSetsTransform / addMaterializingCTETransform call the member instead of the file-local helper, which no longer exists.
One guard is needed inside it: when pipe.numOutputPorts() == 0 the DroppingTransform would itself be childless, so those pipes keep the plain sinks. A pipe with no data output cannot gate anything behind it, so it is not a reachable case for this bug.
On dropTotals and dropExtremes: I left them alone, and they are still reachable, so here is what I measured rather than assumed. The remaining Pipe::dropExtremes callers are the four join builders (joinPipelinesYShaped, joinPipelinesByLayers, joinPipelinesRightLeft, joinPipelinesByShards), QueryPipeline::complete, and Pipe::addChains. Probing a self-joined materialized CTE and an INSERT ... SELECT from one, both with extremes = 1, passes on the patched build. Instrumenting Pipe::dropPort to log a stack trace on every call showed it is not reached at all on those shapes, so the extremes branch there never carries a gated CTE reader. Converting them would change the join and completion topology with no reproducer to justify it, so I would rather not.
Worth flagging separately: while probing extremes I found SET extremes = 1 plus UNION ALL over a materialized CTE aborting with the same message, and it reproduces identically on unpatched master via a different path (Pipe::dropPort is never called, so it is not the NullSink mechanism this PR addresses). I will handle that as its own investigation rather than growing this PR.
Verification for this revision, debug build d1de1099d1bec3335d8d0b9d8fd167e62544954c: 04561_materialized_cte_totals_gate matches its reference, master aborts on the same file; the original fuzzer shape from #110176 and the INSERT shape both pass; every other materialized-CTE stateless test behaves identically to master (the differences are all a missing test cluster or no server in clickhouse-local, not this change).
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/19 (84.21%) · Uncovered code |
CI finish ledger - 2e3feecEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
174/174 check-runs completed, 156 success, 18 skipped; The stack is Session id: cron:our-pr-ci-monitor:20260803-163000 |
| pipe.addTotalsSource(std::move(source)); | ||
| } | ||
|
|
||
| void QueryPipelineBuilder::dropTotalsAndExtremes() |
There was a problem hiding this comment.
@groeneai You should also cover Pipe::dropTotals() and Pipe::dropExtremes(). Probably, you should add Pipe::dropTotalsAndExtremes(). Also check all the usages of Pipe::dropTotals() and Pipe::dropExtremes().
There was a problem hiding this comment.
Done in 735abc8.
Pipe::dropTotalsAndExtremes added, and the logic moved down into it. The DroppingTransform wiring lived in QueryPipelineBuilder::dropTotalsAndExtremes, so the two callers that drop both streams through Pipe directly still attached a childless NullSink: Pipe::addChains (Pipe.cpp:654-655 on master, the INSERT path) and QueryPipeline::complete(Pipe) (QueryPipeline.cpp:563-564). Both now call the new method, and QueryPipelineBuilder::dropTotalsAndExtremes forwards to it, so the builder is unchanged for its own callers.
dropTotals and dropExtremes keep the NullSink, and I would rather not convert them. Each drops one stream and leaves the other in place, so there is no "drop both" pipe shape for a DroppingTransform to forward the data path through, and every remaining caller drops extremes only:
| master | function | why extremes only |
|---|---|---|
QueryPipelineBuilder.cpp:217 |
addExtremesTransform |
drops the extremes it is about to recompute |
:366, :405, :432, :766 |
joinPipelinesYShaped, joinPipelinesPaired, joinPipelinesYShapedByShards, joinPipelinesByShards |
each throws NOT_IMPLEMENTED a few lines later if either side has totals |
:483 |
joinPipelinesRightLeft |
keeps totals; only the right side's totals are special-cased at :501 |
Predicate: git grep -nE '\b(dropTotals|dropExtremes)\s*\(' -- src/, which is 21 lines on master. joinPipelinesPaired landed after this branch's base, so on the branch the same predicate gives 15: those nine call sites (eight join-builder lines plus addExtremesTransform), the two declarations, the two definitions, and the two calls inside the new method's no-data-output fallback.
One real bug came out of the audit, and it was in the transform, not the callers. DroppingTransform::prepare called setNeeded on the totals and extremes inputs and pulled from them. Requesting a stream that is being dropped makes the upstream produce it, so TotalsHavingTransform evaluated HAVING on the totals row:
SELECT count() FROM (SELECT number AS k FROM numbers(3) GROUP BY k WITH TOTALS HAVING throwIf(count() = 3) = 0);Each group has one row and the totals row has three, so this returned 3 before and raised Code: 395 after. Same on INSERT ... SELECT and on a dependent materialized view. It closes the inputs instead now, which is what NullSink did (NullSink.h:15-18) - but only once the data streams are done, because closing a DelayedPortsProcessor output finishes its pair and releases the gate. Closing immediately fixes the throwIf case and reintroduces the abort, so the two have to be checked together. All three shapes are in 04561_materialized_cte_totals_gate with expected values taken from a pristine master build.
Verified on a debug build: 04561 passes here and aborts on master. A mutant forcing the NullSink path reproduces the abort; a mutant restoring the drain reproduces Code: 395. Across the 223 stateless tests mentioning totals, extremes or materialized CTEs, 04561 is the only status change attributable to this branch.
On #113683: agreed, and thanks for pointing at this one. The complete(ISink) and complete(Chain) overloads there are reached by the EXPLAIN ANALYZE plus extremes = 1 shape, which is a separate mechanism from this WITH TOTALS gate - under EXPLAIN ANALYZE with WITH TOTALS and no extremes, master aborts and this branch does not. I have left those two overloads alone here.
There was a problem hiding this comment.
@groeneai, keeping NullSink does not solve the problem. NullSink is always starts immediately in the query by ExecutingGraph and it breaks waiting of Materialized CTE. You should have supporting dropping a single port in the DroppingTransform
There was a problem hiding this comment.
Confirmed, and I checked the mechanism rather than taking it on faith: initializeExecution seeds every node with no direct edges (src/Processors/Executors/ExecutingGraph.cpp:280-288), and NullSink::prepare closes its input unconditionally (src/Processors/Sinks/NullSink.h:17), so a NullSink sitting on a DelayedPortsProcessor output releases the gate before the materialized CTE is built. 735abc8f still leaves that in two places:
- the
output_ports.empty()fallback inside the newPipe::dropTotalsAndExtremes, which callsdropTotalsanddropExtremes; - the single-stream call sites,
QueryPipelineBuilder.cpp:217inaddExtremesTransformplus the ten join-builder lines:366,:367,:405,:406,:432,:433,:483,:484,:766,:767(line numbers onmaster).
So the table in my previous comment answered the wrong question. It argued that those callers do not need a combined drop, which is true and beside the point: each of them still attaches a childless sink, and that is the thing that breaks the gate.
Accepting single-port support. It is smaller than it sounds, because DroppingTransform already takes has_totals and has_extremes as independent flags: createInputPorts appends each aux input only when its flag is set, prepare skips the null aux pointers, and Pipe::addTransform sizes and connects from the same two booleans. A totals-only or extremes-only instance therefore already constructs and runs today, and is already reached whenever a pipe has only one of the two streams. What is missing is only that dropTotals and dropExtremes do not route through it. I will make them do that, and check whether the no-data-output case is reachable at all rather than leaving a NullSink there by default.
On scope: the sites reached by QueryPipeline::complete(std::shared_ptr<ISink>) and complete(Chain) through the file-local drop (QueryPipeline.cpp:505), and uniteExtremes (Pipe.cpp:43), which builds its own EmptySink at Pipe.cpp:59 and calls neither dropTotals nor dropExtremes, both land here too. I had left the first out on the grounds that #113683 owned it; you closed that one and #113043, so consolidating here is your call and I am following it. No fourth pull request.
There was a problem hiding this comment.
Done in 8b57d5e. NullSink is gone from all three drop entry points, so nothing childless is attached to a discarded stream any more.
Single-port support. dropTotals, dropExtremes and dropTotalsAndExtremes now all route through one private Pipe::dropStreams(bool, bool), which discards through a DroppingTransform on the data path. No new capability was needed in the transform: it already took has_totals and has_extremes as independent flags, so createInputPorts appends only the aux input whose flag is set and prepare skips the null pointers. The previous output_ports.empty() fallback to NullSink is deleted rather than kept, because it is unreachable: totals and extremes can only be added to a non-empty pipe, and addTransform rejects an empty one.
Two more sites that had the same shape, both in scope here since you closed #113683 and #113043:
QueryPipeline::complete(std::shared_ptr<ISink>)andcomplete(Chain), which used a file-localdrophelper with the sameNullSink.EXPLAIN ANALYZEreaches that path viapipeline.complete(std::make_shared<EmptySink>(...))(InterpreterExplainQuery.cpp:1293).uniteExtremes, which built its ownEmptySink(Pipe.cpp:59on master) to drain the main output of anExtremesTransform. ADroppingTransformis the wrong tool there because that path has to keep the extremes value, not discard it, so it now uses anExtremesOnlyTransformthat produces only the extremes and needs no sink. This is theUNION/INTERSECT/EXCEPTcase and it carries Fix materialized CTE "gate is missing" error with extremes and UNION #113043's test, as promised there.
Measured, on a debug build. Before this commit the union shape aborted on this very branch (rc=134, gate error) while the totals and EXPLAIN ANALYZE shapes already passed, so the three sites are independent; after it all three return rc=0 deterministically, and unmodified master aborts on each. A 563-test sweep over the totals/extremes/materialized-CTE surface has zero regressions against a pristine master arm: identical failure sets and identical reason buckets, with six differences that are all master-arm failures fixed by upstream drift.
I also strengthened the three regression tests. They asserted results and extrema, which are byte-identical whether the CTE is materialized or inlined, so they would have kept passing if planning silently stopped materializing it. Each now asserts first that the shape really is planned with a MaterializingCTETransform, and the union test that the united-extremes path is present; both read 1 today and 0 once materialization is lost.
…s discarded
A materialized CTE read behind an IN-subquery is activated through a
DelayedPortsProcessor gate that opens once the CTE has been materialized. Discarding a
totals or extremes port attached a node with no outputs, and
ExecutingGraph::initializeExecution seeds every such node before the pipeline runs.
NullSink closes its input immediately, so when that input was a gate output the gate's
paired input was closed and the reader ran before its data was there:
Reading from materialized CTE '...' before its materialization completed -
DelayedPortsProcessor gate is missing in the query plan. (LOGICAL_ERROR)
The discard now goes through DroppingTransform, which keeps a data output connected and
is therefore never seeded. This covers the drop entry points in Pipe, the single-stream
fallbacks, and completion with a sink or a chain, which is the path EXPLAIN ANALYZE
takes. Uniting extremes across the arms of a set operation cannot discard its input,
because the united extremes value has to be preserved, so it uses an accumulating
ExtremesOnlyTransform that needs no sink at all. Each auxiliary input takes its header
from the port it is connected to, because a totals stream may be finalized while the data
stream is not, which is what the NullSink this replaced did.
The regression tests assert row counts and extrema, which are identical whether the CTE
is materialized or inlined, so each carrier also asserts that its own shape is planned
with materialization. Every such assertion was checked to read 1 today and 0 with
enable_materialized_cte = 0. The INSERT carrier is a shell test, because its pipeline is
built by InterpreterInsertQuery and only EXPLAIN PIPELINE INSERT reflects it.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109408&sha=848d6f40422826ac03b60db0219ec027ebed9b48&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Carrier pull request: ClickHouse#109408
Closes ClickHouse#110176
8b57d5e to
23920b4
Compare
CI finish ledger - 23920b4CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, There is nonetheless one failing row to own, and it is invisible to the GitHub check-runs API, so I am
Not PR-caused: this diff is a query-planner fix for materialized CTEs with The merged retry hardening in #113409 is deliberately not linked as this row's owner, because it was
So this is a live post-fix residual, not a stale build, and merging Session id: cron:our-pr-ci-monitor:20260808-070000 |
|
Hi — this looks like a backport candidate for |
|
Verified independently. The branch list is right on affectedness, but the single label to ask for is Affectedness. I ran the bug's shapes against Label. Port resolution. Caveat. Could a maintainer apply |
Closes: #110176
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERROR(Reading from materialized CTE '...' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan) when a reused materialized CTE (enable_materialized_cte) is read on a branch whoseWITH TOTALSorextremesoutput is discarded, including outer aggregation,INSERT ... SELECT, set operations andEXPLAIN ANALYZE.Description
Reopened issue #110176 (STID 2467-2c2d). Minimal reproducer (aborts in debug/sanitizer builds):
Root cause: the totals or extremes port is discarded by attaching a node with no
outputs.
ExecutingGraph::initializeExecutionseeds every such node, andNullSinkcloses its input at once, so when that input is a
DelayedPortsProcessoroutput thegate opens before the materialized CTE has been built and the fail-fast check in
MemorySource::generatefires.Three entry points discarded a stream that way, and all three are fixed here by
keeping a consumer that has outputs and is therefore never seeded:
Pipe::dropTotals,dropExtremesanddropTotalsAndExtremesnow discard throughone
DroppingTransformon the data path. It already took independenthas_totalsand
has_extremesflags, so single-stream drops need no new capability, and theprevious no-data-output fallback was unreachable and is gone.
QueryPipeline::complete(std::shared_ptr<ISink>)andcomplete(Chain)used afile-local
drophelper with the sameNullSink.EXPLAIN ANALYZEreaches thatpath via
pipeline.complete(std::make_shared<EmptySink>(...)).uniteExtremesbuilt its ownEmptySinkto drain the main output of anExtremesTransform. It now uses anExtremesOnlyTransform, which produces only theextremes and so needs no sink; this is the
UNION/INTERSECT/EXCEPTcase.Verified both directions on a debug build: the three regression tests abort on
unmodified master and pass here, 30/30 deterministic, and a 563-test sweep over the
totals/extremes/materialized-CTE surface shows zero regressions against a pristine
master arm (identical failure sets and reason buckets).
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109408&sha=848d6f40422826ac03b60db0219ec027ebed9b48&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29