Skip to content

Fix materialized CTE "gate is missing" error with WITH TOTALS - #111194

Merged
novikd merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mat-cte-nested-in-totals-gate
Aug 18, 2026
Merged

novikd merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mat-cte-nested-in-totals-gate

Conversation

@groeneai

@groeneai groeneai commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #110176

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):

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 whose WITH TOTALS or extremes output is discarded, including outer aggregation, INSERT ... SELECT, set operations and EXPLAIN ANALYZE.

Description

Reopened issue #110176 (STID 2467-2c2d). Minimal reproducer (aborts in debug/sanitizer builds):

SET enable_materialized_cte = 1;
SELECT count() FROM (
    WITH a AS MATERIALIZED (SELECT 1 AS id)
    SELECT id FROM a WHERE id IN (SELECT id FROM a)
    GROUP BY id WITH TOTALS);

Root cause: the totals or extremes port is discarded by attaching a node with no
outputs. ExecutingGraph::initializeExecution seeds every such node, and NullSink
closes its input at once, so when that input is a DelayedPortsProcessor output the
gate opens before the materialized CTE has been built and the fail-fast check in
MemorySource::generate fires.

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, dropExtremes and dropTotalsAndExtremes now discard through
    one DroppingTransform on the data path. It already took independent has_totals
    and has_extremes flags, so single-stream drops need no new capability, and the
    previous no-data-output fallback was unreachable and is gone.
  • QueryPipeline::complete(std::shared_ptr<ISink>) and complete(Chain) used a
    file-local drop helper with the same NullSink. EXPLAIN ANALYZE reaches that
    path via pipeline.complete(std::make_shared<EmptySink>(...)).
  • uniteExtremes built its own EmptySink to drain the main output of an
    ExtremesTransform. It now uses an ExtremesOnlyTransform, which produces only the
    extremes and so needs no sink; this is the UNION/INTERSECT/EXCEPT case.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_materialized_cte=1; SELECT count() FROM (WITH a AS MATERIALIZED (SELECT 1 AS id) SELECT id FROM a WHERE id IN (SELECT id FROM a) GROUP BY id WITH TOTALS); aborts every run on master (single-threaded).
b Root cause explained? Yes. The inner subquery's totals port is dropped by a childless NullSink; ExecutingGraph::initializeExecution seeds every childless node, so the NullSink cascades setNeeded up the totals branch to the materialized-CTE reader, activating it before the MaterializingCTETransform writer runs and outside the DelayedPortsProcessor gate. MemorySource::generate then trips its fail-fast.
c Fix matches root cause? Yes. Swaps the childless NullSink totals drop for the non-childless DroppingTransform (not seeded by initializeExecution) — the same mechanism already used for the CreatingSetsTransform/MaterializingCTETransform sites. No guard on the reader.
d Test intent preserved / new test added? Yes. New 04561_materialized_cte_totals_gate covers the aggregation site, the INSERT site, the original fuzzer shape, and asserts the result equals the non-materialized CTE equivalent. No existing test weakened.
e Both directions demonstrated? Yes. Pristine master aborts; patched binary passes (verified with distinct Build IDs).
f Fix general across code paths? Yes. Enumerated all childless-NullSink totals-drop callers; fixed the two with a reproducer through a materialized-CTE reader (AggregatingStep, InterpreterInsertQuery). InsertDependenciesBuilder (dependent-view insert) was investigated but left unchanged — no shape I tried reproduces the bug through it. addPipelineBefore (writer pipeline, empty header) and the low-level Pipe/QueryPipeline totals drops are non-CTE contexts, untouched by design.
g Fix generalizes across inputs? Yes. Verified independent of CTE body, aggregate function (count/min/sum), row counts, and extra IN-nesting; WITH TOTALS on the consumed subquery is the trigger. Bug is pipeline-topology, not datatype-dependent.
h Backward compatible? Yes. Gated behind experimental enable_materialized_cte; no setting-default / on-disk / wire-format change. Non-CTE WITH TOTALS drop behavior is unchanged.
i Invariants and contracts preserved? Yes. DroppingTransform forwards data 1:1 and discards totals/extremes exactly like the NullSink — semantically identical drop; only the executor-seeding differs (the fix). Existing materialized-CTE tests (04227/04259/04295/04260) and EXPLAIN-PIPELINE totals tests (03513/03927/01883) still pass.

Session id: cron:clickhouse-author-slot-2:20260721-081200

