Skip to content

Do not re-check dependencies after the table was shut down - #112220

Open
tiandiwonder wants to merge 6 commits into
masterfrom
fix-detach-post-shutdown-dependency-recheck
Open

tiandiwonder wants to merge 6 commits into
masterfrom
fix-detach-post-shutdown-dependency-recheck

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A DROP or DETACH TABLE ... PERMANENTLY that races a concurrently created dependent is reported as rejected with HAVE_DEPENDENT_OBJECTS, but the object it refused to remove is left attached and broken:

  • a dictionary becomes unloadable — dictGet fails with Dictionary ... not found (BAD_ARGUMENTS);
  • a MaterializedView keeps reading and stays in system.tables, but silently stops receiving inserts from its source;
  • a plain MergeTree happens to survive unharmed.

The state persists until the object is re-attached or the server restarts. The MaterializedView case is a silent data miss: nothing in the failed DETACH tells the user that inserts stopped materializing.

Root cause

InterpreterDropQuery::executeToTableImpl checks for dependents twice, with the irreversible step between them:

  1. checkTableCanBeRemovedOrRenamed — takes databases_mutex, checks, releases it;
  2. table->flushAndShutdown() — no lock held;
  3. DatabaseCatalog::removeDependencies — re-takes databases_mutex and throws HAVE_DEPENDENT_OBJECTS if any dependent exists.

Because steps 1 and 3 acquire the mutex separately and dependency registration is not serialized on the referenced object (InterpreterCreateQuery::createTable releases its DDLGuard before addTableDependencies; ALTER locks only the dependent), a concurrent CREATE/ALTER slips 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::removeDependencies gains a DependentsPolicy, defaulting to Throw so no other caller changes. The two InterpreterDropQuery call sites that run after the shutdown pass Warn: the removal completes and logs a warning naming the dependents, which are left referencing a removed object.

Removing db.dict (uuid) while some tables still depend on it: db.dep. The dependency check passed
before the table was shut down, so these dependents were registered concurrently and 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 CREATE landing 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::removeDependencies removes 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 with check_table_dependencies = 0.

Because the change lives in the interpreter and the catalog and touches no IStorage lifecycle method, it behaves identically for every engine — unlike a post-hoc rollback of the shutdown, which is only safe for dictionaries (StorageReplicatedMergeTree::startupImpl throws TABLE_IS_DROPPED on its latched shutdown flags).

Two details worth a reviewer's attention:

  • Warn reports the same filtered set that would have thrown, so a DROP DATABASE with ordinary internal dependencies stays silent; only cross-database dependents are reported.
  • InterpreterRenameQuery deliberately keeps Throw: its removeDependencies call 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 failing flushAndShutdown itself, the lockExclusively timeout on Ordinary databases, and a failing detachTablePermanently leave 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, a MaterializedView, a MergeTree and a ReplicatedMergeTree, and covers the DROP DATABASE same-database/cross-database filter. 04649_... is the must-not-act side and passes on unfixed code too. With the fix reverted, 04648_... fails with Code: 630 and leaves each object still in system.tables.

Related: #105259
Related: #111742

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed DROP and DETACH TABLE ... PERMANENTLY being 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 a MaterializedView that silently stopped receiving inserts — until it was re-attached or the server restarted.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29da9f9]

Summary: ✅


AI Review

Summary

This PR replaces the post-flushAndShutdown dependent re-check with a warning so DROP / DETACH ... PERMANENTLY can finish instead of leaving the source attached but shut down. That table-level fix is directionally right, but the database-wide paths still reuse the old "ignore same-database dependents" shortcut after the table snapshot is already frozen, so they can still create dangling dependents and half-applied DDL.

PR Metadata
  • Changelog category should be Bug Fix, not Improvement: this PR fixes user-visible misbehavior in an existing released feature.
  • Exact replacement text:
### Changelog category (leave one):
- Bug Fix
  • Changelog entry is required for Bug Fix, and the current entry is specific and user-readable.
Findings

❌ Blockers

[src/Interpreters/DatabaseCatalog.cpp:1958] The new Warn path still reuses the DROP DATABASE same-database filter after executeToDatabaseImpl has already frozen tables_to_drop. A dependent created in that window is no longer an "ordinary internal dependency": it will not be dropped later, but it is still filtered out here. DROP DATABASE can therefore remove the source table, then fail later in detachDatabase(..., check_empty=true) with DATABASE_NOT_EMPTY, leaving the new same-db object attached against a removed source.

Suggested fix: do not reuse the plain is_drop_database filter in the post-shutdown path. Pass either the unfiltered set there, or a snapshot-aware filter that only suppresses dependents that were part of the original database-drop snapshot.

[src/Interpreters/InterpreterDropQuery.cpp:375] TRUNCATE DATABASE inherits the same bug, but without the later safety net. executeToDatabaseImpl rewrites database truncation to per-table Drop queries, so is_drop_or_detach_database is true here as well. A same-db dependent created after tables_to_drop is collected is filtered out of the post-shutdown check, the source table is still dropped, and there is no final db->empty() check because TRUNCATE DATABASE never detaches the database. The result is a successful TRUNCATE DATABASE that silently leaves a dangling dependent against a removed source.

Suggested fix: for database-wide truncation, use the unfiltered dependent set (or the same snapshot-aware filtering described above) before allowing the Warn path to proceed.

Tests

⚠️ Add a focused stateless race for TRUNCATE DATABASE with a same-database dependent created after tables_to_drop is collected. Current coverage demonstrates the DROP DATABASE failure mode, but it does not exercise the truncate path that currently succeeds and leaves the dangling dependent behind.

Final Verdict

Request 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 DROP DATABASE and TRUNCATE DATABASE.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 28, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jul 28, 2026
tiandiwonder and others added 2 commits July 28, 2026 04:51
…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.

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.

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.

tiandiwonder and others added 2 commits July 28, 2026 09:11
…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(

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.

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.

@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.70% +0.00%

Changed lines: Changed C/C++ lines covered: 48/48 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026

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

can be tested Allows running workflows for external contributors comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants