Skip to content

Do not apply DROP fault injection to CREATE OR REPLACE internal DROPs - #114420

Merged
tiandiwonder merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-cor-cleanup-drop-internal
Aug 13, 2026
Merged

tiandiwonder merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-cor-cleanup-drop-internal

Conversation

@groeneai

@groeneai groeneai commented Aug 12, 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):

Fixes CREATE OR REPLACE leaking an internal _tmp_replace_* table, and CREATE OR REPLACE VIEW failing with NOT_IMPLEMENTED, when ignore_drop_queries_probability is 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 REPLACE builds 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 from make_drop_context, which did not mark it DDL-internal, so InterpreterDropQuery treated 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 by SHOW TABLES, holding its data, surviving a restart, one per statement. Otherwise (a materialized view, say) the DROP is rewritten to TRUNCATE, whose branch takes an exclusive lock under the outer statement's query id while that id already holds read locks, raising RWLockImpl::getLock(): Cannot acquire exclusive lock while RWLock is already locked. That fired twice on master, under Stress test (amd_tsan) and Stress test (arm_debug).

A third internal DROP is misclassified the same way. CREATE OR REPLACE VIEW uses that machinery only on Atomic or Replicated; other engines drop the view in place through doCreateTable. StorageView implements no TRUNCATE, so there the rewrite fails the statement with NOT_IMPLEMENTED and the stale view survives.

The fix marks both contexts DDL-internal, as the sibling helper in the same function and InterpreterDropQuery::executeDropQuery already do; that asymmetry is why plain CREATE ... AS SELECT was 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
  • New test 04796_create_or_replace_internal_drop_not_ignored fails on master and passes with the fix, on every shape it covers.
  • All three sites covered by shape: CREATE OR REPLACE TABLE ... AS SELECT over MergeTree takes the skip path (stray _tmp_replace_* count accumulates 1, 2, 5, 6 on master); CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE takes the rewrite-to-TRUNCATE path; CREATE OR REPLACE VIEW on a non-Atomic database fails on master with Truncate 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.
  • 50 randomized runs each, on the final binary, of the new test, 03013_ignore_drop_queries_probability, 00916_create_or_replace_view and 01866_view_persist_settings: 200/200. Same for 04492, 04524, 04326, 04328 on the first binary: 200/200.
  • A/B sweep of the 41 tests matching 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.
  • All 8 Common.RWLock* unit tests pass.
  • Replicated databases measured on both binaries across every reachable CREATE OR REPLACE shape: no change, no INCORRECT_QUERY. That path already marks the context internal (DatabaseReplicatedTask::makeQueryContext), so the fix is a no-op there.

Version info

  • Merged into: 26.8.1.1308 (included in 26.8 and later)

groeneai and others added 3 commits August 11, 2026 18:45
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]>
@groeneai

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

Pre-publication review by an independent model (engine: codex; 3 rounds over this branch,
5 findings; plus my own cold review of the resulting code).

# Sev Finding Verdict Evidence / action
1 ❌ Non-Atomic CREATE OR REPLACE VIEW still injects faults into its internal DROP (InterpreterCreateQuery.cpp:2232-2247) AGREE, fixed @ 1274e46 Second site marked DDL-internal. Measured: on the one-site build the arm failed Code: 48 Truncate is not supported by storage View, and the stale view survived; fixed build returns the new definition. Branch witness in the server log: 1 rewrite on base, 0 with the fix
2 ❌ The regression test fault-injected its own teardown DROPs, so it leaked its own objects AGREE, fixed @ 3f88626 Rewritten to keep every object in databases it creates itself, removed by one DROP DATABASE, which the injection gate structurally exempts (InterpreterDropQuery.cpp:214-220). Zero ignore_drop_queries_probability = 0 overrides remain. Negative control: with a plain DROP TABLE instead, 5 objects leak
3 💡 The test's comment claimed leaked _tmp_replace_* tables are invisible to users AGREE, fixed @ a76740f They are listed by SHOW TABLES; comment now says so, matching the test's own oracle
4 ⚠ The remaining database-mode exclusion tags are unnecessary now that the test owns its databases DISAGREE Both are load-bearing. no-replicated-database also gates ON CLUSTER prefixing (clickhouse-test:855-858), and the materialized-view arm uses POPULATE, which InterpreterCreateQuery.cpp:1908-1922 rejects with Code: 344 SUPPORT_IS_DISABLED on a Replicated database. Same tag additionally gates the shared-catalog and cloud modes at clickhouse-test:2979 and :2824. no-ordinary-database is a no-<build_flag> tag (:3024, flag set at :5145 from the server's allow_deprecated_database_ordinary), so it tracks a server profile, not what engine the test's own CREATE DATABASE picks. Precedent: 01148_zookeeper_path_macros_unfolding.sql keeps the tag and creates its own Ordinary database
5 💡 The intended description did not use full GitHub URLs for its issue links AGREE, fixed pre-publication Self-inflicted while condensing the body; restored, and this gate pass was re-run against the corrected description rather than published over a stale one

My own cold review of the resulting code found no blockers. I enumerated the invariant's carriers
independently (every reader of the context flag this PR sets) and confirmed the only one that can
change a DROP's behaviour besides the intended gate is
DatabaseReplicated::tryEnqueueReplicatedDDL, which is unreachable here: a replicated
CREATE OR REPLACE only ever runs as a DDL-log entry, whose context already sets both this flag
and the replicated-internal client flag, and the latter short-circuits shouldReplicateQuery. On
that path the flag was therefore already set before this change, which is why the measurements
there show no difference.

I also noticed, outside this PR's scope, that StorageMaterializedView::dropTempTable builds its
DROP from a context that is not marked internal either, so a refreshable view's stale target table
can still be skipped by the same injection. It belongs to a different feature and I have not
reproduced it, so I am not raising it here.

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

Session id: cron:clickhouse-review-slot-11:20260812-025200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no thread fuzzer or concurrency needed: SET ignore_drop_queries_probability = 1, then a CREATE OR REPLACE TABLE ... AS SELECT throwIf(number = 50, 'stop') ... with one row per block so the statement fails after the temporary table is created and populated. SELECT count() FROM system.tables WHERE name LIKE '%tmp_replace%' is 1 on master, 0 with the fix.
b Root cause explained? make_drop_context in doCreateOrReplaceTable did not mark its context DDL-internal, so secondary_query was false in InterpreterDropQuery and the ignore_drop_queries_probability gate treated an engine-internal cleanup DROP as a user DROP: it either returned without dropping (storage stores data on disk) or rewrote the DROP into a TRUNCATE, whose exclusive lock under the outer query id collides with the read locks that id already holds.
c Fix matches root cause? Yes. It corrects the mis-classification at the layer that owns it, rather than widening a bound, tagging a test, or guarding the throw site.
d Test intent preserved / new tests? New test 04796_create_or_replace_internal_drop_not_ignored. No existing test weakened or removed; 03013_ignore_drop_queries_probability still passes 50/50. The new test also pins the setting's real contract, that a user DROP is still skipped.
e Demonstrated both directions? Yes, via clickhouse-test, same config and a freshly wiped data dir per arm, server buildId() asserted against each binary: the test FAILS on pristine master (stray count 1, 2, 5, 6) and PASSES with the fix.
f General, not a narrow patch? Three internal-DROP sites reach the gate, and all three are fixed. make_drop_context has exactly two call sites, both in doCreateOrReplaceTable (the catch-block temporary cleanup and the post-rename drop of the replaced table); both were measured to leak on master and both are fixed by one line. The third is the CREATE OR REPLACE VIEW branch of doCreateTable, which a non-Atomic database reaches instead of doCreateOrReplaceTable: there the rewritten DROP lands on StorageView, which supports no TRUNCATE, so the replacement failed outright with NOT_IMPLEMENTED and the old view survived. Measured before and after on an Ordinary database. The two paths that already set this flag (make_internal_context in the same function, and InterpreterDropQuery::executeDropQuery) are unchanged.
g Generalizes across inputs? Both branches of the gate are covered by shape: CREATE OR REPLACE TABLE ... AS SELECT over MergeTree takes the skip path, CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE takes the rewrite-to-TRUNCATE path. Database engines: Atomic (the routed path), Ordinary and Memory (both reach the doCreateTable view branch and were measured to fail identically before the fix), and on a Replicated database every reachable CREATE OR REPLACE shape. Also exercised: the default probability = 0 control, failure and success paths, and repeated replaces. Type wrappers are not implicated (DDL control flow, not expression typing).
h Backward compatible? Yes. ignore_drop_queries_probability defaults to 0, so this path is unreachable on any default configuration and behaviour is byte-identical. No setting is added or changed, so no SettingsChangesHistory.cpp entry is needed.
i Invariants/contracts preserved? Yes. The change only marks a context: no new lock, allocation or error path. The cleanup DROP now really drops, which is what the catch block's own comment already states it must do. Because a real Drop sets uuid_to_wait where a Truncate does not, I checked that this cannot make the cleanup block under database_atomic_wait_for_drop_and_detach_synchronously = 1 (which was set in the failing CI run): 356 ms with the fix vs 355 ms on master, with a 120 s timeout that never fired.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ddc0de6]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Join is supported only for pipelines with one output port, got A and B (STID: 4488-4e11) FAIL cidb

AI Review

Summary

This PR correctly marks the CREATE OR REPLACE cleanup DROPs it touches as DDL-internal and adds focused stateless coverage for the leak / TRUNCATE rewrite regressions. I do not think it is fully complete yet, because the same ignore_drop_queries_probability misclassification still exists in the refreshable materialized view temp-table cleanup path.

Findings

⚠️ Majors

  • src/Storages/StorageMaterializedView.cpp:750-773 and src/Storages/MaterializedView/RefreshTask.cpp:1444 [dismissed by author -- https://github.com/Do not apply DROP fault injection to CREATE OR REPLACE internal DROPs #114420#discussion_r3764096321]: the PR fixes doCreateOrReplaceTable / doCreateTable, but RefreshTask::executeRefreshUnlocked still routes both the success and failure cleanup paths through StorageMaterializedView::dropTempTable, which executes InterpreterDropQuery(drop_query, refresh_context) on a context from createRefreshContext that never calls setDDLOrOnClusterInternal(true). In InterpreterDropQuery, that means the cleanup DROP is still treated as a user DROP whenever ignore_drop_queries_probability fires; for on-disk targets it returns early and leaks the stale .tmp.inner_id.* table. I still consider this real because the current code path is unchanged after the dismissal, and it is the same invariant this PR is fixing elsewhere. Suggested fix: mark the cleanup context DDL-internal before calling InterpreterDropQuery, or route this cleanup through InterpreterDropQuery::executeDropQuery, then add a focused refreshable-MV regression.
Final Verdict

Changes needed: the main CREATE OR REPLACE fix looks correct, but the internal-cleanup-DROP invariant is still broken for refreshable materialized view temp-table cleanup.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @tavplubix, could you review this? The DROPs CREATE OR REPLACE issues internally (its temporary-table cleanup, and the drop of the replaced table after the swap) were built on a context that was never marked DDL-internal, so InterpreterDropQuery classified them as user DROPs and ignore_drop_queries_probability either skipped one outright, stranding a populated _tmp_replace_* table, or rewrote it into a TRUNCATE that asks for an exclusive lock under the outer statement's query id. The same misclassification affects the separate CREATE OR REPLACE VIEW path a non-Atomic database takes.

@tiandiwonder tiandiwonder self-assigned this Aug 12, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Aug 12, 2026
/// 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.

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.

optional: remove the comment.

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.

Removed in ddc0de6.

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

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.

optional: remove the comment

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.

Removed in ddc0de6.

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

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.

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.

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.

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.

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.

@groeneai please fix it in a followup PR.

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.

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.

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.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ddc0de6

Every failure below has an owner: a fixing PR (ours 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
Stress test (amd_tsan) / Logical error: Join is supported only for pipelines with one output port, got 3 and 1 (STID 4488-4e11) chronic trunk bug in QueryPipelineBuilder::joinPipelinesYShaped, not caused by this diff (this PR touches only src/Interpreters/InterpreterCreateQuery.cpp plus its own test); 21 unrelated PRs carry the same STID in 30d, 0 master rows #109393 (ours, open) - it modifies the exact aborting frame src/QueryPipeline/QueryPipelineBuilder.cpp:374

All other 175 checks are green or skipped (157 success / 17 skipped / 1 failure).
Build (arm_release) / Post Hooks shows a CIDB row marked FAIL while the check itself
concluded success - fleet-wide bookkeeping noise on a passing job, not a test failure.
The Config Workflow / Finish Workflow FAIL rows in CIDB belong to the previous head
3f88626385fa, which ran before the can be tested label was applied.

Session id: cron:our-pr-ci-monitor:20260812-120000

@tiandiwonder
tiandiwonder added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit 3b9bc03 Aug 13, 2026
180 of 181 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 14, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Aug 15, 2026
`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.
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RWLockImpl::getLock re-entrant deadlock in CREATE OR REPLACE internal DROP (STID 2043-3c5c)

3 participants