Skip to content

Keep database replication running after refused drops and detaches - #127896

Open
aschoube wants to merge 3 commits into
ClickHouse:masterfrom
aschoube:fix/127875-refused-database-replication
Open

aschoube wants to merge 3 commits into
ClickHouse:masterfrom
aschoube:fix/127875-refused-database-replication

Conversation

@aschoube

@aschoube aschoube commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #127875
Related: #123694

InterpreterDropQuery::executeToDatabaseImpl stops database replication before checking whether its tables can be dropped or detached. A refusal then leaves the database attached with its replication worker shut down. For a Replicated database, subsequent DDL fails with DATABASE_REPLICATION_FAILED. For a MaterializedPostgreSQL database, new rows in PostgreSQL silently stop arriving.

Run the existing table refusal checks before stopReplication for databases with replication threads. Remember only the storage whose size check consumed force_drop_table, so its drop does not need the flag a second time; the other tables are checked again after flushAndPrepareForShutdown, as on master. Release the checked tables before stopReplication, because the replication worker may be executing a DROP TABLE ... SYNC that waits until nothing else holds the table. Check database detachability before shutdown, and reject detaching a nonempty MaterializedPostgreSQL database before its replication handler is stopped.

Reproduced and validated with a master-based Debug build, version 26.11.1.1, at ce534743bf1, before and after applying the fix:

Case Before After
Replicated: refuse DROP DATABASE with max_table_size_to_drop = 1, then create another table CREATE TABLE fails with DATABASE_REPLICATION_FAILED DDL succeeds; existing table accepts an insert and contains 1,001 rows
MaterializedPostgreSQL: refuse DETACH DATABASE, then insert 1,000 more rows into PostgreSQL ClickHouse remains at 1,000 rows while PostgreSQL has 2,000 ClickHouse reaches 2,000 rows without a restart
MaterializedPostgreSQL: refuse a size-limited DROP DATABASE, then insert 1,000 more rows into PostgreSQL ClickHouse remains at 1,000 rows while PostgreSQL has 2,000 ClickHouse reaches 2,000 rows without a restart

Added 05452_refused_drop_database_keeps_replication, which also checks a subsequent successful detach/attach and drop and a Buffer table that fills its destination during the drop, test_drop_database_while_worker_drops_table_sync in test_replicated_database, which drops the database while its worker executes a DROP TABLE ... SYNC from another replica, two parameterizations of test_refused_database_drop_keeps_replication in the existing PostgreSQL integration cluster, and 05452_refused_drop_database_access_keeps_replication, which checks DROP DATABASE and DETACH DATABASE by a user who may not drop the table and DROP DATABASE of a table that a dictionary in another database reads. All four regression cases fail without the fix and pass with it.

The patched Debug build, both existing PostgreSQL table attachment/detachment tests, 03362_create_table_after_truncate_replicated_database, and 05325_replicated_database_drop_view_with_time_series_inner_table pass. A separate check verifies that a size-limited database drop authorized by force_drop_table succeeds and consumes the flag once. C++ style, Python lint and Black checks pass.

This does not make database drops transactional: cancellation or an execution-time failure after shutdown has begun can still leave a partially processed database. The related PR addresses the broader table-shutdown ordering.

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 DROP DATABASE refused by access, table size or dependency checks, or a DETACH DATABASE refused by access checks, no longer stops replication of a Replicated or MaterializedPostgreSQL database. An unsupported DETACH DATABASE of a nonempty MaterializedPostgreSQL database is also refused before stopping replication.


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

Check table refusals before stopping database replication, and reject unsupported detaches of nonempty `MaterializedPostgreSQL` databases before shutting down their handler. Preserve one-shot `force_drop_table` checks.

Add regressions for `Replicated` DDL and PostgreSQL replication after refused database operations.

Closes: ClickHouse#127875
@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 labels Oct 27, 2026
@aschoube

aschoube commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai can you do a first level of review

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Disclosure: #123694 is my PR and overlaps with this one (details at the end).

I applied 19777b9 to master a6418d9 and tested a debug build on local servers. Two findings are inline: a hang in stopReplication while this function still holds table references, and a size check that is skipped for a table that grows after the pre-check.

Checked and fine:

  • Refused size drop of a Replicated database: CREATE TABLE afterwards fails with DATABASE_REPLICATION_FAILED on master and works here.
  • force_drop_table with one table over the limit: the database is dropped and the flag is consumed once.
  • DROP DATABASE during a refresh of a refreshable view in a Replicated database: master refuses on the .tmp.inner_id table after dropping .inner_id; this PR refuses before touching any table, and the refresh keeps running.
  • MaterializedPostgreSQL (from the code, I did not run PostgreSQL): detachTable always throws on master, so refusing a nonempty DETACH DATABASE up front changes no outcome. The only other caller of assertCanBeDetached, DatabaseCatalog::detachDatabase, calls it after an empty() check, so the override cannot fire there.
  • Other engines: the only change is the earlier assertCanBeDetached(true) on DETACH DATABASE, the same check master runs at the end.

Overlap with #123694: both edit the else size check in executeToTableImpl and the stopReplication call, and add the same std::set<std::weak_ptr<IStorage>, std::owner_less<>> member, so they conflict textually. Neither covers the other. With each diff applied to the same master: both keep replication after the refused size drop; in the refreshable view case only this PR refuses before the stop (#123694 refuses after it, so DDL then fails with DATABASE_REPLICATION_FAILED); in the Buffer case from the inline comment #123694 refuses (after the stop) and this PR drops the table. From the code: only this PR refuses the MaterializedPostgreSQL DETACH DATABASE and pre-checks access and checkTableCanBeDetached; only #123694 runs the checks before preparing tables for shutdown in databases without replication.

@groeneai

Copy link
Copy Markdown
Collaborator

I re-checked 8aa26b1 (applied to master 2170ef3, debug build) on local servers. Both findings are fixed:

  • Hang: with the steps of test_drop_database_while_worker_drops_table_sync on two local replicas, DROP DATABASE ... SYNC returns within about 1 s after the failpoint is released (3 of 3 runs). With only tables_to_check.clear() removed it is still running after 120 s and finishes only after I kill the worker's DROP TABLE t SYNC, so the test catches it.
  • Size check: 05452_refused_drop_database_keeps_replication matches its reference (3 of 3 runs). With force_drop_table and one table over the limit, or a materialized view whose inner table is over the limit, the database is dropped and the flag is consumed, as on master.

The PR still keeps replication running where it should. DROP DATABASE ... SETTINGS max_table_size_to_drop = 1 on a Replicated database, master 41a73de vs this PR:

Case master 8aa26b1
a table over the limit refused, then CREATE TABLE fails with DATABASE_REPLICATION_FAILED refused, then CREATE TABLE works
two tables over the limit, force_drop_table present drops one, refuses the other, then CREATE TABLE fails refuses before dropping anything, then CREATE TABLE works
refreshable MV with a refresh in progress refused after the refresh is stopped, then CREATE TABLE fails refused, the refresh completes, then CREATE TABLE works
Buffer that flushes into dst during the drop refused, dst keeps 1000 rows, then CREATE TABLE fails same as master

The MaterializedPostgreSQL message and the test tags look good (I read the PostgreSQL change, I did not run it). From my side all four threads can be resolved.

@SmitaRKulkarni SmitaRKulkarni added the can be tested Allows running workflows for external contributors label Nov 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ee72b9f]

Summary: ✅


AI Review

Summary

Reviewed #127896 at ee72b9f11be06886dac87b0b2c60633fb0bb7a87, including all prior discussion and the current code. The change checks database and table refusals before stopping replication in Replicated and MaterializedPostgreSQL databases, preserving one-use force_drop_table authorization. The previous access/dependency regression-coverage finding is addressed by 05452_refused_drop_database_access_keeps_replication. No unresolved findings or new inline findings remain.

Missing context / blind spots
  • ⚠️ Latest-head targeted stateless and integration CI jobs are still pending, and no local ClickHouse binary or build is available. Execution evidence comes from the documented before/after runs in the PR discussion; completed targeted CI would independently confirm those results.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 10, 2026
…'s replication

`DROP DATABASE` and `DETACH DATABASE` by a user who may not drop the table, and `DROP DATABASE` of a table that a
dictionary in another database reads, are refused. The data is kept, and `CREATE TABLE` still works afterwards.
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ee72b9f11 with master b19283523 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.72, programs/clickhouse-keeper ×0.79 (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 _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.0 s 8.8 s +6.0 s (+210%)
programs/clickhouse-keeper _GLOBAL__sub_I_TargetLibraryInfo.cpp 4.8 s 8.9 s +5.1 s (+134%)
Compile time of recompiled translation units

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

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

Job report

@aschoube

Copy link
Copy Markdown
Contributor Author

I have kept tables_to_check.clear() before stopReplication, the size recheck for tables that did not consume force_drop_table, the database-level MaterializedPostgreSQL message, and the tags on 05452_refused_drop_database_keeps_replication. tables_with_checked_drop now holds weak references.

@groeneai could you re-review the current revision and the four still-open threads? Your last check confirmed those four findings were addressed; I have left thread resolution to the reviewer.

@groeneai

Copy link
Copy Markdown
Collaborator

I re-checked ee72b9f. The only change since 8aa26b1, which I checked on 2026-11-10, is the new 05452_refused_drop_database_access_keeps_replication test. tables_with_checked_drop was already a std::set<std::weak_ptr<IStorage>, std::owner_less<>> in 8aa26b1, so the hang and size-check results of that re-check still apply: the set does not keep a table alive across stopReplication, and it is only compared by owner, never locked.

The new test, on a debug build of this PR applied to master 79929b2c:

Build Result
this PR passes 7 of 7 runs
master a33e1c1 fails 3 of 3: the CREATE TABLE after the first ACCESS_DENIED gets DATABASE_REPLICATION_FAILED
this PR without the checkAccess before stopReplication fails 3 of 3 at the first ACCESS_DENIED step, same error
this PR without the checkTableCanBeRemovedOrRenamed before stopReplication fails 2 of 2: both ACCESS_DENIED steps pass, the step after HAVE_DEPENDENT_OBJECTS fails

(Runs that hit my machine's Invalid time zone: zoneinfo/UTC error on every query are not counted.) This matches CI on ee72b9f: Bugfix validation reproduces both 05452 tests on master, and the five flaky checks passed them 50 of 50.

I cannot resolve the four threads: GitHub does not allow it for my account on this PR. As the PR author you can, and from my side all four are addressed. Two of them (the tables_to_check hang and the size check) have no Nit: prefix, so the review-threads gate, back on master since #130509, counts them as blocking: until they are resolved, the next CI run of this PR is limited and its Mergeable Check is red.

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A refused DROP DATABASE or DETACH DATABASE stops the replication of a Replicated or MaterializedPostgreSQL database

3 participants