Skip to content

Refuse RENAME/EXCHANGE of tables while DROP DATABASE is running - #133016

Closed
Marouane-elfadli wants to merge 18 commits into
ClickHouse:masterfrom
Marouane-elfadli:fix-132379-drop-database-vs-rename
Closed

Marouane-elfadli wants to merge 18 commits into
ClickHouse:masterfrom
Marouane-elfadli:fix-132379-drop-database-vs-rename

Conversation

@Marouane-elfadli

@Marouane-elfadli Marouane-elfadli commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #132379
Related: #132599
Related: #123694
Related: #51851
Related: #71333

Supersedes #132599, which I am closing: its branch was based on an old master, so its diff contained unrelated changes. This PR has the same fix on a clean branch, with the review comments of #132599 addressed.

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

A RENAME TABLE or EXCHANGE TABLES of the tables of a database no longer runs concurrently with DROP DATABASE of that database. Before, a table moved to another database during the drop was still shut down by it and stayed read-only (TABLE_IS_READ_ONLY for ReplicatedMergeTree) and unable to merge (MergeTree) until a restart, and an EXCHANGE could make the drop remove the wrong table. Such a rename is now refused with UNFINISHED while the database is being dropped. Closes #132379.

Description

DROP DATABASE collects the storages of the database, calls flushAndPrepareForShutdown on them, then drops them by name. A concurrent RENAME/EXCHANGE could change the tables of the database in between:

  • RENAME TABLE a.t TO b.t moved a prepared table to another database, where it stayed read-only / without merges after the drop succeeded.
  • EXCHANGE TABLES a.t AND b.u made the drop remove the original b.u, while the prepared a.t survived as b.u.
  • RENAME TABLE a.t TO a.t2 made the drop fail with DATABASE_NOT_EMPTY and left the prepared table unusable.

DROP DATABASE already holds getLockForDropDatabase exclusively for the whole collect/prepare/drop phase. The fix makes every RENAME/EXCHANGE take a shared lock on all databases it touches (tryGetLockForRestartReplica) before taking its table guards:

  • while a drop runs, the rename fails immediately with UNFINISHED;
  • a rename already in progress finishes first, because the drop waits for the exclusive lock;
  • the lock is only tried, so there is no lock-order deadlock with the drop.

Changes:

  • InterpreterRenameQuery.cpp: the fix.
  • InterpreterDropQuery.cpp, FailPoint.cpp: one new failpoint, drop_database_holding_drop_lock, a pause point right after prepare_tables, under the lock, used by the test. No behaviour change otherwise.
  • Test 05829_drop_database_blocks_rename: pauses the drop after its tables are prepared, checks that cross-database RENAME/EXCHANGE and an in-database RENAME of its tables are refused with UNFINISHED while a rename inside the other database still works, then checks that the surviving table is writable and mergeable.
  • 01150_ddl_guard_rwr: tolerates the new error code 341 (UNFINISHED), because the test races renames with DETACH DATABASE.

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

@Marouane-elfadli

Copy link
Copy Markdown
Contributor Author

@PedroTadim Hi , I’ve opened this PR. I spent time since yesterday understanding the issue more deeply and reworking the solution with my own approach, using LLM assistance along the way. You were right about having too many failpoints, so I reduced them to one focused failpoint and addressed the previous feedback. Could you take another look and let me know what you think of the new approach? Thanks for your guidance!

@Marouane-elfadli

Copy link
Copy Markdown
Contributor Author

@groeneai take a look on this and give me your opinion about it !

@PedroTadim PedroTadim self-assigned this Nov 19, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Nov 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2504de8]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Nov 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. external Author is not a member of the ClickHouse organization and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Nov 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

I checked the current head (a3aa5adf). It does not build yet, so I applied the PR to current master (6349b3bdc14) with the two build fixes from points 1 and 2 below, built it, and ran the tests with tests/clickhouse-test and randomized settings.

What holds:

  • The fix works. 05829_drop_database_blocks_rename and 01150_ddl_guard_rwr pass 5 out of 5 runs. With the InterpreterRenameQuery.cpp change reverted, both new tests fail 3 out of 3.
  • The thread-local lock reuse fixes the nested TimeSeries rename the bot found. With only the "already held by this thread" check removed, 05829_rename_time_series_inner_tables_vs_drop_database fails 3 out of 3 (rename failed, 5 tables left in src). With the check, it passes. So the nested InterpreterRenameQuery does see the outer locks.

What blocks:

  1. Fast test cannot compile StorageTimeSeries.cpp (error: no member named 'as' in 'DB::SecretString'). Commit a3aa5adf uploaded an older copy of that file. Besides the failpoint, it reverts master's hasSettingsChanges() / getSettingsChanges() / setSettingsChanges() calls in StorageTimeSeries::alter and two documentation links. The diff of that file should only contain the #include, the FailPoints declaration and the pauseFailPoint call.
  2. Commit c9020bab removed PAUSEABLE_ONCE(drop_database_holding_drop_lock) from FailPoint.cpp, but InterpreterDropQuery.cpp still uses it. With point 1 fixed, the link fails with undefined symbol: DB::FailPoints::drop_database_holding_drop_lock.
  3. 05829_rename_time_series_inner_tables_vs_drop_database failed on its first run against a fresh server: a server logs a deprecation warning when it creates its first Ordinary database, and that warning reaches the test's stderr. I set CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal before sourcing shell_config.sh, as 01114_database_atomic.sh does, and the test then passed 5 out of 5 runs on a fresh server.

Smaller: ### Description still lists one failpoint and one test. It does not mention the nested-rename lock reuse, the StorageTimeSeries failpoint or the second test.

I'd rather not give a score. Once these are fixed I see nothing else blocking, and the review and merge decision belong to the maintainers. CI runs again on the next push.

Refactor database locking mechanism during rename operations to use optional locks.
Added a comment regarding database creation warnings and clarified behavior of RENAME and DROP operations.
@Marouane-elfadli

Copy link
Copy Markdown
Contributor Author

@groeneai I think its good right know ! ?

Comment on lines +64 to +65
databases_locked_by_rename.insert(database_name);
locks.emplace_back(database_name, std::move(*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.

[Blocker] Keep thread-local lock ownership consistent when allocation fails

databases_locked_by_rename.insert succeeds before locks.emplace_back, which can throw while allocating the vector or copying the database name. The constructor's catch calls release, but that only erases names already present in locks. The current name therefore stays in the thread-local set after its actual shared lock has been released.

Every later rename on this server thread then takes the contains shortcut for that database without acquiring its mutex, even while DROP DATABASE holds the exclusive lock. This restores the original race: a prepared table can escape the drop, or an exchange can cause the other database's table to be deleted. An isolated allocation-fault reproduction using the helper verbatim confirmed that the stale entry survives and the next construction makes no catalog lock attempt.

Record the lock in locks before publishing its name in the thread-local set, so the existing catch can clean up either insertion failure. Add coverage that injects an allocation failure and verifies that a subsequent rename still acquires the real database lock.

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 781048a68 with master 9c91e34a4 (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

6 object files changed (+26.60 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterRenameQuery.cpp.o 136.81 KiB 159.25 KiB +22.45 KiB (+16.41%)

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

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +1.5 s (+6%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator

I checked the new head (781048a6).

Fixed:

  • Points 1 to 3 from my previous comment. Fast test and the builds pass. Against master, StorageTimeSeries.cpp now only adds the failpoint (I checked the PR merge commit). The TimeSeries test sets CLICKHOUSE_CLIENT_SERVER_LOGS_LEVEL=fatal.
  • The five flaky checks (asan/ubsan, msan, tsan, debug, binary) ran each of the three tests 25 times, and every run passed.

Still open:

  1. The bot's blocker on lines 64-65 is correct. If locks.emplace_back throws, the database name stays in databases_locked_by_rename but its lock is released, so every later rename of that database on this thread skips the lock. I copied the class into a standalone program and injected a std::bad_alloc into emplace_back. With the current order, the next construction made 0 lock attempts and was not refused while the exclusive lock was held. With locks.emplace_back moved before databases_locked_by_rename.insert, it was refused. So swapping these two lines fixes it. The case is hard to reach: with the default min_allocation_size_to_throw_on_memory_limit = 0 the memory tracker never refuses these small allocations, so it takes a real allocation failure or a non-default value of that setting.
  2. ### Description is still the old one. It lists one failpoint and one test, and it does not mention the nested-rename lock reuse, the StorageTimeSeries failpoint or the second test.

Minor: in Files changed, FailPoint.cpp shows 14 more failpoints that are not yours, because the file was uploaded from a newer master. The merge result adds only your two, so this is harmless, but a reviewer may wonder about them.

Moving the lock into execute(), before the table guards, looks fine to me. DROP DATABASE takes the database guard, then this lock, then the table guards, so the order is the same. The rename only tries the lock, so it cannot deadlock with the drop.

Once these two points are fixed, I see nothing else blocking. The review and the merge decision belong to the maintainers.

Comment thread src/Common/FailPoint.cpp Resolved
/// and the nested rename would fail halfway through the outer one.
thread_local std::set<String> databases_locked_by_rename;

class RenameDatabaseLocks

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.

@Marouane-elfadli why did you need to create this class that you call only once?

Removed a fail point for time series renaming and added a new pauseable fail point for silk fiber socket send timeout.
Refactor database locking mechanism in InterpreterRenameQuery.
@Marouane-elfadli

Marouane-elfadli commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@PedroTadim i stop this PR give up i try my best i think GROENAI HE CAN fix this bug
sorry again for wasting your time

@groeneai

Copy link
Copy Markdown
Collaborator

Thanks, I'll take #132379 from here. I'm investigating it and will post the PR link (or my findings) here.

@groeneai

Copy link
Copy Markdown
Collaborator

I opened #133361 for #132379. It builds on the approach of this PR: every RENAME and EXCHANGE try-locks the shared side of restart_replica_mutex for each database it touches and fails with UNFINISHED while DROP, DETACH or TRUNCATE DATABASE holds it exclusively. It has one failpoint, no new class and no try/catch, and the main commit credits you as co-author.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 24, 2026
…s a refresh

Since `Refuse RENAME and EXCHANGE of the tables of a database being dropped`
(ClickHouse#133016) `DROP DATABASE` holds the exclusive side of `restart_replica_mutex`
from listing its tables until it has dropped them, and every `RENAME` and
`EXCHANGE` try-locks the shared side, failing with `UNFINISHED`. The window in
which `test_drop_database_concurrent_exchange` exchanged a table (stopping a
refreshable view that waits for its refresh) is inside that lock, so the
exchange is now refused and the other database's table keeps its own row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 24, 2026
`DROP DATABASE` now refuses a concurrent `RENAME` or `EXCHANGE` of its tables
(ClickHouse#133016), so the window this case exchanged a table in is closed, and its
remaining assertion (the exchange fails with `UNFINISHED`) holds with either
lookup in the pre-flight. `05839_drop_database_refuses_concurrent_rename`
covers that refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DROP DATABASE concurrent with RENAME TABLE to another database leaves the moved table read-only / without merges

3 participants