Skip to content

Fix a table permanently stuck in the drop queue after a failed materialized-CTE query - #113397

Merged
nikitamikhaylov merged 3 commits into
masterfrom
fix-materialized-cte-plan-self-reference
Aug 12, 2026
Merged

nikitamikhaylov merged 3 commits into
masterfrom
fix-materialized-cte-plan-self-reference

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A query that uses a materialized CTE and fails during query-plan optimization leaks the CTE's whole plan graph for the life of the process, together with every table reference that plan carries. The user-visible consequence is that DROP TABLE ... SYNC on any table the CTE read from never returns:

  • the table disappears from system.tables but stays in system.dropped_tables with TablesToDropQueueSize stuck above zero, indefinitely;
  • on SharedCatalog the local drop/detach queue is wedged permanently and re-emits Table ... is stuck in the local drop or detach queue for N seconds because its storage is still referenced (use count is 4) every 60 s — which is how this surfaced, as the failing Tables stuck in SharedCatalog local drop or detach queue sub-check of Stress test (amd_tsan, SharedCatalog, meta in keeper) on the private PR linked above (test 04041_materialized_cte_parallel_replicas.sql);
  • the leaked memory is never reclaimed; only a server restart clears either symptom.

Reproduced on vanilla ClickHouse — plain MergeTree, Atomic database, no SharedCatalog and no stress harness. The three-way comparison isolates the trigger: no CTE query at all → drop takes 0 s; a materialized-CTE query that completes → 1 s; a materialized-CTE query that throws inside optimize → never completes.

CREATE TABLE t (uid Int16) ENGINE = MergeTree ORDER BY uid;
INSERT INTO t VALUES (1);
SET enable_materialized_cte = 1;

WITH a AS MATERIALIZED (SELECT * FROM t)
SELECT count() FROM a AS l JOIN a AS r ON l.uid = r.uid
SETTINGS query_plan_max_optimizations_to_apply = 1;   -- Code: 572 TOO_MANY_QUERY_PLAN_OPTIMIZATIONS

DROP TABLE t SYNC;   -- hangs forever

This is pre-existing and not introduced by the PR where it was observed. Severity is capped by reachability: enable_materialized_cte defaults to 0 and is tier Experimental, so a default deployment cannot hit it — but for a user who has opted in, the hang is permanent.

Root cause

MaterializedCTE and its query plan hold each other. addPlansForMaterializedCTEs in Planner.cpp builds the CTE's plan, appends a MaterializingCTEStep into that same plan, and then stores the plan back into the CTE:

MaterializedCTE --plan--> QueryPlan --node--> MaterializingCTEStep --strong--> MaterializedCTE
        ^                                                                              |
        +------------------------------------------------------------------------------+

MaterializingCTEStep held a strong MaterializedCTEPtr, so the graph was self-sustaining with no external holder. The only thing that broke the cycle was the claim — DelayedMaterializingCTEsStep::makePlansForCTEs moving materialized_cte->plan out — and that runs from resolveMaterializingCTEs at the very end of QueryPlan::optimize, after the first pass, the second pass, and addStepsToBuildSets (which executes IN-subquery pipelines inline and can throw). Any exception raised in optimize before that point therefore abandoned the cycle permanently.

The leaked plan is what pins the table: every Planner run ends with extendQueryContextAndStoragesLifetime, so the plan carries addStorageHolder, addTableLock and the interpreter Context; with parallel replicas, ReadFromParallelRemoteReplicasStep inside it holds the query_tree (and hence TableNode::storage) plus a local-replica plan with its own storage holder. Both DatabaseCatalog::dropTableFinally and SharedDatabaseCatalog::dropLocalTables gate the final drop on isSharedPtrUnique(storage) — SharedCatalog deliberately takes no exclusive table lock there, so the refcount is the synchronization — and one leaked StoragePtr blocks the entry forever.

Fix

Move the strong reference out of the cycle, mirroring what StorageMemory::materialized_cte already does for exactly this reason (its declaration carries a comment explaining the same cycle):

  1. MaterializingCTEStep now holds a MaterializedCTEWeakPtr — the alias already existed in MaterializedCTE.h and was unused. transformPipeline locks it and throws LOGICAL_ERROR if it has expired, rather than taking any fallback path.
  2. MaterializingCTEsStep — the step that replaces DelayedMaterializingCTEsStep in addPlansForMaterializingCTEs and becomes the parent node of every claimed CTE plan — takes over the strong handles. DelayedMaterializingCTEsStep::makePlansForCTEs now returns a ClaimedCTE { cte, plan } per claim instead of a bare plan, so each handle travels with the plan it belongs to and the replacing step owns exactly the CTEs whose plans hang below it. A CTE claimed elsewhere — by a recursive buildSetInplace that materialized it inplace — has its plan attached under that other step and stays out of this list.

That gives an unbroken chain of strong ownership from the consuming plan across the whole lifetime, with no cycle at any point: DelayedMaterializingCTEsStep::ctes (plus TableNode::materialized_cte) owns the CTE from planning until the claim, MaterializingCTEsStep::ctes from the claim until the pipeline is built, and MaterializingCTETransform / MemorySource during execution. When the consuming plan dies before the claim, the delayed step releases its handles, the MaterializedCTE drops to zero, and its plan — now holding only a weak back-reference — dies with it.

The fix is placed here rather than at the Planner site because appending MaterializingCTEStep only at claim time would also break the cycle but would change what QueryPlan::optimize sees at the CTE plan's root (empty header, returns_single_stream, preserves_sorting), risking silent plan changes in tryRemoveRedundantSorting and optimizeLazyMaterialization. Releasing cte->plan from ~DelayedMaterializingCTEsStep was rejected too: the same MaterializedCTE can be referenced by delayed steps in several plans, so destroying one plan could null out a plan another still has to claim.

Regression test: 04700_materialized_cte_plan_self_reference.sh. It drives the failing query with query_plan_max_optimizations_to_apply = 1 — which throws after the cycle exists and before the claim — and then requires DROP TABLE ... SYNC to complete, bounded by timeout 30 so a regression fails in 30 s with a clear signal instead of burning the harness timeout. On the unfixed binary it prints STUCK and fails in 31 s; with the fix it passes in 1.5 s. All 27 existing tests that set enable_materialized_cte pass unchanged, including 04260_explain_pipeline_materialized_cte and 04043_materialized_cte_serialize_query_plan, so neither EXPLAIN output nor plan serialization is affected.

Two notes on scope. InterpreterSelectQueryAnalyzer sets optimization_settings.materialize_ctes = false for the automatic-parallel-replicas candidate plan, which would leak such a CTE unconditionally; the change above covers that for free, but it is unreachable today because considerEnablingParallelReplicas refuses to build the candidate plan unless every step supports dataflow-statistics collection and DelayedMaterializingCTEsStep does not (verified on a live server: Some steps in the plan don't support dataflow statistics collection. Skipping optimization. Unsupported steps: DelayedMaterializingCTEs_14, ...). The third materialize_ctes = false site, collectFiltersForAnalysis, plans a dummy-table clone in which every table expression — including the CTE's StorageMemory — has been replaced by ReadFromDummy, so it never reaches a MaterializedCTE either.

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 a permanent DROP TABLE hang and memory leak after a query using a materialized CTE failed. The table stayed stuck in the drop queue until the server was restarted.

Version info

  • Backported to: 26.3.68.6

`Planner::addPlansForMaterializedCTEs` appends a `MaterializingCTEStep`
into the CTE's own plan and then stores that plan into
`materialized_cte->plan`, while the step holds a strong
`MaterializedCTEPtr`. That is a reference cycle with no external holder,
and the only thing that broke it was
`DelayedMaterializingCTEsStep::makePlansForCTEs` moving the plan out -
reached from `resolveMaterializingCTEs` at the very end of
`QueryPlan::optimize`, after both optimization passes and after
`addStepsToBuildSets`.

So a materialized-CTE query that threw inside `optimize` before that
point leaked the whole graph for the life of the process, including the
`StoragePtr` copies and table locks the plan carries from
`extendQueryContextAndStoragesLifetime`. Both `DatabaseCatalog` and
`SharedDatabaseCatalog` gate the final drop on
`isSharedPtrUnique(storage)`, so the leaked reference pinned the table
in the drop queue forever: `DROP TABLE ... SYNC` never returned, and
SharedCatalog re-emitted `stuck in the local drop or detach queue` every
60 s.

Move the strong reference out of the cycle, the way
`StorageMemory::materialized_cte` already does: `MaterializingCTEStep`
holds `MaterializedCTEWeakPtr`, and `MaterializingCTEsStep` - which
replaces `DelayedMaterializingCTEsStep` in
`addPlansForMaterializingCTEs` and becomes the parent of every claimed
CTE plan - takes over the strong handles. Ownership is then continuous
across planning, claim and pipeline build without ever forming a cycle.

Observed in `Stress test (amd_tsan, SharedCatalog, meta in keeper)` on
ClickHouse/clickhouse-private#67155 (test
`04041_materialized_cte_parallel_replicas.sql`); pre-existing, not
introduced there.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e269f5]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests, amd64) FAIL
Scraping system tables FAIL cidb IGNORED
Bugfix validation (functional tests, aarch64) FAIL
Scraping system tables FAIL cidb IGNORED
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL IGNORED

AI Review

Summary

This PR breaks the self-reference between MaterializedCTE and its planned MaterializingCTEStep, then transfers strong ownership to MaterializingCTEsStep only for the CTE plans that are actually claimed, with a focused stateless regression test for the pre-claim exception path. I reviewed the current diff, surrounding ownership and pipeline paths, and all prior discussion, and I did not find any remaining correctness, lifetime, or coverage issues that warrant a new review comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 33/36 (91.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
@tiandiwonder
tiandiwonder requested a review from novikd August 5, 2026 01:19
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Note: the leak this fixes is now failing Stress test (arm/amd_asan_ubsan) master-wide — LeakSanitizer: detected memory leaks with an all-indirect (cycle) report of a materialized-CTE graph (TemporaryTableHolder, StorageMemory, Context::createCopy via QueryTreeBuilder::buildSelectExpression, QueryPlan nodes). The same signature hit 14 stress runs across 13 different PRs since 2026-08-07 18:27 UTC (97032, 113212, 112950, 112302, 108648, 93111, 107106, 112968, 108349, 109299, 112940, 111990, 110166), e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112968&sha=67d6349e63df05bb4c1ab01c424acbfbbdb2daf9&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 — consistent with a stress-killed query dying before resolveMaterializingCTEs claims the plan.

@PedroTadim

Copy link
Copy Markdown
Member

@tiandiwonder we need this merged ASAP, it's failing a lot in the CI

@nikitamikhaylov

Copy link
Copy Markdown
Member

Talked to @azat, the Bugfix validation check failed mainly because a server on the old version wasn't able to stop in time (because of the table permanently stuck in the DROP queue) which is a topic of this fix.

So, everything works correctly, we can merge.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit fa4ccb8 Aug 12, 2026
177 of 181 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the fix-materialized-cte-plan-self-reference branch August 12, 2026 15:16
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 13, 2026
A per-arch Bugfix Validation job could report FAIL, and so block the PR as
unvalidated, on a run where the bug did reproduce.

invert_bugfix_validation_status decides the verdict, then the COLLECT_LOGS
stage appended ClickHouseProc.extra_tests_results with a bare
extend_sub_results. That call re-derives the parent status from its children
(Result._update_status), so a single FAIL artifact row overwrote the verdict.
The gate in new_tests_check.py reads the job status with strict is_success, so
any_bugfix_validation_passed then found no validating arch and refused the
merge with "No per-arch Bugfix Validation job validated the bug". Those rows
are produced inside prepare_logs, after the run is over, so they can never be
part of the verdict.

Seen on ClickHouse#113397: the PR's own bug hung DROP TABLE ... SYNC, the graceful stop
timed out, the still-running server kept its status file locked and every
clickhouse local system-table dump failed with CANNOT_OPEN_FILE. Both arches
reported Failed: 1, Passed: 0 while their regression test row was OK. The more
convincingly such a bug reproduces, the likelier the job discarded its own
result.

Attach those rows through attach_post_verdict_artifacts, which restores the
captured status on a labelled bugfix-validation job. The rows stay visible in
the report, they just stop voting. The captured status is restored rather than
forced to OK so that every verdict the inverter can set survives: reproduction
OK, no-repro SKIPPED, inconclusive ERROR. Scoping the restore to
is_labeled_bugfix_validation, the same guard the inverter uses, leaves ordinary
functional jobs reddening on a failed dump, which is real signal.

Labelling the row LOG_CHECK or moving the append before the inverter was
rejected: extra_tests_results is empty at that point, and a FAIL row reaching
the inverter is flipped to OK and counted as a reproduction, so a broken log
dump would become evidence that the bug was validated. A test records this.

Only the ordering is fixed here. The graceful-stop timeout that left the lock
held is a separate problem.

Related: ClickHouse#113397
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
robot-ch-test-poll added a commit that referenced this pull request Nov 21, 2026
Cherry pick #113397 to 26.3: Fix a table permanently stuck in the drop queue after a failed materialized-CTE query
robot-clickhouse added a commit that referenced this pull request Nov 21, 2026
…ueue after a failed materialized-CTE query
alexey-milovidov added a commit that referenced this pull request Nov 21, 2026
Resolve the conflicts of backporting #113397 to 26.3.

The 26.3 branch does not have the two-pass `resolveMaterializingCTEs`
(`DelayedMaterializingCTEsStep::optimizePlans`) and
`removeAllDelayedMaterializingCTEsStep`, so `makePlansForCTEs` keeps its
26.3 signature with `optimization_settings` and still optimizes the plan
of each CTE it claims. On top of that the fix is applied as in master:
`MaterializingCTEStep` refers to its `MaterializedCTE` weakly,
`makePlansForCTEs` returns `ClaimedCTE` pairs, and `MaterializingCTEsStep`
takes over the strong handles of exactly the CTEs it claimed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 21, 2026
alexey-milovidov added a commit that referenced this pull request Nov 21, 2026
Backport #113397 to 26.3: Fix a table permanently stuck in the drop queue after a failed materialized-CTE query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport v26.4-must-backport v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants