Skip to content

Remove a table's named-collection dependency only after its metadata is dropped - #116768

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:drop-table-keeps-named-collection-dependency-until-metadata-gone
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:drop-table-keeps-named-collection-dependency-until-metadata-gone

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115378 (comment)
Related: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115378&sha=ddf8970d88156a2099f64ac83a7eab96b19f6674&name_0=PR&name_1=Stress%20test%20(arm_tsan)
Related: #112805
Related: #110529

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 a DROP TABLE that fails partway leaving what it depended on unprotected: a following DROP NAMED COLLECTION was wrongly allowed and the server then failed to start, and a table the dropped one depended on could be removed even with check_table_dependencies enabled.

Description

Found in a Stress test (arm_tsan) Cannot start clickhouse-server failure. The Kind::Drop branch released the table's dependencies before database->dropTable, so a dropTable that throws left the table on disk with its dependencies gone. No fault injection is needed: DatabaseAtomic::dropTableImpl's txn->commit can throw on a Keeper session expiry before the local rename. Two dependencies are affected, both fixed here.

  1. The named collection: the next DROP NAMED COLLECTION was wrongly allowed, the collection was deleted from disk, and every later start failed to attach the surviving table. That erase now runs after dropTable, and its name-based branch is allocation-free so it cannot throw there.

  2. The DatabaseCatalog edges, raised in review: a table the dropped one depended on could be removed even with check_table_dependencies enabled, reproduced with a dictionary. These are restored on the exception path rather than moved, because checkTableCanBeRemovedOrRenamedUnlocked does not filter dependents by existence: holding them across dropTable would refuse a concurrent drop while naming a table no longer in the catalog.

A ONCE failpoint at the vacated position pins both orderings. 04318_remote_storage_engine_access is untouched now: master hardened it itself.

This does not fix the failure I was asked to look at: that is the detached-table variant, which #112805 already fixes along with the permanent-Detach reorder. It inserts a line between the two statements this PR reorders, so a trivial conflict is expected.

Not addressed, all pre-existing and none affecting the next start: a materialized view is unsubscribed by flushAndShutdown before the dependencies are captured, so a failed drop leaves it disconnected until a restart (measured identical without this change); a concurrent drop inside the window can still remove a dependency, leaving a stale edge; dropTableFinally re-registering from the background drop; lazy_load_tables = 1; and StorageMongoDB.


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


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

…is dropped

In the `Kind::Drop` branch of `InterpreterDropQuery::executeToTableImpl` the call to
`NamedCollectionFactory::removeDependencies` preceded `database->dropTable`. Anything
that throws inside `dropTable` therefore left the table with its on-disk metadata
intact while its dependency was already gone, so the next `DROP NAMED COLLECTION` was
wrongly permitted, the collection was deleted from disk, and every later server start
failed to attach the surviving table.

The throw does not need fault injection. `DatabaseAtomic::dropTableImpl` has no
try/catch and its `txn->commit` can throw on a Keeper session expiry before the local
rename; `DatabaseOnDisk::dropTable`'s rollback re-attaches the table and rethrows
without restoring the dependency, and its window spans the whole `table->drop`.

Moving the call after `dropTable` returns is safe from anywhere in the sequence:
`removeDependencies` is a total, idempotent, non-throwing, in-memory-only erase, so the
success path keeps the same observable end state. The map is rebuilt as tables attach,
so a dependency lost to a crash self-heals on restart; the collection deletion the old
order permitted does not, which is why the ordering is what has to change.

A `ONCE` failpoint at the position the call vacated pins the invariant. Its
`isPredefinedDatabase` guard wraps `fiu_do_on` rather than sitting in its body: for a
one-shot point `fiu_fail` marks the point consumed before returning, so a guard inside
the body would let a drop in `system` burn the one shot and skip the throw, making the
regression test flaky instead of failing.

Found while investigating a `Stress test (arm_tsan)` `Cannot start clickhouse-server`
failure. That particular run is the detached-table variant, which is a different defect;
this change closes the sibling ordering hole in the `Drop` path.

`04318_remote_storage_engine_access` dropped its named collection without checking that
the preceding `DROP TABLE` had removed the table. Under the stress profile that drop can
be a no-op or be rewritten into a `DETACH`, and the test then passed while leaving a
table that no later server start could load. It now pins both stress settings on that
statement and only drops the collection once no attached or detached table references it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding), plus my own cold
review of the resulting tree before that gate ran.

