Skip to content

Do not drop a named collection that a detached table still uses - #112805

Open
alexey-milovidov wants to merge 160 commits into
masterfrom
fix-drop-named-collection-detached-table
Open

alexey-milovidov wants to merge 160 commits into
masterfrom
fix-drop-named-collection-detached-table

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #125617
Related: #96181
Related: #77366
Related: #110529

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 (added in #96181) 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.

This is how the Stress test (arm_tsan) job fails on master with Cannot start clickhouse-server: the AST fuzzer makes 04320_url_engine_dispatch_partition_and_format leave its URL(named_collection) table detached (the test's ATTACH TABLE never 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

Application: Caught exception while loading metadata: Code: 722. DB::Exception: Waited job failed:
Code: 695. DB::Exception: Load job 'load table test_3.04320_..._n' failed:
Code: 669. DB::Exception: There is no named collection `04320_..._nc`:
Cannot attach table `test_3`.`04320_..._n` from metadata file store/e5b/.../04320_..._n.sql
from query ATTACH TABLE ... ENGINE = URL(`04320_..._nc`, format = 'JSON'). (NAMED_COLLECTION_DOESNT_EXIST)

The same signature accounts for 6 of the 8 Cannot start clickhouse-server failures with a missing named collection in the last 60 days (per play.clickhouse.com); the other two come from 03822_named_collection_drop_dependency_check, which drops the collection with check_named_collection_dependencies = 0 on 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 (and DETACH DATABASE, for every table inside) moves the dependencies of the table into a list of (collection, database, table) entries.
  • DROP NAMED COLLECTION is refused with NAMED_COLLECTION_IS_USED while an entry for the collection exists.
  • ATTACH does 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, and RENAME of the (necessarily re-attached) table; DROP DATABASE removes the entries of the database's detached tables, and RENAME DATABASE re-keys them. The DROP NAMED COLLECTION check itself removes nothing: the table's existence in DatabaseCatalog is 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.
  • A CREATE TABLE or ATTACH TABLE that fails before the table is committed removes the dependencies it registered for exactly its StorageID (database, table, UUID), as createDatabase already 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 ... PERMANENTLY does 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 explicit ATTACH of such a table fails cleanly with NAMED_COLLECTION_DOESNT_EXIST and is recoverable by recreating the collection.
  • A short ATTACH TABLE of 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).
  • The list lives in memory only, which is consistent across a restart: a plainly detached table is attached again at the next start, where regular dependency tracking picks it up, and a permanently detached one records no entry at all. The list is deliberately imprecise in one direction: a stale entry may keep refusing the drop for a while after the detached table itself is gone, or after the table was attached back (until the table is dropped or renamed). In exchange, the DROP NAMED COLLECTION path performs no disk access at all.
  • A RENAME TABLE that moves a table between an Ordinary and an Atomic database changes the identity the dependency is keyed by: the move into Atomic assigns 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 of Atomic databases and by the name for tables of Ordinary ones. 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 the Atomic -> Ordinary direction, the drop check even classified the entry of the still attached table as a leftover of a failed CREATE and dropped the collection from under it. DatabaseOnDisk::renameTable now re-keys the entries of the moved table to its new StorageID, where both identities are known. EXCHANGE is unaffected: it is only supported between two Atomic databases, where the UUIDs do not change.
  • A table of a database with lazy_load_tables = 1 is attached as a StorageTableProxy and 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 COLLECTION was then allowed while such a table still referenced the collection - breaking it at the first access with NAMED_COLLECTION_DOESNT_EXIST - and a DETACH of it had no dependency to move to the list of the detached ones, so the protection above silently disappeared in that mode. DatabaseOrdinary::loadTableLazy now registers the dependency straight from the metadata, via the new tryGetUsedNamedCollectionName helper. An identifier first argument counts as a collection reference only for the engines that resolve their arguments through named collections (a new StorageFactory::StorageFeatures::supports_named_collections flag) - for other engines an identifier means something else, e.g. a cluster name for Distributed - 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 with check_named_collection_dependencies = 0) protects it when it is recreated later. The exception is Remote/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 new StorageFeatures::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. A key = value second argument occurs only in the named-collection form: no positional signature of Remote accepts one there, so parseRemoteFunctionArguments reports 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 bare Remote(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. SETTINGS are skipped when the shape is examined, as parseRemoteFunctionArguments does. MongoDB and MaterializedPostgreSQL were the only flagged engines whose eager argument resolution did not pass the dependent table to tryGetNamedCollectionWithOverrides (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. addDependency ignores an exact duplicate, because the same dependency is registered again when the proxy is materialized. Tables created with CREATE TABLE ... AS f(...) need no lazy branch: a database with lazy_load_tables = 1 deliberately loads them eagerly as a StorageTableFunctionProxy (see DatabaseOrdinary::shouldLazyLoad), and that load registers the dependency via ITableFunction::getUsedNamedCollectionName.
  • The cleanup of stale active dependencies (leftovers of a failed 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 from DatabaseCatalog alone as a proof of staleness: the dependency of an in-flight CREATE/ATTACH is registered while the engine arguments are resolved, before the table is committed to the catalog, and a concurrent DROP NAMED COLLECTION could prune it and drop the collection while the create later succeeds — recreating the broken metadata this PR fixes. The creating query holds the DDLGuard of 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>, making db.name the name the loader knows it by - is not created through DDL and never appears in DatabaseCatalog: the cleanup consults ExternalDictionariesLoader by 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 ... UUID can 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 new create_table_pause_before_commit failpoint keeps a create inside the window for the tests.
  • A dependency of a table of an Atomic database is resolved by its UUID, because RENAME changes the name recorded in the entry while the table keeps using the collection. CREATE TABLE ... UUID can 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 across RENAME 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 an EXCHANGE, 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 (EXCHANGE and RENAME DATABASE leave the recorded names stale), the entries under the UUID are treated as its own, which can only refuse the drop, never allow it.
  • A database engine resolves named collections from its persisted CREATE DATABASE metadata as well, and that metadata is replayed by a later ATTACH DATABASE or a server start just like table metadata, so ENGINE = S3(nc), Remote, MySQL, PostgreSQL and MaterializedPostgreSQL databases record a dependency of their own (a StorageID with the database name and no table name, built by the new StorageID::createDatabaseOnly - the ordinary two-argument constructor asserts a non-empty table name). DETACH DATABASE moves it to the detached list and DROP DATABASE removes it, but only after DatabaseCatalog::detachDatabase has proved the drop went through: detachDatabase attaches the database back when it cannot finish (a table appeared in it while it was being dropped, or the engine's drop threw), and a database that is live again must keep its dependency. A new drop_database_fail_before_drop failpoint makes that path testable. RENAME DATABASE re-keys the entry to the new name, since the CREATE DATABASE metadata is rewritten under it and keeps referencing the collection; otherwise the entry of the old name was taken for the leftover of a failed CREATE DATABASE and pruned. The entry is registered while DatabaseFactory resolves the engine arguments, before the database is attached, so a CREATE DATABASE that fails after that point removes the entries of the database name again (InterpreterCreateQuery::createDatabase, under the database-level DDLGuard it 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 COLLECTION now 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 what check_named_collection_dependencies already 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 to 0 still allows the drop. No documentation update is needed.

Verified locally (release build)

  • Before: CREATE NAMED COLLECTION + CREATE TABLE ... ENGINE = URL(nc) + DETACH TABLE + DROP NAMED COLLECTION succeeds, and the server then fails to start with the exact error chain above (exit code 210). Same with DETACH DATABASE.
  • After: the drop is refused, the collection stays, the table attaches back, and a restart of a server with the detached table present succeeds.
  • 04660_drop_named_collection_detached_table, 04698_drop_named_collection_detached_after_rename, and 04823_drop_named_collection_broken_attach (all new, covering plain DETACH TABLE (blocks the drop), DETACH TABLE ... PERMANENTLY (does not block; the later ATTACH fails cleanly), DETACH DATABASE, Ordinary databases, renames of the table and of the database before and after the detach, stale dependencies of failed CREATE TABLE, and an ATTACH that fails after the dependencies were registered — the drop stays refused), and 04836_drop_named_collection_inflight_create (new, runs DROP NAMED COLLECTION against a CREATE TABLE and an ATTACH TABLE paused between the dependency registration and the commit to the catalog: the drop blocks on the DDLGuard and is refused), and 04840_drop_named_collection_cross_engine_rename (new, moves a table between an Ordinary and an Atomic database in both directions and then detaches the table and its database), and 04848_drop_named_collection_reused_uuid (new, prunes the stale entry of a failed CREATE TABLE ... UUID while 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), plus 03822_named_collection_drop_dependency_check and 04003_named_collection_drop_dependency_check_dict pass.
  • 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 DATABASE of a MaterializedPostgreSQL database keeps its dependency), 05025_drop_named_collection_aborted_database_drop (new, a DROP DATABASE failed inside detachDatabase by the new failpoint leaves the database attached and its dependency intact), and 05026_drop_named_collection_committed_reused_uuid (new, a committed CREATE TABLE ... UUID reusing the UUID of a failed create no longer keeps the collection of the failed create alive, while its own collection is still protected), and 05048_drop_named_collection_reused_uuid_rename (new, the same after the reusing table is renamed: the recorded name follows the table across RENAME 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), and 05153_drop_named_collection_aborted_create_database (new, a CREATE 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), and 05223_drop_named_collection_aborted_attach_database (new, an ATTACH DATABASE of a detached database - one using the collection itself and an Atomic one whose table uses another collection - failed by the new attach_database_fail_after_load failpoint after the tables were loaded leaves both collections protected by the entries DETACH DATABASE recorded; 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 an Atomic database with lazy_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 after DETACH 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, the DETACH DATABASE that precedes ATTACH DATABASE leaves 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 with check_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), and test_drop_not_used_by_lazily_loaded_distributed_table (new integration test: a collection named after the cluster of a lazily loaded Distributed table 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 bare ENGINE = 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: an ENGINE = Remote(nc, database = 'system') table in a database with lazy_load_tables = 1, the collection dropped with check_named_collection_dependencies = 0, a restart while it is missing, and the drop of the recreated collection refused - the unambiguous key = value shape registers the dependency from the AST alone), and test_drop_not_used_by_lazily_loaded_remote_table (new integration test: a collection named after the cluster of a lazily loaded ENGINE = Remote(cluster, system, one) table, created after the table, is droppable after a restart; verified to fail without the fix - the drop was refused with NAMED_COLLECTION_IS_USED by the unrelated table), and test_drop_while_used_by_lazily_loaded_table_function (new integration test pinning that a CREATE TABLE ... AS bigquery(collection) table in a database with lazy_load_tables = 1 keeps blocking the drop after a restart, before the first access and after a DETACH TABLE: such tables are loaded eagerly as a StorageTableFunctionProxy, which re-registers the dependency; passes without any code change, confirming no lazy table-function branch is needed)), and test_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), and test_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 qualified db.name).

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 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 COLLECTION now counts detached tables as dependents and is refused with NAMED_COLLECTION_IS_USED, as check_named_collection_dependencies already does for attached tables.


Workflow [PR]
Sync PR [sync-upstream/pr/112805]

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

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f15a01d]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_named_collections/test.py::test_keeper_storage_lagging_replica FAIL cidb
test_named_collections_encrypted/test.py::test_local_storage_missing_key FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Protects named collections referenced by detached and lazily loaded objects, dictionaries, and database engines. One blocker and two majors remain at f15a01da; the dictionary finding is a remaining variant of an earlier finding, whose thread was reopened.

Findings

❌ Blockers

  • Dependency protection is lost on allocation failure — src/Common/NamedCollections/NamedCollectionsFactory.cpp:923–964. markDependenciesDetached erases active entries before allocating detached replacements. If allocation throws, the table and its metadata survive without either dependency, permitting a checked DROP NAMED COLLECTION and a later NAMED_COLLECTION_DOESNT_EXIST. The rename/re-key methods have the same ordering problem, and insertDetachedDependency can leave its two indexes inconsistent. DatabaseCatalog::undropTable:1711–1715 likewise restores metadata before allocating its protection. Stage allocations before irreversible changes, or roll back while preserving every surviving definition's dependencies. Existing thread.

⚠️ Majors

  • Checked drops lose storage-backed existence semantics — src/Common/NamedCollections/NamedCollectionsFactory.cpp:428–448 and src/Interpreters/InterpreterDropNamedCollectionQuery.cpp:128. Unlike removeFromSQL, the new checked path omits loadIfInStorage and tests only loaded collections. A Keeper collection not yet loaded by this replica incorrectly produces NAMED_COLLECTION_DOESNT_EXIST; IF EXISTS silently leaves it stored. Encrypted entries skipped because their key is unavailable also become impossible to drop through the default checked path. Preserve storage-aware existence and unreadable-entry handling, including the interpreter's early shortcut. Existing thread.

  • Dictionary metadata recovery misses accepted scalar collection names — src/Storages/NamedCollectionsHelpers.cpp:527–528. SOURCE(CLICKHOUSE(NAME 123)) resolves a collection named 123: dictionary configuration generation stringifies the numeric literal, and normalization preserves its numeric type. This helper handles only string literals and identifiers. Repeating 05454_drop_named_collection_undrop_dictionary with that source leaves restored metadata without a dependency after the failed UNDROP TABLE; a checked collection drop then succeeds and breaks subsequent dictionary loading. Apply the same scalar conversion as the configuration builder, or reject dictionary restoration before moving metadata. Source-traced; not executed locally. Reopened thread and reply.

Tests
  • ⚠️ Add focused allocation-failure coverage proving that failed transfers and metadata restoration retain dependency protection and consistent indexes.
  • ⚠️ Cover the numeric dictionary NAME variant in the restore regression. Validate storage-backed drops with existing test_keeper_storage_lagging_replica and test_local_storage_missing_key, including IF EXISTS.
Missing context / blind spots
  • ⚠️ The current-head CI report contains passing Fast test and tidy checks, but no results yet for the relevant targeted integration/stateless jobs. No ClickHouse binary is available here; those CI results would provide runtime validation.
Final Verdict

Status: ❌ Block

Make dependency transitions exception-safe, restore storage-aware checked drops, and handle accepted scalar dictionary collection names, with the focused validation above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 23/25 (92.00%) · Uncovered code

Full report · Diff report

…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.
alexey-milovidov and others added 3 commits August 3, 2026 21:51
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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@alexey-milovidov alexey-milovidov self-assigned this Aug 6, 2026
…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.
@alexey-milovidov

alexey-milovidov commented Aug 6, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Reworked as suggested in the review: the metadata inspection is gone (net -224 lines). NamedCollectionFactory now keeps an in-memory list of (collection, database, table) entries — DETACH TABLE (and DETACH DATABASE, for the tables inside) moves the table's dependencies there, DROP NAMED COLLECTION throws NAMED_COLLECTION_IS_USED while an entry exists, attaching a table with that name back removes the entry, and DROP DATABASE removes the entries of its detached tables. The list is deliberately imprecise as allowed: it does not survive a restart, and a stale entry may keep refusing the drop for a while after the detached table is gone. Renames need no special handling anymore: the entry is recorded under the table's current name at detach time. Tests 04660/04698 updated and pass locally, along with 03822 and 04003.

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9299363c8 with master c9dc272bf (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

158 object files changed (+315.94 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Common/NamedCollections/NamedCollectionsFactory.cpp.o 244.42 KiB 343.30 KiB +98.88 KiB (+40.46%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropNamedCollectionQuery.cpp.o 107.46 KiB 151.41 KiB +43.95 KiB (+40.90%)
src/CMakeFiles/dbms.dir/Storages/NamedCollectionsHelpers.cpp.o 157.70 KiB 189.39 KiB +31.69 KiB (+20.10%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorageCluster.cpp.o 1.02 MiB 1.03 MiB +19.29 KiB (+1.85%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorage.cpp.o 2.97 MiB 2.99 MiB +17.13 KiB (+0.56%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1915 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 matched translation units cost -875.4 s (-9%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Formats/FormatFactory.cpp 45.0 s 24.5 s -17.8 s (-42%)

Job report

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.
alexey-milovidov and others added 2 commits August 8, 2026 03:48
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`.
alexey-milovidov and others added 2 commits August 9, 2026 12:32
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (clean merge; all translation units touched by this PR compile on the merged tree). Status of the last run (3abdc885):

@groeneai, thanks for the analysis of the AST fuzzer oracle failure and the fix in #129420.

# Conflicts:
#	src/TableFunctions/ITableFunction.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve the conflict in src/TableFunctions/ITableFunction.h: master removed getFunctionURINormalized (replaced by checkSourceAccessForURI), so I kept only this PR's private used_named_collection_name. The clickhouse binary builds on the merged tree. Locally, 35 of the 38 stateless tests added or changed here pass; the other 3 need the CI test configuration (test_shard_localhost, custom_local_disks_base_directory, the secrets grant).

The only red checks at c3a2d039 were the four Bugfix validation jobs. They are red because some of the PR's tests also pass on the master binary, which is expected:

  • 05340_drop_named_collection_nested_redis_target is a negative guard for this PR's own dependency logic (a nested redis target never holds a collection), and 03822_named_collection_drop_dependency_check is an existing test that this PR extends.
  • The 20 integration cases are existing tests in test_named_collections/test.py. The validation runs the whole module because this PR adds new cases there.

New cases in both suites do fail on master, as they should.

alexey-milovidov and others added 2 commits November 10, 2026 02:46
Fixes `readability-redundant-access-specifiers` in the `arm_tidy` build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the only CI failure: Build (arm_tidy) failed with readability-redundant-access-specifiers, because the merge that resolved the ITableFunction.h conflict left a second private: before used_named_collection_name. I removed it and merged master again. The merge was clean, and the translation units it touched compile.

alexey-milovidov and others added 5 commits November 11, 2026 09:20
…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]>
alexey-milovidov and others added 4 commits November 16, 2026 11:34
# 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]>
alexey-milovidov and others added 2 commits November 22, 2026 04:16
…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]>
@clickhouse-gh clickhouse-gh Bot added comp-config Server configuration infrastructure: XML/YAML config parsing, preprocessor (includes, substitutio... and removed comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Nov 22, 2026
alexey-milovidov and others added 3 commits November 24, 2026 21:04
…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]>
Comment on lines +963 to +964
for (const auto & collection_name : collection_names)
insertDetachedDependency(collection_name, table_id.database_name, table_id.table_name);

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.

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

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.

[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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-config Server configuration infrastructure: XML/YAML config parsing, preprocessor (includes, substitutio... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DROP NAMED COLLECTION succeeds while a database uses the collection, and the server then fails to start

3 participants