Skip to content

Make waitTableFinallyDropped respond to query cancellation - #97586

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-drop-database-hung-on-cancellation
Mar 4, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-drop-database-hung-on-cancellation

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 21, 2026 •

Copy link
Copy Markdown
Member

Summary

  • DatabaseCatalog::waitTableFinallyDropped used condition_variable::wait with a predicate that only checked if the table was removed from the dropped set or if the server was shutting down. When a DROP DATABASE query was killed, the wait was never interrupted — the condition variable was not notified on cancellation and the predicate never checked for it.
  • Changed to wait_for with a 1-second timeout in a loop, checking an is_cancelled callback on each iteration. InterpreterDropQuery passes a callback that checks ProcessListElement::isKilled.
  • Observed in Stress test (amd_tsan): three DROP DATABASE IF EXISTS test_5 queries stuck for 2500+ seconds in waitTableFinallyDropped, all with is_cancelled: 1.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97531&sha=87c4f2c71430de0439d1640f137554d5d1012611&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
#97531

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):

Fix DROP DATABASE with database_atomic_wait_for_drop_and_detach_synchronously hanging indefinitely when the query is killed.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.3.1.356

@clickhouse-gh

clickhouse-gh Bot commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [788aa42]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Feb 21, 2026
@ClickHouse ClickHouse deleted a comment from CLAassistant Feb 21, 2026
`DatabaseCatalog::waitTableFinallyDropped` used `condition_variable::wait`
with a predicate that only checked if the table was removed or the server
was shutting down. When a query was killed, the wait was never interrupted,
causing `DROP DATABASE` queries to hang indefinitely in the stress test.

Changed to `wait_for` with a 1-second timeout in a loop, checking an
`is_cancelled` callback each iteration. The `InterpreterDropQuery` caller
passes a callback that checks `ProcessListElement::isKilled`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97531&sha=87c4f2c71430de0439d1640f137554d5d1012611&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov
alexey-milovidov force-pushed the fix-drop-database-hung-on-cancellation branch from bc7eba4 to a66af62 Compare February 21, 2026 22:28

Copilot AI left a comment

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.

Pull request overview

This PR makes DROP DATABASE ... SYNC (with database_atomic_wait_for_drop_and_detach_synchronously=1) stop waiting indefinitely in DatabaseCatalog::waitTableFinallyDropped when the query is cancelled, by polling with a timeout and checking a cancellation callback provided by InterpreterDropQuery.

Changes:

  • Extend DatabaseCatalog::waitTableFinallyDropped to accept a cancellation callback and switch to a timed wait loop.
  • Pass a cancellation predicate from InterpreterDropQuery based on ProcessListElement::isKilled().
  • Update DatabaseReplicated to call the new waitTableFinallyDropped signature.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/Interpreters/InterpreterDropQuery.h Adjusts helper signature to accept ContextPtr for cancellation integration.
src/Interpreters/InterpreterDropQuery.cpp Wires process-list based cancellation into the synchronous drop wait.
src/Interpreters/DatabaseCatalog.h Changes waitTableFinallyDropped API to accept a cancellation callback.
src/Interpreters/DatabaseCatalog.cpp Implements timed waiting + periodic cancellation checks during final-drop wait.
src/Databases/DatabaseReplicated.cpp Adapts call site to new waitTableFinallyDropped signature.
Comments suppressed due to low confidence (1)

