Repository navigation
Do not apply DROP fault injection to CREATE OR REPLACE internal DROPs - #114420
tiandiwonder merged 4 commits into
Conversation
CREATE OR REPLACE builds the replacement under a temporary _tmp_replace_* name and publishes it by rename. It issues two DROPs internally: cleaning up the temporary table if the statement fails, and dropping the replaced table after the swap. Both take their context from make_drop_context, which did not mark it DDL-internal, so secondary_query was false in InterpreterDropQuery::executeToTableImpl and the ignore_drop_queries_probability gate treated an engine-internal cleanup as a user DROP. Two things follow. If the temporary storage reports storesDataOnDisk() the gate returns without dropping, so a populated _tmp_replace_* table is stranded: it is listed by SHOW TABLES, keeps its data, survives a restart, and one leaks per statement. Otherwise the DROP is rewritten into a TRUNCATE, and the TRUNCATE branch takes lockExclusively under the outer statement's query id while that id already holds read locks on the object, so RWLockImpl::getLock throws "Cannot acquire exclusive lock while RWLock is already locked". That fired twice on master under Stress test (d134c6d, 1033651). The sibling helper make_internal_context in the same function already sets this flag, and so does InterpreterDropQuery::executeDropQuery for the inner table of a materialized view, so the plain CREATE ... AS SELECT path was already immune and only REPLACE was exposed. Setting it restores that symmetry. Fault injection keeps its purpose: user DROPs are still skipped, which the new test pins alongside both leak paths. The read lock that the assertion reports is not identified here. RWLockImpl records only query_id -> count and no thread ids, so the message cannot name the holder. The fix does not depend on it: with no rewrite to TRUNCATE, no exclusive lock is requested at all. ignore_drop_queries_probability defaults to 0, so behaviour is unchanged on any default configuration and no SettingsChangesHistory entry is needed. A Replicated database is unaffected: DatabaseReplicatedTask::makeQueryContext already sets this flag before the entry executes, and Context::createCopy inherits it, so the flag was already true on that path. Measured on both binaries across every reachable CREATE OR REPLACE shape there. Closes ClickHouse#110893
CREATE OR REPLACE VIEW is executed by doCreateOrReplaceTable only when the database engine is Atomic or Replicated. On any other engine it falls through to doCreateTable, whose own replace-view branch drops the existing view in place with a context that was not marked DDL-internal. So that DROP was classified as a user DROP too, and ignore_drop_queries_probability rewrote it into a TRUNCATE. StorageView supports no TRUNCATE, and the single-table Truncate path does not consult supportsTruncate(), so the statement failed with NOT_IMPLEMENTED and the old view survived: worse than the leak the previous commit fixes, and the same defect class, setting and gate. Measured on an Ordinary database with the setting at 1: before, the replace raised "Truncate is not supported by storage View" and SELECT still returned the old definition; after, the new definition is returned. A Memory-engine database reaches the same site with the same outcome. The test's own setup and teardown DROPs now pin the setting to 0. They are ordinary user DROPs, so the injection the test turns on ate them as well and left five objects behind, which made a second run in the same database fail with TABLE_ALREADY_EXISTS. Also corrects the test header: the stranded temporary is listed by SHOW TABLES, so it is not invisible to the user.
The test turns the DROP fault injection on, so its own setup and teardown DROPs were being eaten by it and it pinned the setting to 0 on each of them. DROP DATABASE is structurally exempt from the injection (the flag is computed once from the original statement and carried into every table the recursion visits, InterpreterDropQuery.cpp:214-220,676), so putting every object in a database the test creates and dropping that database at the end needs no pin at all. @rschu1ze is removing that pinning idiom from stateless tests in ClickHouse#113117, so this avoids adding seven fresh occurrences of it. Assertions and the reference file are unchanged: the system.tables predicates follow currentDatabase(), which USE moves to the created database. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 rounds over this branch,
My own cold review of the resulting code found no blockers. I enumerated the invariant's carriers I also noticed, outside this PR's scope, that Severity: ❌ blocker / ⚠ major / 💡 nit. DISAGREE verdicts carry recorded Session id: cron:clickhouse-review-slot-11:20260812-025200 |
Pre-PR validation gate (click to expand)
|
|
Workflow [PR], commit [ddc0de6] Summary: ❌
AI ReviewSummaryThis PR correctly marks the Findings
Final VerdictChanges needed: the main LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code |
|
cc @tuanpach @tavplubix, could you review this? The DROPs |
| /// Don't check dependencies during DROP of the view, because we will recreate | ||
| /// it with the same name and all dependencies will remain valid. | ||
| drop_context->setSetting("check_table_dependencies", false); | ||
| /// A step of one user statement, not a user DROP: `ignore_drop_queries_probability` must not skip it. |
There was a problem hiding this comment.
optional: remove the comment.
| { | ||
| ContextMutablePtr drop_context = Context::createCopy(current_context); | ||
| drop_context->setQueryContext(std::const_pointer_cast<Context>(current_context)); | ||
| /// Steps of one user statement, not user DROPs: `ignore_drop_queries_probability` must not skip them. |
There was a problem hiding this comment.
optional: remove the comment
| ContextMutablePtr drop_context = Context::createCopy(current_context); | ||
| drop_context->setQueryContext(std::const_pointer_cast<Context>(current_context)); | ||
| /// Steps of one user statement, not user DROPs: `ignore_drop_queries_probability` must not skip them. | ||
| drop_context->setDDLOrOnClusterInternal(true); |
There was a problem hiding this comment.
This still leaves the same invariant broken for refreshable materialized views. After both the success and failure paths in RefreshTask::executeRefreshUnlocked (src/Storages/MaterializedView/RefreshTask.cpp:1444-1472), StorageMaterializedView::dropTempTable builds an ASTDropQuery::Drop and runs InterpreterDropQuery(drop_query, refresh_context) without refresh_context->setDDLOrOnClusterInternal(true) (src/Storages/StorageMaterializedView.cpp:750-773). With ignore_drop_queries_probability enabled, that cleanup DROP is still treated as a user DROP, so on-disk targets can be skipped and leaked as the stale .tmp... table after a refresh. This needs the same internal flag (or the shared InterpreterDropQuery::executeDropQuery helper) before the PR's “internal cleanup DROPs are not fault-injected” contract is actually complete.
There was a problem hiding this comment.
The mechanism is right: createRefreshContext never sets the flag, so
dropTempTable's cleanup DROP is fault-injectable the same way.
I am not fixing it here. It is a different statement (a background refresh, not
CREATE OR REPLACE), a different subsystem, and outside this PR's frozen
changelog entry. I also have no user-runnable input with an observed
before/after for it, only a code reading, so I am not filing it as work either.
Stated here so it is on the record; already disclosed in the adjudication
comment above.
There was a problem hiding this comment.
Will do. Opening a follow-up PR for the dropTempTable path.
To be explicit about why the existing is_refreshable_view exemption in InterpreterDropQuery does not already cover it: that check dynamic_casts the table being dropped to StorageMaterializedView, but dropTempTable drops the inner .tmp... target table, not the view, so the cast is null and the injection gate applies to both call sites in RefreshTask::executeRefreshUnlocked (the success and the failure path).
I will post the PR link here once it is up, with a regression test that shows the stale .tmp... target leaking on master and gone with the fix, and that a genuine user DROP is still skipped so the setting keeps working.
There was a problem hiding this comment.
Follow-up is open: #114622.
It carries a regression test whose three positive arms (refresh success path, refresh
failure path, Replicated database) leak the stale .tmp.inner_id.<uuid> on master and
are clean with the fix, plus a fourth arm asserting a genuine user DROP is still
skipped, so ignore_drop_queries_probability keeps doing what it is for.
One thing worth flagging, since it is not the one-liner this looked like: marking the
refresh context internal breaks the refresh outright in a Replicated database. The
publishing RENAME runs on that same shared context, and tryEnqueueReplicatedDDL
rejects a non-initial query unless the interpreter also passes flags.internal, which
neither the Rename nor the Drop interpreter did. So the internal intent goes on the
interpreter instead, mirroring the member InterpreterCreateQuery already has.
Requested inline by @ tiandiwonder on the PR. Both restated what setDDLOrOnClusterInternal(true) already says on the next line, and both took their meaning from the defect being fixed rather than stating a local invariant. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - ddc0de6Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All other 175 checks are green or skipped (157 success / 17 skipped / 1 failure). Session id: cron:our-pr-ci-monitor:20260812-120000 |
3b9bc03
`ignore_drop_queries_probability` exists to make a *user* `DROP TABLE` silently do
nothing (or become a `TRUNCATE`) so the stress suite exercises the case where the
table you asked to drop is still there. It must only ever hit statements the user
issued.
`StorageMaterializedView::dropTempTable` is engine-internal cleanup: after a
refreshable materialized view swaps in a freshly built target, it drops the
rotated-out old one. It ran `InterpreterDropQuery` on `refresh_context`, and
`createRefreshContext` never marks that context internal, so `secondary_query` was
false at the injection gate and the cleanup DROP was treated as a user DROP. The
gate's existing refreshable-view exemption does not cover this: that test inspects
the table *being dropped*, which here is the inner target rather than the view, so
the cast yields null. Both exits of `RefreshTask::executeRefreshUnlocked` are
affected, the successful one and the failure one.
When the injection fired, the rotated-out target survived under its internal
`.tmp.inner_id.<uuid>` name, still holding a full copy of the view's data, absent
from the view's metadata, unreferenced by anything that would reap it, and present
again after a restart. For a target that stores no data on disk the DROP was
rewritten to a TRUNCATE instead, leaving the same orphan minus its rows.
Carry the internal intent on the interpreter, mirroring the `internal` member
`InterpreterCreateQuery` already has, and set it only on this one DROP; the shared
`refresh_context` is left untouched. Marking that context instead is the smaller
diff and it is wrong: the publishing RENAME of the same refresh runs on it, and
`DatabaseReplicated::tryEnqueueReplicatedDDL` rejects a non-initial query unless the
interpreter also passes `flags.internal`, which neither the Rename nor the Drop
interpreter did. That asymmetry is why the equivalent one-liner was safe for the
CREATE OR REPLACE sites and is not safe here. Copying the context is worse still,
since a copy loses the parent table UUID, the DDL cancellation token and the
enqueue checks that a lagged replica needs to skip stale temp-table entries.
Passing `QueryFlags{ .internal = internal }` at the replicated enqueue is neutral
for every other DROP: `internal` defaults to false and all three `QueryFlags`
members default, so it equals the `{}` it replaces.
Requested by tiandiwonder as a follow-up to #114420, which established the same
invariant for the DROPs that CREATE OR REPLACE issues internally.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
CREATE OR REPLACEleaking an internal_tmp_replace_*table, andCREATE OR REPLACE VIEWfailing withNOT_IMPLEMENTED, whenignore_drop_queries_probabilityis set. The DROPs it issues internally are steps of one user statement, so DROP fault injection no longer applies to them.Description
Closes: #110893
Related: #110971
CREATE OR REPLACEbuilds the replacement under a temporary_tmp_replace_*name and publishes it by rename. It issues two DROPs internally: cleaning up that temporary table if the statement fails, and dropping the replaced table after the swap. Both took their context frommake_drop_context, which did not mark it DDL-internal, soInterpreterDropQuerytreated them as user DROPs and injected faults.Two things follow. If the storage keeps data on disk the DROP is skipped outright and a populated
_tmp_replace_*table is stranded: listed bySHOW TABLES, holding its data, surviving a restart, one per statement. Otherwise (a materialized view, say) the DROP is rewritten toTRUNCATE, whose branch takes an exclusive lock under the outer statement's query id while that id already holds read locks, raisingRWLockImpl::getLock(): Cannot acquire exclusive lock while RWLock is already locked. That fired twice on master, underStress test (amd_tsan)andStress test (arm_debug).A third internal DROP is misclassified the same way.
CREATE OR REPLACE VIEWuses that machinery only onAtomicorReplicated; other engines drop the view in place throughdoCreateTable.StorageViewimplements noTRUNCATE, so there the rewrite fails the statement withNOT_IMPLEMENTEDand the stale view survives.The fix marks both contexts DDL-internal, as the sibling helper in the same function and
InterpreterDropQuery::executeDropQueryalready do; that asymmetry is why plainCREATE ... AS SELECTwas immune and only REPLACE was exposed. User DROPs are still skipped, which the new test pins. The setting defaults to 0, so a default configuration is unaffected. The read lock the assertion reports is not identified; the fix does not depend on it, since without the rewrite nothing requests an exclusive lock.Validation
04796_create_or_replace_internal_drop_not_ignoredfails on master and passes with the fix, on every shape it covers.CREATE OR REPLACE TABLE ... AS SELECTover MergeTree takes the skip path (stray_tmp_replace_*count accumulates 1, 2, 5, 6 on master);CREATE OR REPLACE MATERIALIZED VIEW ... POPULATEtakes the rewrite-to-TRUNCATEpath;CREATE OR REPLACE VIEWon a non-Atomic database fails on master withTruncate is not supported by storage View, leaving the stale definition readable. Failure path, success path (which leaks the replaced table), and repeated replaces all covered.03013_ignore_drop_queries_probability,00916_create_or_replace_viewand01866_view_persist_settings: 200/200. Same for04492,04524,04326,04328on the first binary: 200/200.create_or_replace/replace_table/tmp_replace/create_as_select, plus a focused sweep of the 14 that reach the view site: each removes exactly one failure (the new test) and introduces none.Common.RWLock*unit tests pass.CREATE OR REPLACEshape: no change, noINCORRECT_QUERY. That path already marks the context internal (DatabaseReplicatedTask::makeQueryContext), so the fix is a no-op there.Version info
26.8.1.1308(included in26.8and later)