Skip to content

Keep the tables and the replication usable when DROP DATABASE is refused - #123694

Open
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-refused-drop-database-keeps-tables
Open

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-refused-drop-database-keeps-tables

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

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 or TRUNCATE DATABASE refused because a table exceeds max_table_size_to_drop, a dictionary in another database depends on one of its tables, or a table does not support the current transaction, now drops no table, leaves every table writable and keeps the replication of a Replicated or MaterializedPostgreSQL database running. Before, the tables processed first were dropped, the remaining ReplicatedMergeTree tables rejected INSERT with TABLE_IS_READ_ONLY, the remaining MergeTree tables never merged again, and DDL queries in a Replicated database failed with DATABASE_REPLICATION_FAILED, until a restart. Closes #62933. Closes #74791.

Description

Closes: #62933
Closes: #74791
Related: #120643
Related: #127875

On 26.9, a DROP DATABASE refused by max_table_size_to_drop or by a dependent dictionary leaves ReplicatedMergeTree tables rejecting INSERT (TABLE_IS_READ_ONLY), MergeTree tables failing OPTIMIZE (ABORTED) and a Replicated database failing DDL (DATABASE_REPLICATION_FAILED).

Failing job: Upgrade check (amd_release) on #119598. Its stress phase ran DROP DATABASE IF EXISTS test_7, refused with HAVE_DEPENDENT_OBJECTS; test_7.t_lightweight_mut_3 stayed read-only, so KILL MUTATION failed.

executeToDatabaseImpl stopped the replication and called flushAndPrepareForShutdown on every table, and only then ran the checks that can refuse the drop. The transaction, dependency and size checks now run for all tables first. The replication can change the tables until it is stopped, so they are listed and checked again after the stop. The size check can consume force_drop_table: with the flag and two or more tables over the limit, the statement is refused, consuming the flag; use max_table_size_to_drop = 0 or drop the tables one by one.

Not covered: KILL QUERY during the loop, a missing per-table DROP TABLE grant, a refusal that appears only after refreshable views or the replication were stopped (they stay stopped).

Validation: each refusal route has a case that fails on master and passes here, including a Replicated database. Refreshable views: a running refresh's temporary table does not block the drop; a leftover one refuses it before the stop.

🤖 Generated with Claude Code


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

groeneai and others added 5 commits October 3, 2026 08:58
`InterpreterDropQuery::executeToDatabaseImpl` called `flushAndPrepareForShutdown`
on every table of the database and only then ran, per table, the checks that can
refuse the drop: transaction support, cross-database dependencies
(`checkTableCanBeRemovedOrRenamed`) and `max_table_size_to_drop`
(`checkTableCanBeDropped`). Preparation is irreversible, so when one table refused,
the tables processed before it were already dropped and the remaining ones stayed
prepared but alive: `ReplicatedMergeTree` tables became read-only "due to shutdown"
(INSERT, OPTIMIZE and KILL MUTATION fail with TABLE_IS_READ_ONLY) and `MergeTree`
tables had their merges cancelled forever (OPTIMIZE FINAL fails with ABORTED), until
`SYSTEM RESTART REPLICA`, DETACH/ATTACH or a restart.

In the Upgrade check of ClickHouse#119598 the stress phase ran `DROP DATABASE IF EXISTS test_7`,
which was refused with HAVE_DEPENDENT_OBJECTS because a dictionary in `test_7_1`
reads `test_7.table_for_dict`. That left `test_7.t_lightweight_mut_3` read-only and
the pre-upgrade KILL MUTATION failed.

Run the three deterministic checks for all collected tables before any table is
prepared (and again after the refreshable-MV re-collect), the order DROP TABLE and
DETACH PERMANENTLY already use. `Context::checkCanBeDropped` removes the
`force_drop_table` flag when it authorizes an over-limit drop, so the storages
checked here are remembered by identity and the per-table loop does not check
their size again; a storage swapped in under a checked name is a different object
and is still checked. With the flag and two or more over-limit tables the statement
is now refused before touching any table.

Not covered: KILL QUERY during the loop, a dependent created after the checks, a
missing per-table DROP TABLE grant, and `stopReplication` of Replicated databases.

Closes ClickHouse#62933

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… stops

A refresh in progress of a refreshable materialized view owns a filled
`.tmp.inner_id.<uuid>` table in the same database. `DROP DATABASE` stops such views
before collecting the final list of tables, and stopping the view drops that table
with the size limit disabled, so master never checks its size. The pre-flight added
by the previous commit ran before the views were stopped and size-checked it, so a
`DROP DATABASE` that master accepts was refused with
TABLE_SIZE_EXCEEDS_MAX_DROP_SIZE_LIMIT, or spent `force_drop_table` on the transient
table.

The first pre-flight now runs after the list of views to stop is known and skips the
size check of refresh temporary tables when there are such views; the transaction
and dependency checks stay unconditional. A temporary table that survives the stop
(a leftover of a crashed refresh) is in the re-collected list and is size-checked by
the second pre-flight. The name test is shared with the dependency sort.

New integration case `test_drop_database_during_refresh`: fails on the previous
commit, passes on master and with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…resh

The previous commit skipped the size check of every `.tmp.inner*` table in the
first pre-flight whenever `DROP DATABASE` stops a refreshable view. Only the
temporary table of a refresh that is running is dropped by stopping its view. A
leftover of a crashed or failed refresh next to an idle view survives the stop, so
the second pre-flight refused the statement after the view's refresh task had
been shut down for good: the view stayed registered but no longer refreshed until
restart.

The first pre-flight now skips only `.tmp` + the inner table name of each view to
be stopped whose refresh task is `Running`; the second one skips nothing. The name
helper and the dependency-sort change are reverted.

New integration case `test_drop_database_refused_by_refresh_leftover`: fails on
the previous commit and on master (the view is gone from `system.view_refreshes`
after the refused drop), passes with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit skipped the size check of `.tmp` + the inner table name in
the first pre-flight whenever the view's refresh task was `Running`. That state
is set as soon as an attempt is requested, before the attempt creates (CREATE OR
REPLACE) its temporary table, so a leftover of an earlier failed refresh under
that name was still exempt. Stopping the view does not drop a leftover, so the
second pre-flight refused the statement after the view's refresh task had been
shut down for good.

`RefreshTask` now publishes whether the attempt in progress has created its
temporary table (set right after `prepareRefresh`, cleared when the attempt
returns), and `DROP DATABASE` exempts the name only while that holds.

New integration case `test_drop_database_refused_by_leftover_of_pending_refresh`
(holds the attempt with the `refresh_mv_skip_execution` failpoint): fails on the
previous commit and on master (the view is gone from `system.view_refreshes`
after the refused drop), passes with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the ExecutionState::temp_table_created comment that repeated the accessor's, and fold the pre-flight comment into one line.

Co-Authored-By: Claude Opus 5.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 Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

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

Pre-publication review by an independent model (engine: codex; 4 rounds, 4 findings, the last round clean) plus my own review (5 nits).

# Sev Finding Verdict Evidence / action
1 ❌ The first pre-flight size-checks the temporary table of a refresh in progress, which stopping the view drops without a size check AGREE, fixed @ adec91c integration case test_drop_database_during_refresh
2 ❌ (raised twice) A refusal can come only after refreshable views were stopped; deterministic with a leftover temporary table of an idle view, which the exemption skipped AGREE, fixed @ 8f187a8 a leftover is size-checked before any view is stopped; integration case test_drop_database_refused_by_refresh_leftover
3 💡 With force_drop_table and two or more tables over the limit the flag is consumed and nothing is dropped AGREE stated in the description with the workaround
4 💡 A storage that drops its own inner table through a fresh interpreter re-checks its size (TimeSeries view, MaterializedPostgreSQL) AGREE, noted experimental engines with force_drop_table only; not blocking
5 ❌ (same axis, third round) Running is reported before the refresh has created its temporary table, so a leftover one was still exempt AGREE, fixed @ 2f8704a the refresh task now reports when its own temporary table exists, and only then is it exempt; integration case test_drop_database_refused_by_leftover_of_pending_refresh
6 💡 The pre-flight size check runs before the per-table DROP TABLE privilege check AGREE, noted fails safe: the size guard only gets stricter; the privilege pre-flight is out of scope (see description)
7 💡 The second pre-flight (after the refreshable-view re-collect) has no case of its own AGREE, noted it only matters for a table that appears while views are stopped; the per-table loop keeps every check as the fallback
8 💡 While a refresh is still replacing an over-limit leftover temporary table, a concurrent DROP DATABASE is refused up front AGREE, noted nothing is touched and a retry succeeds; exempting it earlier is finding 5

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

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05320_drop_database_refused_keeps_tables_working fails on every master run (each refusal route isolated: 4/4 runs each), and test_force_drop_table::test_drop_database fails at its first step for both Ordinary and Atomic.
b Root cause explained? executeToDatabaseImpl calls flushAndPrepareForShutdown on all tables, then runs the per-table checks that can refuse the drop (transaction support, cross-database dependency, max_table_size_to_drop). Preparation is irreversible, so on a refusal the tables before the refusing one are already dropped and the rest stay prepared: ReplicatedMergeTree read-only, MergeTree merges cancelled forever.
c Fix matches root cause? Yes. The three deterministic checks run for every table before any is prepared, the order DROP TABLE and DETACH ... PERMANENTLY already use. No un-prepare, no retry, no harness change.
d Test intent preserved / new tests added? New stateless test (dependency, size, TRUNCATE DATABASE, transaction, plus a successful drop) and new integration cases for the size limit, force_drop_table accounting, a DROP DATABASE during a refresh in progress, and two refused by a leftover temporary table of a refreshable view (idle, and with a refresh requested that has not created its own temporary table yet). Existing tests unchanged.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: master fails, fix passes (stateless, integration, and a clickhouse local MergeTree probe: ABORTED vs merged). Deleting each new check reddens exactly its case; making the loop re-check size reddens the force-flag case; size-checking the temporary table of a running refresh reddens the refresh case; exempting it for an idle view reddens the leftover case; exempting it for a refresh that has not created it yet reddens the pending-refresh case.
f Fix is general across code paths? One function serves DROP DATABASE, TRUNCATE DATABASE without TABLES, DETACH DATABASE / read-only disk (transaction check), ON CLUSTER, and the refreshable-MV early prepare (checked before it and again after the re-collect; only a temporary table that the refresh in progress has already created, which stopping the view drops, skips the size check, as on master). TRUNCATE ... TABLES does not prepare tables. Not covered: KILL QUERY mid-loop, missing per-table DROP TABLE grant, Replicated database stopReplication.
g Fix generalizes across inputs (params/datatypes/wrappers)? Database engines Atomic, Ordinary, the Replicated-database test flavour (10/10); ReplicatedMergeTree, MergeTree, dictionary source; drop and truncate; force flag with one and with two over-limit tables. No column types involved.
h Backward compatible? (maintainer-approved exception only) No setting or format change. Intended behaviour change: a refused statement drops no table; with the force flag and two or more over-limit tables it is refused up front (before, the first was dropped and the rest stranded). Error codes unchanged.
i Invariants and contracts preserved? Each storage is size-checked once (identity set of weak_ptr, no strong reference held). The drop-database lock is held across pre-flight and loop. A storage renamed into a checked name is a different object and is checked again. The loop keeps all its checks as the fallback.

Session id: cron:clickhouse-impl-slot-4:20261003-131200

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [046f745]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR checks transaction support, dependencies and table size before preparing a database's tables for shutdown or stopping its replication. The deterministic refusal paths have regression coverage, but the revised force-drop accounting still permits an over-limit table to be deleted without its check consuming the force flag.

Missing context / blind spots
  • ⚠️ Full CI for head 046f745a6a58 is still running. Earlier targeted reports at 50a80db2dce2 show the stateless regression and force-drop integration cases passing; no local server binary is available. The completed current-head CI report will close this validation gap.
Findings

❌ Blockers

  • src/Interpreters/InterpreterDropQuery.cpp:673-679: A force-drop exemption must belong to the table whose check consumed the flag. Here, another table or partition drop can remove the shared file between the two filesystem observations. An under-limit table is then incorrectly exempted; an insert that grows it before shutdown preparation bypasses the final max_table_size_to_drop check, allowing unintended deletion above the limit. Propagate the actual consumption result from the check and add focused concurrent-consumption coverage. This is a remaining path for the existing size-check finding, whose claimed fix is incomplete.
Final Verdict

Status: ❌ Block

Make force-drop exemptions depend on the actual consuming check, and verify that another drop consuming the flag cannot bypass the final size guard.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 3, 2026
/// Last, because it may consume the `force_drop_table` flag.
for (const auto & table : tables_to_check_size)
{
table->checkTableCanBeDropped(table_context);

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.

Because this result is cached in tables_with_checked_size, the later executeToTableImpl path never re-runs checkTableCanBeDropped after prepare_tables() has frozen the tables. That weakens max_table_size_to_drop for ReplicatedMergeTree: a concurrent INSERT can still land between this preflight and flushAndPrepareForShutdown(), grow the table past the limit, and the database drop will still delete it. Can we revalidate the size after the tables are prepared (or otherwise freeze writes before trusting this preflight result)?

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.

🕵 Done in 802b9d8: only the tables whose check consumed force_drop_table are now remembered (detected by the flag file disappearing during their check). Those tables cannot be checked again, because the flag is gone. Every other table is no longer cached, so executeToTableImpl checks its size again after prepare_tables, as on master. A table that grows past the limit in that window is therefore still refused, at the cost of leaving the remaining tables prepared for shutdown (the pre-PR behaviour for that narrow race).

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] The final size-check bypass is still reachable through the new flag detection at src/Interpreters/InterpreterDropQuery.cpp:673-679: disappearance of the server-wide force_drop_table file does not establish that this table consumed it.

For example, with a 1 MiB limit:

  1. The preflight reads that the flag exists for an under-limit a.t.
  2. A concurrent DROP TABLE b.u consumes the flag in another database.
  3. The check of a.t returns because it is below the limit (Context::checkCanBeDropped, src/Interpreters/Context.cpp:9021-9022), but the missing file makes this code insert a.t into tables_with_checked_size anyway.
  4. An INSERT grows a.t above the limit before prepare_tables. The check at InterpreterDropQuery.cpp:403-404 is then skipped, deleting an over-limit table whose drop never consumed the flag.

Please propagate whether the particular check actually used the flag from the consuming operation, instead of inferring ownership from two filesystem observations. Cover consumption by a concurrent table/partition drop as well as the existing serial flag cases.

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.

I am leaving this as is: misattributing the flag needs a second drop that consumes the single-use force_drop_table file during this one size check, plus an INSERT that pushes the table over the limit before prepare_tables. Master accepts the same check-then-drop race (executeToTableImpl checks the size before flushAndShutdown, and the IStorage::checkTableCanBeDropped comment calls a size change during the operation not very important), while propagating the result from the consuming check would change that virtual and its 9 overrides.

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

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 046f745a6 with master d31a6eff9 (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

8 object files changed (+23.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropQuery.cpp.o 722.55 KiB 743.16 KiB +20.61 KiB (+2.85%)

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

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

Job report

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - afb7b5f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the same job is red on master and on 116 PRs in 24h; the clickhouse_fuzzer link outgrows the 2 GiB reach of the small code model #122521 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04653_bloom_filter_fixed_string_constant_scalar not from this PR: a replica receives the Dynamic constant without its active member type, so the FixedString value no longer equals the String one and that replica's rows drop out (1 instead of 3); 14 PRs today #118988 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05213_timeseries_metric_families_target not from this PR: a replica resolves the unqualified timeSeriesMetricFamilies(ts_new) argument in default (UNKNOWN_TABLE); 47 PRs in 48h #118518 (external, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a replica cannot run the SQL SECURITY DEFINER view's read as the definer, so the row policy check fails with ACCESS_DENIED; 58 PRs in 48h #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database: the replicated CREATE VIEW qualifies a nested WITH alias with the database, so the view reads the same-named table; 124 PRs in 48h a fix task is created (fix in progress, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the rows above #122521, #118988, #118518, #123729 and the fix task above
CH Inc sync - CH Inc sync (private, not actionable by me)

None of these touches DROP DATABASE or refreshable views, and 05320_drop_database_refused_keeps_tables_working passed. The six test_force_drop_table FAIL rows under Bugfix validation (integration tests, *) are the expected result: the new tests fail on master, and both validation jobs passed. All 157 checks completed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261003-200032

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@buggins

buggins commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

A DROP DATABASE refused by these checks still leaves a Replicated or MaterializedPostgreSQL database without replication until a restart: executeToDatabaseImpl calls database->stopReplication() before check_tables runs, and nothing starts the replication again when the drop is refused. For example, after DROP DATABASE rr SETTINGS max_table_size_to_drop = 1 is refused, every DDL query in the Replicated database rr fails with DATABASE_REPLICATION_FAILED.

Running check_tables before stopReplication would close this as well. One thing to keep in mind there: until replication is stopped, the DDL worker of a Replicated database (or the replication of a MaterializedPostgreSQL database) can still create tables, so a table could appear between the checks and the stop.

Related: #127875
Related: #127918

…TABASE can proceed

A refused DROP DATABASE of a Replicated or MaterializedPostgreSQL database left
its replication stopped until a server restart: every later DDL query in a
Replicated database failed with DATABASE_REPLICATION_FAILED. The refusal checks
now run before stopReplication. The replication can create, drop and rename
tables until it is stopped, so the tables are listed and checked again after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Keep every table usable when DROP DATABASE is refused Keep the tables and the replication usable when DROP DATABASE is refused Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and fixed in 39fdac4: the checks now run before stopReplication. Since the replication can create tables until it is stopped, the tables are listed and checked again after the stop, and no table is prepared for shutdown before that second check passes.

After a refused DROP DATABASE rr SETTINGS max_table_size_to_drop = 1, and after one refused with HAVE_DEPENDENT_OBJECTS, CREATE TABLE in rr now succeeds; on master both fail with DATABASE_REPLICATION_FAILED. 05320 has a Replicated case for it. Not covered: a refusal caused by a table or dependent that appears while the replication is being stopped still leaves it stopped, as on master.

This also closes #74791. #127896 adds the same checks before stopReplication, so the two PRs now overlap there.

The first list of tables is taken before `stopReplication()`, and the
references to the storages were kept until after it. Stopping the
replication of a `Replicated` database joins its DDL worker; if that worker
is executing a `DROP TABLE ... SYNC` replicated from another replica, it
waits until nobody holds the dropped table, so both waited for each other
until the worker's query was killed.

Measured with two servers (replica B runs `DROP DATABASE` while its DDL
worker, paused by `database_replicated_stop_entry_execution`, executes
`DROP TABLE t SYNC` from replica A): DROP DATABASE hung for more than 60 s
on the previous head, with the worker in `waitTableFinallyDropped` and the
drop in `DDLWorker::shutdown`; with this change it finishes in about 2 s
(3 of 3), as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e60d7bb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, targeted) / test_storage_kafka/test_multi_consumer_quota.py::test_temporary_lock_quota_is_retained_across_rounds not from this PR: the server stopped on a TSan data race inside librdkafka (rd_kafka_toppar_op_version_bump vs an unlocked read in rd_kafka_toppar_handle_Offset on the broker thread while the consumer shuts down). Same race on 2 other PRs and master in 30 days ClickHouse/librdkafka#23 (mine, open)
Integration tests (amd_tsan, targeted) / the other 4 test_multi_consumer_quota.py tests collateral: their setup ran DROP DATABASE IF EXISTS test SYNC against the server that had already stopped (ATTEMPT_TO_READ_AFTER_EOF) ClickHouse/librdkafka#23 (mine, open)
Build profile diff infra, not from this PR: the CI logs cluster rejected every readiness probe (No connection to LogCluster), so the job never compared anything. 189 of 193 runs since 2026-10-26 22:00 UTC are red, on 167 PRs #126200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above ClickHouse/librdkafka#23 and #126200
Sync - CH Inc sync (private, not actionable by me)

The 3 FAIL rows under each Bugfix validation (integration tests, *) job are the expected failures on master (the bug reproduced); both jobs passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-150018

alexey-milovidov and others added 2 commits November 2, 2026 15:33
…DATABASE`

The size check before `prepare_tables` was cached for all tables, so
`executeToTableImpl` did not check them again after
`flushAndPrepareForShutdown`, and an `INSERT` in between could make a
table exceed `max_table_size_to_drop` unnoticed. Now only the tables whose
check consumed `force_drop_table` are skipped later (they cannot be checked
again, because the flag is gone); the others are checked again after they
are prepared for shutdown, as before this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123694&sha=e60d7bb84471e235f3b81bf0fc307ea416a7ea2e&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%20targeted%29 (test_storage_kafka/test_multi_consumer_quota.py, TSan data race in rd_kafka_toppar_op_version_bump, contrib/librdkafka/src/rdkafka_partition.c:204) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to this PR, which only changes DROP DATABASE. The Build profile diff failure is an infrastructure error (LogClusterNotReady).

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Same race as on #101783 and #115453, and the fix is already in progress: ClickHouse/librdkafka#23.

The write is rd_kafka_toppar_op_version_bump (rdkafka_partition.c:204, from rd_kafka_toppar_pause_resume on the librdkafka main thread, under the toppar lock). The read is the unlocked rktp->rktp_op_version in rd_kafka_toppar_handle_Offset (:1516), which the broker thread runs inline when it fails the pending requests of a terminating handle (rdkafka_broker.c:5084). The patch reads the field once, under the lock.

It has been open and mergeable since 2026-10-21, with no review yet. It is based on ClickHouse/v2.15.1, the current pin. #128315 moves the pin to ClickHouse/v2.16.0, which does not have the fix (upstream did not change this function); the patch applies to it unchanged, so if #128315 merges first I'll retarget #23 there. Once #23 merges, I'll send the ClickHouse PR that bumps the submodule.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

ClickHouse/librdkafka#23 is merged, and #129623 bumps contrib/librdkafka to a commit that contains it, so I won't send a separate bump PR.

groeneai and others added 2 commits November 9, 2026 14:35
…gh the query storage cache

`DatabaseCatalog::tryGetTable` goes through `Context::getOrCacheStorage`, which pins
each qualified name to the storage it first resolved to for the rest of the query,
following that storage across a concurrent rename or exchange. The pre-flight checks
ran this lookup before the per-table loop, so the loop's own lookup in
`executeToTableImpl`, made under the table's DDL guard, got the pinned storage instead
of the table that has the name now.

With `EXCHANGE TABLES db1.t AND db2.t` between the pre-flight and the loop (the window
is open while stopping a refreshable view waits for its refresh), `DROP DATABASE db1`
dropped `db2.t` and then failed with `DATABASE_NOT_EMPTY` because `db1.t` was left.
Master never looks the tables up before the loop, so it drops the current `db1.t` and
leaves `db2.t` alone. `DETACH DATABASE` runs the same pre-flight lookup.

Look the table up in the database being dropped, like the dependency sort below does;
that is the lookup `getTableImpl` makes for a name without a UUID, so the storage the
pre-flight remembers for `force_drop_table` is the one the loop finds.

The new integration case parks a refresh where stopping the view cancels it, runs the
exchange while `DROP DATABASE` waits there, and checks that the exchanged table
survives: it fails on the previous head with `DATABASE_NOT_EMPTY` and passes on master
and with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s replaced

With `lazy_load_tables = 1`, a table nobody has read since the database was
attached is a `StorageTableProxy`. The size check of the `DROP DATABASE`
pre-flight loads it and may consume `force_drop_table`, and the exemption was
remembered under the proxy. Since ClickHouse#118699 the database replaces an unused proxy
by its loaded storage on the next lookup, so `executeToTableImpl` got the
loaded storage, missed the exemption and checked the size again without the
flag: an authorized `DROP DATABASE` was refused with
`TABLE_SIZE_EXCEEDS_MAX_DROP_SIZE_LIMIT` after the tables were prepared for
shutdown (merges cancelled).

Record and look up the exemption by `resolveStorageProxy`, the loaded storage
of a lazy proxy, which is what the database replaces it with. An unrelated
storage swapped in under the same name still does not match.

Reported by clickhouse-gh[bot]:
ClickHouse#123694 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 17, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 17, 2026 05:59

AI review of a later commit does not approve the PR, see the AI Review comment.

`StorageRabbitMQ::checkTableCanBeDropped` and `StorageNATS::checkTableCanBeDropped`
set a plain `mutable bool drop_table`. Every caller on master holds the table's DDL
guard, but the pre-flight of `DROP DATABASE` calls the hook while holding only the
database guard, so a concurrent `DROP TABLE` of the same table writes the field and
reads it in `StorageRabbitMQ::shutdown` with no ordering against that write: a data
race.

The value stored is always `true`, so an atomic flag is enough and keeps the
behaviour unchanged. The side-effect-free `checkTableSizeBelowDropLimit` used by
`CREATE OR REPLACE` is not a drop-in replacement here: its materialized view and
`TimeSeries` overrides also check their inner tables, which `DROP DATABASE` checks
as tables of their own, so `force_drop_table` would be consumed twice.

Reported by clickhouse-gh in ClickHouse#123694 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 17, 2026
@stresshouse

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6fc0cdfa-11b2-4d87-bbd0-e6a9df6fb0a1
  • MIRAI run: 8a7f367d-a81e-40c9-bfb1-0160f871a0f9
  • PR check IDs:
    • clickbench_856925_1795381354
    • clickbench_856931_1795381354
    • tpch_adapted_1_official_856945_1795381354
    • tpch_adapted_1_official_856975_1795381354

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

groeneai and others added 3 commits November 24, 2026 00:00
…tabase-keeps-tables

# Conflicts:
#	src/Storages/RabbitMQ/StorageRabbitMQ.h
…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]>
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master and resolved the conflict in StorageRabbitMQ.h (head 046f745). After #133016 the EXCHANGE in test_drop_database_concurrent_exchange is refused while DROP DATABASE runs, so that case no longer tests this PR and I removed it; 05839_drop_database_refuses_concurrent_rename covers the refusal.

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

3 participants