Skip to content

Make the cleanup DROP of a failed CREATE ... AS SELECT killable - #113504

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-unkillable-create-as-select-cleanup-drop
Aug 6, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-unkillable-create-as-select-cleanup-drop

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

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 CREATE TABLE ... AS SELECT whose populating SELECT failed becoming unkillable when database_atomic_wait_for_drop_and_detach_synchronously is enabled: the internal cleanup DROP of the temporary table waited for the background drop queue and ignored both KILL QUERY and max_execution_time.

Description

A plain CREATE TABLE ... AS SELECT on an Atomic database populates a temporary table and publishes it with a RENAME; if the populate fails, an internal DROP cleans it up. That DROP runs on a context built from the global context, which copies the caller's settings but not its process list element.

With database_atomic_wait_for_drop_and_detach_synchronously = 1 the copied settings make that DROP synchronous, so it waits in DatabaseCatalog::waitTableFinallyDropped. The only way out is the throw_if_cancelled callback, which InterpreterDropQuery::waitForTableToBeActuallyDroppedOrDetached derives from the context's process list element. Without one it is a no-op, so the wait -- and the whole CREATE -- ignores KILL QUERY and max_execution_time for as long as the drop queue is busy.

Observed as a Stress test (arm_release) hung check: an internal query sat in that wait for 655 s with is_cancelled = 1 and max_execution_time = 10. The sibling factory used by CREATE OR REPLACE copies the caller's context, so its cleanup DROP was already killable; this restores that property for the plain-create path.

Validated with a deterministic fixture: a failpoint parks the background drop thread where the waiter's predicate still holds, so the wait is always entered. Before the change the query stays in the wait and only releasing the failpoint ends it; after it, it returns 1.3 s after the KILL. Reverting only the added line reddens the new test. 50/50 randomized runs pass; 61 neighbouring drop-queue tests show no regression.

The factory's other caller (CREATE TABLE IF NOT EXISTS ... AS SELECT losing a race for the target name) has a separate pre-existing bug, left for its own change: it passes the context as a temporary while InterpreterDropQuery keeps only a weak pointer, so the server aborts with LOGICAL_ERROR: Context has expired. That reproduces on unmodified master with no failpoint.

A plain `CREATE TABLE ... AS SELECT` on an Atomic database is executed by
populating a temporary table and publishing it with a RENAME. If the populate
fails, an internal cleanup DROP removes the temporary table. That DROP runs on a
context built from the global context, which copies the caller's settings but
not the caller's process list element.

With `database_atomic_wait_for_drop_and_detach_synchronously` enabled the copied
settings make the DROP synchronous, so it waits in
`DatabaseCatalog::waitTableFinallyDropped`. The only exit from that loop is the
`throw_if_cancelled` callback, which
`InterpreterDropQuery::waitForTableToBeActuallyDroppedOrDetached` derives from
`getProcessListElementSafe()`. With no element the callback is a no-op, so the
wait, and therefore the whole CREATE, ignores both KILL QUERY and
`max_execution_time` for as long as the background drop queue keeps the table.

It showed up as a Stress test (arm_release) hung check: an internal query sat in
that wait for 655 s with `is_cancelled = 1` and `max_execution_time = 10`, so
cancellation had fired and had no effect.

The sibling factory used by CREATE OR REPLACE copies the caller's context and
therefore already carries the element, which is why only the plain-create path
was affected. Pass the element through so the wait the internal context can
already enter is also a wait it can leave. `getProcessListElementSafe` is used
rather than `getProcessListElement` because this factory also runs on the
failure path, where throwing on an expired weak pointer would replace the real
error; returning an empty pointer instead degrades to today's behaviour for a
genuinely internal operation that has no user query.

The regression test enters the wait deterministically by parking the background
drop thread at the existing `database_catalog_drop_finally_before_id_erase`
failpoint, which pauses after `dropTableFinally()` and before the UUID is erased
from `tables_marked_dropped_ids`, so the waiter's predicate still holds and it
cannot leave the loop on its own. Before this change the query stays in the wait
and only releasing the failpoint ends it; after it, the query returns 1.3 s
after the KILL with the failpoint still parked. The cleanup DROP's exception is
logged and swallowed while the populate's own error is rethrown, so the client
sees the same error on both sides and the test asserts the cancellation from
`system.text_log` instead of from the client's exit code.

