Skip to content

Make waitDetachedTableNotInUse cancellable and shutdown-aware - #102804

Merged
antonio2368 merged 6 commits into
masterfrom
fix-wait-detached-cancellable
May 11, 2026
Merged

antonio2368 merged 6 commits into
masterfrom
fix-wait-detached-cancellable

Conversation

@antonio2368

@antonio2368 antonio2368 commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

DatabaseAtomic::waitDetachedTableNotInUse was an infinite while(true) busy-wait with 100ms sleep, no cancellation, no shutdown check, and no diagnostics. When a concurrent query held a StoragePtr (e.g. a system.replicas snapshot iterating all replicated tables), the refcount stayed above 1 and DETACH DATABASE hung indefinitely, causing 41 hung check failures in 30 days across stress test variants.

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
  • Add regression test 04099_detach_database_sync_cancellation

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

Make DETACH DATABASE ... SYNC and other operations that call waitDetachedTableNotInUse cancellable via KILL QUERY and responsive to server shutdown, preventing indefinite hangs when a concurrent query holds a table reference.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.507

`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]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06f58fc]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
04099_detach_database_sync_cancellation FAIL cidb

AI Review

Summary

This PR makes waitDetachedTableNotInUse cancellation-aware and shutdown-aware, wires cancellation callbacks through all call sites, and adds a regression test for DETACH DATABASE ... SYNC cancellation. I did not find correctness, safety, or compatibility issues that require changes.

ClickHouse Rules
Item Status Notes
Deletion logging ✅
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 15, 2026
antonio2368 and others added 2 commits April 15, 2026 12:07
Remove default argument from virtual `waitDetachedTableNotInUse`
declaration — clang-tidy forbids defaults on virtual methods. All call
sites already pass the callback explicitly.

Fix test to use `DETACH DATABASE ... SYNC` keyword instead of the
`database_atomic_wait_for_drop_and_detach_synchronously` setting, which
does not set `query.sync` for database-level operations and thus never
entered `waitDetachedTableNotInUse`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Use `int64_t` instead of `long` for `use_count` to satisfy
`google-runtime-int`.

Add bounded wait in test: on the old binary without the fix, `KILL
QUERY` has no effect and the DETACH hangs forever. A 10s polling loop
detects this and fails explicitly instead of letting the test runner
timeout at 60s, which bugfix validation cannot distinguish from an
error.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ antonio2368
❌ Ubuntu


Ubuntu seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 85.00% (68/80) · Uncovered code

Full report · Diff report

@antonio2368
antonio2368 added this pull request to the merge queue May 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks May 11, 2026
@antonio2368
antonio2368 added this pull request to the merge queue May 11, 2026
Merged via the queue into master with commit 66ce9a3 May 11, 2026
164 of 166 checks passed
@antonio2368
antonio2368 deleted the fix-wait-detached-cancellable branch May 11, 2026 07:40
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: DatabaseAtomic::waitDetachedTableNotInUse — core code present in all supported branches.

Why this might apply: The bug affects DETACH DATABASE SYNC, ATTACH TABLE, RESTART REPLICA, and similar operations that call waitDetachedTableNotInUse. The affected code (DatabaseAtomic::waitDetachedTableNotInUse) predates all supported branches. PR description mentions 41 hung check failures in 30 days across stress tests.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 11, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Jun 15, 2026
… parent DB is missing

`DataLakeConfiguration::getCatalog` (introduced by ClickHouse#100334) looked up the parent
database in `DatabaseCatalog` and threw `LOGICAL_ERROR` ("Database X not found")
when `tryGetDatabase` returned `nullptr`. That assertion is wrong: a missing
database here is a transient runtime state, not a logical-invariant violation.

Concretely it can fire during async metadata loading after a server restart
(`AsyncLoader::worker` -> `DatabaseOrdinary::loadTableFromMetadata` ->
`createStorageObjectStorage` -> `getCatalog`) when an unrelated table-load
job in the same database has just thrown (for instance because of
`cannot_allocate_thread_fault_injection_probability`) and the database has
been detached as a result. Stress tests with thread-allocation fault
injection have been hitting this LOGICAL_ERROR sporadically: `STID 2377-2a78`,
3 distinct unrelated PRs over 90 days (PR ClickHouse#98472 on 2026-04-09, PR ClickHouse#100958
on 2026-04-12, PR ClickHouse#102804 on 2026-04-30 - none of which touch this code or
its callers).

Production stack from PR ClickHouse#102804 stress-test (amd_debug):

```
2026.04.30 05:17:39.895829 [ 6955 ] AsyncLoader::worker: Code: 439.
DB::Exception: Cannot schedule a task: fault injected (...): Cannot attach
table `test_1`.`test_max_size_drop` from metadata file ...
2026.04.30 05:17:40.099425 [ 6998 ] {} <Fatal> : Logical error:
'Database test_1 not found'.
[stack: DataLakeConfiguration::getCatalog -> createStorageObjectStorage
        -> registerStorageIceberg -> StorageFactory::get
        -> createTableFromAST -> DatabaseOrdinary::loadTableFromMetadata
        -> AsyncLoader::worker]
```

Fix: combine the two null-checks. `dynamic_pointer_cast` already returns
`nullptr` for a null input, so the function naturally returns `nullptr`
both for "DB not registered" and "DB is not `DataLakeCatalog`" - the same
response either way. This matches the behaviour of `getCatalog` before
ClickHouse#100334, restores backward compatibility for `Iceberg` engine tables
hosted in regular `Atomic`/`Ordinary` databases, and removes the
spurious LOGICAL_ERROR signal from stress-test reports without changing
behaviour for the supported `DataLakeCatalog` -> `Iceberg` path.

Local verification (debug build):
- Compiles, server starts.
- `CREATE TABLE iceberg_t ENGINE = IcebergLocal(...)` inside a regular
  `Atomic` database succeeds, DETACH/ATTACH database cycle succeeds,
  server restart with `async_load_databases=1` reloads the table without
  LOGICAL_ERROR.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102804&sha=40e4eba7d14b8588106464e81b911e8de7a45dc6&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Co-Authored-By: Claude Opus 4.7 <[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