Repository navigation
Unregister a disk defined inline with disk(...) when the last table or database using it is gone - #118681
Unregister a disk defined inline with disk(...) when the last table or database using it is gone#118681alexey-milovidov wants to merge 97 commits into
disk(...) when the last table or database using it is gone#118681Conversation
…gone A disk described by a `disk(...)` function in a table or database definition was added to the disk selector and stayed there for the rest of the server's lifetime. `DROP TABLE`, `DETACH TABLE`, `DROP DATABASE` and `DETACH DATABASE` left it behind, still listed in `system.disks` and still running its background threads. Attaching the public datasets database, for example, creates 21 such disks (its tables carry slightly different `disk(...)` definitions), and every one of them keeps issuing an object storage listing about once a second long after the database is detached. Nothing else can refer to such a disk: it is absent from the configuration, and `ensureDiskIsNotCustom` rejects a plain disk name that resolves to one. So every user of the disk goes through `DiskFromAST::createCustomDisk`, which now hands out a `CustomDiskRegistration` alongside the disk name. The registration is kept by the settings object that holds the resolved name - `MergeTreeSettings` for a table, `DatabaseMetadataDiskSettings` for a database - and a table or database owns its settings, so the registration lives exactly as long as the disk is in use. When the last one is destroyed, the disk is unregistered together with the single-disk storage policy created for it, and shut down when no reference to it is left. Handing the registration out at creation time, rather than reconstructing the set of users later, is what makes this safe: a disk is never unreferenced between the moment it is created and the moment the table being attached takes it over. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [c2dc877] Summary: ❌
|
Build profile diff (arm_release)Comparing commit See the job log for details. |
…s-on-detach # Conflicts: # src/Storages/MergeTree/MergeTreeData.cpp
… them A definition such as `disk(type = cache, disk = disk(...))` creates two disks, and the wrapper keeps a reference to the disk it wraps. The registrations were collected in a flat list, so the order in which the disks were released depended on the container, and an inner disk released first was never shut down: `releaseCustomDisk` saw a reference held by the wrapper and skipped `shutdown`. The registration of a disk now owns the registrations of the disks nested in its definition. It releases its own disk in the destructor body, and the nested registrations are destroyed afterwards, so the disks are always shut down from the outside in, and a nested disk is never shut down while a wrapper still uses it. A table or database holds a single registration, the one of the outermost disk. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`dropTablesParallel` woke up the waiters of `DROP TABLE ... SYNC` while still holding the `StoragePtr` of the dropped table, and destroyed it only after releasing the mutex. Everything owned by the storage - now including the registration of a disk defined inline in the table definition - was released a moment after the query had returned, so the disk could still be listed in `system.disks` right after the drop. This made `05136_custom_disk_released_on_detach` flaky and let `02963_test_flexible_disk_configuration` pass by accident. The storage is now destroyed before the table is erased from the set of tables being dropped and the waiters are notified. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=4e3b61456b84a562b37b450e541bf5de505af7d3&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29 PR: #118681 Co-Authored-By: Claude Fable 5.1 <[email protected]>
`02963_test_flexible_disk_configuration` checked that a custom disk cannot be redefined or referred to by name right after dropping the only table using it. The disk is now unregistered with that table, so the checks are done while the table still exists, and the test also covers the name becoming free after the drop. `05136_custom_disk_released_on_detach` now covers nested definitions: a `cache` and an `encrypted` wrapper sharing the same inner disk, with the inner disk shut down only after both wrappers are gone. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=4e3b61456b84a562b37b450e541bf5de505af7d3&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 PR: #118681 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s-on-detach # Conflicts: # src/Disks/DiskFromAST.cpp # tests/queries/0_stateless/02963_test_flexible_disk_configuration.sh
…he layer A cache disk built by `DiskObjectStorage::wrapWithCache` shares the metadata storage and the object storages of the disk it wraps (the local location is wrapped in a `CachedObjectStorage`, whose `shutdown` forwards to the underlying storage, and the metadata storage in `MetadataStorageFromCacheObjectStorage`, which forwards too). Now that a custom cache disk is shut down when its last table is gone, this would shut down the inner disk under the tables still using it directly or through another wrapper (for S3, `DisableRequestProcessing`; for `s3_plain_rewritable`, the metadata refresh stops). The wrapped disk is always a disk of its own in the disk selector, so its storages are shut down together with it; the layer only shuts down its own background threads. Address review: #118681 (comment) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ngeSettings` Address review: a newly defined inline disk is created by the eligibility check, released at its end and created again by `changeSettings`. Changing the disk of a table is rare, so accept that instead of carrying the registration over. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…parallel runs - Move the nested `cache` / `encrypted` part of `05136_custom_disk_released_on_detach` into the new `05241_custom_nested_disk_released_on_detach` tagged `no-fasttest`: the `encrypted` disk type does not exist in the fast test build. - Drop the `system.text_log` shutdown assertion: whether a released disk is shut down explicitly depends on nobody else (a concurrent `system.disks` query, asynchronous metrics) holding it at that moment. Keep the `system.disks` counts, and check that the inner disk keeps working for the encrypted wrapper after the cache wrapper is dropped. - Put the `local_blob_storage` paths under `CLICKHOUSE_DISKS_FILES`, as master now requires custom local disks to be inside `custom_local_disks_base_directory`. - Use a per-run disk name in `02963_test_flexible_disk_configuration`: the test now expects the disk to be gone after `DROP TABLE ... SYNC`, which a concurrent run of the same test sharing the global name would break. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ach` The test failed everywhere in CI with "Path of the custom local disk must be inside `/var/lib/clickhouse/disks/` directory": `encrypted` checks the path of a non-remote wrapped disk via `getPath`, which for `local_blob_storage` is its metadata path under the server path, not the `path` given in the definition. Wrap the shared inner disk in a second `cache` disk instead, which keeps the point of the test (dropping one wrapper must leave the inner disk working for the other) and lets it run in the fast test as well. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=c6983c4347ca20b693dd90860d87cc5ab83fc8cd&name_0=PR #118681 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h a custom disk The new settings of an `ALTER` take a registration for the already flattened disk name through `tryGetCustomDiskRegistration`; check that the disk stays usable after the `ALTER` and is still released on `DETACH TABLE`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ased_on_detach` The flaky check showed `after detach database` and `after drop database` as `1` instead of `0`. `DETACH DATABASE ... SYNC` waits for the storages of its tables to be released, but not for the database object itself: `DatabaseCatalog::detachDatabase` only drops its own `DatabasePtr`, and a thread that took the pointer a moment earlier (e.g. the asynchronous metrics iterating over all databases) can keep the database, and so its inline disk, alive a bit longer. Wait with a bounded loop for the disks to disappear from `system.disks`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=c5af9e637344c4afb4db9e1f034cc6ca5b3433d8&name_0=PR #118681 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=c5af9e637344c4afb4db9e1f034cc6ca5b3433d8&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%203%2F6) ( The other failures ( |
|
Investigated. Query #4 is Since master picked up #123354, |
The registrations of the disks defined inline with `disk(...)` are now kept by a separate `CustomDiskRegistry` class instead of a map in `ContextSharedPart`. It also owns a background thread that shuts down the disks whose last registration is gone: `shutdown` of a disk waits for its background operations, and the last registration can be destroyed by any thread, e.g. one finishing a query that held the last reference to a dropped table. The disks are shut down in the order they are released, one at a time, and the reference to a disk is dropped before the next one is taken, so a wrapper disk is still shut down before the disk nested in its definition. The disk is now checked for other references when it is about to be shut down rather than when it is released, which makes a transient reference less likely to skip the explicit shutdown. The disks scheduled for shutdown are drained in `ContextSharedPart::shutdown` before the remaining disks of the disk selector are shut down. Also compact the comment of `CustomDiskRegistration`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MergeTreeSettings` no longer holds the registration of a disk defined inline with `disk = disk(...)`. `MergeTreeSettings::loadFromQuery` returns it, the table creation keeps it until the table is constructed and hands it to `MergeTreeData::setCustomDiskRegistration`, and `MergeTreeData::changeSettings` replaces it on `ALTER`. The other users of `applyChanges` / `applyChange` only need the disk while they resolve or validate the settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng down A disk released by the last table or database using it is shut down in the background, and a table created right after that with the same `disk(...)` definition used to create a new disk object at once. Both objects then worked with the same metadata and data for a while: one still shutting down, the other starting up, which includes the access check that writes, reads and removes the same `clickhouse_access_check_<server UUID>` file. `CustomDiskRegistry` now remembers the names of the released disks until their shutdown is finished, and `Context::getOrCreateCustomDisk` waits for it before creating a disk with such a name. The `Stateless tests (amd_asan_ubsan, flaky check, s3 storage, meta in keeper)` job of the sync PR for f98c95b failed with `S3_ERROR` in the access check of a custom disk, right after the same blob had been deleted by two different threads; this may be that overlap. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d-only `plain_rewritable` disk `DiskSelector::findPlainRewritableDisksOverlappingNewDisk` checked writability only for the retiring disk, so a read-only disk (the `read_only` setting, or a read-only object storage) over the prefix of a retiring writer had to wait for it, and failed if the writer stayed referenced. Like `arePlainRewritableDisksOverlapping`, it now ignores a read-only new disk, since it cannot overwrite the metadata of another disk. The new fail point `custom_disk_registry_pause_before_shutdown` keeps a released disk retiring for the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
The other open threads ( |
…s-on-detach Master moved the disk handling of `MergeTreeSettings` to `MergeTreeSettingsDisks.cpp`; the version of `resolveDiskSetting` returning a `CustomDiskRegistrationPtr` is moved there.
…disk has started shutting down The last external reference to a lingering disk can disappear during the timed wait, and `shutdownUnreferencedLingeringDisks` moves the disk to `names_pending_shutdown`. If its shutdown takes longer than the rest of the deadline, `waitForShutdown` returned `false` although nothing used the disk anymore, and creating a disk over its prefix failed. Now the pending shutdown is waited for, and `false` is returned only if the disk is still lingering. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
The red CI on the previous head came only from the review-threads gate (the full suite was skipped). The custom-disk stateless tests of this PR pass locally on the merged tree. Three of them need CI-only configuration and were not checked locally: |
…s-on-detach Conflicts with #129044, which tries older forms of a custom disk definition (other credentials markers) and checks the disks a table names by name: - `getOrCreateCustomDisk` keeps both the alternatives of master and the registration of this PR. The registrations of the disks of the first form are passed as the nested ones: if another form is chosen, its disk exists already, and its registration owns its own nested registrations. - `createCustomDisk`, `loadFromQuery` and `resolveDiskSetting` take `stored_definition` and return a registration. - `Log`, `StripeLog`, `Set` and `Join` use the new `StorageFactory::Arguments::getDiskWithCustomDiskRegistration`, which checks the disk as `getDisk` does and takes its registration together with it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…server_credentials_disk` The test from #129044 relied on a custom disk staying registered after its table is dropped. With this PR, a disk is released when the last table using it is gone, so wrapping `SERVER_DISK`, `WRAPPER_DISK` or `PLAIN_DISK` by name failed with `BAD_ARGUMENTS` (no such disk), and the `from_zk` wrapper would have been created anew instead of being reused. Keep the tables defining these disks until the end of the test, and drop them before it ends. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
Locally, on a build of the merged branch: the custom-disk tests of this PR, The only red CI check is the review-threads gate. It skipped the full suite because of the 3 open threads ( |
…gistration of it `getOrCreateCustomDisk` in `DiskFromAST.cpp` may pick a disk registered under another form of the definition (e.g. one stored by an older version without credentials markers, wrapping the older form of the disk below it). The matching pass held only the `DiskPtr`, and `Context::getOrCreateCustomDisk` then created a new registration from `nested_registrations`, which are the registrations of the disks the first form names. If the last registration of the chosen disk was being destroyed at that moment, the new registration did not own the disk that the reused wrapper actually wraps, and the old registration released that disk under the new table. Now the disk of another form is taken together with a live registration of it, under `storage_policies_mutex` (`Context::tryGetRegisteredCustomDisk`). If its last registration is being destroyed, the form is skipped as if the disk was already gone, and the first form is used. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s-on-detach Resolve conflicts: keep the custom disk registration of this PR together with the `stored_definition` argument of `createCustomDisk` added on master, the `[[nodiscard]]` attributes and `ensureDiskIsNotInline` from master, and the `ALTER` error handling of this PR together with the metadata cache clear from master.
|
🕵 Merged
The merged tree builds. The PR's custom-disk stateless tests pass on a local server, except for the tests that need the CI server configuration (configured disks and caches, MinIO). All review threads have replies. Three of them are still open for a maintainer to decide: |
…s-on-detach Conflicts: - `src/Disks/DiskFromAST.cpp`: master added the `remote_url_allow_hosts` check of custom disks (`checkCustomDiskRemoteHosts`). It is kept on top of `Context::getOrCreateCustomDisk`: the disk a new wrapper names is checked before the wrapper is built, and the created or reused disk is checked after. - `src/Storages/MergeTree/MergeTreeData.cpp`: master replaced `settings_changes` with `hasSettingsChanges`; the registration of the new disk is kept. - `src/Storages/StorageFactory.cpp`: `getDiskWithCustomDiskRegistration` passes the new `check_remote_hosts` argument, as `getDisk` does. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…in while being released A registration of a custom disk owns the registrations of the disks nested in its definition. When a disk was registered again while its last registration was being destroyed, the new registration took the nested registrations resolved by the new query. They may name other disks than the ones the disk wraps: `disk = 'from_zk /path'` in the definition of a wrapper resolves to another name after the node changes, while the definition, and so the disk, stays the same. The disk that the wrapper still used was then unregistered under it. Now the nested registrations are shared: `CustomDiskRegistry::getOrCreate` gives the new registration the nested registrations of the one being destroyed, which belong to the disk that stays registered. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `modernize-use-nodiscard` check was enabled on master, and the `arm_tidy` builds failed on this method: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118681&sha=c98445a2270c85d0d0d6526003eb09b70516fdd8&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #118681 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
Local run on the merged tree: 19 of the 24 stateless tests this PR adds or changes pass, including the new one. The other 5 ( Four review threads stay open because they need a maintainer decision (frozen data on a released disk, named dependencies of a wrapper after the defining table is dropped, lazily loaded wrappers, and |
`CustomDiskRegistry::getOrCreate` inserted the entry of the disk and moved the nested registrations out of the caller before it allocated the registration. If an allocation failed: - the nested registrations were destroyed under the mutex of the registry and under `storage_policies_mutex` of the caller, and destroying a registration calls `Context::releaseCustomDisk`, which locks `storage_policies_mutex` again: a self-deadlock; - the entry stayed without a registration, so `tryGet` reported the disk as "being unregistered" forever; - the disk was already in the disk selector with no registration, so nothing ever released it. Now `getOrCreate` allocates everything first, takes over the nested registrations only once nothing can throw anymore, and removes the entry it inserted if an allocation fails. `Context::getOrCreateCustomDisk` creates the registration before the disk is created and added to the selector, and keeps it in a variable declared before the lock. If creating the disk or adding it fails, the registration is destroyed after the lock is unlocked and releases whatever has been done by then, like any other last registration. `tryTakeReleasedDisk` creates the registration together with taking a lingering disk, so the disk stays tracked if the registration cannot be allocated. The new test `05840_custom_nested_disk_registration_allocation_failure` fails the allocation of the registration of a wrapper disk, whose nested registration has no other owner, with the fail point `custom_disk_registry_fail_to_allocate_wrapper_registration`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ocation failure `FileCacheFactory::removeUnusedNamesOfReleasedDisks` inserted the path of a cache into `paths_of_caches_being_destroyed` and only then remembered it in `RemovedCaches::paths`, which is what removes the marker. If that `push_back` failed to allocate, the marker stayed forever, and `waitForCacheDestroyed` waited for a destruction that nobody would finish. Reserve the space in `RemovedCaches` before any marker is published, so nothing throws in between. `RemovedCaches::destroy` also tolerates a missing marker. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ic loop `DatabaseOrdinary::loadTablesMetadata` looked for the next table to process by comparing every pending table with every other pending table, for every processed table: cubic in the number of tables referring to a custom disk by name. Count the pending definitions of every disk instead, and process all tables that are ready in one pass. The order still follows the file names and a table defining a disk is still processed before the tables referring to it. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A disk described by a
disk(...)function in a table or database definition was added to the disk selector when the definition was first resolved, and stayed there for the rest of the server's lifetime.DROP TABLE,DETACH TABLE,DROP DATABASEandDETACH DATABASEall left it behind: still listed insystem.disks, still holding its object storage client, and still running its background threads.It is easy to observe with the public datasets database, whose tables each carry a slightly different
disk(...)definition:Before this change the count stays at the number of distinct definitions that were resolved (21 if every table of that database is touched), and each of those disks keeps listing its object storage about once a second for as long as the server runs. Now it is
0.Approach
Which tables and databases use such a disk cannot be worked out after the fact.
MergeTreeData::getStoragePolicyresolves the disk by name on every call and keeps no pointer to it, so a table that is attached but has no parts holds no reference to its own disk at all; and a table that is being attached is not in the catalog yet while its storage - which can take minutes to construct - is being built. Neither reference counting theDiskPtrnor scanning the catalog is enough on its own.What makes it tractable is that nothing can reach a custom disk except through its definition: the disk is absent from the configuration, and
ensureDiskIsNotCustomrejects a plain disk name that resolves to one. So every user of the disk goes throughDiskFromAST::createCustomDisk, which now returns aCustomDiskRegistrationalongside the disk name. A table keeps the registration inMergeTreeData:MergeTreeSettings::loadFromQueryreturns it, the table creation holds it until the storage is constructed, andMergeTreeData::changeSettingsreplaces it onALTER. A database keeps it in itsDatabaseMetadataDiskSettings, which it owns for its whole lifetime. Handing the registration out at creation time is what makes this safe: the disk is never unreferenced between the moment it is created and the moment the table being attached takes it over.When the last registration is destroyed, the disk is unregistered together with the single-disk storage policy implicitly created for it in
getStoragePolicyFromDisk, and handed toCustomDiskRegistry, which shuts it down on a background thread once nothing else references it. A disk may stay referenced for a short while after the last table using it is gone; until it is shut down, a table or database with the same definition uses that disk again, so two instances of a disk never work on the same metadata and data at once, and a definition with the same name but other settings waits for the old disk to be shut down.shutdownof a disk may wait for its background operations, and the last registration can be dropped by any thread, so it does not run in place. A definition whose name resolves to a disk from the configuration gets no registration, so the existing "already exists and is described by the config" error cannot unregister a real disk while it unwinds.DROP TABLEwithoutSYNCstill keeps the disk fordatabase_atomic_delay_before_drop_table_sec, since the table's data has yet to be deleted from it.A definition may wrap another one, e.g.
disk(type = cache, disk = disk(...)), and the wrapper disk keeps a reference to the disk it wraps. The registration of a disk therefore owns the registrations of the disks nested in its definition, so the disks are always released from the outside in: the wrapper is unregistered and shut down first, and only then the inner disk, which by then has no user left. The background thread shuts the disks down one at a time, in the order they were released, so that order is preserved. A table or database holds a single registration, the one of the outermost disk.DROP TABLE ... SYNCused to wake up its waiter whileDatabaseCatalogstill held theStoragePtrof the dropped table, so whatever the storage owned was released a moment after the query had returned. The storage is now destroyed before the drop is announced, so the disk is gone fromsystem.disksby the time the query returns.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A disk defined inline with a
disk(...)function in aCREATE TABLEorCREATE DATABASEstatement is now unregistered once the last table or database using it is dropped or detached. Previously such a disk remained insystem.disksand kept running its background threads, including periodic object storage requests, until the server was restarted. Also,DROP TABLE ... SYNCnow returns only after the storage object of the dropped table has been destroyed.Workflow [PR]
Sync PR [sync-upstream/pr/118681]