Repository navigation
Fix LOGICAL_ERROR planning a materialized CTE referenced multiple times over a Distributed table - #108924
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260630-101200 |
|
cc @novikd @KochetovNicolai — could you review this? On a per-shard local plan, a materialized-CTE reference can resolve to the temp StorageMemory by name with no subquery; |
|
Workflow [PR], commit [d5b213b] Summary: ✅
AI ReviewSummaryThis PR narrows Final Verdict
|
| /// directly to the temp storage by name (e.g. on a per-shard local plan) carries the | ||
| /// `MaterializedCTE` but no subquery. Prefer a subquery-bearing node as the representative | ||
| /// so `addBuildSubqueriesForMaterializedCTEsIfNeeded` can build the plan. | ||
| if (!inserted && !it->second.table_node->as<TableNode>()->isMaterializedCTE() && table_node->isMaterializedCTE()) |
There was a problem hiding this comment.
!it->second.table_node->as<TableNode>() is always false
There was a problem hiding this comment.
Right, removed. Within one query tree every reference to a CTE resolves to a node that carries the subquery, so the swap could never fire. The new condition keys on "no subquery and no plan" to skip the read-by-name shard reference instead.
| { | ||
| auto cte_subquery = cte_table_node->getMaterializedCTESubquery(); | ||
| if (!cte_subquery) | ||
| throw Exception(ErrorCodes::LOGICAL_ERROR, |
There was a problem hiding this comment.
@groeneai you just removed exception and did not fix anything
There was a problem hiding this comment.
You are right, that was a band-aid. Reverted the continue; the LOGICAL_ERROR guard is back.
The real bug is in collectMaterializedCTEs. On a per-shard local plan (createLocalPlan, to_stage = WithMergeableState) the CTE reference resolves by name to the temp StorageMemory, so the TableNode carries the MaterializedCTE (via extractCTE) but has no subquery. The initiator materializes the CTE once and ships the temp table to the shard as an external table, so the shard must read it directly, not materialize it. Collecting that reference is what produced the unbuildable state the guard caught (and, when it did not throw, an empty materializing step around a read with no plan).
Fix: collectMaterializedCTEs skips a reference that has no subquery and is not plan-backed. Subquery-bearing references, and references whose CTE already has a plan (the forceMaterializeCTE IN-set path), are collected and gated as before, so ordering and the gate are unchanged. The guard stays and now only fires on a genuinely invalid state.
Verified: the reproducers no longer abort and return correct results (distributed == 2x local on 2 shards) across prefer_localhost_replica 0/1 and serialize_query_plan 0/1; non-distributed materialized CTEs are unaffected.
…es over a Distributed table When a MATERIALIZED CTE is referenced from more than one join-tree position over a Distributed table, planning raised "CTE '...' does not have query tree, but was not planned yet" (a LOGICAL_ERROR; aborts the server in debug/sanitizer builds). Root cause is in collectMaterializedCTEs. On a per-shard local plan (createLocalPlan, to_stage = WithMergeableState) the CTE references resolve by name to the CTE's temporary StorageMemory, so the TableNode carries the shared MaterializedCTE (TableNode picks it up via extractCTE) but has no subquery child (isMaterializedCTE() == false). The initiator materializes the CTE once and ships the temporary table to the shard as an external table, so the shard must read it directly. collectMaterializedCTEs collected these subquery-less references and addBuildSubqueriesForMaterializedCTEsIfNeeded then either threw (no subquery to build a materialization plan from) or, worse, wrapped the read in an empty materialization step that materializes nothing - the read only happened to work because the initiator had already populated the table on a single node. Fix: collectMaterializedCTEs no longer collects a reference that has no subquery and is not plan-backed. Such a reference is a read-by-name of a temp table the initiator owns; it has nothing to materialize and is read directly. References that still carry a subquery, or whose CTE already has a plan (e.g. the forceMaterializeCTE path for IN-set subqueries), are collected and gated as before, so multi-level CTE ordering and the materialization gate are unchanged. The LOGICAL_ERROR guard in addBuildSubqueriesForMaterializedCTEsIfNeeded is kept: it now only fires on a genuinely invalid state. Co-Authored-By: Claude Opus 4.8 <[email protected]>
19b3721 to
30adf5a
Compare
|
Updated after reworking the fix (root cause in Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260630-150400 |
CI finish ledger — 30adf5aEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
None of these are caused by this PR (a focused Session id: cron:our-pr-ci-monitor:20260630-183000 |
|
Fixing PR for the |
CI finish ledger — 30adf5aEvery failure below has an owner: a fixing PR (ours or external), or the private sync check. No PR-caused failures (this PR's diff is
A materialized-CTE planner fix cannot cause a reinterpret-scale function bug, a DDL-propagation race, a thread-group double-attach, or a TSan stress-shutdown deadlock; all are pre-existing trunk signatures with owning fix PRs. Session id: cron:our-pr-ci-monitor:20260630-203000 |
CI finish ledger — f54e395Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The earlier partial fix #111528 (pin Session id: cron:our-pr-ci-monitor:20260729-103000 |
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
@groeneai, we have fixed |
…/fix-materialized-cte-distributed-shard-plan
|
Merged master into the branch. New head is I checked that #112385 was really what this branch was missing rather than assuming it: its fix I rebuilt as well, because the merge brings in the |
CI finish ledger - 0f7fe63Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Notes. Neither failure is caused by this PR, whose diff is one planner file plus its own stateless Session id: cron:our-pr-ci-monitor:20260801-093000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · Uncovered code |
An IN-set pipeline built during index analysis runs standalone under its own CompletedPipelineExecutor, so no DelayedPortsProcessor from any other plan can gate its readers. When such a plan reads a materialized CTE that nothing in it materializes, MemorySource::generate observes is_built == false and throws "Reading from materialized CTE '<name>' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan". The reference is left ungated for a correct reason. A materialized CTE reading a Distributed or remote() table plans a shard-local plan, and the deeper CTE is resolved there by name, so TableNode::isMaterializedCTE() is false; the CTE is also not yet plan-backed, so collectMaterializedCTE declines to gate it - the arm ClickHouse#108924 added deliberately for a read-by-name of a temp table the initiator owns. That plan is later executed as a standalone in-place set pipeline, where the outer gate does not reach. Push a DelayedMaterializingCTEsStep onto the plan before an in-place build runs it, covering every CTE the plan's node tree reads while no step in that tree materializes it, reusing the existing gate machinery. The step becomes the root, so it dominates every reader; is_materialization_planned keeps the attachment idempotent when another plan already claimed the CTE. Both entry points are covered (buildSetInplace and buildOrderedSetInplace, the latter on both its clone and destructive branches). Measured on the rebased tree, fresh server per arm, build id and fixture row count asserted before each arm: arm base fixed remote() + IN over deeper CTE, reused gate 9 Distributed engine, same shape gate 9 Distributed, non-primary-key column gate 9 remote() + PREWHERE gate 9 buildSetInplace route (ordered build off) gate 9 plain MergeTree control 9 9 force_primary_key control (03928 shape) 4 4 EXPLAIN indexes=1 sees the set condition 1 1 same, use_index_for_in_with_subqueries=0 0 0 The last two are an oracle and its negative control: the index path is still taken. An empty source stays 0 on both. 04712 fails on the pre-fix binary through the test runner and passes after, 50 of 50 randomized runs; the materialized-CTE family is green on both binaries except 04041, whose output is byte-identical on each. Closes: ClickHouse#113184
No related open issue found (surfaced by the AST fuzzer).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERROR(CTE '...' does not have query tree, but was not planned yet) when aMATERIALIZEDCTE is referenced from more than one join-tree position (for example two joined subqueries, or a joined subquery plus a scalar subquery inWHERE) in a query over aDistributedtable. The query now executes instead of raising the exception (it aborted the server in debug/sanitizer builds).Description
Found by the AST fuzzer: STID
0250-35b7, checkAST fuzzer (amd_debug).Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102866&sha=f405a561e225d69a9533751eb4f099372847da83&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
(The fuzzer surfaced this on an unrelated PR's run; the bug is pre-existing on master.)
Reproducer (2-shard cluster):
Root cause is in
collectMaterializedCTEs. On a per-shard local plan (createLocalPlan,to_stage = WithMergeableState) the CTE references resolve by name to the CTE's temporaryStorageMemory, so theTableNodecarries the sharedMaterializedCTE(picked up viaextractCTE) but has no subquery child (isMaterializedCTE() == false). The initiator materializes the CTE once and ships the temporary table to the shard as an external table; the shard reads it directly.These subquery-less references were still collected, and
addBuildSubqueriesForMaterializedCTEsIfNeededthen either threw (no subquery to build the materialization from) or wrapped the read in a materialization step that materializes nothing.Fix:
collectMaterializedCTEsno longer collects a reference that has no subquery and is not plan-backed. References that still carry a subquery, or whose CTE already has a plan (theforceMaterializeCTEpath for IN-set subqueries), are collected and gated exactly as before, so CTE ordering and the materialization gate are unchanged. TheLOGICAL_ERRORguard in the consumer is kept and now only fires on a genuinely invalid state.Regression cases added to
04036_materialized_cte_distributed_race.