Repository navigation
Fix a table permanently stuck in the drop queue after a failed materialized-CTE query - #113397
Conversation
`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]>
|
Workflow [PR], commit [8e269f5] Summary: ❌
AI ReviewSummaryThis PR breaks the self-reference between Final Verdict✅ No findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 33/36 (91.67%) · Uncovered code |
|
🕵 Note: the leak this fixes is now failing |
|
@tiandiwonder we need this merged ASAP, it's failing a lot in the CI |
|
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. |
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
Cherry pick #113397 to 26.3: Fix a table permanently stuck in the drop queue after a failed materialized-CTE query
…ueue after a failed materialized-CTE query
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]>
Backport #113397 to 26.3: Fix a table permanently stuck in the drop queue after a failed materialized-CTE query
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 ... SYNCon any table the CTE read from never returns:system.tablesbut stays insystem.dropped_tableswithTablesToDropQueueSizestuck above zero, indefinitely;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 failingTables stuck in SharedCatalog local drop or detach queuesub-check ofStress test (amd_tsan, SharedCatalog, meta in keeper)on the private PR linked above (test04041_materialized_cte_parallel_replicas.sql);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 insideoptimize→ never completes.This is pre-existing and not introduced by the PR where it was observed. Severity is capped by reachability:
enable_materialized_ctedefaults to0and is tierExperimental, so a default deployment cannot hit it — but for a user who has opted in, the hang is permanent.Root cause
MaterializedCTEand its query plan hold each other.addPlansForMaterializedCTEsinPlanner.cppbuilds the CTE's plan, appends aMaterializingCTEStepinto that same plan, and then stores the plan back into the CTE:MaterializingCTEStepheld a strongMaterializedCTEPtr, so the graph was self-sustaining with no external holder. The only thing that broke the cycle was the claim —DelayedMaterializingCTEsStep::makePlansForCTEsmovingmaterialized_cte->planout — and that runs fromresolveMaterializingCTEsat the very end ofQueryPlan::optimize, after the first pass, the second pass, andaddStepsToBuildSets(which executes IN-subquery pipelines inline and can throw). Any exception raised inoptimizebefore that point therefore abandoned the cycle permanently.The leaked plan is what pins the table: every
Plannerrun ends withextendQueryContextAndStoragesLifetime, so the plan carriesaddStorageHolder,addTableLockand the interpreterContext; with parallel replicas,ReadFromParallelRemoteReplicasStepinside it holds thequery_tree(and henceTableNode::storage) plus a local-replica plan with its own storage holder. BothDatabaseCatalog::dropTableFinallyandSharedDatabaseCatalog::dropLocalTablesgate the final drop onisSharedPtrUnique(storage)— SharedCatalog deliberately takes no exclusive table lock there, so the refcount is the synchronization — and one leakedStoragePtrblocks the entry forever.Fix
Move the strong reference out of the cycle, mirroring what
StorageMemory::materialized_ctealready does for exactly this reason (its declaration carries a comment explaining the same cycle):MaterializingCTEStepnow holds aMaterializedCTEWeakPtr— the alias already existed inMaterializedCTE.hand was unused.transformPipelinelocks it and throwsLOGICAL_ERRORif it has expired, rather than taking any fallback path.MaterializingCTEsStep— the step that replacesDelayedMaterializingCTEsStepinaddPlansForMaterializingCTEsand becomes the parent node of every claimed CTE plan — takes over the strong handles.DelayedMaterializingCTEsStep::makePlansForCTEsnow returns aClaimedCTE { 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 recursivebuildSetInplacethat 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(plusTableNode::materialized_cte) owns the CTE from planning until the claim,MaterializingCTEsStep::ctesfrom the claim until the pipeline is built, andMaterializingCTETransform/MemorySourceduring execution. When the consuming plan dies before the claim, the delayed step releases its handles, theMaterializedCTEdrops to zero, and its plan — now holding only a weak back-reference — dies with it.The fix is placed here rather than at the
Plannersite because appendingMaterializingCTESteponly at claim time would also break the cycle but would change whatQueryPlan::optimizesees at the CTE plan's root (empty header,returns_single_stream,preserves_sorting), risking silent plan changes intryRemoveRedundantSortingandoptimizeLazyMaterialization. Releasingcte->planfrom~DelayedMaterializingCTEsStepwas rejected too: the sameMaterializedCTEcan 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 withquery_plan_max_optimizations_to_apply = 1— which throws after the cycle exists and before the claim — and then requiresDROP TABLE ... SYNCto complete, bounded bytimeout 30so a regression fails in 30 s with a clear signal instead of burning the harness timeout. On the unfixed binary it printsSTUCKand fails in 31 s; with the fix it passes in 1.5 s. All 27 existing tests that setenable_materialized_ctepass unchanged, including04260_explain_pipeline_materialized_cteand04043_materialized_cte_serialize_query_plan, so neitherEXPLAINoutput nor plan serialization is affected.Two notes on scope.
InterpreterSelectQueryAnalyzersetsoptimization_settings.materialize_ctes = falsefor 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 becauseconsiderEnablingParallelReplicasrefuses to build the candidate plan unless every step supports dataflow-statistics collection andDelayedMaterializingCTEsStepdoes not (verified on a live server:Some steps in the plan don't support dataflow statistics collection. Skipping optimization. Unsupported steps: DelayedMaterializingCTEs_14, ...). The thirdmaterialize_ctes = falsesite,collectFiltersForAnalysis, plans a dummy-table clone in which every table expression — including the CTE'sStorageMemory— has been replaced byReadFromDummy, so it never reaches aMaterializedCTEeither.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a permanent
DROP TABLEhang 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
26.3.68.6