src/Interpreters/InterpreterDropQuery.cpp:119

  • This change fixes a cancellation hang in a core DROP DATABASE sync path, but there doesn’t appear to be a regression test covering it. Please add a stateless test that starts DROP DATABASE ... SYNC with database_atomic_wait_for_drop_and_detach_synchronously=1, kills it, and asserts it terminates promptly (and returns a cancellation error rather than hanging).
        DatabaseCatalog::instance().waitTableFinallyDropped(uuid_to_wait, [&]() -> bool

Comment thread src/Interpreters/DatabaseCatalog.cpp Outdated
if (is_cancelled && is_cancelled())
{
LOG_DEBUG(log, "Stop waiting for the table {} to be dropped because the query was cancelled", toString(uuid));
return;

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

On cancellation this function logs and returns void without signalling the caller (no return value, no exception). Callers waiting synchronously may therefore continue as if the table was fully dropped. Consider either throwing QUERY_WAS_CANCELLED on cancellation, or changing the API to return a status (e.g. dropped vs cancelled) so callers can handle it explicitly.

Suggested change
return;
throw Exception(
ErrorCodes::QUERY_WAS_CANCELLED,
"Query was cancelled while waiting for the table with UUID {} to be dropped",
uuid);

Copilot uses AI. Check for mistakes.
auto process_list_element = context_->getProcessListElementSafe();
DatabaseCatalog::instance().waitTableFinallyDropped(uuid_to_wait, [&]() -> bool
{
return process_list_element && process_list_element->isKilled();

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The cancellation callback only checks isKilled() and waitTableFinallyDropped() returns without throwing. Since executeQuery() doesn’t re-check cancellation after interpreter->execute(), this path can make a killed DROP DATABASE/DROP TABLE report success instead of returning QUERY_WAS_CANCELLED. Prefer calling process_list_element->checkTimeLimit() (or otherwise throwing) when cancellation is detected, so the cancellation propagates as an exception.

Suggested change
return process_list_element && process_list_element->isKilled();
if (process_list_element && process_list_element->isKilled())
process_list_element->checkTimeLimit(); /// will throw QUERY_WAS_CANCELLED or a timeout exception
return false;

Copilot uses AI. Check for mistakes.

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.

What about adding the following function to return precise cancel reason?

void QueryStatus::throwIfKilled() const
{
    if (!is_killed)
        return;
    throwProperExceptionIfNeeded(limits.max_execution_time.totalMilliseconds(), 0);
}

@tiandiwonder tiandiwonder left a comment

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.

please add test case, claude code can help.

if (query.kind == ASTDropQuery::Kind::Drop)
DatabaseCatalog::instance().waitTableFinallyDropped(uuid_to_wait);
{
auto process_list_element = 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.

better to use query_status(more readble)
QueryStatusPtr query_status = context_->getProcessListElementSafe();

auto process_list_element = context_->getProcessListElementSafe();
DatabaseCatalog::instance().waitTableFinallyDropped(uuid_to_wait, [&]() -> bool
{
return process_list_element && process_list_element->isKilled();

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.

What about adding the following function to return precise cancel reason?

void QueryStatus::throwIfKilled() const
{
    if (!is_killed)
        return;
    throwProperExceptionIfNeeded(limits.max_execution_time.totalMilliseconds(), 0);
}

alexey-milovidov and others added 2 commits February 26, 2026 23:09
…add test

- Add `QueryStatus::throwIfKilled` that throws `QUERY_WAS_CANCELLED` or
  `TIMEOUT_EXCEEDED` with the precise cancel reason.
- Change `waitTableFinallyDropped` callback from `std::function<bool()>` to
  `std::function<void()>` that throws on cancellation instead of returning
  a bool. This ensures the caller gets an exception rather than silently
  continuing as if the drop succeeded.
- Rename `process_list_element` to `query_status` for readability.
- Add regression test for DROP DATABASE sync cancellation.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@tiandiwonder tiandiwonder left a comment

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.

Looks good now. please fix the test failure.

alexey-milovidov and others added 3 commits February 27, 2026 20:23
The test was failing in CI with "having exception in stdout" because the
`DROP DATABASE` command's stderr (containing the expected
`QUERY_WAS_CANCELLED` exception) was merged into stdout via `2>&1`.
Changed to `2>/dev/null` since we expect the cancellation exception and
don't need it in the output.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Instead of suppressing all stderr with `2>/dev/null`, use
`grep -v QUERY_WAS_CANCELLED` to filter out only the expected
exception, so unexpected errors would still be visible.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The ClickHouse client outputs exceptions in multiple lines, so
`grep -v QUERY_WAS_CANCELLED` only removed the last line while
the preceding lines (`Received exception from server...`,
`(query: ...)`) passed through and appeared in stdout.

Join lines with `tr '\n' ' '` so the entire exception is on a
single line and gets filtered out by `grep -v`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 4, 2026
Merged via the queue into master with commit fda8ef3 Mar 4, 2026
145 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-drop-database-hung-on-cancellation branch March 4, 2026 03:09
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 4, 2026
antonio2368 added a commit that referenced this pull request Apr 15, 2026
`DatabaseAtomic::waitDetachedTableNotInUse` was an infinite busy-wait
with no cancellation, shutdown check, or diagnostics. When a concurrent
query held a `StoragePtr` (e.g. `system.replicas` snapshot), DETACH
DATABASE hung indefinitely, causing 41 hung check failures in 30 days.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=58cd21f1f03e688719d58648aa1b2decb96ab996&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

Apply the same fix pattern from PR #97586 (`waitTableFinallyDropped`):
- Add `std::function<void()> throw_if_cancelled` parameter so `KILL
  QUERY` works
- Check `DatabaseCatalog::isShuttingDown()` to exit on server shutdown
- Log `use_count` every ~10s for diagnostics
- Do a final cleanup pass on shutdown before throwing `UNFINISHED`
- Update all 5 call sites to pass cancellation callbacks

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants