Repository navigation
Do not drop a named collection that a detached table still uses - #112805
alexey-milovidov wants to merge 160 commits into
Conversation
A table detached with a plain `DETACH TABLE` keeps its metadata file, so the server attaches it again on the next start. It is gone from `DatabaseCatalog` though, so `isTableExist` returns false for it, and the `check_named_collection_dependencies` check treated its dependency as a stale leftover of a failed `CREATE TABLE`: it removed the dependency and let `DROP NAMED COLLECTION` succeed. The `ATTACH` replayed at startup then threw `NAMED_COLLECTION_DOESNT_EXIST`, which aborts loading the metadata, and the server did not start at all (`Code: 722 ... Code: 695 ... Code: 669`). Now a table that is merely detached still counts as a dependent, so the drop is refused with `NAMED_COLLECTION_IS_USED` and the message says which tables are detached. The same applies to a table inside a database detached with `DETACH DATABASE`, which also comes back at startup. A table detached with `DETACH TABLE ... PERMANENTLY` is not loaded at startup and its dependency is removed right away, so it keeps holding nothing. Also deduplicate the table names in the message: the `URL` engine resolves its arguments twice (once to dispatch on the scheme, once to create the delegate storage), so every such table was listed twice per resolution. This is how the `Stress test (arm_tsan)` job on master fails with `Cannot start clickhouse-server`: the AST fuzzer makes `04320_url_engine_dispatch_partition_and_format` leave its `URL(named_collection)` table detached, and the test then drops the named collection. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8aad759007771032aa94d7f4eee3e18103dd63c3&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29 Related: #96181 Related: #77366 Related: #110529 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [f15a01d] Summary: ❌
AI ReviewSummaryProtects named collections referenced by detached and lazily loaded objects, dictionaries, and database engines. One blocker and two majors remain at Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Make dependency transitions exception-safe, restore storage-aware checked drops, and handle accepted scalar dictionary collection names, with the focused validation above. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 23/25 (92.00%) · Uncovered code |
…tached from A named collection dependency is registered while the engine arguments of a table are resolved, which happens before the table is created, so a `CREATE TABLE` that fails after that point leaves behind the dependency of a table that never came to exist. The previous check treated such a leftover as a live dependent whenever anything with that name could be attached at the next server start: - for a detached database it only checked that the database metadata file is there, so a failed `CREATE TABLE db.t` followed by `DETACH DATABASE db` blocked `DROP NAMED COLLECTION` forever, even though `t` has no metadata to attach from; - for a name-based database (`Ordinary`, ...) any table that later takes the name of the failed one was accepted as the original dependent, even if it does not use the collection at all. Now the decision is made from the metadata the table would really be attached from: the metadata file of the table itself is located (through the database, or, for a detached database, through the path its own metadata says it uses), and the table has to be the dependent - the same UUID for a database that has UUIDs, and a definition that mentions the collection for a name-based one. The name check is deliberately coarse, because keeping a collection that nothing uses is only an annoyance, while dropping one that a table does use breaks the next server start. A stale dependency is also removed with the new `NamedCollectionFactory::removeDependency`, which removes the dependency on this one collection only: the same table may depend on other collections, and those dependencies can be perfectly valid.
…ection-detached-table
The AI review found two paths where a detached dependent of a named collection was still classified as stale: 1. A detached database created with `SETTINGS disk = ...` keeps its table metadata on the configured metadata disk, not on the default database disk. The check now recovers the disk from the `disk` setting of the stored database definition. 2. `RENAME TABLE` and `RENAME DATABASE` deliberately do not rewrite the names stored in a UUID-tracked dependency, so probing the metadata under the stale name found nothing after the table was detached. The check now searches the metadata files for the `ATTACH` query that carries the dependent's UUID, sweeping the other databases, attached and detached, when the stored database name went stale as well. Co-Authored-By: Claude Fable 5 <[email protected]>
The probes read from the database disk, whose metadata can be kept in Keeper, and every Keeper request must have a current component set. Without it the `db disk, meta in keeper` configuration failed with the logical error `Current component is empty` on `DROP NAMED COLLECTION` (the private CH Inc sync CI: stateless `04546` and integration `test_storage_s3_intelligent_tier`/`test_cloud` runs). Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
I don't like the implementation - it is too complex.
Can we do it differently? On DETACH TABLE, we check the named collection dependencies, and remember the list of pairs: (collection_name, db.table). On an attempt to drop a named collection, we throw an error that the named collection cannot be dropped because it could be referenced by a detached table. Remove the entry on attaching back.
This does not have to be precise. This could still refuse even if the detached table was finally dropped.
…ection-detached-table
…inspecting metadata Instead of deciding from the metadata the detached table would be attached from (which required probing database disks and sweeping metadata directories for renamed tables), keep a simple in-memory list of (collection, database, table) entries in `NamedCollectionFactory`: - `DETACH TABLE` (and `DETACH DATABASE`, for the tables inside) moves the dependencies of the table into the list; - `DROP NAMED COLLECTION` refuses while an entry for the collection exists; - `ATTACH` (any `addDependency` for a table with that name) removes the entry, and `DROP DATABASE` removes the entries of its detached tables. The list is deliberately imprecise: it does not survive a server restart (a permanently detached table no longer blocks the drop after one), and a stale entry may keep refusing the drop for a while after the detached table is gone. In exchange there is no disk access at all on the `DROP NAMED COLLECTION` path.
|
🕵 Reworked as suggested in the review: the metadata inspection is gone (net -224 lines). |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes158 object files changed (+315.94 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1915 translation units recompiled, 9126 s compile time in total, 1915 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
|
The list of detached dependencies is in memory only, so a permanently detached table blocked the drop only until a restart, while its metadata survived the restart - the code and the tested contract disagreed (review finding). A permanently detached table is not loaded at startup, so dropping a collection it references cannot break the server start: `DETACH TABLE ... PERMANENTLY` now removes the dependencies without recording them, uniformly before and after a restart. A later `ATTACH` of such a table fails cleanly with `NAMED_COLLECTION_DOESNT_EXIST` and is recoverable by recreating the collection. A plainly detached table stays consistent too: it is attached again at the next start, where regular dependency tracking picks it up.
The record protecting a detached table's named collections was removed in `addDependency`, which runs while the engine arguments are resolved - but an `ATTACH` can still fail after that (checking the format name, creating the storage), leaving the table detached with no protection: the failed attach's dependency of a table that does not exist in the catalog was then cleaned up as stale, and `DROP NAMED COLLECTION` succeeded, reintroducing the broken server start the record is there to prevent. Now `ATTACH` does not remove the record at all. It is removed by the events that prove the metadata under the recorded name is gone or harmless - `DROP TABLE`, `DETACH TABLE ... PERMANENTLY`, `RENAME` of the (necessarily re-attached) table, `DROP DATABASE` - and by the `DROP NAMED COLLECTION` check itself for a table that exists in `DatabaseCatalog` again, which proves the attach went through. `RENAME DATABASE` re-keys the records of its detached tables, whose metadata moves along with the database. The new test `04823_drop_named_collection_failed_attach` covers the failed `ATTACH` (the drop stays refused, and stays refused on a second attempt after the stale-dependency cleanup), the release of a lingering record by a rename of the re-attached table, and a database rename over a detached table. Co-Authored-By: Claude Fable 5 <[email protected]>
The style check rejected `04823_drop_named_collection_failed_attach.sh` because a test file name must not contain the word "fail". Renamed to `04823_drop_named_collection_broken_attach`. Co-Authored-By: Claude Fable 5 <[email protected]>
…CTION` check The check pruned an entry whose table exists in `DatabaseCatalog` again, taking the existence as proof that the attach went through and the live dependency was validated by the first pass. That is racy: a concurrent `ATTACH` registers its live dependency after the first pass already ran, and a concurrent `DETACH` records the entry while the table is still in the catalog - in both windows the table exists, yet nothing in the drop query has validated the live dependency, so the prune deleted the only protection and the drop could succeed while the table still uses the collection. The drop path is now read-only: every recorded entry refuses the drop, and entries are removed only by the events that prove the metadata under the recorded name is gone or harmless - `DROP TABLE`, `DETACH TABLE ... PERMANENTLY`, `RENAME` of the table, and `DROP DATABASE`.
…ection-detached-table
…s stale The cleanup of stale dependencies (leftovers of a failed `CREATE TABLE`) in `InterpreterDropNamedCollectionQuery` treated the table's absence from `DatabaseCatalog` as a proof of staleness, but the dependency is registered while the engine arguments are resolved, before the table is committed to the catalog: a concurrent `DROP NAMED COLLECTION` could prune the dependency of an in-flight `CREATE`/`ATTACH` and drop the collection while the create later succeeds, leaving metadata that references a collection that no longer exists. The creating query holds the `DDLGuard` of the table name for the whole window between the registration and the commit, so the drop now re-checks the table's existence under that guard before pruning: once the guard is acquired, no create is in flight, and the table's absence proves the entry is stale. Adds the `create_table_pause_before_commit` failpoint and a test that runs `DROP NAMED COLLECTION` against a `CREATE TABLE` and an `ATTACH TABLE` paused inside the window. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Merged
@groeneai, thanks for the analysis of the AST fuzzer oracle failure and the fix in #129420. |
# Conflicts: # src/TableFunctions/ITableFunction.h
|
🕵 Merged The only red checks at
New cases in both suites do fail on |
Fixes `readability-redundant-access-specifiers` in the `arm_tidy` build. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Fixed the only CI failure: |
…ce changed A reload of a dictionary defined in the configuration files registers the dependency on the collection of its new source, but the entry of the old collection stayed, so `DROP NAMED COLLECTION` of the old collection kept failing with `NAMED_COLLECTION_IS_USED`. Check such an entry against the current definition held by `ExternalDictionariesLoader` and prune it when the definition no longer references the collection. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/InterpreterRenameQuery.cpp
… dictionary entry When a configuration dictionary with a `<database>` changes its source to another collection, the entry of the old collection stays registered under the qualified dictionary name without a UUID. `DROP NAMED COLLECTION` then resolved it through the catalog, and any table with that qualified name was accepted as a live dependent, even an unrelated `Atomic` table with its own UUID that never referenced the collection. A table with a UUID records its dependencies under that UUID, so such a table cannot own an entry without one: for an obsolete dictionary entry, only a table without a UUID is taken as its owner now. Add an integration test with the database-qualified fixture and an unrelated `Memory` table of the same name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp # src/Interpreters/InterpreterRenameQuery.cpp # src/Interpreters/StorageID.h
`tryGetNamedCollectionWithOverrides` resolves the first identifier of `Remote` as a collection whenever one with that name exists and accepts any non-`equals` function after it as an override, so `remote(nc, rand())` resolves through `nc`. The metadata classifier treated such a list as positional and registered no dependency, both for a nested `remote` target and for a lazily loaded `Remote` table, so a checked `DROP NAMED COLLECTION` succeeded and left the table unable to resolve. Now a list whose arguments after the first are all functions that are not table functions is taken for a collection reference. Literals or identifiers after the first argument, and a table function target such as `Remote(cluster, numbers(1))`, stay positional. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`parseRemoteFunctionArguments` runs the collection resolver before it considers the positional signatures, and the resolver accepts any non-`equals` function after the collection name, a table function included. So `remote(nc, numbers(1))` resolves through `nc` when it exists, exactly like `remote(nc, rand())`, but the classifier `tryGetUsedNamedCollectionName` still excluded table functions and registered no dependency. Register it conservatively for any function after the identifier. The nested `Remote(..., remote(nc, numbers(1)))` case is added to `05813_drop_named_collection_remote_function_override`, and the lazy `ENGINE = Remote(nc, numbers(1))` case with a server restart to `test_drop_collection_recreated_under_lazily_loaded_bare_remote_table`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ME TABLE` `NamedCollectionFactory::renameDependencies` moved every entry recorded under the old name, including the UUID-less registration of a configuration dictionary whose qualified name matches a table of an `Atomic` database. The loader keeps identifying the dictionary by the name from its definition, so the moved entry escaped the check against the current dictionary definition in `DROP NAMED COLLECTION`, and the renamed, unrelated table kept an obsolete collection from being dropped. A table with a UUID records its entries under that UUID, so an entry without a UUID under its name is not its own: the rename interpreter now tells `renameDependencies` whether the renamed tables have UUIDs, and such entries stay where they are. `test_drop_collection_replaced_in_database_qualified_config_dictionary_source` is parametrized to rename the unrelated table before the dictionary source changes. This commit also contains the integration part of the previous commit: the lazily loaded `ENGINE = Remote(nc, numbers(1))` case with a server restart in `test_drop_collection_recreated_under_lazily_loaded_bare_remote_table`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ection-detached-table Conflict in `src/TableFunctions/ITableFunction.h`: both sides added members to the `protected` section. Kept this PR's `setUsedNamedCollectionName` and `getUsedNamedCollectionNameForUpdate` together with `appendNamedArgumentIndexes` and `partition_by` from `master`, and dropped the `protected` declaration of `getSourceAccessObject`, which `master` made public. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…CH` fails after removing the permanent-detach flag `DatabaseOnDisk::createTable` removes the permanent-detach flag before `attachTable` publishes the table. A table detached with `DETACH TABLE ... PERMANENTLY` records no named collection dependency, and the one registered by the `ATTACH` query is removed when the query fails. If `attachTable` throws in between, the table stays detached while its metadata is loaded at the next server start again, so `DROP NAMED COLLECTION` succeeded and the start failed with `NAMED_COLLECTION_DOESNT_EXIST`. Keep the dependencies as the ones of a detached table in that case (`markDependenciesDetached`), and add the `database_attach_table_fail_after_removing_detached_permanently_flag` failpoint with a regression test. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ection-detached-table Conflicts: `master` added the `caller` (`RemoteDescriptionCaller`) and `limit_total_addresses` parameters to `StorageMySQL::getConfiguration`, `StoragePostgreSQL::getConfiguration` and `parseRemoteFunctionArguments`, where this branch added `used_named_collection_name`. Both are kept, with `used_named_collection_name` as the last parameter. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `functional_tests_check` of the style check rejects test names that include `fail`: `05843_drop_named_collection_failed_attach_of_permanently_detached` is now `05843_drop_named_collection_aborted_attach_of_permanently_detached`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112805&sha=f9959a3c3954c59098961e2bea7b1fb49fbe5fbc&name_0=PR&name_1=Style%20check PR: #112805 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ection-detached-table Conflict in `tests/integration/test_named_collections/test.py`: both sides appended tests at the end of the file (`test_keeper_storage_lagging_replica` on `master`); both are kept. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| for (const auto & collection_name : collection_names) | ||
| insertDetachedDependency(collection_name, table_id.database_name, table_id.table_name); |
There was a problem hiding this comment.
[Blocker] Keep dependency protection when a transfer allocation throws
markDependenciesDetached erases the active entries at lines 936/957 before allocating their detached replacements here. For a previously attached URL(nc) table, if the first detached-set allocation throws, neither container retains its dependency. The caller in InterpreterDropQuery has not called detachTable yet, so the table and its metadata survive, but a subsequent checked DROP NAMED COLLECTION nc succeeds. The persisted definition can then fail to load with NAMED_COLLECTION_DOESNT_EXIST.
This is reachable through std::bad_alloc, or MEMORY_LIMIT_EXCEEDED when min_allocation_size_to_throw_on_memory_limit enables enforcement for generic allocations. The same erase-before-allocation pattern appears in rekeyDependencies, renameDependencies, and renameDatabaseDependencies. Also, insertDetachedDependency can update the collection index and then throw while updating the table index, leaving an entry normal cleanup cannot find.
Please make these transfers exception-safe, preserving protection for surviving metadata on every exit and updating both detached indexes transactionally. Add focused allocation-failure coverage that verifies the collection remains protected after the failed transition.
| || (detached_it != detached_dependencies.end() && std::get<0>(*detached_it) == query.collection_name)) | ||
| return false; | ||
|
|
||
| if (!exists(query.collection_name, lock)) |
There was a problem hiding this comment.
[Major] Preserve storage-backed existence in the checked drop path
Unlike removeFromSQL, this method never calls loadIfInStorage: exists only checks loaded_named_collections. A collection created through another server sharing Keeper storage can therefore exist on disk while this server's update task has not loaded it. Checked DROP NAMED COLLECTION now throws NAMED_COLLECTION_DOESNT_EXIST; DROP ... IF EXISTS silently succeeds without removing it. Encrypted entries skipped at startup because their key is unavailable also cannot be dropped, although dropping such an entry is the supported recovery path.
The existing test_keeper_storage_lagging_replica in test_named_collections/test.py exercises the first case, and test_local_storage_missing_key in test_named_collections_encrypted/test.py exercises the second. Please preserve loadIfInStorage and StoredEntry::unreadable handling under the final factory lock. The interpreter's earlier IF EXISTS shortcut must use the same storage-aware existence check, otherwise it still skips the removal.
Closes: #125617
Related: #96181
Related: #77366
Related: #110529
A table detached with a plain
DETACH TABLEkeeps its metadata file, so the server attaches it again on the next start. It is gone fromDatabaseCatalogthough, soisTableExistreturns false for it, and thecheck_named_collection_dependenciescheck (added in #96181) treated its dependency as a stale leftover of a failedCREATE TABLE: it removed the dependency and letDROP NAMED COLLECTIONsucceed. TheATTACHreplayed at startup then threwNAMED_COLLECTION_DOESNT_EXIST, which aborts loading the metadata, and the server did not start at all.This is how the
Stress test (arm_tsan)job fails on master withCannot start clickhouse-server: the AST fuzzer makes04320_url_engine_dispatch_partition_and_formatleave itsURL(named_collection)table detached (the test'sATTACH TABLEnever reaches the server), and the test then drops the named collection.CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8aad759007771032aa94d7f4eee3e18103dd63c3&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29
The same signature accounts for 6 of the 8
Cannot start clickhouse-serverfailures with a missing named collection in the last 60 days (perplay.clickhouse.com); the other two come from03822_named_collection_drop_dependency_check, which drops the collection withcheck_named_collection_dependencies = 0on purpose, and are the case #110529 handles by tolerating the missing collection at startup.Changes
Per review feedback, the implementation is a simple in-memory bookkeeping in
NamedCollectionFactory(an earlier revision inspected the metadata the detached table would be attached from, which required probing database disks and sweeping metadata directories after renames):DETACH TABLE(andDETACH DATABASE, for every table inside) moves the dependencies of the table into a list of (collection, database, table) entries.DROP NAMED COLLECTIONis refused withNAMED_COLLECTION_IS_USEDwhile an entry for the collection exists.ATTACHdoes not remove the entry by itself: the dependencies are registered while the engine arguments are resolved, and the attach can still fail after that (an unknown format name, a failure creating the storage), leaving the table detached — the entry must keep protecting it. Instead, the entry is removed by the events that prove the metadata under that name is gone or harmless:DROP TABLE,DETACH TABLE ... PERMANENTLY, andRENAMEof the (necessarily re-attached) table;DROP DATABASEremoves the entries of the database's detached tables, andRENAME DATABASEre-keys them. TheDROP NAMED COLLECTIONcheck itself removes nothing: the table's existence inDatabaseCatalogis racy against in-flight attaches and detaches (the table can exist while nothing in the drop query has validated its live dependency), so the drop path is read-only and every recorded entry refuses the drop.CREATE TABLEorATTACH TABLEthat fails before the table is committed removes the dependencies it registered for exactly itsStorageID(database, table, UUID), ascreateDatabasealready does for database engines: otherwise a retry under the same name and UUID with another collection would be taken for a user of the old collection (05397_drop_named_collection_aborted_create_same_uuid).DETACH TABLE ... PERMANENTLYdoes not record an entry: a permanently detached table is not loaded at startup, so dropping a collection it references cannot break the server start. A later explicitATTACHof such a table fails cleanly withNAMED_COLLECTION_DOESNT_EXISTand is recoverable by recreating the collection.ATTACH TABLEof a permanently detached table removes the permanent-detach flag before the table is published. If the attach fails in between, the table stays detached while its metadata is loaded at the next start again, so the dependencies registered by the failed query are kept as the ones of a detached table (05843_drop_named_collection_aborted_attach_of_permanently_detached).DROP NAMED COLLECTIONpath performs no disk access at all.RENAME TABLEthat moves a table between anOrdinaryand anAtomicdatabase changes the identity the dependency is keyed by: the move intoAtomicassigns a fresh UUID to the table and the move out of it drops the UUID, while a dependency is keyed by the UUID for tables ofAtomicdatabases and by the name for tables ofOrdinaryones. The rename interpreter only knows the names, so the entry used to keep the identity the table had before the move and nothing found it afterwards: the detach recorded no entry and, for theAtomic -> Ordinarydirection, the drop check even classified the entry of the still attached table as a leftover of a failedCREATEand dropped the collection from under it.DatabaseOnDisk::renameTablenow re-keys the entries of the moved table to its newStorageID, where both identities are known.EXCHANGEis unaffected: it is only supported between twoAtomicdatabases, where the UUIDs do not change.lazy_load_tables = 1is attached as aStorageTableProxyand its real storage is built only on the first access, so the engine arguments are not resolved at load time and the dependency on the named collection they name stayed unregistered.DROP NAMED COLLECTIONwas then allowed while such a table still referenced the collection - breaking it at the first access withNAMED_COLLECTION_DOESNT_EXIST- and aDETACHof it had no dependency to move to the list of the detached ones, so the protection above silently disappeared in that mode.DatabaseOrdinary::loadTableLazynow registers the dependency straight from the metadata, via the newtryGetUsedNamedCollectionNamehelper. An identifier first argument counts as a collection reference only for the engines that resolve their arguments through named collections (a newStorageFactory::StorageFeatures::supports_named_collectionsflag) - for other engines an identifier means something else, e.g. a cluster name forDistributed- and for them the signal is time-stable: whether the collection currently exists is deliberately not checked, so the dependency of a collection that is missing at load time (say, after a drop withcheck_named_collection_dependencies = 0) protects it when it is recreated later. The exception isRemote/RemoteSecure, where the same identifier is also a valid positional argument - a cluster name - when the named-collection lookup does not resolve (marked by the newStorageFeatures::named_collection_argument_is_ambiguous; every other flagged engine treats an unknown collection as an error, not as a fallback to a positional form). For them the helper decides from the shape of the argument list first, replicating the decision the engine's own argument parsing would make on the same metadata - which is exactly what a non-lazy load of it does. Akey = valuesecond argument occurs only in the named-collection form: no positional signature ofRemoteaccepts one there, soparseRemoteFunctionArgumentsreports a missing collection instead of reparsing the arguments positionally, and the shape alone proves the reference - the dependency is registered without looking at the collection namespace, exactly as for the unambiguous engines, so a collection missing at load time is protected when it is recreated later. A genuinely positional-looking list (Remote(cluster, system, one)) never references a collection. A bareRemote(x)means a collection exactly when a collection with that name exists at the moment the proxy is materialized, which may be after it is created (or recreated), so the dependency is registered conservatively without looking at the namespace; if the table has already been materialized as a cluster reference, this only makes a same-named collection harder to drop.SETTINGSare skipped when the shape is examined, asparseRemoteFunctionArgumentsdoes.MongoDBandMaterializedPostgreSQLwere the only flagged engines whose eager argument resolution did not pass the dependent table totryGetNamedCollectionWithOverrides(they registered the dependency at the lazy load but not when the storage is built); they now pass it, so both load modes register the same dependency.addDependencyignores an exact duplicate, because the same dependency is registered again when the proxy is materialized. Tables created withCREATE TABLE ... AS f(...)need no lazy branch: a database withlazy_load_tables = 1deliberately loads them eagerly as aStorageTableFunctionProxy(seeDatabaseOrdinary::shouldLazyLoad), and that load registers the dependency viaITableFunction::getUsedNamedCollectionName.CREATE TABLE, pre-existing from Add check to ensure no named collection is dropped if still in use #96181) no longer treats the table's absence fromDatabaseCatalogalone as a proof of staleness: the dependency of an in-flightCREATE/ATTACHis registered while the engine arguments are resolved, before the table is committed to the catalog, and a concurrentDROP NAMED COLLECTIONcould prune it and drop the collection while the create later succeeds — recreating the broken metadata this PR fixes. The creating query holds theDDLGuardof the table name for the whole window between the registration and the commit, so the drop re-checks the table's existence under that guard before pruning: once the guard is acquired, no create is in flight, and the table's absence proves the entry is stale. (A dictionary defined in the configuration files -StorageID::fromDictionaryConfig, whose definition can also set a root<database>, makingdb.namethe name the loader knows it by - is not created through DDL and never appears inDatabaseCatalog: the cleanup consultsExternalDictionariesLoaderby that qualified name for every entry before the catalog, keeps the entry while the dictionary's definition stays in the configuration, and prunes an entry with an empty database name, which nothing else can own, only when the definition is gone.) The pruning removes only the exact stale entry (the collection and the recorded database, table and UUID):CREATE TABLE ... UUIDcan reuse the UUID of a failed create under a different table name, which the guard of the recorded name does not synchronize with, and removing everything under the UUID would erase the live dependency of such an in-flight create — the collection it uses could then be dropped from under the committed table. A newcreate_table_pause_before_commitfailpoint keeps a create inside the window for the tests.Atomicdatabase is resolved by its UUID, becauseRENAMEchanges the name recorded in the entry while the table keeps using the collection.CREATE TABLE ... UUIDcan reuse the UUID of a failed create under a different name, though, and the table that owns the UUID then has nothing to do with the collection of the failed create - it must not keep that collection alive. The two cases are told apart by the name recorded in the entry, which is set when the dependency is registered and follows the table acrossRENAME TABLE(only the entries under the exact old name are re-keyed - an entry of another name under the same UUID is precisely the leftover of a failed create, and anEXCHANGE, which runs the re-keying once per direction, skips the UUID entries so that the second direction does not move the entries the first one just did). An entry carrying another name while the live table has entries under its current name belongs to the create that failed and is pruned; when the live table has no entry under its current name (EXCHANGEandRENAME DATABASEleave the recorded names stale), the entries under the UUID are treated as its own, which can only refuse the drop, never allow it.CREATE DATABASEmetadata as well, and that metadata is replayed by a laterATTACH DATABASEor a server start just like table metadata, soENGINE = S3(nc),Remote,MySQL,PostgreSQLandMaterializedPostgreSQLdatabases record a dependency of their own (aStorageIDwith the database name and no table name, built by the newStorageID::createDatabaseOnly- the ordinary two-argument constructor asserts a non-empty table name).DETACH DATABASEmoves it to the detached list andDROP DATABASEremoves it, but only afterDatabaseCatalog::detachDatabasehas proved the drop went through:detachDatabaseattaches the database back when it cannot finish (a table appeared in it while it was being dropped, or the engine'sdropthrew), and a database that is live again must keep its dependency. A newdrop_database_fail_before_dropfailpoint makes that path testable.RENAME DATABASEre-keys the entry to the new name, since theCREATE DATABASEmetadata is rewritten under it and keeps referencing the collection; otherwise the entry of the old name was taken for the leftover of a failedCREATE DATABASEand pruned. The entry is registered whileDatabaseFactoryresolves the engine arguments, before the database is attached, so aCREATE DATABASEthat fails after that point removes the entries of the database name again (InterpreterCreateQuery::createDatabase, under the database-levelDDLGuardit holds for the whole create); otherwise a database created under the same name later, with another engine or another collection, kept the collection of the failed create from being dropped for good.Documented behavior impact
DROP NAMED COLLECTIONnow rejects a collection that a detached table or a table in a detached database references, where it previously succeeded (and left a server that could not start). This is whatcheck_named_collection_dependenciesalready promises - "Check that DROP NAMED COLLECTION will not break tables that depend on it" - so the documented behavior of the setting does not change, and setting it to0still allows the drop. No documentation update is needed.Verified locally (release build)
CREATE NAMED COLLECTION+CREATE TABLE ... ENGINE = URL(nc)+DETACH TABLE+DROP NAMED COLLECTIONsucceeds, and the server then fails to start with the exact error chain above (exit code 210). Same withDETACH DATABASE.04660_drop_named_collection_detached_table,04698_drop_named_collection_detached_after_rename, and04823_drop_named_collection_broken_attach(all new, covering plainDETACH TABLE(blocks the drop),DETACH TABLE ... PERMANENTLY(does not block; the laterATTACHfails cleanly),DETACH DATABASE,Ordinarydatabases, renames of the table and of the database before and after the detach, stale dependencies of failedCREATE TABLE, and anATTACHthat fails after the dependencies were registered — the drop stays refused), and04836_drop_named_collection_inflight_create(new, runsDROP NAMED COLLECTIONagainst aCREATE TABLEand anATTACH TABLEpaused between the dependency registration and the commit to the catalog: the drop blocks on theDDLGuardand is refused), and04840_drop_named_collection_cross_engine_rename(new, moves a table between anOrdinaryand anAtomicdatabase in both directions and then detaches the table and its database), and04848_drop_named_collection_reused_uuid(new, prunes the stale entry of a failedCREATE TABLE ... UUIDwhile a create of a different table reusing the UUID is paused inside the window: the drop of the old collection succeeds, and the drop of the collection the new table uses stays refused; verified to fail without the fix), plus03822_named_collection_drop_dependency_checkand04003_named_collection_drop_dependency_check_dictpass.04907_drop_named_collection_database_dependency(new, a database using the collection blocks the drop and releases it when dropped),05024_drop_named_collection_database_rename(new,RENAME DATABASEof aMaterializedPostgreSQLdatabase keeps its dependency),05025_drop_named_collection_aborted_database_drop(new, aDROP DATABASEfailed insidedetachDatabaseby the new failpoint leaves the database attached and its dependency intact), and05026_drop_named_collection_committed_reused_uuid(new, a committedCREATE TABLE ... UUIDreusing the UUID of a failed create no longer keeps the collection of the failed create alive, while its own collection is still protected), and05048_drop_named_collection_reused_uuid_rename(new, the same after the reusing table is renamed: the recorded name follows the table acrossRENAME TABLE, so the stale entry of the failed create is not taken for the renamed table's own pre-rename entry - the drop of the failed create's collection succeeds and the renamed table's own collection stays protected), and05153_drop_named_collection_aborted_create_database(new, aCREATE DATABASE ... ENGINE = S3(nc)that fails after the collection was resolved leaves no dependency behind: the collection can be dropped once the database name is reused by a database without a collection or with another collection, whose own collection stays protected), and05223_drop_named_collection_aborted_attach_database(new, anATTACH DATABASEof a detached database - one using the collection itself and anAtomicone whose table uses another collection - failed by the newattach_database_fail_after_loadfailpoint after the tables were loaded leaves both collections protected by the entriesDETACH DATABASErecorded; they attach back and are released only once the databases are dropped) pass.test_named_collections/test.py::test_drop_while_used_by_lazily_loaded_table(new integration test: a table using a named collection in anAtomicdatabase withlazy_load_tables = 1, a server restart so the table comes back as a never-accessed proxy, and the drop refused both while it is attached and afterDETACH TABLE). It is an integration test because the hole is only reachable once the in-memory list is empty, i.e. after a restart: without one, theDETACH DATABASEthat precedesATTACH DATABASEleaves its own entry behind and that entry refuses the drop on its own. Verified that it fails without the fix (the drop succeeds) and passes with it.test_drop_collection_recreated_under_lazily_loaded_table(new integration test: the collection is dropped withcheck_named_collection_dependencies = 0, the server restarts while it is missing, and the drop of the recreated collection is refused; verified to fail without the fix), andtest_drop_not_used_by_lazily_loaded_distributed_table(new integration test: a collection named after the cluster of a lazily loadedDistributedtable is droppable; passes before and after, pinning the behavior).test_drop_collection_recreated_under_lazily_loaded_bare_remote_table(new integration test: the same for the bareENGINE = Remote(nc)form, then the first read resolves through the recreated collection; the scenario was checked by hand against a local server built from this head),test_drop_collection_recreated_under_lazily_loaded_remote_table(new integration test: anENGINE = Remote(nc, database = 'system')table in a database withlazy_load_tables = 1, the collection dropped withcheck_named_collection_dependencies = 0, a restart while it is missing, and the drop of the recreated collection refused - the unambiguouskey = valueshape registers the dependency from the AST alone), andtest_drop_not_used_by_lazily_loaded_remote_table(new integration test: a collection named after the cluster of a lazily loadedENGINE = Remote(cluster, system, one)table, created after the table, is droppable after a restart; verified to fail without the fix - the drop was refused withNAMED_COLLECTION_IS_USEDby the unrelated table), andtest_drop_while_used_by_lazily_loaded_table_function(new integration test pinning that aCREATE TABLE ... AS bigquery(collection)table in a database withlazy_load_tables = 1keeps blocking the drop after a restart, before the first access and after aDETACH TABLE: such tables are loaded eagerly as aStorageTableFunctionProxy, which re-registers the dependency; passes without any code change, confirming no lazy table-function branch is needed)), andtest_drop_while_used_by_config_defined_dictionary(new integration test: a dictionary defined in the configuration files with a MongoDB source resolving a named collection - the one source that resolves collections for configuration-defined dictionaries - blocks the drop, and a second drop attempt stays refused, proving the first one did not prune the dependency; verified to fail without the fix - the drop succeeded), andtest_drop_while_used_by_database_qualified_config_dictionary(new integration test: the same for a configuration-defined dictionary with a root<database>in its definition, whose dependency carries the database name and whose loader key is the qualifieddb.name).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the server failing to start after a named collection was dropped while a detached table (or a table in a detached database) still referenced it.
DROP NAMED COLLECTIONnow counts detached tables as dependents and is refused withNAMED_COLLECTION_IS_USED, ascheck_named_collection_dependenciesalready does for attached tables.Workflow [PR]
Sync PR [sync-upstream/pr/112805]