Skip to content

Do not apply DROP fault injection to a refreshable view's cleanup DROP - #114622

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-refreshable-mv-cleanup-drop-internal
Aug 15, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-refreshable-mv-cleanup-drop-internal

Conversation

@groeneai

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

Fixed a refreshable materialized view leaking its rotated-out target table when ignore_drop_queries_probability is enabled. The DROP a refresh issues to clean up the previous target is a step of the refresh, not a DROP the user asked for, so the fault injection no longer applies to it.

Description

Follow-up to #114420, requested by @ tiandiwonder in #114420 (comment).

ignore_drop_queries_probability makes a DROP TABLE silently do nothing (or become a TRUNCATE) so the stress suite exercises "the table you dropped is still there". It must only affect DROPs the user issued.

Root cause. After a refresh swaps in a new target, StorageMaterializedView::dropTempTable drops the rotated-out one via InterpreterDropQuery(drop_query, refresh_context). createRefreshContext never marks that context internal, so the gate treated the cleanup DROP as a user DROP. Its existing refreshable-view exemption does not cover this: that test inspects the table being dropped, which here is the inner target, not the view. Both refresh exits are affected. When it fires, the old target survives as .tmp.inner_id.<uuid> still holding a full copy of the view's data, outside the view's metadata and surviving restart.

The change. InterpreterDropQuery gains an internal member mirroring the one InterpreterCreateQuery already has, dropTempTable sets it, and the shared refresh_context is untouched. Marking that context instead would break the refresh outright in a Replicated database: the publishing RENAME runs on it, and DatabaseReplicated rejects a non-initial query unless the interpreter also passes flags.internal, which neither the Rename nor the Drop interpreter did. That is why #114420's one-liner was safe there and is not here. QueryFlags{ .internal = internal } at the replicated enqueue is behaviour-neutral for every other DROP, since all its members default to false. The interpreter's other policy branches (ON CLUSTER dispatch, access and dependency checks) deliberately keep applying.

Validation. New test 04887_refreshable_mv_cleanup_drop_not_ignored: three positive arms (success path, failure path, Replicated database) leak on master and are clean with the fix; a fourth asserts a genuine user DROP is still skipped. 50 randomized runs plus 50 with ignore_drop_queries_probability=0.2 were green, as were 04247, 04796, 04218 and 04327.

Version info

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

`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 ClickHouse#114420, which established the same
invariant for the DROPs that CREATE OR REPLACE issues internally.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (0 blockers, 0 majors)

An independent cold review plus a second-model gate ran against this diff before it
was pushed. The gate returned 0 findings. The cold review raised four nits; two
died on measurement, one is recorded below, one was folded into the description.

Cold review, independent of the implementation notes. The carrier list was
re-derived from scratch before comparing it to the plan's: the only bare-context
direct InterpreterDropQuery constructions in src/ are the four in
InterpreterCreateQuery.cpp (all already on contexts that call
setDDLOrOnClusterInternal(true)) and StorageMaterializedView.cpp:773, which this
fixes; every indirect caller routes through the static executeDropQuery helper,
which sets the flag itself. Both lists agree, so the enumeration is closed.

⚠️ Nit, folded into the description rather than the code. The other policy
branches of InterpreterDropQuery were enumerated and deliberately left applying
(access checks are a security boundary, not an injection artifact; the dependency
checks must keep protecting the target; the ON CLUSTER dispatch is unreachable from
a refresh). That reasoning existed but was not visible in the PR, so a sentence was
added to ### Description. No code change.

💡 Two nits withdrawn on measurement, recorded because the checking is the point.
(1) The test's comment about why the DROP DATABASE teardown is reliable looked wrong
until the stress runner was read: it appends
ignore_drop_queries_probability=0.2 to every client invocation, so the claim holds
and only the attribution is loose. (2) The missing SYNC on the teardown looked like
a deviation until the convention was counted: 267 of 335 DROP DATABASE lines in
tests/queries/0_stateless/*.sh omit it.

Test-liveness, checked rather than assumed. Reverting the fix reddens all three
positive arms, and the fourth arm is a real negative control (probability 1 always
fires and MergeTree stores data on disk, so the user's table must survive) rather than
a tautology. One thing worth stating because its absence looks like a race: arm 2 is
deterministic despite refresh_retries defaulting to 2, since an out-of-schedule
refresh runs with attempt_number decremented to 0 and a failure does not increment
it, so the retry branch is never taken and the next refresh falls to the 1-year
schedule.

Also verified: no gitlink or submodule drift, no SettingsChangesHistory obligation,
no test weakened or removed, no no-parallel tag, and the single added source comment
is a standing invariant rather than a note about this fix.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59b8f0b]

Summary: ✅


AI Review

Summary

This PR makes the cleanup DROP issued by a refreshable materialized view explicit as an internal step, so ignore_drop_queries_probability no longer turns that cleanup into a no-op or a TRUNCATE that leaves orphan .tmp.inner_id.* tables behind. I traced the ordinary and Replicated paths through StorageMaterializedView::dropTempTable, InterpreterDropQuery, and the replicated-DDL worker, and I did not find a correctness or safety issue that still holds in the current code.

Final Verdict

No findings.

LLVM Coverage Report

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

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ignore_drop_queries_probability = 1 pinned in a SETTINGS clause on the view's SELECT (a session SET never reaches the background refresh), then two SYSTEM REFRESH VIEW / SYSTEM WAIT VIEW: the rotated-out target is left behind as .tmp.inner_id.<uuid> with 1000 rows, every run.
b Root cause explained? createRefreshContext never marks the refresh context internal, so at InterpreterDropQuery.cpp:205 secondary_query is false and the :220 gate admits dropTempTable's cleanup DROP. The existing refreshable-view exemption does not cover it: :210 inspects the table being dropped, which is the inner target, not the view.
c Fix matches root cause? Yes. Internal intent is carried on the interpreter, which is what the gate is really asking about. No widened bound, no defensive check at the symptom site, no orphan sweeper.
d Test intent preserved / new tests added? New 04887_refreshable_mv_cleanup_drop_not_ignored (4 arms). Nothing weakened or removed; 04247, 04796, 04218, 04327 and 02932_refreshable_materialized_views_* all stay green.
e Both directions demonstrated? Yes. Same harness, only the binary differing: success path, failure path and Replicated database all report leak count 1 on master and 0 with the fix; the negative arm (a genuine user DROP is still skipped) reads 1 on both, which is what shows the gate was narrowed rather than disabled. With the fix the refresh still runs with the setting present and equal to 1 (system.query_log).
f Fix is general across code paths? All four direct InterpreterDropQuery(...) constructions outside the interpreter enumerated: three in InterpreterCreateQuery.cpp (already on internal contexts) plus StorageMaterializedView.cpp:773 (this one). Every indirect caller goes through executeDropQuery, which sets the flag itself. No bare-context internal DROP remains in src/. Both refresh exits share dropTempTable and both are tested.
g Fix generalizes across inputs (params/datatypes/wrappers)? Both gate outcomes covered, not only the reported one: a MergeTree target (skipped DROP, populated orphan) and a Memory target (DROP rewritten to TRUNCATE, emptied orphan) each leak on master and are clean with the fix. Also Atomic and Replicated databases, success and failure refreshes, and an empty as well as a populated previous target. No column types are involved, so the type-wrapper axis does not apply.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or re-defaulted, no serialization or format change, no new validation on existing data, so no SettingsChangesHistory.cpp entry and no experimental gate. The QueryFlags{ .internal = internal } at the replicated enqueue equals the {} it replaces for every existing caller: internal defaults to false and all three QueryFlags members default. The four other interpreters that pass {} are untouched.
i Invariants and contracts preserved? refresh_context is never mutated or copied, so the refresh DDL metadata (parent table UUID, DDL cancellation, enqueue checks) and the drop-size bypass of #104900 hold by construction, with 04247 as the live guard. The new member is set on one interpreter whose lifetime is the surrounding try, so there is no shared state, concurrency or lifetime surface. Access checks and dependency checks are deliberately left alone, so an internal DROP gains no privilege; the catch (...) cleanup-failure path is unchanged.

Session id: cron:clickhouse-impl-slot-6:20260813-080400

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

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @evillique, could you review this? A refreshable view's cleanup DROP of its rotated-out target was still subject to ignore_drop_queries_probability, so the old target leaked as a populated .tmp.inner_id.<uuid>; the internal intent now rides on InterpreterDropQuery rather than on the shared refresh context, because marking that context would make tryEnqueueReplicatedDDL reject the publishing RENAME of the same refresh.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 59b8f0b46 with master c42c154da (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
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.72 MiB -3.01 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 59b8f0b

No failures on this head. 177 jobs, 0 incomplete, 0 dropped, 159 OK, 18 skipped (each with a
recorded reason: not labelled pr-performance x6, reused from cache x3, no integration-test
updates x3, unaffected by the changed files x2, ci-toolchain x2, no prior failed tests, no
Coordination changes). Config Workflow and Finish Workflow both succeeded; last completion
2026-08-13T17:26:46Z.

Check / test Reason Owner / fixing PR
- no failing check on this head -

Bugfix validation (functional tests, amd64/aarch64) both report job status OK. Their
Failed: 1 summary line is the master-binary arm: the regression test must fail without the fix
for the validation to pass, so that row is the assertion succeeding, not a failure.

The six amd_llvm_coverage jobs report non-zero pre-diagnosis failure counts in their summary
lines; every one of those tests passed on rerun and each job's own result tree carries zero
failing leaves.

Session id: cron:our-pr-ci-monitor:20260813-180000

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into ClickHouse:master with commit aec8b1d Aug 15, 2026
529 of 535 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 16, 2026
alexey-milovidov pushed a commit to hinata34/ClickHouse that referenced this pull request Aug 18, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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-request PR origin: a maintainer pinged or directed groeneai 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.

4 participants