The same factory's other consumer, the lost-race DROP taken when a concurrent
query creates the target name during the populate, is left unchanged here: it
passes its context as a temporary while `InterpreterDropQuery` keeps only a weak
pointer, so it aborts with `LOGICAL_ERROR: Context has expired` before reaching
any wait. That reproduces on unmodified master with no failpoint and needs its
own fix.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 dropped self-finding, 1 noted nit, 0 blockers)

Two independent reviews ran against this diff before it was opened: a cold code review that did not
read the implementation notes first, and a separate second-model gate pass. The gate returned zero
findings. The cold review filed one blocker and one nit, and re-measurement refuted the blocker,
which I am recording here rather than dropping silently.

# Finding Verdict
1 💡 The last paragraph explains the neighbouring pre-existing crash as "passes the context as a temporary while InterpreterDropQuery keeps only a weak pointer". I filed this as a blocker, believing it contradicted C++ temporary lifetime: a temporary materialized as a function argument lives to the end of the full expression, and the whole chained InterpreterDropQuery(...).execute() is one full expression. DROPPED, my finding was wrong. My model linked libstdc++. ClickHouse builds against its vendored libc++ with _LIBCPP_ABI_VERSION 999, and _LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI is gated on >= 2, so std::shared_ptr carries __attribute__((__trivial_abi__)). For a trivial_abi class passed by value the callee destroys the parameter, so the constructor really does release the context before .execute() runs. Same model built twice from one source, differing only in that attribute: without it the shape returns normally; with it the context is destroyed before execute is entered and the weak lock throws Context has expired, while a named-variable positive control succeeds in both builds. The captured server aborts agree, at InterpreterCreateQuery.cpp:2706:99 on unmodified master, where column 99 is the execute() token. The paragraph is correct as written and was left unchanged.
2 ⚠️ The added comment says "the internal DROPs below", but the same factory also builds the context for the publishing RENAME, not only for the two DROPs. Noted, not blocking. Verified the RENAME gains no behaviour: throwIfKilled / isCurrentQueryKilled / getProcessListElement / checkTimeLimit have zero occurrences in every file of the rename chain (InterpreterRenameQuery.cpp, DatabaseAtomic.cpp, DatabaseOnDisk.cpp, DatabasesCommon.cpp, DatabaseCatalog.cpp, DatabaseReplicated.cpp), so the successful-publish path is unchanged. Not worth re-touching src/ for one word.

Checks that came back clean, each re-derived from source rather than taken from the implementation
notes: the legality of setProcessListElement on a copy of the global context, with the existing
InterpreterExecuteAsQuery precedent for the identical three-call shape; the choice of
getProcessListElementSafe over the throwing accessor, which matters because this factory also runs
inside the failure path where a LOGICAL_ERROR would replace the user's real error; the whole
root-cause chain from the copied setting to the condition variable whose only exit is the callback;
the absence of any stranding risk, since the wait runs after the table is already queued for
background removal, so leaving the wait abandons the wait and not the drop; the new test's
discriminator, which is asserted while the failpoint is still parked and therefore cannot pass on a
reverted build, with its two log assertions correctly labelled as controls rather than
discriminators; the failpoint window sitting genuinely inside the waiter's predicate; and the fact
that none of the three settings the test depends on is touched by the runner's randomization.

Freshly re-checked before opening: no competing pull request. Seventeen open candidates were found by
keyword and each full diff was grepped for the symbols this change touches; every one scored zero
while this diff scores two, so the zeros are meaningful. The nearest neighbours edit different
functions or a different file entirely. Merges cleanly into current master, and all six load-bearing
files are byte-identical between this base and master.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Answer
a Deterministic repro? Yes. The existing database_catalog_drop_finally_before_id_erase failpoint parks the background drop thread after dropTableFinally() and before the UUID is erased from tables_marked_dropped_ids, so the waiter's predicate still holds and the wait is entered on demand. Not a timing race.
b Root cause explained? The internal cleanup context copies the caller's settings (so database_atomic_wait_for_drop_and_detach_synchronously makes the DROP synchronous) but not the caller's process list element, which is the only thing waitForTableToBeActuallyDroppedOrDetached can build its throw_if_cancelled callback from. With no element the callback is a no-op and waitTableFinallyDropped's loop has no other exit.
c Fix matches root cause? Yes: the missing field is supplied in the factory that omits it, restoring symmetry with the sibling factory used by CREATE OR REPLACE. No timeout, no settings change, no guard at the wait site.
d Test intent preserved / new test? New test 04765_kill_create_as_select_cleanup_drop.sh. Its oracle is 6 lines: a kill_landed control that is true on both binaries, the returned_while_blocked discriminator, a system.text_log control that the wait was entered, the QUERY_WAS_CANCELLED discriminator, and two lines asserting no orphan table and no stranded temporary table.
e Both directions? Pre-fix: is_cancelled = 1 at 1.2 s and the query is still in the wait 16 s later, returning only once the failpoint is released. Post-fix: returns 1.32 s after the KILL with the failpoint still parked. As the runner reports it: pre-fix [ FAIL ] 64.09 sec with -returned_while_blocked 1 / +returned_while_blocked 0, post-fix [ OK ] 3.59 sec. Measured note: the cleanup DROP's exception is logged and swallowed, so the client sees the populate's own error on both arms; asserting the client's error code would have been a vacuous oracle.
f General across code paths? The factory has exactly 3 call sites, so fixing it covers the class. The cleanup DROP is the reported hang and is fixed. The publishing RENAME reaches no wait (InterpreterRenameQuery has zero wait* calls) and harmlessly also gains the element. The lost-race DROP is discussed in the PR body: it hits a separate pre-existing crash before reaching any wait. Controls: the CREATE OR REPLACE cleanup DROP uses the sibling factory and was already killable, and two waitDetachedTableNotInUse sites already build the same callback from the query context.
g Generalizes across inputs? No data path, no types, no parameters. The one input-shaped case is a genuinely server-internal operation with no user query, where getProcessListElementSafe() returns {}, the callback stays a no-op and behaviour is exactly as today.
h Backward compatible? No setting defaults change and no serialization change, so no SettingsChangesHistory.cpp entry is owed. The only behaviour change is that these internal cleanup operations become cancellable, which is the intent.
i Invariants preserved? A cancelled cleanup leaves no leak: the background drop task still owns removal (enqueueDroppedTableCleanup has already run). Verified after the post-fix cancellation: system.dropped_tables drained to 0 and the target table does not exist.

Mutation arm: reverting only the added line and rebuilding reproduced the pristine base build id exactly, and the base arm above measured that binary as FAIL. Re-applying returned the build id exactly to the shipped value, so the shipped tree is byte-for-byte the measured tree.

Neighbours: 61 tests matching the drop-queue / CREATE OR REPLACE family. Every only-in-fix candidate was re-run in isolation on both binaries; 8 of 10 passed on both (load artifacts on a single debug server), one fails on the base binary too, and 03359_ub_merging_aggregated_transform fails on both (4/10 base vs 8/10 fix) with the identical ALL_CONNECTION_TRIES_FAILED cluster error and contains no CREATE ... AS SELECT at all. No regressions.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @evillique @davenger, could you review this? The internal context used to clean up a failed CREATE TABLE ... AS SELECT copies the caller's settings, so database_atomic_wait_for_drop_and_detach_synchronously makes its cleanup DROP wait in DatabaseCatalog::waitTableFinallyDropped, but it does not copy the process-list element that is the wait's only exit, so the whole CREATE ignored KILL QUERY and max_execution_time.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [98170b2]

Summary: ✅


AI Review

Summary

This PR threads the caller's QueryStatus into the internal full-access context used by plain CREATE TABLE ... AS SELECT, which fixes the documented unkillable cleanup DROP in that factory. I found one remaining major gap: the same cancellation invariant is still broken in the shared helper used for other internal synchronous DROPs, so the hang is still reachable through another user-visible DDL path.

Findings

⚠️ Majors

  • src/Interpreters/InterpreterCreateQuery.cpp:2442 This change only fixes make_internal_context. InterpreterDropQuery::executeDropQuery still creates a full-access drop_context from global_context, copies the caller's settings, and never propagates the process-list element. ALTER WINDOW VIEW reaches that helper with sync = true in src/Storages/WindowView/StorageWindowView.cpp:500, so if the background drop queue is blocked the inner-table DROP still sits in DatabaseCatalog::waitTableFinallyDropped() and ignores both KILL QUERY and max_execution_time. Suggested fix: thread current_context->getProcessListElementSafe() into executeDropQuery's drop_context (or centralize these full-access internal DROP contexts in one helper) and add coverage for one of the non-CREATE callers.
