Skip to content

Drop for detached tables - #105499

Open
UberDever wants to merge 96 commits into
ClickHouse:masterfrom
UberDever:morlovsky/feature/drop_detached_tables-v2
Open

UberDever wants to merge 96 commits into
ClickHouse:masterfrom
UberDever:morlovsky/feature/drop_detached_tables-v2

Conversation

@UberDever

@UberDever UberDever commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Experimental Feature

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

Added experimental DROP DETACHED TABLE support, gated by allow_experimental_drop_detached_table, to remove metadata and data for detached tables.

Continues #62490


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

@CLAassistant

CLAassistant commented May 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@UberDever
UberDever force-pushed the morlovsky/feature/drop_detached_tables-v2 branch from b545c7c to d418cf8 Compare May 21, 2026 10:12
@rschu1ze

Copy link
Copy Markdown
Member

For my understanding, why is the feature being "revived" (PR title)?

@UberDever

Copy link
Copy Markdown
Contributor Author

For my understanding, why is the feature being "revived" (PR title)?

It is the revival of this closed PR #62490

@UberDever UberDever changed the title Reviving drop for detached tables Drop for detached tables May 21, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e81f53]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_drop_detached_table/test.py::test_dropped_metadata_rejects_uuid_collision[False] FAIL cidb
test_drop_detached_table/test.py::test_dropped_metadata_rejects_uuid_collision[True] FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

Adds experimental DROP DETACHED TABLE for Atomic and Replicated databases, including delayed cleanup and UNDROP TABLE. Changes are needed: storage reconstruction precedes the old instance's lifetime barrier, can start PostgreSQL replication without guaranteed shutdown, and imposes unrelated privileges on users dropping tables created from table functions. Reviewed head: 9e81f53ac971ca3e69c2da7e1f56f43a86ac752a.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable or build is available, so the reproductions below were traced through current source rather than executed. Focused runtime coverage, including ASan or TSan for the PostgreSQL lifetime path, would close this gap.
Findings

❌ Blockers

  • src/Interpreters/InterpreterDropQuery.cpp:524: Reconstructed PostgreSQL storage starts background work without guaranteed shutdown. The free createTableFromAST helper does not itself call startup; the earlier explanation on the existing lifetime thread was incorrect about that. However, the StorageMaterializedPostgreSQL constructor calls PostgreSQLReplicationHandler::startup, which activates startup_task. A subsequent dependency-check exception or cancellation in prepareDropDetachedTable destroys this temporary storage without calling shutdown. The default destruction destroys nested_table_id and the handler's materialized_storages before the task holders deactivate and join their callbacks, leaving a possible use-after-free. It also resumes replication while the table is supposed to remain detached. Construct a passive cleanup object, or guarantee shutdown before destruction on every exit. Reopened the bot-resolved thread silently with this corrected evidence; no duplicate inline finding was posted.

⚠️ Majors

  • src/Interpreters/InterpreterDropQuery.cpp:523–525: A second storage is constructed before the old detached instance is released. The UUID reservation and waitDetachedTableNotInUse run later in prepareDropDetachedTable. StorageMergeTree constructors already initialize disk paths and load parts. For a writable table with table_disk = true, a long-running read followed by DETACH TABLE t PERMANENTLY; DROP DETACHED TABLE t SYNC fails in acquireTableDiskRoots with BAD_ARGUMENTS, before reaching the intended wait, because the old instance still owns the root. Reserve and wait before reconstruction; avoid constructing a storage merely to enqueue replicated DDL.

  • src/Interpreters/InterpreterDropQuery.cpp:524: The drop grant no longer suffices for persisted table functions. Reconstruction uses the dropping user's context. For metadata from CREATE TABLE t AS file('drop_detached.tsv', 'TSV', 'x UInt64'), createTableFromAST calls ITableFunction::execute, which requires source READ and CREATE TEMPORARY TABLE privileges. A user granted only DROP TABLE ON db.t can drop the attached table but receives ACCESS_DENIED after it is detached. Persisted s3 and other source functions have the same problem. Reconstruct trusted metadata without adding these grants to the drop contract, retaining explicit drop authorization and query-context size/cancellation checks.

Tests
  • ⚠️ Cover cancellation or precommit failure for a detached standalone MaterializedPostgreSQL table using an existing PostgreSQL integration fixture, verifying that reconstruction leaves no running replication tasks and that destruction is safe.
  • ⚠️ Add a focused test holding a writable table_disk table in use across detach, then dropping it synchronously; the drop must reach the cancellable wait before reconstructing storage.
  • ⚠️ Add a stateless access test for a detached CREATE TABLE ... AS file table, with a user granted only the table's drop privilege.
Final Verdict

❌ Block. Guarantee background-task shutdown on all reconstruction exits, move the lifetime barrier before reconstruction, and preserve the drop-only privilege contract. Add the focused regression coverage above.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 21, 2026
Comment thread src/Parsers/ParserDropQuery.cpp Resolved
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
@UberDever
UberDever force-pushed the morlovsky/feature/drop_detached_tables-v2 branch from 00d41ad to 314d0ff Compare May 27, 2026 14:14
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
Comment thread src/Interpreters/DatabaseCatalog.cpp Resolved
Comment thread src/Storages/StorageBuffer.cpp Resolved
@UberDever
UberDever force-pushed the morlovsky/feature/drop_detached_tables-v2 branch from 1817d25 to 9ad6fd0 Compare May 29, 2026 10:51
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@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: 565/598 (94.48%) · Uncovered code

Full report · Diff report

…rop_detached_tables-v2

# Conflicts:
#	docs/en/sql-reference/statements/detach.md
#	docs/en/sql-reference/statements/drop.md
…d_tables-v2' into morlovsky/feature/drop_detached_tables-v2
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9e81f53ac with master 312c31c8b (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

119 object files changed (+131.86 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseAtomic.cpp.o 474.62 KiB 506.85 KiB +32.23 KiB (+6.79%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropQuery.cpp.o 646.90 KiB 674.80 KiB +27.89 KiB (+4.31%)
src/CMakeFiles/dbms.dir/Databases/DatabasesCommon.cpp.o 458.57 KiB 476.42 KiB +17.86 KiB (+3.89%)

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

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.86, programs/clickhouse-keeper ×1.05 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.2 s 16.4 s +10.2 s (+165%)
Compile time of recompiled translation units

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

Job report

@abashkeev abashkeev added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
…rop_detached_tables-v2

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- dropped PR record [email protected]: no such setting in the merged declarations
- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Parsers/ASTDropQuery.cpp Resolved
Comment thread docs/reference/statements/drop.mdx Resolved
Resolve include overlaps and retain the updated DatabaseOrdinary::setMergeTreeEngine declaration alongside detached-table support.

Related: ClickHouse#105499
Include `detached` in `ASTDropQuery::updateTreeHashImpl` with one assertion in the existing hash test. Move detached-table documentation into `ParserDropQuery::getDocumentation` and remove direct generated-page edits.

Related: ClickHouse#105499
Resolve overlapping includes and experimental settings while preserving
`DROP DETACHED TABLE`. Remove the deleted `StatementFactory.h` and
`registerStatements.h` includes from `ParserDropQuery.cpp`.

Related: ClickHouse#105499
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105499&sha=8060d5ccee3e7193cda8da0cd1ab6e6a22cc0681&name_0=PR
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
Preserve per-file startup drop-queue detection together with detached-table UUID recovery.

Related: ClickHouse#105499
Drop inner tables within the replicated metadata transaction after cancellable
preparation. Reject existing UUID mappings when recovering dropped metadata.
Add replicated `TimeSeries` and UUID collision regressions. Update the cancellation
fixture for the current `samples` schema and verify data retention.

Validated the build, 16 integration cases, four stateless tests, the tree-hash
test, startup recovery, and compiled statement documentation.

Related: ClickHouse#105499
CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105499&sha=c97f269a03c6d5e4e4f7963ec35d6f7bb3a22560&name_0=PR&name_1=Style%20check
Comment on lines +523 to +525
auto detached_table
= createTableFromAST(*detached_create, table_id.getDatabaseName(), data_path, getContext(), LoadingStrictnessLevel::FORCE_RESTORE)
.second;

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 — wait for the old detached instance before reconstructing it

createTableFromAST runs before prepareDropDetachedTable, so the second storage is constructed before waitDetachedTableNotInUse has released the old one. StorageMergeTree immediately calls initializeDirectoriesAndFormatVersion and loadDataParts in its constructor; this is not a passive metadata object.

A concrete failure is a writable MergeTree with table_disk = true: start a long-running read, DETACH TABLE t PERMANENTLY, then DROP DETACHED TABLE t SYNC. The old instance still owns the disk root, so the new constructor fails in acquireTableDiskRoots with BAD_ARGUMENTS before the intended wait is reached. For other tables the second constructor can already load/repair the same files while the old instance remains in use.

Please reserve the UUID and complete the cancellable wait before constructing the replacement storage, and cover the table_disk case in a focused regression test.

detached_create->setDatabase(table_id.getDatabaseName());
detached_create->setTable(table_name);
auto detached_table
= createTableFromAST(*detached_create, table_id.getDatabaseName(), data_path, getContext(), LoadingStrictnessLevel::FORCE_RESTORE)

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 — do not require source-read privileges to drop stored metadata

Passing the user's query context into createTableFromAST re-executes table-function access checks for persisted CREATE TABLE ... AS table_function definitions. Its as_table_function branch calls ITableFunction::execute, which checks source READ access and CREATE TEMPORARY TABLE before returning a storage.

For example, have an administrator create t AS file('drop_detached.tsv', 'TSV', 'x UInt64'), grant another user only DROP TABLE ON db.t, and detach t. That user can drop the attached table with the same grant, but DROP DETACHED TABLE db.t now fails with ACCESS_DENIED for READ ON FILE (and then needs CREATE TEMPORARY TABLE as well). The same problem affects persisted s3 and other source table functions.

Please reconstruct trusted stored metadata without imposing source-read/temporary-table grants on the dropping user, while retaining the explicit DROP TABLE check and query-context size/cancellation checks. Add a regression using a user with only the drop grant.

@clickhouse-gh clickhouse-gh Bot added comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Nov 19, 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-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants