Repository navigation
Conversation
An `extremes = 1` query whose UNION/INTERSECT/EXCEPT branches read a materialized CTE, where at least one branch also builds a set (`IN (subquery)`), failed with Logical error: 'Reading from materialized CTE 'a' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan' The gate was not actually missing from the plan, it was bypassed. When two or more united branches carry an extremes port, `Pipe::unitePipes` calls `uniteExtremes`, which built `Resize -> ExtremesTransform -> EmptySink`. That sink only existed to swallow the transform's main-output rows, because `ExtremesTransform::prepare` emits its extremes chunk only once the main output has been drained to `Finished`. `ExecutingGraph::addEdges` records a direct edge only for connected output ports, so a sink with zero outputs has none and `initializeExecution` seeds it. The seed propagated up through the extremes chain into the inner `CreatingSets` gate, whose `prepare` reacts to its first output event by calling `setNeeded` on its main-side inputs, before the outer gate had released the delayed CTE writer. The CTE reader then ran, observed `is_built == false`, and threw. Replace the transform/sink pair with `ExtremesOnlyTransform`, one input and one output carrying only extremes. With no main-output stream there is nothing to drain, so no childless node exists for the executor to seed. The returned port is the processor's only output and the caller always connects it, which removes the defect structurally rather than patching one instance of it. The per-chunk min/max merge is shared verbatim as `accumulateExtremes`, so the extremes values, including the `isColumnConst` case, cannot drift between the two processors. Commit 641fc75 established this defect class and fixed the two writer-side paths via `DroppingTransform`; `uniteExtremes` was the remaining uncovered site. `ExtremesTransform` itself is unchanged for its other caller, `ExtremesStep`.
The five committed queries all had arms whose extremes coincide, so merge(arms) == arms[0] in every one of them. A uniteExtremes that never merged across arms would have left all five references byte-identical: the test proved only that the united extremes port exists, not that the extremes-of-extremes computation is correct. Both halves of uniteExtremes moved in this change (the accumulation body relocated to a free function, the driver swapped from ISimpleTransform to IAccumulatingTransform), so leaving the value half untested was the wrong coverage split. Add two queries whose asserted extremes are unreachable from any single arm: a two-arm EXCEPT discriminating the max (arms (0,4) and (15,19)) and a three-arm INTERSECT discriminating both bounds (arms (5,9), (0,9) and (5,19)), which also keeps the Resize-with-three-inputs path covered. Both are set operations, which yield one deterministic row set where a UNION ALL's arm order does not, and both stay at top level because an enclosing subquery would make addExtremesTransform drop the united extremes and recompute them over the final rows. Each retains its IN-subquery, so the inner CreatingSets gate and the abort regression are preserved. Verified by mutating the accumulation to keep only the first arm's chunk: the two new queries fail on an extremes value while the old five-query file still passes on that same mutant. The reference was regenerated on a pristine master build from the same queries with the IN-subquery removed, not copied from the build under test. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 rounds, 2 findings) plus my own
Severity: ❌ blocker / I also verified independently, reading the code cold before the evidence bundle, that the fix Session id: cron:clickhouse-review-slot-10:20260802-235600 |
Pre-PR validation gate
Regression sweep of 232 extremes, totals, union, intersect, materialized CTE and creating-sets tests: 227 pass and no existing Because Session id: cron:clickhouse-review-slot-10:20260802-235600 |
|
cc @novikd @PedroTadim, could you review this? |
|
Workflow [PR], commit [b1f9d3e] Summary: ❌
AI ReviewSummaryThis PR fixes the materialized-CTE scheduling bug in Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 23/23 (100.00%) · Uncovered code |
|
@groeneai why did you tagged me? |
|
Sorry, my mistake. I picked you as the materialized CTE component owner, but that is wrong: my own routing notes had you recorded for it and the component tree does not list you there at all. The right reviewer is @ novikd, who owns the feature and wrote the earlier |
CI finish ledger — b1f9d3eEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All 171 other checks passed ( Why the three fuzzer/stress reds are not caused by this diff, measured rather than argued. The The shape also does not go through the function this PR changes. 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;The necessary ingredients are Session id: cron:our-pr-ci-monitor:20260803-123000 |
|
Fixing PR for the three It is the The minimal reproducer published in the ledger is covered verbatim by the new test there, and the |
|
You are right that the PR is red, and right that it belongs with #111194. Both, for the same reason: there are three separate childless-sink sites, and the red checks here are not the one this PR changes. I will fold this into #111194 and close this PR. The measurement, because it decides which change is still missing there. Taking the query from this PR's own failing
So the wrapper is the whole difference, and the aborting form goes through a different helper. The third site is the one this PR changes: Separately, your point on #111194 that keeping |
|
Closing as agreed; the change moves into #111194 with the single-port |
Changelog category (leave one):
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 planfor a query withextremes = 1whoseUNION,INTERSECTorEXCEPTbranches read a materialized CTE and at least one branch also builds a set, for example withIN (subquery).Description
No related open issue found for this shape. It is a sibling of the
WITH TOTALSmechanism in #111194 and was reported publicly in that PR's review as a separate investigation.Reproducer, which aborts on current master in debug and sanitizer builds:
Root cause: the gate is not missing from the plan, it is bypassed. When two or more united branches carry an extremes port,
Pipe::unitePipescallsuniteExtremes, which builtResize -> ExtremesTransform -> EmptySink. That sink existed only to drain the transform's main output, becauseExtremesTransformemits its extremes chunk only after that output reachesFinished. A sink with zero outputs has no direct edge, soinitializeExecutionseeds it; the seed reached the innerCreatingSetsgate, which then calledsetNeededon its main-side inputs before the outer gate had released the delayed CTE writer. The CTE reader ran early and threw.The fix replaces the transform and sink with
ExtremesOnlyTransform, one input and one output carrying only extremes. With no main-output stream there is nothing to drain and no childless node to seed, so the defect is removed structurally rather than patched at one instance. The per-chunk min/max merge is shared verbatim asaccumulateExtremes, so extremes values cannot drift;ExtremesTransformis unchanged for its other caller,ExtremesStep.Commit 641fc75 established this defect class and fixed the two writer-side paths via
DroppingTransform.uniteExtremeswas the remaining uncovered site.Performance: two processors instead of three, only on the extremes branch. No new setting or format change, so no
SettingsChangesHistory.cppentry.Validation
uniteExtremesis shared by everyunitePipescaller that unites two or more extremes-carrying branches, includingUnionStep,IntersectOrExceptStep,CreatingSetsStep,MaterializingCTEStep,AggregatingStepand multi-shard reads throughReadFromRemote, so the extremes result was proven unchanged rather than argued.MemorySource::generateatReadFromMemoryStorageStep.cpp:87) and passes after the change.Nullable, all-NULL,LowCardinality,LowCardinality(Nullable), const columns,Floatwith NaN and infinities,String,Date,Decimal,Array,Tuple,Map, multi-column, empty branches,WITH TOTALS,UNION DISTINCT,INTERSECT,EXCEPTand aggregation. Byte-identical, with denormals quoted so NaN and infinity stay distinguishable.ExtremesSteppath: seven single-pipe probes byte-identical, confirming the other caller is untouched.LIMIT 0,LIMIT 1early termination, and multi-chunk accumulation withmax_block_size = 3.EXPLAIN PIPELINE graph=1shows the childlessEmptySinkgone andExtremesOnlyTransform's single output feeding the gate; the only remaining childless node is the gate itself..referencechanged. The 5 failures fail identically on a pristine master build for environment reasons, distributed access and missing stateful data.extremes = 1is pinned per statement so runner randomization cannot make it vacuous.