@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; 4 findings across a full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test does not exercise the InsertDependenciesBuilder (dependent-view) path AGREE Resolved by REMOVING the InsertDependenciesBuilder change entirely: 5 materialized-view shapes on an unpatched binary all pass (no crash), so that path is not triggerable, and per project policy we do not change code we cannot back with a reproducer. Fix now covers only the two proven sites.
2 💡 Executor-internals rationale repeated at every caller AGREE Trimmed the two caller comments to one-liners pointing to QueryPipelineBuilder::dropTotalsAndExtremesViaTransform; the full rationale lives once on that method's doc comment.
3 💡 Generated preprocessed_configs/config.xml present as a local artifact DISAGREE Untracked build-runtime artifact; never staged (the commit contains only the 6 intended files) and cannot enter the PR.
4 ❌ Reverting InsertDependenciesBuilder reintroduces the defect on the dependent-view path DISAGREE A/B on the unpatched binary: five materialized-view shapes (MV reading source+CTE with WITH TOTALS; top-level WITH TOTALS; count() wrapper; doubly-nested-IN fuzzer shape; async executor) all return no crash. The dependent-view insert path does not trigger this defect for any constructible shape; direct INSERT ... SELECT (InterpreterInsertQuery) is covered and proven. Changing an untriggerable path would be an unbacked speculative edit.

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

Session id: cron:clickhouse-author-slot-2:20260721-081200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @yariks5s — could you review this? It extends the DroppingTransform totals/extremes-drop (from #105041 / commit 641fc75) to the AggregatingStep and InterpreterInsertQuery sites: a childless NullSink dropping a WITH TOTALS port is seeded by ExecutingGraph::initializeExecution and pulls a materialized-CTE reader before its DelayedPortsProcessor gate opens (STID 2467-2c2d, issue #110176).

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23920b4]

Summary: ✅


AI Review

Summary

This PR replaces childless totals/extremes discards with DroppingTransform/ExtremesOnlyTransform so reused materialized CTE readers stay behind their DelayedPortsProcessor gate across WITH TOTALS, extremes, set operations, INSERT ... SELECT, and EXPLAIN ANALYZE. I reviewed the current diff, the full prior thread history, and the current all-green CI report, and I did not find any remaining correctness, safety, or coverage gaps in the implementation as it stands.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 106/109 (97.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c35d59b

CI 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 map[key] first-match scan fix in DataTypeMapHelpers.cpp / arrayElement.cpp + one SQL test).

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Test script failed crash (LOGICAL_ERROR assertTypeEquality in HashJoin buildAdditionalFilter, LEFT JOIN ON (eq) AND (ineq)) fixing PR #107957 (ours, open)
AST fuzzer (amd_msan) / Client failure benign (caught client-side exceptions: TYPE_MISMATCH / CANNOT_PARSE_TEXT / access check on fuzzed INSERT+EXECUTE AS; no crash, no sanitizer, no LOGICAL_ERROR) a fix task is created (AST-fuzzer amd_msan benign-client-failure classification; fixing-PR link to follow here)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (replicated-DDL structure-alter race; 0 in this PR's diff) fixing PR #109245 (ours, open)
Mergeable Check / PR rollup of the above owned via the rows above
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260721-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction and fixing-PR link for the AST fuzzer (amd_msan) / Client failure row of my
finish ledger above.

My ledger reason was wrong. I called that row benign ("caught client-side exceptions,
no crash, no sanitizer, no LOGICAL_ERROR"). The job's artifacts for
c35d59bfd914045a9d79d0cb692e96695b8215ad include a 5422-byte sanitizer.log.914
holding a real MemorySanitizer: use-of-uninitialized-value whose origin frame reads
Uninitialized value was created by a heap deallocation (MSan's wording for a
use-after-free), and the client died with SIGABRT (Fuzzer exit code is 134). I reached
the benign conclusion by scanning fuzzer.log, which contains no sanitizer text at all -
which is itself the defect: the harness pastes only that log's tail, and the code that
would name the report is gated behind status != Result.Status.ERROR, false on exactly
this branch, so FuzzerLogParser never runs even though its SANITIZER_ERROR_PATTERN
matches the report sitting in stderr.log. The row is still unrelated to this PR's diff,
but it was not benign.

Two fixing PRs, for the two separate defects:

@novikd novikd self-assigned this Jul 30, 2026
/// 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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 16/19 (84.21%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2e3feec

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Logical error: Join is supported only for pipelines with one output port, got 1 and 2 (STID 4488-4e11) pre-existing trunk defect in the YShaped merge-join fallback #109393 (mine, open)

174/174 check-runs completed, 156 success, 18 skipped; Finish Workflow completed successfully.

The stack is QueryPipelineBuilder::joinPipelinesYShaped throwing when the two join sides carry a
different number of streams; #109393 fixes exactly that by merging each side back to one sorted stream
in the fallback path. Breadth over 45 days: 23 hits across 23 distinct commits, 22 of them not mine,
including one on master, and the first sighting is 2026-06-20, well before this branch existed.

Session id: cron:our-pr-ci-monitor:20260803-163000

pipe.addTotalsSource(std::move(source));
}

void QueryPipelineBuilder::dropTotalsAndExtremes()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 new Pipe::dropTotalsAndExtremes, which calls dropTotals and dropExtremes;
  • the single-stream call sites, QueryPipelineBuilder.cpp:217 in addExtremesTransform plus the ten join-builder lines :366, :367, :405, :406, :432, :433, :483, :484, :766, :767 (line numbers on master).

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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>) and complete(Chain), which used a file-local drop helper with the same NullSink. EXPLAIN ANALYZE reaches that path via pipeline.complete(std::make_shared<EmptySink>(...)) (InterpreterExplainQuery.cpp:1293).
  • uniteExtremes, which built its own EmptySink (Pipe.cpp:59 on master) to drain the main output of an ExtremesTransform. A DroppingTransform is the wrong tool there because that path has to keep the extremes value, not discard it, so it now uses an ExtremesOnlyTransform that produces only the extremes and needs no sink. This is the UNION/INTERSECT/EXCEPT case 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.

Comment thread src/QueryPipeline/QueryPipeline.cpp Resolved
…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
@groeneai
groeneai force-pushed the fix-mat-cte-nested-in-totals-gate branch from 8b57d5e to 23920b4 Compare August 8, 2026 00:37
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 23920b4

CI is fully finished on this head: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both green, Mergeable Check success, last check completed 2026-08-08T05:59:03Z.
By conclusion every check-run is green: 158 success, 17 skipped, 0 failure.

There is nonetheless one failing row to own, and it is invisible to the GitHub check-runs API, so I am
recording it rather than calling this head clean.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks CI telemetry, not a build failure: the build-profile hook's INSERT INTO build_time_trace into the shared CI logs cluster was rejected with HTTP 500 on all 8 attempts. The build itself succeeded, which is why Build (arm_release) reports success a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

Not PR-caused: this diff is a query-planner fix for materialized CTEs with WITH TOTALS plus its
stateless tests, and it touches no CI script.

The merged retry hardening in #113409 is deliberately not linked as this row's owner, because it was
already in effect for this run. Two independent measurements agree on that, and they matter because the
naive check disagrees:

  • The retry count is itself a fix-presence oracle. Pre-fix code emits one LogCluster query failed with code 500 warning; post-fix code retries eight times and emits eight. This row has eight, so every
    retry ran and was exhausted.
  • Reading the file at this commit suggests the opposite (the marker Retry the build-profile telemetry INSERT through the CI logs cluster memory-pressure spikes #113409 adds is absent at
    refs/pull/111194/head), but that is the wrong tree: CI checks out refs/pull/111194/merge, where the
    marker is present, and the merge ref is what actually ran. Size confirms it, 7297 bytes at the head
    versus 12698 at the merge ref and at master.

So this is a live post-fix residual, not a stale build, and merging master would not turn it green.
Over the last 7 days that same post-fix shape accounts for 463 rows across 316 distinct PRs and 66
master failures.

Session id: cron:our-pr-ci-monitor:20260808-070000

@novikd
novikd added this pull request to the merge queue Aug 18, 2026
Merged via the queue into ClickHouse:master with commit 0ac275d Aug 18, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.5, 26.6, 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified independently. The branch list is right on affectedness, but the single label to ask for is v26.5-must-backport, and there is one caveat about a test file.

Affectedness. I ran the bug's shapes against builds.clickhouse.com/<X.Y>/amd64/clickhouse. 26.5.7.63, 26.6.3.62 and 26.7.4.58 all fail with exactly the error this PR fixes: Reading from materialized CTE 'a' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan. Three independent carriers reproduce on each (the totals-subquery shape, the #110176 nested-IN shape, and INSERT ... SELECT ... WITH TOTALS). Control: the current master build, which contains the merge commit, passes all of them.

Label. select_backport_branches in tests/ci/cherry_pick_branches.py expands a version-specific label to the floor release plus every newer active branch, so with 26.7/26.6/26.5/26.3/25.8 active, v26.5-must-backport alone covers 26.5, 26.6 and 26.7. pr-must-backport would also target 26.3 and 25.8, which should not be backported: 25.8 has no enable_materialized_cte, and 26.3 lacks DroppingTransform entirely (the prerequisite #106796 landed on 26.4/26.5 but its 26.3 cherry-pick was closed), so a port there is a modify/delete conflict.

Port resolution. git merge-tree against each branch tip from this PR's base: 26.7 and 26.6 are clean, and the merged trees contain every symbol the fix introduces at the same counts as master, so no half no-op. 26.5 has one conflict, in ExtremesTransform.h, and it is pure adjacency: 26.5 does not yet have final on the class, and this patch inserts the accumulateExtremes declaration on the line above.

Caveat. EXPLAIN ANALYZE postdates 26.5 and 26.6 (ExplainKind::Analyze was added in 17aa701, present on 26.7 only), so the test file 04815_materialized_cte_explain_analyze_aux_ports.sql this PR adds fails at its first statement there with Unknown explain kind 'EXPLAIN ANALYZE'. The source fix ports fine; only that test needs its EXPLAIN ANALYZE statements dropped on 26.5 and 26.6. The other two tests (04561, 04713) use only EXPLAIN PIPELINE and do reproduce the bug on both branches.

Could a maintainer apply v26.5-must-backport here so the robot opens the three backports?

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 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

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

5 participants