# Sev Finding Verdict Evidence / action
1 ❌ A concurrent DROP NAMED COLLECTION can still discard the retained dependency inside DatabaseOnDisk::dropTable, between its detachTable (:387) and the metadata rename (:393), after which the rollback at :404-410 restores the table without its collection DISAGREE The window is real, but it is not the invariant this change establishes, it is unreachable on the default engine, and this change narrows it rather than leaving it alone. DatabaseAtomic::dropTableImpl renames the metadata to the dropped path (DatabaseAtomic.cpp:230) before detachTableUnlocked (:231), both inside one lock_guard on the database mutex, and it has no rollback, so no interval exists there in which the table is absent from the catalog while live metadata survives; its only pre-mutation throw site is txn->commit() at :222, which is the hazard this change does cover. DatabaseOnDisk::dropTable is inherited unoverridden only by DatabaseOrdinary, which needs allow_deprecated_database_ordinary (default false, Settings.cpp:7355); Atomic, Replicated, Backup, Memory, Overlay and Remote all override it and there is no Lazy engine any more. On master the dependency is erased before dropTable is entered at all, so the same concurrent drop succeeds deterministically over an unbounded window; after this change it has to land inside :387-:393 and be followed by a throw. The prescribed remedy, serializing the stale-dependency classification with the table's DDLGuard, is a rewrite of InterpreterDropNamedCollectionQuery's isTableExist predicate, and #112805 already does exactly that: it takes getDDLGuard(dep.database_name, dep.table_name, nullptr) and re-resolves under it, adds getDetachedDependents, and ends with removeFromSQLIfNoDependencies. InterpreterDropQuery holds that same guard across database->dropTable (:179), so #112805 closes this window; writing it here would rewrite the same function as a live PR.
2 💡 The new test's failpoint is server-global, and no-parallel serializes only within one clickhouse-test process DISAGREE Correct as stated, and the in-tree answer rather than something to change here. The stress runner starts up to min(8, cpu_count()) concurrent clickhouse-test processes against one server (ci/jobs/scripts/stress/stress.py:626,700,930), so a foreign DROP TABLE could consume the one shot in the window between SYSTEM ENABLE FAILPOINT and the test's own drop. That window is two consecutive statements in a single client round trip, and 121 of the 151 in-tree stateless tests that enable a failpoint rely on no-parallel alone, including the neighbouring drop-path point drop_database_before_exclusive_ddl_lock. A REGULAR point would remove my exposure and arm every foreign DROP TABLE for the whole enable window instead, and per-table scoping does not exist: enableFailPoint takes only a name.

Severity: blocker / major / nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Session id: cron:clickhouse-review-slot-8:20260827-172800

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%. SYSTEM ENABLE FAILPOINT drop_table_fail_before_metadata_drop then DROP TABLE t (throws FAULT_INJECTED), then DROP NAMED COLLECTION must still be rejected. Shipped as 05045_drop_table_keeps_named_collection_dependency_on_failure.
b Root cause explained? Yes. In the Kind::Drop branch of InterpreterDropQuery::executeToTableImpl the named-collection dependency was released before database->dropTable, so a dropTable that throws leaves the table's on-disk metadata in place with the dependency already gone; the next DROP NAMED COLLECTION is then wrongly allowed and the following server start cannot attach the table.
c Fix matches root cause? Yes. The ordering hazard is removed rather than compensated for: one call moves after dropTable returns. No retry, no new state, no check at the failure site.
d Test intent preserved / new tests added? Yes. New regression test for the ordering. 04318_remote_storage_engine_access keeps every existing assertion and gains one: it no longer drops the collection without first confirming the table is gone. No test weakened, none skipped, no blanket no-random-* tag added.
e Both directions demonstrated? Yes. With the removal put back before dropTable (failpoint kept in place) the new test fails with "The query succeeded but the server error '769' was expected"; on unpatched master it fails with Cannot find fail point; with the fix it passes. For 04318, replaying the exact mutation from the failing run (DROP TABLE rewritten to DETACH TABLE) the old test passes green while leaving an unloadable table and no collection, and the new one fails loudly and preserves the collection.
f Fix is general across code paths? Yes. All 13 carriers of the invariant enumerated. DROP DATABASE / TRUNCATE DATABASE inherit the fix through the per-table fan-out (executeToDatabaseImpl calls executeToTableImpl); InterpreterRenameQuery already calls renameDependencies after renameTable succeeds, which is the ordering this establishes. The detached-table variant, the isTableExist predicate and the database-engine case are deliberately left to #112805 rather than duplicated. Three residuals are disclosed in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not applicable by construction: the change reorders two statements and inspects no value or type. NamedCollectionFactory::removeDependencies is total over StorageID and handles both the UUID-keyed and the name-keyed path.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or defaulted differently and no serialization or format change, so no SettingsChangesHistory.cpp entry is needed. The only behaviour difference is that a DROP TABLE which throws now keeps the dependency, which is the safe direction.
i Invariants and contracts preserved? Yes. flushAndShutdown and the exclusive table lock still precede the removal. removeDependencies is a non-throwing in-memory erase, so it cannot break the dropTable postcondition, and on the success path the observable end state is identical. The dependency map is rebuilt as tables attach, so a lost in-memory entry self-heals on restart; the on-disk collection deletion it used to permit does not, which is what the ordering now prevents.

Validation: new test and 04318 both 50/50 clean under randomized settings; the whole
named-collection and drop-table test batch was run against this branch and against its base, and
exactly one outcome changes (the new test). shellcheck clean. Debug build, Build ID verified for
every arm.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c95632d]

Summary: ✅


AI Review

Summary

The PR preserves dependencies when DROP TABLE fails before removing metadata and makes named-collection dependency removal allocation-free. Request changes: two existing findings remain because an exception from dropTable can also occur after the table has been irreversibly removed. Reviewed head: c95632d27a9c908eb5c4279df7234fec097a59f3.

Findings

⚠️ Majors

  • src/Interpreters/InterpreterDropQuery.cpp:416: Restore catalog dependencies only when the table survives. In DatabaseOnDisk::dropTable, the cleanup at src/Databases/DatabaseOnDisk.cpp:456–464 runs outside the rollback block, after detaching the table and renaming its live metadata. An I/O exception there reaches this unconditional restore. For an Ordinary dictionary sourced from another table, that recreates a loading-dependency edge for a nonexistent dictionary; dropping its source is then incorrectly rejected with HAVE_DEPENDENT_OBJECTS. Distinguish committed drops from rolled-back drops before restoring edges, or make cleanup after the commit non-throwing while retaining retryable cleanup. Existing thread.

  • src/Interpreters/InterpreterDropQuery.cpp:421: Remove named-collection edges when the old table is gone. The same post-commit cleanup exception skips this call, leaving the old name-based edge. Recreating that Ordinary table name with ENGINE = Memory makes DROP NAMED COLLECTION reject a collection the replacement table never used: its stale-edge filter sees the replacement name as an existing dependent. Run dependency removal for committed drops even when subsequent cleanup reports an exception. Existing thread.

Tests
  • ⚠️ 05045_drop_table_keeps_dependencies_on_error.sh injects failure before entering dropTable; it cannot detect either post-commit regression. Add a focused Ordinary case that injects a cleanup exception after metadata removal, then verifies the dictionary's source remains droppable and recreating the old table name does not falsely protect the named collection.
Final Verdict

Status: ⚠️ Request changes. Distinguish committed drops from failures that preserve the table, apply both dependency updates accordingly, and cover the post-commit failure path. Both findings already have inline threads; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @tuanpach, could you review this? In the Kind::Drop branch of InterpreterDropQuery::executeToTableImpl the named-collection dependency was released before database->dropTable, so a dropTable that throws left the table metadata on disk with its dependency already gone, which let the next DROP NAMED COLLECTION delete the collection and stopped every later server start. The change moves that one call after dropTable returns and pins the ordering with a ONCE failpoint test.

The Style check's `functional_tests_check` rejects any test under `tests/queries`
whose path contains "fail" (`ci/jobs/check_style.py:238-239`), so
`05045_drop_table_keeps_named_collection_dependency_on_failure.sh` turned it red.

This is a pure rename of the `.sh` and its `.reference`. The test body, the failpoint
name and the source change are untouched, because the rule matches the path and not
the file content.

Co-Authored-By: Claude Opus 5 <[email protected]>
@@ -363,8 +365,15 @@ BlockIO InterpreterDropQuery::executeToTableImpl(const ContextPtr & context_, AS
table_lock = table->lockExclusively(context_->getCurrentQueryId(), context_->getSettingsRef()[Setting::lock_acquire_timeout]);

DatabaseCatalog::instance().removeDependencies(table_id, check_ref_deps, check_loading_deps, is_drop_or_detach_database);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What do you think about either putting it into a try catch, both DatabaseCatalog::instance().removeDependencies and NamedCollectionFactory::instance().removeDependencies(table_id); or putting them after database->dropTable(context_, table_id.table_name, query.sync); altogether (although for sync it may wait a while, investigate)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The try/catch, for four measured reasons. I built the fixture on this branch using the failpoint it adds.

First, a correction to the reproducer: a materialized view is not enough. With mv ... TO dst, an inner-table MV, a plain view, a Merge table and a Distributed table all reading src, loading_dependencies_table is empty for every one of them and DROP TABLE src succeeds immediately. The default check reads loading_dependencies (check_referential_table_dependencies is off by default) and none of those register there. A dictionary does: with dict1 sourced from src, DROP TABLE src gives Code: 630 HAVE_DEPENDENT_OBJECTS; after DROP DICTIONARY dict1 throws in the window, the dictionary is still present, its edge is gone, and DROP TABLE src then succeeds and destroys the source of a live dictionary. So the bug is real.

Second, on sync: the wait is not inside dropTable. executeToTable calls executeToTableImpl and only then waitForTableToBeActuallyDroppedOrDetached if query.sync, so a call moved after dropTable still finishes before the wait starts. DROP TABLE ... SYNC of a 280 MiB table returned from dropTable in 0.10s. The one exception is a materialized view with an inner table: DatabaseAtomic::dropTable calls dropInnerTableIfAny(sync, ...), which issues a nested sync DROP and does wait inside dropTable.

Third, the reason I would not move them even so: checkTableCanBeRemovedOrRenamedUnlocked does not filter dependents by existence. Measured with no code change, a plain DETACH TABLE usesdict leaves its edge behind, and DROP DICTIONARY dict1 is then refused with Code: 630 ... because some tables depend on it: e1.usesdict, naming a table that is no longer in the catalog. Moving the removal after dropTable creates that same state between the two statements, so it trades a rare wrong-allow for a wrong-refuse, and if the moved call throws the edge leaks until the next restart.

Fourth, the restore fits the existing API exactly: removeDependencies already returns the three vectors, DatabaseCatalog::addDependencies(const StorageID &, const std::vector<StorageID> &, ...) takes exactly those, and DatabaseCatalog.cpp already uses a restore-on-failure idiom around line 1975. It needs an explicit catch (...) { restore; throw; } rather than a SCOPE_EXIT, since a restore that throws while unwinding would terminate.

One note on severity, because it is not symmetric with the named-collection edge: loading_dependencies is rebuilt from metadata at startup, so after a restart the edge is back, DROP TABLE src is refused again and the server starts normally. The named-collection case is worse only because the lost edge lets DROP NAMED COLLECTION delete the collection file from disk. The generic ordering is also pre-existing: master has that line in the same place, and a build carrying master's ordering behaves identically on the arm above.

I will add the try/catch here since it is the same function.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Pushed as 3785209. The saved edges are restored in a catch (...) wrapping the failpoint and dropTable, and the regression test gained a dictionary arm that fails without it: on the previous head DROP TABLE t_dep_src returns success instead of HAVE_DEPENDENT_OBJECTS, then UNKNOWN_TABLE because the source is gone. Both halves live in one test file so that two tests cannot consume each other's ONCE failpoint, hence the rename.

Two limits are in the description rather than fixed here, both pre-existing and measured identical with and without this change: a materialized view is unsubscribed by flushAndShutdown before the edges are captured, so a failed drop leaves it disconnected until a restart; and a concurrent drop of the dependency inside the window can still remove it, leaving the restore to re-add a stale edge.

@evillique evillique self-assigned this Aug 27, 2026
The `Kind::Drop` branch removed the table's `DatabaseCatalog` dependency edges
before `database->dropTable`. If anything inside `dropTable` throws, the table
keeps its on-disk metadata while its edges are gone, so a table it depends on can
then be dropped even though `check_table_dependencies` is on by default.

Reproduced with a dictionary, which is what registers a loading dependency: with
`dict1` sourced from `src`, `DROP TABLE src` is refused with
`HAVE_DEPENDENT_OBJECTS`, and after `DROP DICTIONARY dict1` throws in that window
the dictionary is still present, its edge is gone, and `DROP TABLE src` succeeds
and destroys the source of a live dictionary. A materialized view is not enough:
materialized views, plain views, `Merge` and `Distributed` register nothing in
`loading_dependencies`, which is the graph the default check reads.

The edges are restored on the exception path rather than removed after
`dropTable`, because `checkTableCanBeRemovedOrRenamedUnlocked` does not filter
dependents by existence: holding them across `dropTable` would refuse a
concurrent drop of the dependency while naming a table no longer in the catalog,
and would leak them until the next restart if the moved call threw. An explicit
`catch` is used rather than a scope guard because a restore that threw while
unwinding would terminate. If `dropTable` throws after the metadata rename the
restore leaves stale edges until the next start, which is the safe direction: a
wrong refusal is recoverable, a wrong permission destroys data.

Unlike the named-collection dependency this one is rebuilt from metadata at
startup, so losing it never prevents the server from starting.

The regression test covers both halves in one file so that two tests cannot
consume each other's `ONCE` failpoint; it is renamed accordingly.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c95632d27 with master e4f63d9ce (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5ed71d8a8; 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.

Compile time of recompiled translation units

9 translation units recompiled, 22 s compile time in total, 9 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 37852095bdc1b97a31a700bde67f8e8b8f4a99d1

CI is fully finished on this head: 174 unique check-runs, 155 success, 18 skipped by digest, one
failure. Config Workflow, Style check, Code Review and Finish Workflow are all success.
The failure has an owner and is not caused by this PR, whose diff is the named-collection
dependency ordering in InterpreterDropQuery plus its regression test.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Logical error: The metadata stream of AlignStreams ended before all data stream rows were matched (STID 0250-329b) trunk logical error in the streaming read plan, aborting the server at src/Storages/MergeTree/Streaming/ReadingPlan/AlignStreams.cpp:333 from AlignStreamsProcessor::work. The signature first appears 2026-08-26 and measures 14 CIDB rows over 14 distinct PRs, so it is not specific to this branch, which touches nothing under src/Storages/MergeTree/Streaming fixing PR #116531 (external, open)

The two Bugfix validation (functional tests, amd64/aarch64) FAIL rows for
04318_remote_storage_engine_access are not failures. They carry check_status = success, the
documented inversion where this PR's regression test is expected to fail against the master binary,
which is the proof the bug reproduces.

Session id: cron:our-pr-ci-monitor:20260828-033000

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

The only conflict is in `04318_remote_storage_engine_access.sh`, and it is resolved
by taking master's side whole.

This branch pinned that test's `DROP TABLE` with
`SETTINGS ignore_drop_queries_probability = 0, ast_fuzzer_runs = 0` and then asserted
the table was gone before the collection was dropped. Since then `e71a2e2ff65d7`
landed the same protection on master as `SET ast_fuzzer_any_query = 0`, which covers
the fuzzed `DETACH` that was the only channel able to strand the collection
reference: a `DROP` skipped or rewritten by `ignore_drop_queries_probability` returns
before `removeDependencies`, so the table keeps its edge and the following
`DROP NAMED COLLECTION` is refused rather than stranding anything.

Keeping this branch's version would therefore re-add an
`ignore_drop_queries_probability` pin that master no longer uses (ClickHouse#113117 removed the
carriers) for a channel master already covers, so the whole hunk goes, and the two
`.reference` lines that only existed for its assertion go with it.

`04318` is now byte-identical to master and drops out of this pull request. The
source fix and `05045_drop_table_keeps_dependencies_on_error` are unchanged; the
failpoint entry re-applied on top of master's current `FailPoint.cpp` list without
displacing any of the entries added upstream since this branch was cut.

Co-Authored-By: Claude Opus 5 <[email protected]>
DROP TABLE now prunes the collection edge only after database->dropTable
has removed the table metadata, so a throw inside
NamedCollectionFactory::removeDependencies can no longer be undone: the
drop has already committed, and an exception there would report a failure
for a table that is gone.

The name-based branch (non-Atomic databases: Ordinary, persistent MySQL,
persistent PostgreSQL) had two allocation sites on that path, either of
which can throw under memory pressure: a std::vector of the iterators to
erase after the scan, and a lookup key that copied both name strings.
Erasing in place while walking the range, keyed by a tuple of references,
removes both. boost::multi_index invalidates only the erased element's
iterator, so the range's end survives the loop; the library's own
erase(first, last) is written the same way.

03822_named_collection_drop_dependency_check asserted the erase with a
DROP NAMED COLLECTION issued after the DROP TABLE, which passes even when
the edge is left behind, because InterpreterDropNamedCollectionQuery
prunes edges whose dependent table no longer exists. Recreating the table
name before that assertion makes it bite: with the erase disabled the
test fails with NAMED_COLLECTION_IS_USED, and it passes both with the
previous implementation and with this one.

Co-Authored-By: Claude Opus 5 <[email protected]>
}
/// Only once the metadata is gone: a `dropTable` that throws leaves the table on disk, and it
/// is attached again at the next start, so it must keep blocking `DROP NAMED COLLECTION`.
NamedCollectionFactory::instance().removeDependencies(table_id);

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.

database->dropTable is not a pure "metadata still survives" step on non-Atomic engines. DatabaseOnDisk::dropTable can still throw after replaceFile has already moved the metadata out of the live name and detached the table (src/Databases/DatabaseOnDisk.cpp:400-429), for example from the removeRecursive / removeFileIfExists cleanup at the end.

When that happens this line is skipped even though the old table name is already gone, so the name-based named-collection edge survives. Recreating the same Ordinary table name then makes DROP NAMED COLLECTION fail for a table that no longer uses the collection, which is the same stale-edge shape 03822_named_collection_drop_dependency_check.sh now checks on the success path.

Can we either make DatabaseOnDisk::dropTable non-throwing once the metadata rename has committed, or let the caller distinguish post-commit exceptions so NamedCollectionFactory::removeDependencies still runs after the old name is irreversibly gone?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - be3b112c935cf1d90a41588019f42374c73185fa

CI is fully finished on this head: 172 unique check-runs, 153 success, 18 skipped by digest, one
failure. Config Workflow, Style check, Code Review and Finish Workflow are all success.
The single failure has an owner and is not caused by this PR, whose diff is the named-collection
dependency ordering in InterpreterDropQuery, one failpoint and three stateless tests: it touches
nothing under src/Processors or src/AggregateFunctions.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 (STID 2270-38be) trunk logical error that aborts the server on a chunk whose port header is k UInt64, s AggregateFunction(countResample(10, 5, 1), UInt64, UInt64): an empty -Resample range serializes to a zero-byte state, the reader returns 0 rows for it and StorageLog then drops the column, so a 1-column chunk reaches a 2-column port. First seen 2026-09-13 20:20Z and since measured on unrelated branches and once on true master, so it is not specific to this branch. Tracker: issue #119727 fixing PR #119728 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The two Bugfix validation (functional tests, amd64/aarch64) FAIL rows for
03822_named_collection_drop_dependency_check are not failures. They carry
check_status = success, the documented inversion where this PR's regression test is expected to
fail against the master binary, which is the proof the bug reproduces.