Final Verdict

⚠️ Needs changes before merge: the targeted CREATE ... AS SELECT path looks fixed, but the same cancellation invariant is still broken in the shared internal DROP helper used by at least ALTER WINDOW VIEW.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · 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
internal_context->makeQueryContext();
internal_context->setSettings(current_context->getSettingsRef());
/// The settings copied above can make the internal DROPs below wait; the element is the only way out.
internal_context->setProcessListElement(current_context->getProcessListElementSafe());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this only fixes one instance of the invariant you rely on here. make_internal_context now carries the caller's QueryStatus, but InterpreterDropQuery::executeDropQuery still builds a full-access drop_context from global_context, copies the caller's settings, and never calls setProcessListElement (src/Interpreters/InterpreterDropQuery.cpp:890). ALTER WINDOW VIEW reaches that helper with sync = true (src/Storages/WindowView/StorageWindowView.cpp:500), so if the background drop queue is blocked its inner-table DROP still waits in waitTableFinallyDropped with no way for KILL QUERY or max_execution_time to break it. Please thread current_context->getProcessListElementSafe() through that helper as well, or centralize these internal full-access DROP contexts so the cancellation behavior stays consistent.

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.

Both citations check out against current master, and the mechanism is real: executeDropQuery builds drop_context from global_context at InterpreterDropQuery.cpp:890, that file has zero setProcessListElement calls, and drop_query->sync = sync at :883 makes the inner DROP wait regardless of ignore_sync_setting (which clears the setting, not the already-set flag).

The carrier is wider than ALTER WINDOW VIEW. A plain DROP TABLE <mv> SYNC reaches the same wait with no experimental settings, and so does CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE when the populate throws, which recurses out of the function this PR changes:

waitTableFinallyDropped <- waitForTableToBeActuallyDroppedOrDetached <- executeToTable
  <- executeDropQuery                       <-- element lost here
  <- StorageMaterializedView::dropInnerTableIfAny <- DatabaseAtomic::dropTable
  <- executeToTableImpl <- executeToTable
  <- InterpreterCreateQuery::doCreateOrReplaceTable

So I implemented your suggestion (a), built it, and it worked as intended: both shapes became killable, and a mutant carrying only this PR's existing line reddened exactly the new assertion. Measured on the pristine base and on this PR's head both shapes hang identically, so the defect is pre-existing rather than introduced here.

I then reverted it, because propagating the element there converts the hang into a corrupt catalog. DatabaseAtomic::dropTable:199-204 calls dropInnerTableIfAny before dropTableImpl, so the new cancellation throw aborts the parent's own removal. With the line, DROP TABLE mv SYNC returns after the KILL but leaves the view attached with its inner table already gone, so SELECT FROM mv gives Code: 60 and the view is only recoverable by dropping it again; the CREATE OR REPLACE case leaves a visible _tmp_replace_* materialized view behind. Without the line the parent is removed correctly. Deterministic on repeated runs.

The reasoning that a cancellation check can only add a way to stop holds for the wait but not for its caller: the throw unwinds a caller that was relying on the wait to finish. Fixing this site therefore needs the ordering in DatabaseAtomic::dropTable repaired first, across the four storages that own inner tables. That is your option (b), and it is a wider change than this one-line context propagation, so it belongs in its own PR rather than here.

Nothing in this PR's description is affected: its changelog entry claims only the plain CREATE ... AS SELECT path, which is what it fixes.

@groeneai

groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 98170b2

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks infra: the build-profile telemetry hook aborts before its retry loop, No connection to LogCluster / LogCluster not ready from the is_ready probe. Non-gating, so the enclosing check-run still reports success a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR). Not #113409: its retries sit inside do_query's response loop, strictly after the is_ready early return, so this mode is untouched

No other check failed on this head: 174 check-runs, 0 incomplete, 17 skipped by should_skip_job, Config Workflow and Finish Workflow both success, and CIDB reports 0 rows with test_status IN ('FAIL','ERROR') besides the one above and 0 with check_status IN ('failure','error').

Session id: cron:our-pr-ci-monitor:20260805-210000

[Corrected 2026-08-05: the owner task already existed and is in progress, so the wording is "moved to pending", not "created". Same owner, no change of disposition.]

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants