Repository navigation
Do not re-check dependencies after the table was shut down - #112220
tiandiwonder wants to merge 6 commits into
Conversation
`DROP` and `DETACH ... PERMANENTLY` check for dependent objects twice: once before `IStorage::flushAndShutdown` and once inside `DatabaseCatalog::removeDependencies` after it. The two checks take `databases_mutex` separately, so a `CREATE`/`ALTER` running concurrently can register a dependent in between, and the second check then throws `HAVE_DEPENDENT_OBJECTS` when the object has already been shut down. The operation is rejected, but the object is left attached and broken: a dictionary becomes unloadable (`Dictionary ... not found`), and a `MaterializedView` keeps reading but silently stops receiving inserts from its source, until it is re-attached or the server restarts. The second check is a duplicate -- same table, same flags -- and its only distinct outcome is to fire after the point of no return. Give `removeDependencies` a `DependentsPolicy`, defaulting to `Throw` so no other caller changes, and pass `Warn` from the two `InterpreterDropQuery` sites that run after the shutdown: the removal now completes and logs a warning naming the dependents, which are left referencing a removed object. The pre-shutdown check is untouched and still rejects every non-concurrent case. `Warn` reports the same *filtered* set that would have thrown, so a `DROP DATABASE` with ordinary internal dependencies stays silent. `InterpreterRenameQuery` keeps `Throw`: its `removeDependencies` call is the only dependency check on the rename path, and it shuts nothing down. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [29da9f9] Summary: ✅
AI ReviewSummaryThis PR replaces the post- PR Metadata
### Changelog category (leave one):
- Bug Fix
Findings❌ Blockers [src/Interpreters/DatabaseCatalog.cpp:1958] The new Suggested fix: do not reuse the plain [src/Interpreters/InterpreterDropQuery.cpp:375] Suggested fix: for database-wide truncation, use the unfiltered dependent set (or the same snapshot-aware filtering described above) before allowing the Tests
Final VerdictRequest changes. The post-shutdown warning path is still unsafe for database-wide operations until the same-database filter becomes snapshot-aware (or is removed) for both |
…settings `check_referential_table_dependencies` defaults to `0`, so every scenario in the test consulted the loading-dependency graph only, leaving the other branch of `getBlockingDependentsUnlocked` untested. Add a race that enables the setting for the removal. `no-random-settings` was copied over without a reason: nothing the test harness randomizes affects `DROP`/`DETACH`, and the test passes with randomization on. Remove it, per the rule of not adding such tags unless strictly necessary. Co-Authored-By: Claude Opus 5 <[email protected]>
The style check greps for the literal $CLICKHOUSE_TEST_ZOOKEEPER_PREFIX (or
{database}) after Replicated*MergeTree(, so the braced ${...} form does not
satisfy it.
Co-Authored-By: Claude Opus 5 <[email protected]>
| } | ||
| return dependents; | ||
|
|
||
| /// For DROP DATABASE we should ignore dependent tables from the same database. |
There was a problem hiding this comment.
Reusing the DROP DATABASE same-database filter in the post-flushAndShutdown Warn path hides a real dangling dependent. By the time we reach this code, executeToDatabaseImpl has already frozen tables_to_drop, so a same-database object created in this window is not an "ordinary internal dependency" anymore: it will not be dropped later.
The result is that we remove the source table, then db->empty() makes detachDatabase(..., check_empty=true) reattach the database with DATABASE_NOT_EMPTY, leaving the new dictionary or view attached against a removed source with no warning. The new same_db scenario in 04648_detach_post_shutdown_dependency_recheck already demonstrates the failed DROP DATABASE; I think Warn needs the unfiltered set here, or a snapshot-aware filter that can distinguish dependents that were part of the original database-drop snapshot from ones that appeared too late.
…object Letting a removal finish when a dependent was registered concurrently leaves that dependent with an edge to an object that is gone. The edge is not transient: the dependency graph is rebuilt from the dependent's metadata on every startup, and `removeUnresolvableDependencies` only drops the missing name from the local loading-schedule graph, not from the catalog. Pin what that state does across a restart: the server starts, unrelated tables load, the dependent attaches and is readable (only evaluating its unresolvable default fails), the loader logs the unresolved dependency, the edge is reconstructed -- recreating the object under the same name makes removing it refused again -- and dropping the dependent clears it. Both `async_load_databases` modes are covered. The synchronous one is the load-bearing half: there a failing table load stops startup, so a dangling dependent that could not attach would turn a race into a server that will not restart. Co-Authored-By: Claude Opus 5 <[email protected]>
In Cloud runs `SharedEngineReplacer` rewrites `ReplicatedMergeTree` to `SharedMergeTree` throughout the test file -- echoed strings included -- so a label that spells the engine out ends up disagreeing with the reference. The private sync run failed 10/10 on exactly that one line. The replacement itself is wanted: it is what gives this case its `SharedMergeTree` coverage for free, and the run confirms the removal behaves the same there. Only the labels had to stop naming the engine. Co-Authored-By: Claude Opus 5 <[email protected]>
|
|
||
| /// Same reasoning as in the DETACH PERMANENTLY branch above: the table is already shut down, | ||
| /// so a concurrently registered dependent must not turn into a throw here. | ||
| DatabaseCatalog::instance().removeDependencies( |
There was a problem hiding this comment.
TRUNCATE DATABASE also comes through this DROP TABLE branch: executeToDatabaseImpl rewrites it to per-table Drop queries in src/Interpreters/InterpreterDropQuery.cpp:516-518 and then runs executeToTableImpl over the frozen tables_to_drop snapshot in src/Interpreters/InterpreterDropQuery.cpp:676-689. Because current_query_ptr->table == nullptr, is_drop_or_detach_database is still true here, so the post-shutdown Warn path applies the same same-database filter.
If a same-db dependent is registered after that snapshot, it will never be processed later, but we still drop the source table here. Unlike DROP DATABASE, there is no later db->empty() check to stop the operation, because TRUNCATE DATABASE never detaches the DB. The race therefore becomes a successful TRUNCATE DATABASE that silently leaves a dangling dependent against a removed source. I think the warn path needs either the unfiltered set for database-wide truncation, or a snapshot-aware filter that only suppresses dependents that were part of the original database snapshot.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 48/48 (100.00%) · Uncovered code |
Problem
A
DROPorDETACH TABLE ... PERMANENTLYthat races a concurrently created dependent is reported as rejected withHAVE_DEPENDENT_OBJECTS, but the object it refused to remove is left attached and broken:dictGetfails withDictionary ... not found(BAD_ARGUMENTS);MaterializedViewkeeps reading and stays insystem.tables, but silently stops receiving inserts from its source;MergeTreehappens to survive unharmed.The state persists until the object is re-attached or the server restarts. The
MaterializedViewcase is a silent data miss: nothing in the failedDETACHtells the user that inserts stopped materializing.Root cause
InterpreterDropQuery::executeToTableImplchecks for dependents twice, with the irreversible step between them:checkTableCanBeRemovedOrRenamed— takesdatabases_mutex, checks, releases it;table->flushAndShutdown()— no lock held;DatabaseCatalog::removeDependencies— re-takesdatabases_mutexand throwsHAVE_DEPENDENT_OBJECTSif any dependent exists.Because steps 1 and 3 acquire the mutex separately and dependency registration is not serialized on the referenced object (
InterpreterCreateQuery::createTablereleases itsDDLGuardbeforeaddTableDependencies;ALTERlocks only the dependent), a concurrentCREATE/ALTERslips in between and step 3 throws after the object has already been shut down.Step 3 is a duplicate of step 1 — same table, same flags. Its only distinct outcome is to fire after the point of no return.
Solution
Stop letting the duplicate check throw there, while keeping the check itself.
DatabaseCatalog::removeDependenciesgains aDependentsPolicy, defaulting toThrowso no other caller changes. The twoInterpreterDropQuerycall sites that run after the shutdown passWarn: the removal completes and logs a warning naming the dependents, which are left referencing a removed object.The pre-shutdown check is untouched and still rejects every non-concurrent case, so the guarantee is given up only inside the race window — where it was already unenforceable, since a
CREATElanding one microsecond after the drop completes is not rejected either. The resulting dangling dependent is bounded: the drop path never removed incoming edges anyway (TablesDependencyGraph::removeDependenciesremoves the dependencies of a table, not its dependents), the server still starts, and the state clears when the dependent is dropped or altered. It is also already reachable today withcheck_table_dependencies = 0.Because the change lives in the interpreter and the catalog and touches no
IStoragelifecycle method, it behaves identically for every engine — unlike a post-hoc rollback of the shutdown, which is only safe for dictionaries (StorageReplicatedMergeTree::startupImplthrowsTABLE_IS_DROPPEDon its latched shutdown flags).Two details worth a reviewer's attention:
Warnreports the same filtered set that would have thrown, so aDROP DATABASEwith ordinary internal dependencies stays silent; only cross-database dependents are reported.InterpreterRenameQuerydeliberately keepsThrow: itsremoveDependenciescall is the only dependency check on the rename path, and rename shuts nothing down. A test guards this.What this does not fix. The dependency check is not the only thing that can throw after
flushAndShutdown: a failingflushAndShutdownitself, thelockExclusivelytimeout onOrdinarydatabases, and a failingdetachTablePermanentlyleave the same half-state. Those are genuine failures rather than a redundant check, so they need the architectural fix — do not shut the storage down until the operation commits — and are tracked separately.Tests.
04648_...drives the race with a new failpoint that pauses between shutdown and dependency removal, over a dictionary, aMaterializedView, aMergeTreeand aReplicatedMergeTree, and covers theDROP DATABASEsame-database/cross-database filter.04649_...is the must-not-act side and passes on unfixed code too. With the fix reverted,04648_...fails withCode: 630and leaves each object still insystem.tables.Related: #105259
Related: #111742
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
DROPandDETACH TABLE ... PERMANENTLYbeing rejected after the table had already been shut down, when a dependent object was created concurrently. Previously this left the object attached but broken — an unloadable dictionary, or aMaterializedViewthat silently stopped receiving inserts — until it was re-attached or the server restarted.