Session id: cron:our-pr-ci-monitor:20260914-203131

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Dear @evillique, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

The test arms the drop_table_fail_before_metadata_drop fail point, and
the failpoint_tests_are_isolated style rule (67965ab) now requires
every stateless test that enables a fail point to be tagged both
no-parallel and no-fasttest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
{
/// The table keeps its metadata and is attached again at the next start, so it must keep its
/// dependencies: without them a table it depends on can be dropped while it still needs it.
DatabaseCatalog::instance().addDependencies(table_id, removed_ref_deps, removed_loading_deps, removed_view_deps);

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.

This catch assumes every database->dropTable exception means the table is still alive, but DatabaseOnDisk::dropTable can also throw after the old name is already gone: its removeRecursive / removeFileIfExists cleanup at src/Databases/DatabaseOnDisk.cpp:426-429 runs after the metadata has been renamed out of the live path and after the table is detached from the database.

On that post-commit path, re-adding removed_*_deps resurrects a table that no longer exists in the DatabaseCatalog dependency graphs, so the next DROP TABLE of one of its dependencies is wrongly rejected with HAVE_DEPENDENT_OBJECTS until restart. Can we split dropTable exceptions into rolled-back vs committed, or make the post-rename cleanup non-throwing, before restoring dependencies here?

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9b205353-2eab-4c7e-b8cb-ff4c115961ff
  • MIRAI run: 2a9eb020-6e19-40d1-b732-d64ce9fab396
  • PR check IDs:
    • clickbench_944087_1791759353
    • clickbench_944093_1791759354
    • clickbench_944099_1791759354
    • tpch_adapted_1_official_944111_1791759354
    • tpch_adapted_1_official_944122_1791759354
    • tpch_adapted_1_official_944158_1791759354

alexey-milovidov and others added 2 commits October 17, 2026 03:30
…med-collection-dependency-until-metadata-gone

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…med-collection-dependency-until-metadata-gone

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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants