Skip to content

Enforce allow_non_metadata_alters on the mutation path, and document what it blocks - #115287

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:allow-non-metadata-alters-mutation-path
Sep 23, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:allow-non-metadata-alters-mutation-path

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115058

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

allow_non_metadata_alters = 0 now also rejects the ALTER commands that reach a MergeTree table as explicit mutations: UPDATE, DELETE WHERE, the five MATERIALIZE forms, APPLY DELETED MASK, APPLY PATCHES and REWRITE PARTS. Previously the check only saw the commands represented by the schema-alter path, so these rewrote parts anyway. DELETE FROM and UPDATE stay permitted, including ON CLUSTER. The setting description now lists what is refused, and that the check is MergeTree-only.

Description

The setting was only read in MergeTreeData::checkAlterIsPossible. The commands listed above go into a MutationCommands segment, which calls checkMutationIsPossible, whose Settings parameter MergeTreeData declared unused. The fix names it and rejects when hasNonEmptyMutationCommands() holds, the predicate that already decides whether the mutation runs, so guard and execution cannot drift.

Plain DELETE FROM needed care: under the default lightweight_delete_mode it synthesizes ALTER TABLE ... UPDATE _row_exists = 0, which the storage cannot tell from the user-written form. Exempting by shape would reopen the hole, so the synthesizing interpreter grants it on a private context.

A setting cannot carry that provenance across nodes: the worker re-clamps shipped settings against its own profile. So DELETE FROM ... ON CLUSTER now dispatches the DELETE itself, as InterpreterUpdateQuery does. Two consequences:

  • DDLWorker now leader-routes ASTDeleteQuery, so a replicated shard runs it once, not once per replica. This also covers a multi-shard Replicated database, which is reached by a plain DELETE rather than by ON CLUSTER: it replicates the DELETE at database level, and ON CLUSTER against it is rejected as a non-initial query both before and after this PR. Mid-upgrade an old and a new worker can both execute one entry, which duplicates the mutation and converges; the two closest precedents also shipped ungated.
  • InterpreterDeleteQuery now inlines SQL user-defined functions, as the interpreters it used to re-enter did. That store is not replicated by default, so an unexpanded body either failed with UNKNOWN_FUNCTION on the other hosts or, if defined differently there, silently deleted different rows there.

Refusals happen only where the setting is 0, but the two bullets above apply at any value of it, including the default. @PedroTadim, the compatibility question is open if you prefer the docs half.

Validation, allow_non_metadata_alters = 0 on a debug build

Three binaries: base, the guard without the caller exemption, and the fix.

Statement base guard only fix
the mutation commands listed above OK 524 524
user-written ALTER ... UPDATE _row_exists = 0, local and ON CLUSTER OK 524 524
DELETE FROM (default mode) OK 524 OK
DELETE FROM ... ON CLUSTER, profile constrains the setting to 0 OK 524 OK
DELETE FROM (lightweight_update mode) OK OK OK
lightweight UPDATE ... SET OK OK OK
DROP COLUMN of an ALIAS, ADD COLUMN, COMMENT COLUMN, MODIFY SETTING OK OK OK
the alters already refused before this change 524 524 524
every refused statement again under = 1 OK OK OK

524 is ALTER_OF_COLUMN_IS_FORBIDDEN, the code the existing alter-path guard already throws.
DELETE FROM is the only cell where the middle column differs from the fix, so the relaxation
is exactly one statement wide.

01413_allow_non_metadata_alters is extended with these cases and fails without the fix; each
new expected-error line was justified against the base binary first, where all of them succeed.
The clustered cases need a settings profile, which a stateless test cannot set, so they live in
test_allow_non_metadata_alters_on_cluster (11 arms). Two assert a single mutation entry per
shard, one for a ReplicatedMergeTree table reached by ON CLUSTER, one for a multi-shard
Replicated database reached by a plain DELETE; both fail on the base binary with 2 entries.
lightweight_deletes_sync is 2 and the DDL output mode is THROW, so that read happens after
every host finished, with no polling or sleep. Two define a function on
one host only, and differently on each host: without the inlining they fail with
UNKNOWN_FUNCTION and with divergent surviving keys respectively.


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

Version info

  • Merged into: 26.10.1.487-master (included in 26.10 and later)

allow_non_metadata_alters is documented as a switch against ALTERs that
rewrite data on disk, but it only rejected the AlterCommand-shaped subset.
InterpreterAlterQuery::parseAlterCommandSegments classifies UPDATE, DELETE,
MATERIALIZE INDEX/PROJECTION/STATISTICS/COLUMN/TTL, APPLY DELETED MASK,
APPLY PATCHES and REWRITE PARTS as MutationCommands, and that branch calls
checkMutationIsPossible, whose Settings parameter MergeTreeData left unused.
So the setting was never consulted for the statements that most obviously
rewrite parts, and each of them still queued a system.mutations entry.

Name the parameter and reject when the commands are non-empty mutations,
reusing MutationCommands::hasNonEmptyMutationCommands so the rejected set
stays in sync with the set that would actually be mutated.

Plain DELETE FROM re-enters this path, because lightweight_delete_mode
defaults to ALTER_UPDATE and InterpreterDeleteQuery synthesizes
ALTER TABLE ... UPDATE _row_exists = 0. The storage cannot distinguish that
from a user-written statement of the same shape: both arrive as a
MutationCommand of type UPDATE with identical ast_text, and there is no
provenance field. Exempting it by shape would therefore reopen the hole for
ALTER ... UPDATE, so the exemption is set by the synthesizing interpreter on
the private context copy it already builds for mutations_sync, which no
user-typed query can reach.

Measured on a debug build, allow_non_metadata_alters = 0: all ten mutation
forms plus a user-written _row_exists assignment now fail with
ALTER_OF_COLUMN_IS_FORBIDDEN and succeeded before; DELETE FROM, lightweight
UPDATE, and metadata-only ALTERs keep working; and with the setting enabled,
which is the default, nothing changes.

The description also stated neither which statements are refused nor that the
check is MergeTree-only, which is the second half of the report.

Closes: ClickHouse#115058
Review round 1. The previous commit relaxed allow_non_metadata_alters for the
lightweight delete that InterpreterDeleteQuery synthesizes, by setting it on the
context copy that branch already builds. That only holds locally: for
DELETE FROM ... ON CLUSTER the settings travel in the DDL entry and the worker
re-clamps them against its own profile, so an operator who constrains the setting
to 0 saw the clustered DELETE refused with ALTER_OF_COLUMN_IS_FORBIDDEN, which
contradicts what this change promises. Dispatch the ASTDeleteQuery itself before
the ALTER is synthesized, the way InterpreterUpdateQuery already does, so each
host re-derives its mode and grants its own relaxation locally and provenance
never travels as a setting.

StorageWindowView::cleanup() synthesizes an ALTER ... DELETE against its inner
AggregatingMergeTree table for the same kind of internal reason, and
threadFuncCleanup swallows the exception, so a profile-level 0 would silently
stop freeing outdated windows. Grant it the same exemption. Those two are the
only InterpreterAlterQuery construction sites outside the interpreter itself.

Three corrections to the setting's description, each measured rather than
reasoned: DELETE FROM and UPDATE are permitted because the setting governs ALTER
DDL and not the dedicated statements, not because they write patch parts, which
is false in the default lightweight_delete_mode = alter_update; RENAME COLUMN is
refused for any column including an ALIAS, since getMutationStageDecision sets
requires_mutation unconditionally for it, unlike DROP COLUMN; and UPDATE is
refused as a heavyweight mutation, i.e. under the default alter_update_mode.

Tests: pin alter_update_mode and lightweight_delete_mode in the new 01413
section, since the corrections above make both load-bearing, and add an arm
asserting that an ALTER UPDATE running as a lightweight update is permitted. The
clustered cases need a settings profile, which a stateless test cannot express
because the DDL worker reads the default profile rather than the issuing user's,
so they go in a two-node integration test instead. That test fails on the
previous commit on exactly the two DELETE FROM ... ON CLUSTER cases and passes
here, with the four refusal arms green on both.
Shipping the DELETE itself through executeDDLQueryOnCluster lets each host
derive its delete mode and its own allow_non_metadata_alters relaxation from
its own profile, which a shipped setting cannot do because the worker
re-clamps it. But taskShouldBeExecutedOnLeader only leader-routes
ASTAlterQuery, ASTOptimizeQuery, ASTDropQuery, ASTCreateIndexQuery and
ASTDropIndexQuery, so an ASTDeleteQuery entry ran on every replica of a
shard and each local run called mutate(), producing N duplicate Keeper
mutation entries for one statement. Before this PR the rewritten
ALTER ... ON CLUSTER was an ASTAlterQuery and was leader-routed, so this is
a regression this PR would otherwise introduce.

The executing leader re-parses the entry with ON CLUSTER stripped, so the
local lightweight-delete path with its relaxation is still what runs.
ASTUpdateQuery is deliberately left out: UPDATE ... ON CLUSTER already
shipped an ASTUpdateQuery and was already absent from that list, so it is
pre-existing behaviour and out of scope here.

The integration test grows a ReplicatedMergeTree arm. The existing arms use
plain MergeTree with a separate INSERT per host, so each node owns private
rows and the row-count assertions are satisfied by the faulty per-replica
behaviour; with two replicas of one shard and a single INSERT, a doubled
mutation becomes observable. It asserts one mutation entry per shard and
convergent row counts, and fails with 2 without the routing change.
The clustered DELETE branch added by this PR ships the DELETE statement itself
instead of a rewritten ALTER, and InterpreterDeleteQuery has never inlined SQL
user-defined functions. At the base of this PR that was harmless, because a
clustered DELETE always re-entered an interpreter that does inline before it
dispatches: InterpreterAlterQuery for the default lightweight_delete_mode, and
InterpreterUpdateQuery for the lightweight_update modes. The new branch returns
before either, so the queued entry carried the function call unexpanded.

The user-defined function store is not replicated by default, and ON CLUSTER on
CREATE FUNCTION is rejected only when it is, so a function legitimately exists
on the initiator alone. Such a DELETE then either failed with UNKNOWN_FUNCTION
on the hosts where the function is absent, or deleted different rows on hosts
where it is defined differently, diverging the replicas of a shard with no error
anywhere. validateNonDeterministicMutationsForStorage does not catch that: a
function wrapping deterministic functions is itself deterministic.

Inline for every DELETE rather than only the clustered one, matching
InterpreterUpdateQuery, which inlines unconditionally before its own ON CLUSTER
branch. The local path is unaffected: it re-formats the predicate into a
synthesized ALTER or UPDATE that the downstream interpreter inlines again, and a
second pass is a no-op once no function call remains. Inlining precedes
substituteDatabaseInTableFunctions, because a body can itself contain a table
function whose database has to be qualified.

ASTDeleteQuery::predicate and ::partition are separate pointers to nodes that
children also holds, and the class did not override forEachPointerToChild, so
the replacement landed in children alone while the member kept pointing at the
unexpanded node. formatQueryImpl reads the member, which is what
executeDDLQueryOnCluster ships, so the override is what makes the expansion
reach the other hosts when the whole predicate is one function call.

Two integration arms cover both consequences: a function defined on one host,
and a function defined differently on each. Without this commit the first fails
with UNKNOWN_FUNCTION from the second host and the second silently deletes
different rows on each.

During a rolling upgrade of one shard, a clustered DELETE may be picked up by
both an old worker, which does not leader-route ASTDeleteQuery and so creates no
shard marker, and a new one, which finds the marker absent and executes too.
Measured on a mixed two-node cluster in both initiator directions: two identical
mutation entries, both completed, no failures, convergent rows, i.e. duplicated
work that converges. The two closest precedents for widening this list shipped
without a version gate.

The description of allow_non_metadata_alters also gains CLEAR INDEX, CLEAR
PROJECTION and CLEAR STATISTICS, which set requires_mutation unconditionally;
qualifies CLEAR COLUMN as physical-column-only, which is how it behaves; and
states that UPDATE is refused whenever it runs as a heavyweight mutation rather
than only under the default alter_update_mode.
The two arms that check a DELETE FROM ... ON CLUSTER predicate carrying a SQL
user-defined function asserted less than the contract they exist to defend. The
contract is that the initiator's function body decides which rows are deleted on
every host, but one arm asserted only a row count and the other only that the two
hosts agreed with each other. The expansion substitutes arguments positionally, so
"the body was inlined but the argument bound wrong" produces a uniformly wrong
result that both of those assertions accept. Assert the exact surviving key set on
each host instead, which reddens on host divergence and on a uniform wrong answer
alike.

Verified by mutating the initiator's body: both arms fail, where the previous
assertions would have passed.

Also narrow a comment in 01413 that claimed every refused command is re-run once
the setting is enabled. Nine of the eleven are. MATERIALIZE PROJECTION cannot be,
because the projection is dropped earlier so that DELETE FROM is permitted at all,
and the _row_exists assignment is only interesting in the refused direction; say
so rather than overstating the coverage.

The first sentence of the setting description was ungrammatical, and it is visible
both in system.settings and in the autogenerated documentation page this change set
out to clarify.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 5 rounds (4 blockers, 5 majors agreed and fixed; 6 findings refuted)

An independent cold review plus a second-model gate ran on every revision, adjudicated against
recorded measurements. The final round returned zero findings from both reviewers. Only items that
changed the code or a claim are listed.

❌ Blocker — the caller exemption did not survive ON CLUSTER. A setting cannot carry
provenance across nodes: the DDL worker re-clamps shipped settings against its own profile, so
DELETE FROM ... ON CLUSTER was refused on a cluster whose profile pins the setting to 0. Fixed by
dispatching the DELETE itself, as InterpreterUpdateQuery already does.

❌ Blocker — that dispatch lost one-execution-per-shard routing. ASTDeleteQuery was not in the
worker's leader-routable list, so every replica of a shard created its own mutation entry, where the
rewritten ALTER had been leader-routed. Fixed by adding it to the same predicate that already
covers ALTER ... DELETE WHERE.

❌ Blocker — SQL user-defined functions were not inlined. The interpreters this path used to
re-enter inline them; shipping the raw statement did not. That store is not replicated by default,
so a body defined on the initiator alone failed with UNKNOWN_FUNCTION elsewhere, and one defined
differently silently deleted different rows there. Fixed by inlining before the dispatch. This also
needed a forEachPointerToChild override on ASTDeleteQuery: without it the expansion lands in
children only, while the serialized entry is formatted from the member, so the fix would have been
inert for a whole-predicate WHERE udf(x). Same override the merged UPDATE sibling added for the
same reason.

❌ Blocker — the mixed-version window was undisclosed. Measured on a two-node cluster with one
old and one new worker, both initiator directions: two identical completed mutation entries and
convergent rows. Duplicated work that converges, now stated in the description.

❌ Major — three test oracles were value-blind or unable to observe their own target. The
replicated-routing arm used per-host inserts, so each host legitimately deleted its own copy and the
row counts passed under faulty routing; the two UDF arms asserted only a row count and
host-to-host equality, which both hold when the initiator inlines the wrong argument and every host
agrees on the wrong row. Replaced with a shared ReplicatedMergeTree arm asserting exactly one
mutation entry per shard, and with the exact surviving key set on both hosts. Each new oracle was
verified by mutating the thing it exists to catch, not only by reddening on the old binary.

❌ Major — the setting description contained three inaccuracies, and a PR-body claim was false.
Each corrected against the code with a control. The blast-radius sweep also had an incomplete arm
and one confounded run; both were rerun.

💡 Refuted — DELETE FROM and UPDATE really are allowed in every mode they support. The
concern was the supportsDelete() branch, which calls the new guard with the unrelaxed user
context. Every storage whose supportsDelete() is true (KeeperMap, EmbeddedRocksDB,
SystemWasmModules, Iceberg, object storage, and StorageAlias delegating) also overrides
checkMutationIsPossible and discards the settings argument, so the throw is unreachable there.

💡 Refuted — naming KeeperMap and EmbeddedRocksDB as engines that ignore the setting is
correct.
Both override the hook with an explicitly unused settings parameter.

💡 Refuted — a proposed cross-version coordination protocol for the mixed-version window. The
transient is duplicated work that converges, and the two closest precedents for widening the
leader-routable list also shipped ungated.

⚠️ Noted, not changed — the setting gates admission, not execution. A mutation already
committed before the setting is turned off keeps running, because the background executor never
calls this hook. That matches the pre-existing alter-path guard.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
Check Verdict
a Deterministic repro Yes. Single statement, 100% reproducible: SET allow_non_metadata_alters=0; ALTER TABLE t UPDATE v = 42 WHERE key = 1 succeeds before the change.
b Root cause explained Yes. parseAlterCommandSegments routes the explicitly-mutating ALTER forms into a MutationCommands segment, which runCommandSegments sends to checkMutationIsPossible, whose Settings parameter MergeTreeData declared unused. The setting is read only in checkAlterIsPossible, on the other branch.
c Fix matches root cause Yes. The parameter is named and consulted at the point that already exists for this purpose. No new call site, no new setting, no guard bolted on elsewhere.
d Test intent preserved, tests added Yes. 01413_allow_non_metadata_alters extended in place; existing assertions untouched; the two pre-existing SHOW CREATE TABLE reference lines are byte-identical. A two-node test_allow_non_metadata_alters_on_cluster covers the clustered cases, which need a settings profile that a stateless test cannot express. Assertions are error codes, not system.mutations counts, so nothing is timing-dependent.
e Demonstrated in both directions Yes. Three binaries measured (base, guard-without-exemption, fix); table in the PR description. Every new test arm also fails on a binary without its corresponding fix, so none is vacuous: the integration test reddens on exactly the two DELETE FROM ... ON CLUSTER cases, and its replicated arm observes 2 mutation entries for one statement before the routing fix and 1 after, with the four refusal arms green throughout. The two user-defined-function arms fail on the immediately preceding binary with UNKNOWN_FUNCTION from the second host and with divergent surviving keys ([0,2,3,...] against [0,1,3,...]), and both pass after; the full file is 10/10, and 50 repeats of it are green. Those two arms assert the initiator's exact surviving key set on every host, which was checked against a mutation of the initiator's function body: both arms redden, where a row count or a host-to-host comparison would not.
f General across code paths Yes. No MergeTree subclass overrides checkMutationIsPossible, so StorageMergeTree, StorageReplicatedMergeTree and SharedMergeTree inherit it; StorageMaterializedView and StorageAlias forward the same Settings. The other call site is behind supportsDelete(), which MergeTreeData does not override. The synthesized-ALTER carrier class is closed: InterpreterAlterQuery is constructed in exactly two places outside its own file, InterpreterDeleteQuery and StorageWindowView::cleanup(), and both are exempted. For the inlining, the three interpreters a DELETE can reach now all expand: InterpreterAlterQuery (:418), InterpreterUpdateQuery (:92) and InterpreterDeleteQuery, the last of which had never called the visitor. Engines outside the family are unchanged by design and now documented.
g General across inputs Yes. All ten mutation command types, both values of lightweight_delete_mode and of alter_update_mode, the _row_exists assignment shape, local and ON CLUSTER forms, distributed_ddl_entry_format_version 1 and 5, plain MergeTree and ReplicatedMergeTree targets, metadata-only alters, and both values of the setting. The rejected set is hasNonEmptyMutationCommands(), the same predicate that decides whether the mutation runs, so it cannot drift from the set that would rewrite parts. For the inlining: a function inside a larger predicate and one that is the whole predicate (the case needing the forEachPointerToChild override), a body containing a merge() table function (whose database is qualified, proving inlining precedes the substitution), a recursive definition (still Recursive function call detected), the supportsDelete engine path, and the IN PARTITION slot, which the grammar rejects for any non-literal with or without a function.
h Backward compatible Deliberate behaviour change, scoped by the default. allow_non_metadata_alters defaults to true, so only setups that explicitly opted into the restriction see the new refusals, which is what they asked for. The default is unchanged, so no SettingsChangesHistory.cpp entry applies; verified against 04652_system_documentation_settings_history, 03999_stateless_settings_history and 02117_show_create_table_system.
i Invariants and contracts preserved Yes. Inlining is unconditional, matching the sibling, and the local path is byte-identical to before: it re-formats the predicate into a synthesized statement that the downstream interpreter expands again, and the second pass is a no-op once no call remains (measured, five shapes, output identical on both binaries). During a rolling upgrade of one shard the routing change is not carried in the entry, so an old and a new worker can both execute one DELETE; measured on a mixed two-node cluster in both initiator directions, that is two identical completed entries, no failures, convergent rows, i.e. duplicated work that converges, and it is disclosed in the commit message and the PR body. The guard runs before any state is read and throws ALTER_OF_COLUMN_IS_FORBIDDEN, the same code the sibling alter-path guard uses. No locking or ownership change. Each exemption lives on a context private to the statement that sets it and is discarded afterwards, so nothing else observes the relaxed value; the clustered path now re-establishes it per host instead of shipping it. The clustered dispatch is placed after the existing supportsLightweightDelete, enable_lightweight_delete and projection-mode checks, so an unsupported request still fails on the initiator with its original error rather than fanning out. One-execution-per-shard is preserved for replicated storage: DDLWorker leader-routes the shipped ASTDeleteQuery as it already did the rewritten ALTER, and the executing leader re-parses the entry with ON CLUSTER stripped, so the local path with its relaxation is what runs.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9f9777c]

Summary: ✅


AI Review

Summary

This PR extends allow_non_metadata_alters to the explicit-mutation path, changes clustered DELETE to ship ASTDeleteQuery itself so each host re-derives lightweight-delete mode, and adds focused coverage for clustered UDF expansion and leader routing. I still see one new fail-fast regression in the guard placement, plus two previously discussed concerns that remain real in the current code.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:6178] allow_non_metadata_alters = 0 is enforced only when runCommandSegments reaches a MutationCommands segment, after any earlier AlterCommands segments have already been applied in InterpreterAlterQuery.cpp:345-375. A query such as ALTER TABLE t ADD COLUMN x UInt8, DELETE WHERE 0 now commits the ADD COLUMN and only then throws ALTER_OF_COLUMN_IS_FORBIDDEN, so a protective exception leaves permanent schema changes behind.
    Suggested fix: reject non-empty mutation segments during preflight, before runCommandSegments starts executing earlier segments.

⚠️ Majors

  • [dismissed by author -- https://github.com/Enforce allow_non_metadata_alters on the mutation path, and document what it blocks #115287#discussion_r3889030689] [src/Interpreters/InterpreterDeleteQuery.cpp:120] DELETE ... ON CLUSTER still silently executes only locally on supportsDelete() engines because the direct-delete branch never inspects delete_query.cluster. The new clustered dispatch only covers the supportsLightweightDelete() path, so the cluster-scoped contract remains broken for KeeperMap, EmbeddedRocksDB, Iceberg/object-storage deletes, system.wasm_modules, and aliases of them.
    Suggested fix: move the clustered dispatch or an explicit rejection above the supportsDelete() / supportsLightweightDelete() split.

💡 Nits

  • [dismissed by author -- https://github.com/Enforce allow_non_metadata_alters on the mutation path, and document what it blocks #115287#discussion_r3890698885] [src/Core/Settings.cpp:5098] The new lightweight_delete_mode docs now describe per-host clustered execution, but the structured DELETE statement docs in src/Parsers/ParserDeleteQuery.cpp:194-196 still say every DELETE is rewritten to ALTER TABLE ... UPDATE. The published docs will disagree until one side is updated.
    Suggested fix: update the DELETE statement registration in ParserDeleteQuery.cpp in the same PR, or narrow the new setting text.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make allow_non_metadata_alters = 0 reject mixed ALTER statements before any earlier segment is applied.

LLVM Coverage Report

Measured on commit 9f9777c.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 85/86 (98.84%) · 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 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @tuanpach, could you review this? allow_non_metadata_alters = 0 was only read on the alter path, so the ALTER forms that reach a MergeTree table as explicit mutations rewrote parts anyway; the guard now also runs in checkMutationIsPossible. Because plain DELETE FROM synthesizes an identical ALTER ... UPDATE _row_exists = 0, the exemption is granted by the synthesizing interpreter rather than by statement shape, which means DELETE FROM ... ON CLUSTER now dispatches the DELETE itself and DDLWorker leader-routes ASTDeleteQuery.

@ringerc

ringerc commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

@groeneai Some of the following may have been answered indirectly in the PR body, but I'd like to call each out explicitly:

Will this have any impact if a cluster is running mixed clickhouse versions during a rolling upgrade - will the old-version clickhouse cluster accept and handle the incoming DELETE where it previously expected to only see the expandded replicated ALTER ... DELETE ... the leader generated from the user-originated lightweight DELETE?

Are there any likely future consequences for this change in replication mode if row-security policy enforcement is extended to lightweight UPDATE and DELETE ? Discuss succinctly.

Will the changes to lightweight DELETE and UPDATE replication have any user-visible impact when this setting is left at default?

What defenses - comments, persistent agent instructions, additional tests, assertions, code structural choke-points to enforce conformance, etc - are in place to prevent this regressing when ALTER is extended with future capabilities?

@ringerc ringerc left a comment •

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.

After an initial somewhat superficial my-human-eyes-and-brain read over the PR, see the comments below.

I also note that the PR code has changes for the DELETE FROM ... path but no apparent changes on the UPDATE path. Is this intentional, or an oversight?

Edit: Per this analysis the UPDATE path already does the right thing but the DELETE path didn't; this PR brings DELETE up to parity with UPDATE.

I'm a little concerned about how it makes changes to inlining and query replication for the DELETE FROM ... path alone, without apparently checking for consistency with other paths like UPDATE and SELECT.

Edit: It looks like that inlining is consistent with how UPDATE works per 99ca3b4 but that change didn't apply the same logic to DELETE. That makes it less concerning, it's fixing an inconsistency not introducing major new behaviour.

Comment thread src/Core/Settings.cpp Outdated
Comment on lines +5522 to +5523
- `UPDATE` whenever it runs as a heavyweight mutation, which is the default
`alter_update_mode = 'heavy'` and every case the other modes fall back to, `DELETE WHERE`,

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 passage appears to claim that UPDATE and DELETE ... are blocked by allow_non_metadata_alters = 0, but on lines 5528...5531

Other `ALTER` statements are allowed, including `ADD COLUMN`, `COMMENT COLUMN`,
`MODIFY SETTING`, an `Enum` extension, and `DROP COLUMN` of an `ALIAS` column. The
`DELETE FROM` and `UPDATE` statements are allowed in every mode they support: the setting
governs `ALTER` DDL, not the dedicated delete and update statements.

this text appears to say they are permitted. The verbiage "allowed in every mode they support" is unspecific, and the claim " setting governs ALTER DDL, not the dedicated delete and update statements" appears to directly contradict the prior passage.

So does this block DELETE FROM ... and UPDATE ... or not, and if it can, under what circumstances?

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.

You are right, and it was ambiguous rather than merely unspecific: the bullet list used the bare word UPDATE for the ALTER TABLE ... UPDATE command, and the paragraph below used it for the UPDATE ... SET statement. Two different statements, one word.

Fixed in 3833eea: every command is now spelled with its full statement form, and the paragraph says explicitly that DELETE FROM ... and UPDATE ... SET ... are different statements which this setting never refuses.

To answer the question directly: it does not block them, in any mode. Under the default lightweight_delete_mode = 'alter_update' a DELETE FROM does synthesize the same ALTER ... UPDATE _row_exists = 0 internally, so the storage sees a mutation and would refuse it; the interpreter that synthesizes it grants the exemption on its own private context, so provenance decides, not statement shape. A user-written ALTER TABLE ... UPDATE \_row_exists` = 0` is still refused, which 01413 pins.

I also removed the confine them with permissions advice I had given you earlier on the issue. Measured: DELETE FROM and ALTER ... DELETE WHERE both check ALTER_DELETE, and revoking it fails both with 497. The privileges cannot separate the two forms, and the description now says so.

Comment on lines +72 to +76
/// Inline the bodies of SQL user-defined functions before the database is filled in, otherwise an
/// unqualified table inside a body is resolved later, in a context whose current database is not
/// the database of the deleted-from table.
if (!UserDefinedSQLFunctionFactory::instance().empty())
UserDefinedSQLFunctionVisitor::visit(query_ptr, getContext());

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.

Is this added inlining applied consistently across all query execution paths? It's a significant change that affects the delete path even when allow_non_metadata_alters = 1 so its possible impact needs to be carefully considered.

Are there any user-privilege or access-rights implications to this inlining step being done at this point?

@ringerc ringerc Aug 18, 2026 •

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.

Update: Per 99ca3b4 it looks like this change just brings DELETE into conformity with other query paths so it should be fine. I don't have permission to resolve my own review thread though, so I can't close this.

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.

Consistent, yes: InterpreterAlterQuery (:419) and InterpreterUpdateQuery (:93) both already inlined, and this path re-entered one of them, so the expansion was always happening. What changed is only that it now happens here first, in the interpreter that owns the statement. That matters because the clustered branch returns before either of those is reached, so without it the raw statement shipped with the UDF call unexpanded.

You are right that it is unconditional, and I have corrected the PR body: it previously said "behaviour changes only where the setting is 0", which was false for this bullet and for the routing one. Inlining and clustered dispatch change at any value of the setting, including the default.

On access rights: none. The visitor performs no access check of its own and there is no privilege on a SQL UDF to check. Ordering is unchanged in the sense that matters: the expansion precedes checkAccess(AccessType::ALTER_DELETE, table_id) here (:81) exactly as it precedes checkAccess(required_access) in InterpreterUpdateQuery (:93 before :153). The privilege is checked against the deleted-from table, which the expansion does not alter. What the expansion does change is which tables the predicate reads, and those are resolved and access-checked when the mutation's SELECT is planned, not here.

Comment on lines +165 to +167
/// Substitute the database into table functions that use the current database implicitly, e.g.
/// `merge('tables_regexp')`, before `executeDDLQueryOnCluster` replaces `currentDatabase()` with
/// the database of the session. The table identifiers are qualified on each host instead.

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.

Is there any reason this qualification shouldn't be done unconditionally during the initial statement parse and rewrite pass before node-local execution too? Unless the computational cost is significant, which looks unlikely, this might be a sensible defensive step to to take at the point where the client query is received and any implicit session state is bound to the query itself.

It's probably not justifiable to do that in this PR as it expands the scope of these changes past the necessary minimum footprint, but I'd like to flag it for consideration in future.

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.

OK, so upon further review this change makes DELETE consistent with how UPDATE works, so it's the logical way to do it for now.

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.

Agreed on both counts, including that it does not belong here. The cost is negligible: the visitor returns immediately when no SQL UDF exists, which is the guard on this call.

I am not raising a follow-up for it. It has no user-visible consequence I can demonstrate today, so it would be a refactor rather than a fix, and I would rather leave the note here for whoever does canonicalize the parse pass than manufacture a task for it.

Comment on lines +161 to +162
/// The cluster case ships the DELETE itself rather than a rewritten ALTER, so that every host
/// derives its delete mode and its own storage-check relaxation from its own settings.

@ringerc ringerc Aug 18, 2026 •

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.

Is there any difference in the implied session-state that is inherited across a replicated query for an ALTER ... DELETE ... vs a bare DELETE ... that might lead to unexpected changes in how this statement behaves? For example, session/query level settings that might apply to the DELETE when it executes an implied ALTER ... DELETE ... locally but are not currently bound into the replicated DELETE ? Or vice versa?

In other words, can this change in how deletes are replicated cause any surprising changes in behaviour due to side-effects from session state?

Edit to follow-up after some studying and tool-based assessment: this does have a user-visible impact but it makes DELETE more consistent with UPDATE. I'll have an LLM tool post a follow-up with details, but it looks like this mainly needs some emphasis on the corner-case behaviour changes for DELETE in release-notes and maybe a consistency check between update and delete docs to verify claims about clustered execution.

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.

Posted by an LLM on my behalf.

Summary: Session-state semantics do shift, but in the same two directions UPDATE already shifted (per-host mode selection and origin-pinned UDF meaning), so the concern is real but there's a working precedent — the one gap is docs, which only mention alter_update_mode.

Details

Both master's DELETE … ON CLUSTER → ALTER … UPDATE ON CLUSTER rewrite and this PR's ship-DELETE go through executeDDLQueryOnCluster → DDLLogEntry. DDLLogEntry::setSettingsIfRequired serialises context->getSettingsRef().changes(), i.e. every session-level SET the origin performed, and each worker replays them onto the task context before interpreting. So explicit origin SETs ride along identically in both paths. The concern isn't "which settings survive"; it's "which side reads them, and when".

Where the two paths diverge

  1. Mode selection (lightweight_delete_mode). Master resolves the mode once, on origin (that's what turns DELETE into either a lightweight UPDATE _row_exists=0 or an ALTER UPDATE). Every host receives that already-baked decision. The PR defers the choice to each host. If the origin did SET lightweight_delete_mode=…, it rides along in .changes() and hosts see it, so nothing surprising there. What is new: hosts with heterogeneous profile-level defaults will now legitimately pick different modes on different hosts, whereas master silently forced the origin's default onto all of them. The PR body says this is intentional (each host picks its own storage-check relaxation and its own mode), and it's also exactly the semantics UPDATE has had since it started shipping itself instead of ship-ALTER.

  2. Gates re-checked on hosts. enable_lightweight_delete, enable_lightweight_update, projection mode, supportsLightweightDelete, supportsDelete were previously gated only on origin (the shipped ALTER UPDATE doesn't have to satisfy them). On ship-DELETE they re-fire on every host. The same widening happened for UPDATE: hosts run through the full InterpreterUpdateQuery gates. In practice these gates read either server settings or engine capability, neither of which is truly "session state".

  3. lightweight_deletes_sync → mutations_sync mapping. Master does context->setSetting("mutations_sync", lightweight_deletes_sync) on a copied context on origin, and the ALTER ships with that synthesised change. The PR defers it: each host does the same mapping locally when it re-enters InterpreterDeleteQuery on the ship-through. Because .changes() still carries the origin's overridden lightweight_deletes_sync (if any), hosts observe the same value. Symmetric.

  4. UDF inlining timing. Master's ship-ALTER … UPDATE never inlined SQL UDFs at the DELETE layer, so a UDF-defining reference travels as-is and is resolved from whatever UDF registry the host has — which is allow_non_metadata_alters=0 does not block many mutation-triggering ALTERs and its documentation is unclear #115058. The PR inlines unconditionally at the top of InterpreterDeleteQuery, before shipping. The shipped predicate is now bound to the origin's UDF registry snapshot; hosts with locally-different UDFs are no longer surprising, but the semantic is now "origin defines the UDF meaning", which is a new (and correct) invariant. UPDATE did the same move in 99ca3b4 (unconditional UserDefinedSQLFunctionVisitor::visit guarded only by non-empty factory).

  5. Query-body normalisation / default-database pinning. substituteDatabaseInTableFunctions on predicate and partition mirrors what UPDATE already does on predicate and assignments and what ALTER does on command_list. One minor consistency delta: UPDATE's ON CLUSTER branch guards this call by if (resolved_table_id). This PR's DELETE cluster branch does not — it constructs AddDefaultDatabaseVisitor(getContext(), table_id.getDatabaseName()) unconditionally. It's safe here because control has already flowed past a DatabaseCatalog::instance().getTable(table_id, …), so table_id is fully qualified by the time we reach it, but the shape doesn't match UPDATE.

The concrete "gotcha" list

Two behaviour shifts a user could realistically notice:

  • A cluster with heterogeneous defaults now picks per-host mode. A DELETE that used to run as ALTER on every host will now run lightweight on hosts whose default is lightweight_update and as ALTER on hosts whose default is alter_update. Origin's session-level SET lightweight_delete_mode still overrides (via .changes()), so the escape hatch works. This exactly mirrors UPDATE.
  • Origin's UDF definitions are pinned into the shipped query. Master had the opposite (buggy) semantic. UPDATE already made the same switch. Nothing in the docs currently walks a user through this, though — it should probably be mentioned in the same place we talk about alter_update_mode.

The one thing that is not symmetric with UPDATE

UPDATE's ship path is entered unconditionally from InterpreterUpdateQuery — there is no "rewrite to ALTER UPDATE first" branch. The PR's ship-DELETE, by contrast, sits above an inner rewrite-to-ALTER (or rewrite-to-UPDATE) fallback for the local case. A per-host resolution can, on some hosts, still end up producing a locally rewritten ALTER UPDATE — but that inner rewrite is re-executed on the host, on the host's session settings, so it inherits the host's mutations_sync mapping and its own allow_non_metadata_alters relaxation. That's the intended asymmetry.

Bottom line

The change does alter session-state semantics for DELETE ON CLUSTER, in two ways that will be user-visible (per-host mode selection; origin-pinned UDF meaning). Both shifts are already present on the UPDATE side and haven't caused observable trouble there. The one place worth pushing on is documentation: the user-facing note only mentions alter_update_mode, and this PR's DELETE-side counterpart (lightweight_delete_mode) now has the same "each host derives it locally on ON CLUSTER" contract — that should be spelled out, especially given #115058 originated from surprise over exactly this class of divergence.

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.

There is a difference, and it is the point of the change rather than a side effect.

At base, the initiator rewrote the statement to ALTER ... ON CLUSTER ... UPDATE _row_exists = 0 and shipped that. The DDL entry carries the initiator's settings (DDLTask.cpp:126-128), and each worker re-clamps them against its own profile (:356-365, where SettingsConstraints::checkOrClamp erases a rejected change). So the initiator's delete mode was baked in on the initiator, while the setting travelling with it could be silently dropped on arrival. That is precisely how the exemption broke: an operator who constrains allow_non_metadata_alters to 0 to have it enforced got DELETE FROM ... ON CLUSTER failing 524.

Now the DELETE itself is shipped, so each host derives its delete mode and its own relaxation from its own settings. Settings still travel and are still re-clamped the same way; what no longer travels is a decision the initiator made on the initiator's behalf.

One thing genuinely does change and I have made the PR body say so: with distributed_ddl_entry_format_version = 1 no settings ship at all, which the 10-arm matrix covers as its own case.

Comment on lines +246 to +248
/// A user-written `ALTER TABLE ... UPDATE _row_exists = 0` reaches the storage as an
/// identical command, so `allow_non_metadata_alters` can only be relaxed here.
context->setSetting("allow_non_metadata_alters", 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.

Does the placement of this logic have any impact on a cross-version replication environment where the leader is down-version and the executing local node has the new code?

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.

Posted by an LLM on my behalf.

There is a real cross‑version gap here, but only on the DELETE ... ON CLUSTER path — same‑node and Replicated‑database ALTER replay are both fine.

Detail: how this differs from UPDATE, and where the cluster path leaks

How this differs from UPDATE

The reason UPDATE never needed this bypass — and the reason lightweight DELETE does — comes down to interpreter routing:

  • Lightweight UPDATE (InterpreterUpdateQuery::execute) never touches InterpreterAlterQuery. It builds MutationCommands and calls table->updateLightweight(commands, getContext()) directly, which lands in MergeTreeData::updateLightweightImpl (src/Storages/MergeTree/MergeTreeData.cpp:11916). That path does not consult allow_non_metadata_alters. The setting is only ever read at MergeTreeData::checkAlterIsPossible (line 4973), and the only caller of that is InterpreterAlterQuery::execute (src/Interpreters/InterpreterAlterQuery.cpp:352).
  • Heavy ALTER … UPDATE is intentionally gated by the setting; that is the setting's raison d'être.
  • Ship‑UPDATE mode for the DELETE fallback (PR's first branch) re‑enters InterpreterUpdateQuery, so it inherits UPDATE's setting‑free path — no bypass needed.
  • Ship‑ALTER‑UPDATE mode (the block under discussion) is the only path that deliberately routes back through InterpreterAlterQuery, so it is the only path that ever hits the gate. Hence the bypass exists only here, and there is no analogous gap on the UPDATE side to plug.

The comment's assertion — "the setting can only be relaxed here" — is accurate specifically because DELETE's ship‑ALTER fallback re‑enters ALTER, whereas UPDATE never does.

The DELETE ... ON CLUSTER cross‑version gap

Placement of the flip is safe in every topology except DELETE ... ON CLUSTER, and that's the one this comment is really probing.

  • Local ReplicatedMergeTree. Coordinator (up‑version) writes the mutation entry to ZK; peers replay it at the MergeTree mutation layer, which never calls checkAlterIsPossible. Down‑version peers are unaffected. No gap.
  • Replicated database enqueuing the synthesized ALTER ... UPDATE _row_exists = 0. DDLLogEntry::setSettingsIfRequired (src/Interpreters/DDLTask.cpp:111) snapshots context->getSettingsRef().changes() into the ZK entry, so the allow_non_metadata_alters=true override rides along and is applied to the task context on every peer. Peers re‑enter InterpreterAlterQuery with the bypass in place, at any version that knows the setting name (which is every supported version). No gap.
  • DELETE ... ON CLUSTER. This is where placement bites. The PR's cluster branch (earlier in InterpreterDeleteQuery::execute, ~lines 161–178 on the PR branch) ships raw DELETE ... ON CLUSTER via executeDDLQueryOnCluster and returns before the context copy that sets allow_non_metadata_alters is ever constructed. Peers therefore receive a plain DELETE with no such setting change in the DDL entry, and each peer re‑enters its own InterpreterDeleteQuery from scratch. A down‑version peer runs the old code, never sets the bypass, and fails with the exact ALTER_OF_COLUMN_IS_FORBIDDEN error the PR is meant to eliminate. The fix therefore does not reach mixed‑version clusters until every host is upgraded.

Contrast this with today's master and with UPDATE, both of which rewrite ship‑DELETE / ship‑UPDATE to the resolved sub‑query on the origin before calling executeDDLQueryOnCluster. If the PR did the same — rewrite to ALTER ... UPDATE _row_exists = 0 ON CLUSTER on the origin and let setSettingsIfRequired carry allow_non_metadata_alters=true — the setting would ride the ZK entry and the fix would apply to every peer regardless of version. That symmetry with the UPDATE path is also the only version‑independent way to close the gap; trying to attach the bypass to the shipped DELETE context only helps peers that are new enough to honour a bypass they don't otherwise need.

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.

Yes, and it is disclosed in the PR body because I could not design it away.

Routing is not serialized: DDLLogEntry::toString writes no routing field, and each worker recomputes execute_on_single_replica from its own code (DDLWorker.cpp:755). So mid-upgrade an old worker runs the delete locally and pushes no shard marker (that happens only inside the single-replica path, :869/:953), while a new worker finds is_executed_path absent (:927) and executes as well.

I measured the transient on a genuinely mixed two-node cluster, both initiator directions, with each node running a different binary: two identical mutation entries, is_done = 1, parts_to_do = 0, no failure reason, convergent rows. Duplicated work that converges, not divergence.

I deliberately did not add a coordination protocol. The two closest precedents for widening this same list shipped with no version gate and no mixed-version test (f1e1cff27235b97 for CreateIndex/DropIndex, de6f6127074d063 for settings and comment alters), so a bespoke handshake here would be new machinery for a transient that resolves itself. If you would rather have the gate, say so and I will add it.

@ringerc

ringerc commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Posted by an LLM (Claude Opus 4.7) on behalf of @ringerc after reviewing this PR against the linked issue and an earlier proof of concept; the summary flags the InterpreterAlterQuery claim and various other findings, details behind the fold.

The LLM questions the PR's claim about the narrow use of InterpreterAlterQuery, flags the lack of single-node test cover for the new DELETE inlining, and a few lesser details. See the details block below for the verbiage.

Findings on this PR

1. The "closed carrier" claim is inaccurate. The pre-PR validation gate states:

The synthesized-ALTER carrier class is closed: InterpreterAlterQuery is constructed in exactly two places outside its own file, InterpreterDeleteQuery and StorageWindowView::cleanup(), and both are exempted.

A grep of src/ finds several more construction sites that appear to be missed:

  • src/Interpreters/InterpreterDropIndexQuery.cpp:40
  • src/Interpreters/InterpreterCreateIndexQuery.cpp:86
  • src/Interpreters/InterpreterCreateQuery.cpp:3010
  • src/Interpreters/SystemLog.cpp:931
  • src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:467 and :525

The guard itself is at the storage layer (MergeTreeData::checkMutationIsPossible), which is the right locus and catches every synthesizer uniformly — but that is exactly why the exemption cannot be limited to InterpreterDeleteQuery and StorageWindowView if any of the above ever produces a non-metadata mutation. SystemLog's schema-evolution ALTER MODIFY COLUMN and the MaterializedPostgreSQL sync are the concerning ones: on a deployment that pins allow_non_metadata_alters = 0 in a profile (the intended configuration this PR enables), those internal paths could start throwing ALTER_OF_COLUMN_IS_FORBIDDEN on startup or during replication catch-up. Neither the stateless test nor the new integration test exercises this. Options: an internal-context bypass in checkMutationIsPossible, or the same private-context relaxation these carriers received.

2. The added UDF inlining is not covered on the single-node path. UserDefinedSQLFunctionVisitor::visit was previously only reached because InterpreterDeleteQuery re-entered InterpreterAlterQuery / InterpreterUpdateQuery. The PR now calls the visitor unconditionally at the top of InterpreterDeleteQuery::execute (behind !empty() only), so every DELETE FROM — including local, single-node, and at the default allow_non_metadata_alters = 1 — goes through UDF expansion at a new point in the pipeline.

To be explicit: gating the inlining on the setting would be worse, not better. The whole point of the DELETE FROM ... ON CLUSTER rework in this PR is that dispatching the raw statement without expansion was silently unsafe when the UDF was not present on every host or was defined differently across hosts, and that is not a property of the setting value. Inlining unconditionally is the safe choice, matching what the interpreters this path used to re-enter already did. The concern is purely test coverage: the new test_allow_non_metadata_alters_on_cluster covers the ON CLUSTER branch, but there is no arm asserting that the local branch produces identical serialized/executed statements and identical row outcomes for the shapes the visitor now touches earlier (whole-predicate UDF, UDF inside a larger predicate, UDF containing a merge() table function, nested UDF, PARTITION clause). The AddDefaultDatabaseVisitor::substituteDatabaseInTableFunctions step is cluster-only, which is another divergence between the two paths that a single-node test would pin.

Related: ASTUpdateQuery — the sibling that this PR points at as precedent for forEachPointerToChild — is worth double-checking has the same override in place today, so the same latent-inlining case that motivated adding the override to ASTDeleteQuery is actually closed on the UPDATE side too. The PR body asserts it but I did not verify from the diff.

3. The setting docstring reads self-contradictorily. Already flagged inline on src/Core/Settings.cpp:5523, restating here so it doesn't get lost: the bullet list says UPDATE (as a heavyweight mutation) is refused, then the following paragraph says UPDATE is allowed in every mode it supports. Both statements are true, but the shared word UPDATE covers two different statement forms (ALTER TABLE ... UPDATE versus UPDATE ... SET). Same collision for DELETE WHERE versus DELETE FROM. The doc would be clearer if each bullet used the full statement form.

4. MATERIALIZE TTL phrasing. The doc bullet groups MODIFY TTL (refused only when materialize_ttl_after_modify is enabled) with the mutation-form MATERIALIZE TTL (refused unconditionally) without noting the conditional. Worth one line so a reader doesn't infer symmetry.

5. WindowView::cleanup() under a <const/>-pinned profile. The cleanup path uses cleanup_context->setSetting("allow_non_metadata_alters", true). A <const/> profile constraint is exactly the configuration the new integration test uses on default, and it is also the configuration an operator would use in production to enforce the restriction. It would be worth an arm that creates a WindowView, lets its cleanup fire under that profile, and asserts the housekeeping alter is not rejected by the constraint (or that whatever context-internal bypass makes setSetting succeed there is deliberate).

6. Stateless test lever pins one direction only. 01413_allow_non_metadata_alters.sql now sets alter_update_mode = 'heavy' and lightweight_delete_mode = 'alter_update' globally. A companion arm with alter_update_mode = 'lightweight_force' where the same ALTER TABLE ... UPDATE becomes a lightweight rewrite and therefore succeeds would keep the rule from silently drifting if defaults change. Similarly REWRITE PARTS is in the guard set but does not appear to have a matching --{serverError ...} line.

7. Rolling upgrade transient. The PR body already discloses that on a mixed old/new cluster both workers can complete the same DELETE FROM ... ON CLUSTER entry, giving two identical mutation entries that converge. Fine as a disclosed transient, but a one-liner in the changelog entry would surface it for anyone rolling this out. Related to my first question above.

8. Regression-prevention comment. MutationCommands::hasNonEmptyMutationCommands is the choke-point that decides both execution and refusal, which is the right invariant. A short comment on that predicate (and on the checkMutationIsPossible guard) noting that adding a new ALTER form here also widens what allow_non_metadata_alters = 0 refuses would keep the coupling sticky. This is also related to my "what defenses" question above.

None of these block the core fix, which reads correctly: MergeTreeData::checkMutationIsPossible was the missing seam and moving the guard there is the right change. Findings 1 and 2 are the ones I would want addressed before merge; the rest are polish.

@ringerc

ringerc commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Follow-up posted by an LLM (Claude Opus 4.7) on behalf of @ringerc. Short version: InterpreterUpdateQuery and ASTUpdateQuery already have everything the PR is retrofitting onto the DELETE side, though the new docs only mention alter_update_mode and not lightweight_delete_mode.

Why this PR doesn't touch the UPDATE path — long form

Grepping the current tree confirms the UPDATE side already has the pattern this PR retrofits onto DELETE:

  • ASTUpdateQuery::forEachPointerToChild — present (src/Parsers/ASTUpdateQuery.h:37).
  • UserDefinedSQLFunctionVisitor::visit — called unconditionally at the top of InterpreterUpdateQuery::execute (line 99).
  • executeDDLQueryOnCluster self-dispatch with AddDefaultDatabaseVisitor::substituteDatabaseInTableFunctions — present (lines 140–153).

That is what the PR body means by "as InterpreterUpdateQuery already does". Once DELETE has parity with UPDATE on those three, the UPDATE path is covered by the storage-layer guard for free.

Where the guard actually catches UPDATE. Three surfaces:

  1. Heavyweight ALTER TABLE ... UPDATE flows through InterpreterAlterQuery::executeToTable → runCommandSegments → MergeTreeData::checkMutationIsPossible. Exactly the seam the PR adds the guard to. Refused when allow_non_metadata_alters = 0, no UPDATE-specific change required.

  2. ALTER TABLE ... UPDATE under alter_update_mode = 'lightweight_force' (or lightweight_where_possible that succeeds). InterpreterAlterQuery::executeToTable calls tryRewriteToLightweightUpdate at line 526, before the segments-check reaches checkMutationIsPossible. A successful rewrite bypasses the guard — matching the docs' "UPDATE whenever it runs as a heavyweight mutation, which is the default alter_update_mode = 'heavy' and every case the other modes fall back to". When the rewrite fails, the mode falls back to heavy and hits the guard.

  3. Lightweight UPDATE ... SET (InterpreterUpdateQuery) executes via table->updateLightweight(commands, getContext()). This path does not synthesize an ALTER and does not call checkMutationIsPossible. If the storage does not support lightweight update, it throws NOT_IMPLEMENTED — it does not fall back to a heavyweight ALTER. So the setting has nothing to gate here, and the doc line "the DELETE FROM and UPDATE statements are allowed in every mode they support" is accurate for UPDATE precisely because there is no fallback that would produce a heavyweight mutation.

Why DELETE needed extra plumbing but UPDATE didn't. The asymmetry is one shape only:

  • DELETE FROM t WHERE … under the default lightweight_delete_mode = 'alter_update' synthesizes a ALTER TABLE t UPDATE _row_exists = 0 WHERE … internally, indistinguishable at the storage from a user-written form. Hence the private-context relaxation the PR grants inside InterpreterDeleteQuery before it re-enters InterpreterAlterQuery, and the ON CLUSTER self-dispatch so each host derives its own mode.
  • UPDATE ... SET never synthesizes an ALTER ... UPDATE; it either executes as a lightweight update or fails with NOT_IMPLEMENTED. UPDATE ... SET _row_exists = 0 is already re-routed to ALTER_DELETE access at InterpreterUpdateQuery line 121 but still executes via updateLightweight, so still bypasses the storage guard. Nothing to exempt.

Where the PR could still leave something on the table on the UPDATE side:

  1. No integration-test arm for UPDATE ... SET ... ON CLUSTER under the pinned profile. The "UPDATE just works" claim is structural, not asserted. If a future change adds a fallback path in InterpreterUpdateQuery (say, a "heavy_where_lightweight_fails" mode), that fallback would silently punch a hole in exactly the way DELETE did, with no test to catch it.

  2. The ASTUpdateQuery::forEachPointerToChild claim. The PR body asserts the UPDATE sibling has this override. Grep confirms it does (ASTUpdateQuery.h:37). Worth stating explicitly rather than trusting the assertion, because if the UPDATE side ever loses that override the same latent-inlining bug this PR closes for DELETE would silently re-open for UPDATE.

  3. Doc asymmetry. The setting description carefully explains alter_update_mode for the ALTER UPDATE case but says nothing corresponding about lightweight_delete_mode, even though the DELETE path is where the interesting mode-driven behaviour actually lives (it is what forces the private-context relaxation in the first place). One line noting that lightweight_delete_mode = 'lightweight_update' executes via the lightweight surface and therefore bypasses this setting entirely, versus the default 'alter_update' mode which synthesizes an ALTER but is exempted by the interpreter, would make the DELETE story as self-contained as the UPDATE story.

…E inlining locally

Review of ClickHouse#115287 pointed out that the description used the bare words UPDATE and
DELETE WHERE for the ALTER commands and again for the dedicated UPDATE ... SET and
DELETE FROM statements, so the bullet list and the paragraph below it read as
contradicting each other. Every command is now spelled with its full statement form,
MATERIALIZE TTL is marked as unconditional next to the conditional MODIFY TTL, and the
paragraph states what GRANT and REVOKE of ALTER UPDATE and ALTER DELETE can and cannot
separate: measured, both privileges cover the dedicated statement and the ALTER command
together, so they cannot distinguish the two forms.

01413 pinned alter_update_mode to heavy and lightweight only, so the rule that a
lightweight rewrite never reaches the mutation path was unpinned for lightweight_force;
it now has an arm.

The inlining of SQL user-defined functions added to InterpreterDeleteQuery was covered
only through the ON CLUSTER integration test. 04812 now runs the same predicate shapes
through a local DELETE FROM, which pins that the local path keeps resolving an
unqualified table in the body against the deleted-from table's database.
The second added DELETE arm deleted a row the first one had already removed, so it was
satisfied by the previous statement rather than by its own predicate. Each arm now targets
a distinct freshly inserted row, and the two candidate resolutions of the body select
different rows, so a wrong resolution changes the output: verified by mutating the body,
which reddens the reference.

The comment on hasNonEmptyMutationCommands claimed a command answering it always reaches
the guard. A lightweight ALTER UPDATE is intercepted before runCommandSegments and never
reaches it, so the comment is limited to the commands that do take the heavyweight path.
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. Two of these were real defects in my own artifacts, fixed in 3833eea; the five inline threads are answered individually.

UPDATE path untouched: intentional, and checked rather than assumed. At the base commit UPDATE ... SET already had all three pieces: it inlines SQL UDFs (InterpreterUpdateQuery.cpp:93), dispatches the original statement via executeDDLQueryOnCluster (:147), and ASTUpdateQuery already overrides forEachPointerToChild (ASTUpdateQuery.h:37) - I verified that last one in the diff, since you flagged the assertion. DELETE was the odd one out; this makes it match UPDATE rather than diverge. I deliberately did not add ASTUpdateQuery to the leader-routing list: it was already absent at base, so that is pre-existing and belongs in its own change.

Finding 1. The count is wrong, and here is what it means. Five of your six sites carry only commands AlterCommand::parse accepts, so they never reach the mutation segment: ADD_INDEX, MODIFY_SETTING (the SystemLog site is a table_readonly toggle, not MODIFY COLUMN), MODIFY_DATABASE_SETTING (both PostgreSQL sites) and REPLACE_PARTITION. I ran all four under a <const/>-pinned allow_non_metadata_alters = 0 profile: every one succeeded, with a real ALTER ... UPDATE refused 524 in the same session as control. The sixth is real but not mine: DROP INDEX is refused 524 identically on the base binary (MutationCommand::parse accepts DROP_INDEX under parse_alter_commands, and the pre-existing alter-path guard covered it), which is why it is already in the blocked list. The claim I should have made: the guard sits at the storage layer and catches every synthesizer uniformly, and the two carrying mutation-class commands are the two exempted. Startup and replication catch-up are not exposed.

Finding 5. Context::setSetting bypasses constraints by design, which is what makes the exemption work at all. Under that pinned profile DELETE FROM succeeds while a user-written ALTER ... UPDATE \_row_exists` = 0still fails 524 - so the integration test'sarm already pins the mechanismcleanup()` relies on.

Finding 6. First half right and fixed: lightweight_force was unpinned and now has an arm, confirmed live by flipping it to heavy and watching the reference redden. Second half no: REWRITE PARTS does have a serverError arm.

Finding 2, and I want to be precise about what it proves. 04812 now runs the same shapes through a local DELETE FROM, one fresh row per statement so neither arm is satisfied by the previous one, and the two candidate resolutions select different rows. But it does not discriminate this change: on base the local path gives identical output, because the interpreter it re-enters expands the UDF anyway. It is a regression pin against the two paths diverging, not proof of the new call; the clustered arms remain the load-bearing evidence. My second review model wanted these arms deleted for exactly that reason - I kept them as the pin you asked for, but calling them a proof would be wrong.

3, 4, 8 fixed (full statement forms throughout; MATERIALIZE TTL marked unconditional beside the conditional MODIFY TTL; the predicate comment scoped to commands that actually take the heavyweight path, since a lightweight ALTER UPDATE is intercepted before it). 7: the transient is in the body, not the changelog entry, which is one sentence about what the setting refuses - say the word and I will add it.

Row security: nothing here constrains it. The guard is admission-only and reads one boolean; it does not touch predicates or which rows a mutation selects. If anything it helps, since a clustered DELETE now reaches each host as a DELETE rather than a rewritten ALTER, which is the statement a policy check would want to see.

Defenses against a future ALTER form regressing this: the shared predicate, not a comment. A new form becomes refusable exactly when MutationCommand::parse starts accepting it, because one hasNonEmptyMutationCommands decides both what runs as a mutation and what the guard refuses. There is no second list to keep in sync - that is why the guard went to the storage layer rather than the interpreter.

Rolling upgrade is answered inline with the mixed-version measurement. And thanks for the categorisation answer on the issue, particularly the migrator-tool reasoning; ALTER ... UPDATE/DELETE WHERE being in the blocked set is still the open maintainer call, flagged in the body.

Review of ClickHouse#115287 pointed out that lightweight_delete_mode does not say what happens under
ON CLUSTER, which is the class of divergence issue ClickHouse#115058 was reported from. Each host
derives the mode from its own settings, so hosts with different profile defaults can run the
delete in different modes; a session-level change travels with the distributed DDL entry and
overrides that, except on a host that constrains the setting, which clamps the value back.
@groeneai groeneai added the can be tested Allows running workflows for external contributors label Aug 19, 2026
Review of ClickHouse#115287 noted that the existing coverage exercises a ReplicatedMergeTree table in an
ordinary database, which is not the same case as a Replicated database, while the PR body claimed
the latter was covered by the same predicate.

The arm this adds is the reachable form of that case. DELETE FROM ... ON CLUSTER cannot be used
against a Replicated database at all: the host-side entry is a non-initial query, so
DatabaseReplicated::tryEnqueueReplicatedDDL rejects it with INCORRECT_QUERY, both with and without
ignore_on_cluster_for_replicated_database, and both before and after this PR. A plain DELETE reaches
the same routing instead, because the database replicates it whenever it has more than one shard.

Measured over the four-host shape: before the DDLWorker change every replica of a shard mutates the
shared table, so system.mutations holds 2 entries per host, and after it holds 1.
The paragraph said every host derives the mode, which overstates it: DDLWorker leader-routes a
DELETE when the storage supports replication, so a replicated shard runs it on one replica and that
replica's settings are the ones that decide.
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9f9777cf1 with master 4b3f269d1 (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

7 object files changed (+35.37 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDeleteQuery.cpp.o 130.69 KiB 162.87 KiB +32.18 KiB (+24.63%)

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

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

Job report

@ringerc

ringerc commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

@groeneai

Finding 2 ... on base the local path gives identical output, because the interpreter it re-enters expands the UDF anyway ... second review model wanted these arms deleted for exactly that reason - I kept them as the pin you asked for, but calling them a proof would be wrong.

If there's a good justification for not having the local test as it follows a demonstrable common path, that's ok; just ensure that comments clearly call this out so future reviews don't wonder why there's no test cover for the local-only path.

Otherwise fine.

@PedroTadim PedroTadim self-assigned this Aug 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov @alesapin maybe I need your help because allow_non_metadata_alters setting was added by you. It seems it was not updated in a long time, and it doesn't validate many new features. This becomes more complicated to validate when there is a delete computed across nodes. What is your verdict? Removing this setting is not a good idea I would say.

The two DELETE FROM rows read the same on a binary without the routing change,
because the local path re-enters the UPDATE or the ALTER interpreter and both of
those already inline SQL function bodies before the database is filled in. Record
that at the arms so the absent local-only discrimination is not read as a gap.

Asked for by @ringerc in review.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Recorded at the arms in 327f65c.

The comment states the invariant rather than the history: a local DELETE FROM re-enters either the UPDATE or the ALTER interpreter, and both of those already inline SQL function bodies before the database is filled in (InterpreterUpdateQuery.cpp:92-93 then :106; InterpreterAlterQuery.cpp:418-419 then :426). So the two rows hold whichever of the three interpreters does the inlining, which is why there is no arm that discriminates the local path alone.

Measured rather than argued, on two debug binaries: base 82b5e46f and the fix fcc0f60f produce byte-identical output for both DELETE arms. The same pair is not equivalent in general, which is the control for that claim: ALTER TABLE t UPDATE v = 2 WHERE id = 1 under allow_non_metadata_alters = 0 returns OK on base and Code: 524 on the fix.


/// The cluster case ships the DELETE itself rather than a rewritten ALTER, so that every host
/// derives its delete mode and its own storage-check relaxation from its own settings.
if (!delete_query.cluster.empty())

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 ON CLUSTER dispatch now exists only on the supportsLightweightDelete() path. For engines that take the earlier supportsDelete() branch instead (KeeperMap, EmbeddedRocksDB, StorageObjectStorage/Iceberg, system.wasm_modules, and aliases of them), DELETE ... ON CLUSTER still falls through to the local table->mutate() call and silently ignores the cluster clause. That turns a cluster-scoped delete into a single-node delete with no error.

Can we move the !delete_query.cluster.empty() handling above the supportsDelete() / supportsLightweightDelete() split, or explicitly reject ON CLUSTER in the direct-delete branch until that path is wired too?

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 asymmetry is real, but it predates this branch rather than being introduced by it. On master at 2ae8a25a the supportsDelete branch reads delete_query.cluster nowhere, and executeDDLQueryOnCluster is not included in that translation unit at all: the only two reads of the clause are the UPDATE and ALTER text templates, and both sit inside the supportsLightweightDelete branch. So a DELETE FROM ... ON CLUSTER against KeeperMap or EmbeddedRocksDB already falls through to the local mutate call today, exactly as it does here.

What this diff changes is how the lightweight branch dispatches: it ships the DELETE itself instead of a rewritten ALTER. It adds nothing to the direct-delete branch and removes nothing from it, so the gap is unchanged in kind.

I am not folding the rejection into this PR. Making a statement that succeeds today throw is backward incompatible, and it would widen a PR that @ PedroTadim has already asked an area expert to review. A reviewer is welcome to decide otherwise.

groeneai and others added 2 commits August 30, 2026 10:26
Master removed the window view storage in ClickHouse#114747, so the branch's only conflict
is the modify/delete on StorageWindowView.cpp. Accepted the deletion.

The arm it carried relaxed allow_non_metadata_alters around the internal cleanup
ALTER that StorageWindowView issued for windows past the watermark. That
synthesizer no longer exists, so the relaxation has no caller and is dropped
rather than relocated. The other internal synthesizers the branch covers are
unaffected.

Co-Authored-By: Claude Opus 5 <[email protected]>
Build (arm_tidy) failed with readability-duplicate-include on
InterpreterDeleteQuery.cpp:12 and :13, which dropped every downstream job,
including all four Bugfix validation jobs, so Finish Workflow then failed its
new_tests_check hook for having no validation result.

Neither side carried a duplicate on its own. This branch added the two
UserDefined includes to the sorted block; master's legacy-toTime change later
added the same two to the leading block. The merge took both. Removed the pair
this branch added and kept master's placement, so the file's include layout now
matches master exactly. Duplicate includes compile fine, which is why a plain
build of the translation unit did not catch it.

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

Copy link
Copy Markdown
Collaborator Author

Build (arm_tidy) was the only red, and it dropped every downstream job, so nothing else on this PR ran. The master merge took the two UserDefinedSQLFunctionFactory and UserDefinedSQLFunctionVisitor includes from both sides; neither side had a duplicate on its own, and readability-duplicate-include is an error under this repository's WarningsAsErrors. Removed the pair this branch added and kept master's placement, in 81515f2e. clang-tidy-22 gives 2 diagnostics before and 0 after.

Master had moved past the merge base by then, so the branch was conflicting on the file remove-window-view deleted. Merged 2ae8a25a and accepted the deletion: the arm it carried relaxed allow_non_metadata_alters around the cleanup ALTER that StorageWindowView issued, and with that synthesizer gone the relaxation has no caller, so it is dropped rather than relocated. The description no longer names it. 01413_allow_non_metadata_alters and 04812_merge_table_function_in_mutation_udf both pass on the merged tree.

One gap I did not close: nothing pins the initiator-side database substitution for the dedicated clustered DELETE. I measured it here, the persisted command reads merge('<target database>', ...) and the surviving keys are the target database's rather than the session's, but a deterministic read-back needs the executing host's lightweight_deletes_sync pinned, which is more than a stateless arm can do. Say the word and I will add it.

`DELETE FROM ... ON CLUSTER` is queued as itself rather than as a rewritten
`UPDATE` or `ALTER`, so it substitutes the database into the table functions of
its predicate on its own, before `executeDDLQueryOnCluster` replaces
`currentDatabase()` with the database of the session. Nothing pinned that
substitution: every clustered `DELETE FROM` covered so far uses either a literal
predicate or a SQL user-defined function, and both of those shapes return the
same rows whether the substitution runs or not.

Measured with the substitution removed, the new arm deletes `id = 3`, the row
that the source table of the session database selects, instead of `id = 2`. The
twelve pre-existing arms of this test and both predicate shapes above stay green
in that build, so none of them can see the difference.

The read-back is deterministic: the statement waits for the host through
`distributed_ddl_output_mode`, and `lightweight_deletes_sync = 2` makes the host
wait for its own mutation. 13 runs pass, 5 of them concurrent with each other.

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

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_debug, targeted) / Segmentation fault (STID: 2809-3ce4) failure on b49f3f3: #117181.

That crash is pre-existing on master and not caused by this PR. The unguarded dereference is at MutationsInterpreter.cpp:1415, which this PR does not touch and which is still unguarded on master today; it is reachable by ALTER TABLE ... MATERIALIZE TTL over an Alias table or a materialized view whose metadata carries a TTL.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b49f3f3

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
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID 2809-3ce4) not PR-caused, pre-existing trunk crash: MutationsInterpreter.cpp:1415 dereferences source.getMergeTreeData() with no null check, and that accessor is a dynamic_cast returning nullptr for a non-MergeTree storage, so MergeTreeData::getSettings faults on a null this. Every sibling call site in the same file guards the pointer. First-ever signature (frame-keyed 90-day census: 1 row / 1 PR / 0 master, against a positive control of 452 rows / 26 PRs for MutationsInterpreter::prepare) #117181 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found not PR-caused: a cancelled DETACH DATABASE sits 393 s in MergeTreeBackgroundExecutor::removeTasksCorrespondingToStorage, waiting on a mutation whose MutateTask::prepare is blocked in CompletedPipelineExecutor::Data::~Data while isStorageTouchedByMutations builds an IN set index. The nested pipeline's destructor waits with no timeout and no cancellation hook, so is_cancelled = 1 has no effect. Leaf-keyed 30-day census: 4 rows / 4 distinct PRs / 0 true-master rows, against a family-keyed control of 1225 rows / 552 PRs a fix task is created (investigating at full effort - fixing-PR link to follow here)
Upgrade check (amd_release) / Cannot start clickhouse-server not PR-caused, CI-harness defect on master: tests/config/install.sh symlinks silk.xml with no version gate, so the previous-release server rejects enable_silk_runtime with Code: 137 ... UNKNOWN_ELEMENT_IN_CONFIG and never starts. Onset is a cliff at 2026-08-30 13:48:57Z (65 rows / 64 distinct PRs in 7 days, 0 true-master rows, still firing at 19:06Z) #117172 (ours, open)
Upgrade check (amd_release) / Check failed the same job's second abort row (Check failed with exit code 1), same task_url, same event as the line above #117172 (ours, open)

None of the four is attributable to this diff, which only tightens allow_non_metadata_alters
validation so a mutation-triggering ALTER is refused earlier. It touches none of the frames above.

Reports:

Session id: cron:our-pr-ci-monitor:20260830-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_tsan) / Hung check failed, possible deadlock found line on b49f3f3: #113939.

My ledger row above stops one level short of the leaf. The destructor's join really has no timeout, but what it waits for is an S3 retry loop that does have a cancellation hook. hung_check.log truncates the system.stack_trace dump and sql_stacktraces.log holds only the waiting threads, so the leaf is invisible in both; c_stacktraces.log from the same job has all 918 threads:

  • 3 MergeMutate threads block in CompletedPipelineExecutor::Data::~Data joining their pipeline thread.
  • Each of those 3 pipeline threads blocks in PipelineExecutor::executeImpl at pool->wait().
  • Each of the 3 pipelines has a worker parked in AWSClient::AttemptExhaustively -> HttpClient::RetryRequestSleep, on a HeadObject against the dead dummy.parquet target reached from StorageObjectStorageSource::lazyInitialize -> S3ObjectStorage::getObjectMetadata. Two further workers wait on another builder's promise in CreatingSetsTransform::startSubquery, which clears as soon as those HeadObject calls do.

Since pool->wait() needs every worker of its pool to return, the S3 retry is on the critical path of all three pipelines, and nothing else in the chain can release them. This is not thread starvation either: 325 of the 460 global-pool threads were idle.

Client::RetryStrategy::ShouldRetry (src/IO/S3/Client.cpp:110) already exits that loop on CurrentThread::get().isQueryCanceled(), and Client::HeadObject (:418) already reports the cancellation cause instead of the stale S3 error. Both are inert here because a merge or mutate thread group resolves its cancellation predicate through a process-list element it does not have (src/Interpreters/ThreadStatusExt.cpp:159), so the predicate is constant false and the loop runs its full 501-attempt budget. #113939 installs real predicates on that group, which is what makes the existing hook fire.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115287&sha=b49f3f3d9b387d15776d7b412cbdc619a4c05eee&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Comment thread src/Core/Settings.cpp
- `lightweight_update` - run lightweight update if possible, run `ALTER UPDATE` otherwise.
- `lightweight_update_force` - run lightweight update if possible, throw otherwise.

For `DELETE FROM ... ON CLUSTER`, each executing host derives the mode from its own settings, so

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.

The new lightweight_delete_mode text makes DELETE FROM ... ON CLUSTER part of the public contract, but the source-level DELETE statement docs in src/Parsers/ParserDeleteQuery.cpp still describe every DELETE as a rewrite to ALTER TABLE ... UPDATE controlled by lightweight_deletes_sync.

After this branch, the clustered path is queued as DELETE itself and each executing host can re-resolve lightweight_delete_mode, so the setting docs and the statement docs will disagree in the release. Can you update the structured DELETE docs in ParserDeleteQuery.cpp in the same 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.

Checked both doc sites at the current head before answering.

ON CLUSTER is not new to the statement docs: ParserDeleteQuery.cpp:123 and :211 already document DELETE FROM [db.]table [ON CLUSTER cluster] .... This branch changes where the delete mode is resolved, not that surface.

Nothing in that file ties the ALTER TABLE ... UPDATE rewrite to lightweight_deletes_sync. Line 141 attributes only synchronicity to it, and that still holds: the queue entry drops ON CLUSTER (ASTDeleteQuery.h:21, executeDDLQueryOnCluster.cpp:249), so each host runs the local path and copies lightweight_deletes_sync into mutations_sync at InterpreterDeleteQuery.cpp:278.

The imprecise sentence is :194-196, "DELETE queries are transformed to ALTER TABLE ... UPDATE". It omits lightweight_delete_mode = lightweight_update / lightweight_update_force, which run a lightweight update instead. That predates this branch: lightweight_delete_mode is declared on master at Settings.cpp:5029, and the sibling statement docs already state the exception at ParserUpdateQuery.cpp:169. Revert this branch and :194 still needs the same edit, so it is not a contradiction this PR introduces.

I am leaving it out of this PR: it is a standalone master docs fix that also regenerates the autogenerated docs/reference/statements/delete.mdx. The behaviour this branch does add, per-host mode resolution for a clustered delete, is documented on the setting itself at Settings.cpp:5037.

@ringerc

ringerc commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Looks like this is still pending maintainer eyes. I'll keep an eye on it.

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov one last call to review

/// Every command that passes `hasNonEmptyMutationCommands` rewrites parts on disk.
/// Callers that synthesize an ALTER on behalf of a lightweight write relax the setting
/// on their own context copy, so provenance is decided there, not by command shape.
if (!settings[Setting::allow_non_metadata_alters] && commands.hasNonEmptyMutationCommands())

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.

allow_non_metadata_alters = 0 no longer fails this class of ALTER atomically. runCommandSegments applies earlier AlterCommands segments before it reaches the later MutationCommands segment and calls checkMutationIsPossible (InterpreterAlterQuery.cpp:345-375), so a query like ALTER TABLE t ADD COLUMN x UInt8, DELETE WHERE 0 now commits the ADD COLUMN and only then throws ALTER_OF_COLUMN_IS_FORBIDDEN.

That is a user-visible regression from “the statement is refused” to “the statement partially succeeds and then raises”, which is especially risky for a protective setting like this one. Can we reject non-empty mutation segments up front, before any segment runs, instead of only from this per-segment hook?

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.

Measured before answering, on this head (9f9777cf) and on a master build from today (fb2a5923, without this PR).

The ADD COLUMN does survive. It also survives on master, so this PR does not introduce it, and there is no "the statement is refused" baseline to regress from:

binary ALTER TABLE t ADD COLUMN x UInt8, DELETE WHERE 0 with allow_non_metadata_alters = 0
master fb2a5923 rc=0, full success: x added and the DELETE WHERE 0 mutation created and completed
this head Code: 524; x added; 0 mutations

The only change for that statement is that the data-rewriting mutation is refused instead of executed, so strictly less runs than before and nothing previously refused is now accepted.

Per-segment refusal under this setting is pre-existing as well. On the same master build:

SET allow_non_metadata_alters = 0;
ALTER TABLE t ADD COLUMN x2 UInt8, DELETE WHERE 0, DROP COLUMN v;
-- Code: 524 ... '(DROP COLUMN v)' ... (ALTER_OF_COLUMN_IS_FORBIDDEN)
-- x2 committed, and the intervening DELETE WHERE 0 mutation ran to completion

runCommandSegments validates each segment when it reaches it, and this PR changes neither that loop nor segment ordering.

On moving the check up front beside validateMutationsAllowed: that helper is engine-blind because disable_insertion_and_mutation is a server setting. This one is not. checkMutationIsPossible is a per-storage virtual and only MergeTreeData reads the setting; the Join, KeeperMap, EmbeddedRocksDB, Redis, object-storage/Iceberg, Memory and system.wasm_modules overrides all take const Settings & unused. Measured on both binaries: ALTER TABLE <Memory> DELETE WHERE k = 2 under allow_non_metadata_alters = 0 deletes the row and is refused by neither. An up-front reject in the interpreter would start refusing all of those, which is wider than the reported bug and wider than what the setting documents.

So I am keeping the check in the predicate that already decides whether the mutation runs. Atomicity of a multi-segment ALTER is a separate, pre-existing property.

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.

TL;DR: the issue identified is real, but orthorgonal to this PR and not a new regression introduced by it.

@groeneai Look for existing github tickets for the problem. If none are found, raise a new github issue for it. Link to #115287 (comment) for context.

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.

An existing ticket covers it, so I have not raised a new one: #103653 (open since 2026-04-28, comp-ddl + comp-mutations, assigned).

Same defect, different trigger. Its root cause section names this exact seam: runCommandSegments commits each segment as it reaches it, so an earlier segment is already committed when a later one is rejected, and nothing rolls it back. Verified still true on master (fb2a5923): table->alter commits at InterpreterAlterQuery.cpp:367, the next segment's check runs at :374, the loop has no catch, and validateSegmentsCombination (:225) pre-validates nothing across segments beyond partition/execute mixing. Its "Open risks" section already flags "other combinations of DDL + DML across segments", which is what ADD COLUMN x UInt8, DELETE WHERE 0 is.

Its repro trips the seam with RENAME COLUMN c0 TO c1, UPDATE c0 = 1 WHERE true, where the RENAME sticks after the statement fails with NO_SUCH_COLUMN_IN_TABLE, rather than with the setting check. The mechanism, the code location and the suggested fix (cross-segment validation before any commit) are the same, so I read it as covered rather than filing a duplicate.

Agreed on your reading that it is orthogonal to this PR, so I am not touching the diff here.

@ringerc

ringerc commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

@groeneai Rebase this and rebuild it against current master.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The tip 9f9777cf and two earlier commits (4d09e6a8, 3023c2d7) are master merges pushed by @ alexey-milovidov. A rebase would force-push over a maintainer's commits on this branch, so I am not doing that on my own judgement. GitHub also reports this branch as MERGEABLE / CLEAN, so there is no conflict for a rebase to resolve.

I did the rebuild half locally instead of restarting CI:

  • Current master 01b8f1c9 (today, 06:16 UTC) merges into the branch with zero conflicts, and the merge leaves this PR's diff unchanged: the same 15 files, 449 insertions.
  • The merged tree builds clean with the CI-pinned clang-22.
  • This PR's own stateless tests pass on that build: 01413_allow_non_metadata_alters, 04811_merge_table_function_in_mutation_on_cluster, 04812_merge_table_function_in_mutation_udf.
  • A/B against a pristine build of the same master commit: ALTER TABLE t DELETE WHERE key = 999 under allow_non_metadata_alters = 0 is still accepted on master, and is refused on the merged branch with Code: 524 ... will modify data on disk, but setting 'allow_non_metadata_alters' is disabled. So the defect is still live on today's master and the fix still holds against it.

I have not pushed that merge, because it would restart a CI run that finished green on the current head, and the last three refreshes of this branch were the maintainer's own merges rather than mine. If you or a reviewer want the branch refreshed here, say so and I will push a plain non-force master merge (never a rebase).

@ringerc

ringerc commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

@alexey-milovidov @PedroTadim Anything I can do to help progress this?

@alexey-milovidov alexey-milovidov self-assigned this Sep 23, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 9611ce3 Sep 23, 2026
174 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 Sep 23, 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 comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). 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.

allow_non_metadata_alters=0 does not block many mutation-triggering ALTERs and its documentation is unclear

5 participants