Skip to content

Use the database of the updated table in the expression of an UPDATE - #113748

Merged
PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/interpreter-update-query-merge-database-substitution
Aug 9, 2026
Merged

PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/interpreter-update-query-merge-database-substitution

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixes UPDATE and lightweight DELETE reading the wrong tables when the database of the updated table differs from the database of the session. The expression of the mutation is now canonicalized against the database of the updated table, both for the merge table function, which uses the current database implicitly, and for unqualified table identifiers. Previously such names were resolved against the database of the session, so the statement silently updated or deleted rows selected from a different table.

Description

Follow-up to #113185, which did this for ALTER.

With t in db1, a src in both db1 and the session database, and the session on the latter, UPDATE db1.t SET v = 9 WHERE id IN (SELECT id FROM merge('^src$')) updates the row selected from the session's src. The same happens with a plain identifier FROM src, in the assignments, and for DELETE at lightweight_delete_mode = 'lightweight_update'.

InterpreterUpdateQuery::execute had two exits and neither substituted a database, so every unqualified name resolved against whatever current database the interpreting context held. Forcing ALTER ... UPDATE through tryRewriteToLightweightUpdate reaches the same updateLightweight yet resolves in the table's own database.

The fix mirrors the two calls of InterpreterAlterQuery: the narrow substituteDatabaseInTableFunctions in the ON CLUSTER branch, and, past the replicated-database branch, expanding common table expressions then the full visitor. InterpreterDeleteQuery needs no change, since its rewrite goes through this interpreter. The database is also pinned before the access rights are built, so an unqualified target no longer dispatches with an empty database.

Validated on a debug build against pristine master, each added read-back being a witness where the unqualified form reads different rows on the two binaries and a control otherwise. The stateless tests touching UPDATE and lightweight updates show no regression, all three files fail on master and pass with the change, and each mutant reddens only its own arms.

Inlining SQL user-defined functions before the _row_exists split means a UDF expanding to 0 asks for ALTER DELETE, not ALTER UPDATE, as ALTER already does after the same expansion. The value gate is unchanged and no grant permits anything it did not before.

An unqualified UPDATE ... ON CLUSTER now dispatches the database of the initiator, matching ALTER. #107486 pins the same database, so whichever lands second needs a rebase.

Version info

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

`UPDATE` and the lightweight `DELETE` rewrite read the wrong tables, silently, when the
database of the updated table differs from the database of the session. With `t` in `db1`,
a `src` in both `db1` and the session database, and the session on the latter,
`UPDATE db1.t SET v = 9 WHERE id IN (SELECT id FROM merge('^src$'))` updates the row
selected from the session's `src`. The same happens with a plain identifier `FROM src`, in
the expressions of the assignments, and for `DELETE` at
`lightweight_delete_mode = 'lightweight_update'`. The direct `UPDATE` form needs no
non-default session setting.

`InterpreterUpdateQuery::execute` had two exits, `executeDDLQueryOnCluster` and
`table->updateLightweight`, and neither substituted a database, so the expression reached
`MutationsInterpreter` verbatim and every unqualified name resolved against whatever
current database that context held.

This is a disagreement of the engine with itself rather than a choice of semantics:
forcing `ALTER ... UPDATE` through `tryRewriteToLightweightUpdate` calls the same
`table->updateLightweight` (both arms show no mutation and two patch parts, the
lightweight patch-part signature) yet resolves the name in the database of the table.

The two calls of `InterpreterAlterQuery` are mirrored: the narrow
`substituteDatabaseInTableFunctions` inside the `ON CLUSTER` branch, because
`executeDDLQueryOnCluster` builds a visitor that rewrites only a bare `currentDatabase()`
and has no table-function arm; and the full visitor after the replicated-database branch,
which a replica also runs when it re-executes the queued entry with its own database.
`InterpreterDeleteQuery` needs no change, since its rewrite already constructs an
`InterpreterUpdateQuery`. The database of the resolved table is pinned at the existing
best-effort resolution, before the access rights are built, so an unqualified target no
longer reaches the distributed DDL queue with an empty database while those rights are
expanded to the configured default database of every host.

Follow-up to ClickHouse#113185, which did this for `ALTER`.
`AddDefaultDatabaseVisitor` records the aliases of a `WITH` clause only when the clause is
recursive, so with the visitor now running on the expression of an `UPDATE` a plain
`WITH c AS (SELECT id FROM src) SELECT id FROM c` had its alias qualified as if it were a
table and the statement failed with `UNKNOWN_TABLE`. The expression is executable before
this change, so keeping it executable is part of canonicalizing it.

`InterpreterAlterQuery` already runs `ApplyWithSubqueryVisitor` immediately before its own
`AddDefaultDatabaseVisitor`, under a comment naming this exact hazard; the same ordering is
used here for the two sub-expressions the visitor is applied to. The table read inside the
expanded body is then still unqualified, so it is resolved in the database of the updated
table like every other name, which is what the two added assertions check: the row selected
through the alias is the one from the updated table's database, not the session's.
…n UPDATE

`AddDefaultDatabaseVisitor` remembers the names of the recursive common table
expressions it walked in a member that is never cleared, so one instance shared by
two independent expressions carries the names of the first into the second. The
name of a recursive common table expression in the predicate then suppressed the
qualification of a table of the same name in the assignments, and that table was
resolved in the database of the session instead of the database of the updated
table. A separate instance per expression matches the way the visitor is
constructed everywhere else: `InterpreterCreateQuery` builds a fresh one for each
of the three expressions it walks, and every other place walks a single one.

The old analyzer resolves a common table expression in a subquery of a mutation as
a table, so the arms of the test that use one request the analyzer explicitly.
The body of a SQL user-defined function is an opaque function call while the
update expression is canonicalized, so an unqualified table inside a body was
left to be resolved later, in a context whose current database is not the
database of the updated table. `InterpreterAlterQuery` inlines the bodies
before it substitutes the database; the update path did not, so a UDF body was
a way for the carrier this PR closes to survive.

Expand the functions once, before the assignments are classified and therefore
before both database visitors, passing the whole query as the sibling does.

`ASTUpdateQuery::predicate` and `::assignments` are separate pointers to nodes
that `children` also holds, and the class did not override
`forEachPointerToChild`, so a visitor that replaced a child could not repair
them. `UserDefinedSQLFunctionVisitor` replaces the node it is handed when that
node is itself a function call, which is the case when the whole predicate is
one, and without the override the expansion landed in `children` alone while
the member kept pointing at the unexpanded node. Adding the override is what
makes `WHERE udf(id)` resolve in the database of the updated table; the
assignment side already worked, because there the call sits below an
`ASTAssignment` and no member points at it.

Also make the recursive-common-table-expression arm read back a value that
differs from the one the row already holds, so it fails if the statement does
not update the row at all rather than only when it updates the wrong one.
A SQL user-defined function is a global object rather than a database-scoped
one, so a test that creates a function under a fixed name conflicts with
concurrent copies of itself.  The plain flaky check runs the tests a pull
request changes fifty times without partitioning the copies across workers, so
one copy's `DROP FUNCTION` deletes the definition while another is still
running: measured in that shape, the previous form of
`04693_merge_table_function_in_mutation` fails six times of fifty with
`Code: 46` naming the dropped function.

The three arms that need a function move to
`04812_merge_table_function_in_mutation_udf.sh`, which builds the names from
the name of the test database.  That is what every stateless test creating a
function from a per-run-unique name already does, and none of them needs a
`no-parallel` tag, whereas thirty-three of the forty-six that use a plain fixed
name do.  A name cannot be a query parameter, since `ParserCreateFunctionQuery`
parses it as a plain identifier, but a shell test substitutes it before the
server parses the query at all.

The companion test rebuilds its own fixture, so its expected values are
measured rather than carried over, and it prints the whole table after each
statement: an arm therefore also fails when the statement updates no row,
not only when it updates the wrong one.  All three arms are witnesses on
pristine master and on the intermediate revision that lacks the inlining of
function bodies, and the three outcomes are distinct for every arm.

No production code changes.
The three clustered arms the test already had are all repaired on the host: the
rewrite that removes `ON CLUSTER` keeps the database pinned on the initiator, so
a single-host cluster re-enters the same interpreter and runs the full visitor,
which qualifies a bare identifier and inserts a database into a one-argument
`merge`. Reverting the narrow substitution in the `ON CLUSTER` branch therefore
changed no result, and nothing in the corpus pinned that call.

`merge(currentDatabase(), ...)` is the one shape the host cannot repair. The
database is pinned before the access rights are built, so every access element
names a database, `executeDDLQueryOnCluster` leaves `use_local_default_database`
false, and its own visitor replaces `currentDatabase()` with the database of the
session. The entry reaches the queue already carrying that database as a
literal, where the host's `substituteCurrentDatabase` is a no-op. The wrong
table is read and nothing is reported.

Measured on the queued distributed DDL entry, with the source table holding a
different row in each candidate database: with the substitution the entry
carries the database of the updated table and the statement selects 2; without
it, and on the commit before this change, it carries the database of the session
and selects 3, in both cases with no error.

The sibling ALTER section of the same file already covers this form.
… function

`InterpreterUpdateQuery` substitutes the database into table functions twice in the
`ON CLUSTER` branch, once for the predicate and once for the expressions of the
assignments. Only the predicate call had a test: every `SET` clause in this file
assigned a literal, and no other stateless test runs an `UPDATE ... ON CLUSTER` at
all, so deleting the assignments call alone left the whole suite green.

The new arm puts `merge(currentDatabase(), ...)` in a `SET` subquery. That form is
the one the host cannot repair, because `executeDDLQueryOnCluster` has already
replaced `currentDatabase()` with the database of the session by the time the entry
is dequeued; the one-argument `merge('...')` form and a bare identifier are both
recovered on the host, so either of them would read the same value with and without
the call and would be a control rather than a witness.

Measured on Build-ID-asserted binaries: the arm reads 32 with the call present, from
the source table in the database of the updated table, and 33 without it, from the
same-named table in the database of the session. Both differ from the 4 the row
already holds, so the read-back also fails if the statement updates no row at all.
A mutant deleting only the assignments call reddens exactly this one reference line
and leaves the other eleven byte-identical, while the existing mutant deleting the
whole block now reddens two lines, which is what shows the two calls are pinned
independently.

No source change.
@groeneai

groeneai commented Aug 6, 2026

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

An independent model reviewed this change against the code on disk, without access to the
implementation notes, and a second one re-reviewed the diff. Findings and how each was resolved.

❌ A SQL user-defined function in the update expression was not canonicalized.
UserDefinedSQLFunctionVisitor::visit had three call sites in src/ on master
(InterpreterAlterQuery.cpp:419, InterpreterCreateQuery.cpp:1864, TreeRewriter.cpp:1635) and
InterpreterUpdateQuery.cpp was not one of them, while InterpreterAlterQuery expands
user-defined functions at :419 before both of its database visitors at :443 and :498. So the
body of such a function was still an opaque call when the substitution ran, and it was expanded
later, during mutation analysis, in a context whose current database is not necessarily the
database of the updated table. A function body can hold a table reference: the body is parsed as a
plain lambda expression, only its shape is validated, and
02148_sql_user_defined_function_subquery already covers a body that selects from an unqualified
table. Fixed by mirroring the sibling, with arms that read a same-named source table from inside
such a body — nested in the predicate, inside the assignment arithmetic, and as the whole predicate.

❌ Expanding a function whose call is the whole predicate needed a pointer-repair hook.
ASTUpdateQuery::predicate and ::assignments are separate pointers to nodes that children also
holds, so when the visitor replaced the child it left the member aimed at the un-expanded node, and
updatePointerToChild could not repair it because the class did not override
forEachPointerToChild. Measured: with the expansion but without the override, a predicate whose
root is a bare function call still read the session database. The assignment side needed nothing,
because there the call sits under an ASTAssignment and no member points at it. Fixed with the
three-entry override, matching ASTAlterCommand.

❌ A user-defined function name is global, so those arms collided with concurrent copies of the
same test.
ci/jobs/functional_tests.py:179-180 maps the plain flaky check job flavour to
--flaky-check without --no-self-parallel; only targeted adds it, and
tests/clickhouse-test:5333-5340 shows that flag is exactly what partitions all copies of one test
onto a single worker. With rerun_count = 50 spread over the job's several workers, one copy's
DROP FUNCTION removes the definition while another is mid-file. Measured under that shape
(--flaky-check --test-runs 50 --jobs 8 --max-failures 5): the revision with fixed-name functions gives 35 OK / 6 FAIL with 12
UNKNOWN_FUNCTION occurrences, while the three shipped files give 150 of 150. Fixed by moving those
arms into a companion shell test whose function names are built from ${CLICKHOUSE_DATABASE}, i.e.
unique per run — the tree's own convention. Counting a test as per-run-unique when every name it
creates interpolates a CLICKHOUSE_* variable, over the runnable stateless files that run
CREATE FUNCTION: 7 are per-run-unique and none of the 7 carries no-parallel, whereas 47 of the
72 that create at least one plain fixed name do.

❌ The assignments half of the clustered substitution had no witness anywhere in the corpus.
The ON CLUSTER branch calls substituteDatabaseInTableFunctions on both the predicate and the
assignments, but every clustered arm put the table function in the WHERE predicate and every SET
was a bare literal, so deleting the assignments call left the whole suite green. Corpus-wide: exactly
one file contains an UPDATE ... ON CLUSTER at all, and none matched
ON CLUSTER[^;]*SET [^;]*(merge\(|SELECT). Fixed with an arm whose SET reads
merge(currentDatabase(), ...), which is the one shape a host cannot repair for itself and therefore
the only witness available on that path, offset so a statement that updates nothing also fails. The
two calls are now pinned separately: a mutant deleting the whole branch reddens two reference lines,
one deleting only the assignments call reddens exactly one.

⚠️ One test arm could not distinguish a correct result from no result. The recursive
common-table-expression arm read back the same row an earlier arm had already set to the same
value, so it returned the expected number both when the statement did the right thing and when it
did nothing at all; only the wrong-database path differed. That matters here because the defect the
arm pins is itself a skipped qualification, so an oracle blind to a skip is the wrong shape. Fixed
by offsetting the assigned value so all three outcomes differ, and a mutant that turns the
statement into a no-op is now caught, where before it was not.

⚠️ Two rejected alternatives to the collision fix, each with the measurement that rejected it.
Adding no-parallel passes, but costs coverage: over the parameter= job flavours in
ci/defs/job_configs.py, including those assembled with f-strings, there are 11 parallel flavours
and 11 sequential, and 9 of the parallel ones have a sequential twin differing only on that axis —
so the loss is the two twinless flavours plus a halved repeat count elsewhere. Keeping fixed names
with CREATE FUNCTION IF NOT EXISTS and no
DROP also passes, at the cost of leaking two global functions after every run, which nothing would
flag since the runner's leftover check is tables-only. Parameterising the name is not available at
all: ParserCreateFunctionQuery.cpp:27 constructs ParserIdentifier for the function name, and that
constructor defaults allow_query_parameter to false (ExpressionElementParsers.h:36), so a
{name:Identifier} substitution cannot parse in that position — which is why the fix substitutes in
the shell, before the server parses anything.

⚠️ A reviewer read the canonicalization as covering every table function that uses the current
database implicitly, and filed the remaining ones as a blocker.
The mechanism is real:
AddDefaultDatabaseVisitor::visitTableFunction rewrites merge only, so a bare loop(t) or
dictionary(d) still resolves its argument against the session database
(TableFunctionLoop.cpp:110 and :136, TableFunctionDictionary.cpp:52). Not accepted as a blocker
on this change, with the measurement: the limit lives in the shared visitor, which this change does
not touch, and the ALTER path constructs that same visitor with that same scope at
InterpreterAlterQuery.cpp:443 and :498 — so the identical gap exists on the already-shipped path
today, while before this change an UPDATE canonicalized nothing at all. The gap is therefore
narrowed, never widened. What the finding did correct is a clause of the changelog entry, which
generalized to "table functions that use the current database implicitly" where the shipped behaviour
is merge specifically; the entry now names merge, and the limit is disclosed in the validation
gate. Widening the visitor touches a helper with ten construction sites and belongs in its own change.

💡 ASTUpdateQuery::forEachPointerToChild lists three members and not settings_ast, database or
table, which the parser also pushes into children. Left as is: the only visitor that can replace
a database/table child is ReplaceQueryParameterVisitor, and it mutates the identifier in place
rather than reassigning the pointer, as its own comment at ReplaceQueryParameterVisitor.cpp:37-40
states. No visitor replaces settings_ast.

💡 A reviewer proposed also teaching the shared visitor to scope the alias bookkeeping it keeps.
Declined: git grep 'AddDefaultDatabaseVisitor visitor' -- src/ finds ten construction sites on
master, so changing its bookkeeping is a wide behaviour change for something confined to one call
site, which per-expression construction fixes locally.

💡 A reviewer proposed passing the substituted expression through the same helper used for the
clustered path. Declined with measurement: the narrow helper leaves table identifiers alone by
design, and reverting the full visit to it leaves the plain-identifier cases wrong while the table
function cases stay right, which is the arm that justifies the wider scope.

Corrections to the review's own earlier claims. A figure from an earlier internal round ("23 of
30 function-creating tests carry no-parallel") did not reproduce; over the runnable stateless files
that run CREATE FUNCTION the count is 47 of 79. The reasoning attached to it was wrong too: 12 of
the 15 whose first created name starts with a test number do carry the tag, and
02148_sql_user_defined_function_subquery — cited in that round as the precedent for a function body
reading a table — carries -- Tags: no-parallel on its first line. Every countable in this comment
and in the validation gate was re-derived against master before posting rather than carried forward,
and two figures in the description that no predicate reproduced were dropped rather than restated.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Eight arms in one clickhouse local invocation, zero randomization and zero non-default session settings for the UPDATE carriers. Fixture: t in db1, src in both db1 and the session database with a different row, and the updated table carrying enable_block_number_column = 1, enable_block_offset_column = 1 (both required by MergeTreeData::supportsLightweightUpdate, so a fixture without them never reaches the code under test).
b Root cause explained? InterpreterUpdateQuery::execute had two exits, executeDDLQueryOnCluster and table->updateLightweight, and neither substituted a database. AddDefaultDatabaseVisitor had no call site in InterpreterUpdateQuery.cpp or InterpreterDeleteQuery.cpp at all, so the expression reached MutationsInterpreter verbatim and every unqualified name, a table function's implicit database and a plain table identifier alike, resolved against the current database of the session instead of the database of the table. The lightweight path runs synchronously in the query context, so the mechanism is session database against table database rather than a background thread with no database.
c Fix matches root cause? Yes. The canonicalization is added at the interpreter where every caller converges, mirroring InterpreterAlterQuery: a narrow substituteDatabaseInTableFunctions inside the ON CLUSTER branch, a CTE expansion and then the full visitor after the replicated-database branch. No guard at the symptom, no widened bound, no reduced fixture.
d Test intent preserved / new tests added? Both existing tests are extended, a third is added, and no assertion is weakened. The change adds twenty arms across three files (an arm being an added statement beginning UPDATE or DELETE FROM): twelve to the local test, five to the ON CLUSTER one and three to a new companion test, for twenty-eight added reference lines (fourteen, five and nine). Three of the twenty name the database explicitly on the source side and are controls that read the same on both binaries, ordered before the witnesses so a failing run still shows them holding; the other seventeen are witnesses whose rows differ between the two Build-ID-asserted binaries. The three arms that create a SQL user-defined function live in the new companion test because a function name is global rather than database-scoped, so a fixed name collides with concurrent copies of the same test; the companion test builds the name from the test database and therefore needs no no-parallel tag, which is what every existing test that names its functions that way already does. Over the tests under tests/queries/0_stateless that run CREATE FUNCTION, taking a test as per-run-unique when every name it creates interpolates a CLICKHOUSE_* variable, seven are per-run-unique and none of the seven carries a no-parallel tag, whereas forty-seven of the seventy-two that create at least one plain fixed name do. Assertions are on table contents, since system.mutations is empty on the lightweight path and a mutation-text oracle would be vacuous there; the companion test prints the whole table after each statement, so an arm also fails if the statement updates no row at all. Three arms request enable_analyzer = 1 because the old analyzer resolves a common table expression in a subquery of a mutation as a table; the remaining arms keep the old-analyzer coverage they had.
e Both directions demonstrated? Yes, on Build-ID-asserted binaries, with SELECT lower(buildId()) checked against readelf -n before every arm. Across the repro matrices, which carry more controls than the shipped tests do, twenty matrix arms give twelve witnesses that flip (3 to 2, 99 to 77, [1,2] to [1,3]) and eight qualified controls that are unchanged — that pair of counts is of the repro matrices, not of the tests, whose own added controls number three of twenty — the controls including the two ALTER entrances that reach the same storage call and are already correct. All three test files FAIL on pristine master and PASS with the change.
f Fix is general across code paths? InterpreterDeleteQuery needs no change, since its lightweight rewrite already constructs an InterpreterUpdateQuery, which is what the request asked for. Both updateLightweight overrides and the forwarding one in StorageAlias are downstream of the fix. The ALTER paths were already correct. The replicated-database enqueue is deliberately left alone and disclosed below: the initiator does not qualify the entry by design, and each replica re-executes it with its own database, where the same call fires. One pre-existing limit of the shared visitor is inherited rather than introduced: AddDefaultDatabaseVisitor::visitTableFunction canonicalizes merge only, so a bare loop(t) or dictionary(d) still resolves its argument against the session database (TableFunctionLoop.cpp:110 and :136, TableFunctionDictionary.cpp:52). That limit is identical on the ALTER path, which constructs the same visitor at InterpreterAlterQuery.cpp:443 and :498, and this change does not touch the visitor or any table function; before it an UPDATE canonicalized nothing at all, so the gap is strictly narrowed. Widening the visitor is a change to a helper with ten construction sites and belongs in its own PR.
g Fix generalizes across inputs? Measured across merge('re'), merge(currentDatabase(), 're'), plain identifiers, nested table functions, non-recursive common table expressions, recursive ones whose name collides with a table read by the other sub-expression, both sub-expressions of the statement (the predicate and the assignments, which are separate carriers and are pinned by separate mutants), partitioned tables, and the already-qualified form, which is unchanged on both binaries. A table expression inside IN PARTITION is a syntax error, so that clause is not a carrier.
h Backward compatible? No setting default changes, no serialization or wire-format change, so no SettingsChangesHistory entry is owed. The persisted artifact on this path is a patch part, not a mutation command. One behaviour change is disclosed in the description: an unqualified UPDATE ... ON CLUSTER now dispatches the database resolved on the initiator, which is measured to match what ALTER already does byte for byte on the same fixture.
i Invariants and contracts preserved? The full visit is placed after the shouldReplicateQuery branch on purpose: DatabaseReplicated::checkQueryValid strips the target database and DDLTask.cpp asserts it is stripped, so qualifying earlier would violate a stated invariant next to a debug assertion. The CTE expansion is placed before the full visit for the reason InterpreterAlterQuery states in its own comment at the same position, so a common table expression is not qualified as if it were a table. The throwing resolveStorageID below is kept as the existence check for the local path. The database is pinned before the access rights are built, so the rights that are checked and the table that is updated always name the same database; a mutant that moves that one line into the cluster branch is refused with Code: 497 naming a database the statement does not touch.

Mutants: fifteen, each reddening only the arms it should. Reverting the predicate visits reddens the predicate and DELETE arms while the assignment arms stay green; reverting the assignment visits reddens only those two; the two calls the clustered branch makes are pinned separately, so deleting the whole branch reddens two ON CLUSTER arms while deleting only its assignments call reddens exactly one, the arm whose table function sits in a SET expression; narrowing the full visit reddens the plain-identifier arms while the table-function arms stay green; dropping the database pin reddens the differing-default-database arm with the same Code: 371 as pristine master; moving the pin into the cluster branch reddens the access-rights probe; removing the CTE expansion reddens exactly the two common-table-expression arms with Code: 60 naming a qualified alias; sharing one visitor between the two sub-expressions again reddens exactly the one recursive-common-table-expression arm, and leaves every other arm in every file green; reverting the inlining of user-defined function bodies reddens only the companion test and leaves the other two entirely green; reverting the child-pointer repair hook reddens exactly the one arm whose whole predicate is a function call, which is the arm that hook exists for. Reverting the narrow call alone does not change any result on a single-host cluster, and that is reported rather than adjusted: it is visible in the distributed DDL queue entry, which carries the two-argument merge with the call present and the one-argument form without it, and the full visit repairs it when it re-runs per host.

Regression: a slice of 85 stateless tests, every member of which mentions UPDATE, lightweight_delete_mode, lightweight updates or patch parts, was run on both binaries and compared as reason-bucketed failure sets, not counts. No regressions and no accidental fixes; the six failures are identical on both arms and all environmental to the local configuration. 50 randomized and 50 plain runs pass on all three files, and every run on pristine master fails, which is what shows the new arms still detect the defect under randomization. The three files were also run 50 times each under the flaky-check shape that runs a changed test concurrently with copies of itself, without the self-parallel guard: 150 of 150 pass, where a variant of the local test using a fixed function name fails six times in the same shape with Code: 46 naming the dropped function.

Related open work: #107486 independently adds the same target resolution and database pin at the same place, for its own reason (keeping the access checks and the dispatched query on one database), and its comment there states the same argument from the access-rights side. It performs none of this substitution, so it leaves every carrier above red, but it does conflict textually in InterpreterUpdateQuery.cpp; whichever lands second takes a small rebase on those lines.

Session id: cron:clickhouse-review-slot-9:20260806-225600

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @CurtizJ, could you review this? An UPDATE or lightweight DELETE never substituted a database into its expression, so merge('^src$') and a bare src resolved against the session database instead of the database of the updated table, silently touching rows selected from a different table; this adds the same canonicalization InterpreterAlterQuery already does.

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

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6d86477]

Summary: ✅


AI Review

Summary

This PR mirrors InterpreterAlterQuery so direct UPDATE and lightweight DELETE canonicalize unqualified table reads against the updated table's database, and it adds focused regression coverage for merge, plain identifiers, ON CLUSTER, and SQL UDF expansion. I am not ready to approve it because one class of unqualified identifiers still escapes that canonicalization: a recursive WITH alias that collides with a real table name can still leak forward within a single expression and make a later sibling subquery read the session database instead of the updated table's database.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterUpdateQuery.cpp:193] [dismissed by author -- https://github.com/Use the database of the updated table in the expression of an UPDATE #113748#discussion_r3734201432] Splitting AddDefaultDatabaseVisitor per predicate/assignments fixes only cross-expression leakage. Within one expression, AddDefaultDatabaseVisitor still keeps recursive WITH names in one visitor-global with_aliases set (src/Interpreters/AddDefaultDatabaseVisitor.h:126, :148, :274) and never pops them, so a later sibling like (SELECT max(id) FROM src) is still left unqualified after an earlier (WITH RECURSIVE src AS (...) SELECT ...). That means UPDATE can still read the wrong table in exactly the code path this PR claims to fix. Suggested fix: make recursive-CTE alias tracking lexical (push/pop per recursive SELECT, or equivalent scope restoration) instead of visitor-global, then keep the per-expression split on top of that.
Tests
  • ⚠️ Add a regression where a recursive WITH alias collides with a real table name and a later sibling subquery in the same WHERE expression or same assignment reads that table. The current new tests only prove the cross-expression predicate/assignments split; they would stay green if this single-expression leak remained.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.80% -0.10%

Changed lines: Changed C/C++ lines covered: 44/46 (95.65%) · 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 7, 2026
@PedroTadim PedroTadim self-assigned this Aug 7, 2026
/// expressions it walked, and the two expressions have separate scopes.
if (update_query.predicate)
{
AddDefaultDatabaseVisitor visitor(getContext(), table_id.getDatabaseName());

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.

Using one AddDefaultDatabaseVisitor per predicate/assignments still leaves recursive WITH aliases scoped too broadly. AddDefaultDatabaseVisitor keeps with_aliases in one visitor-wide set and never pops names when it leaves a recursive subquery, so a first sibling like

(WITH RECURSIVE src AS (...) SELECT max(id) FROM src)

still pollutes a later sibling in the same expression:

(SELECT max(id) FROM src)

The second src is then left unqualified and resolves in the session database, so UPDATE can still read the wrong table for a single-expression case. The alias tracking needs to be stack-scoped per recursive SELECT, not shared across the whole expression visitor.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is right, and I reproduced it: with a recursive alias whose name collides with a physical table, the second sibling is left unqualified and reads the session database. Controls on the same binary, where the correct read is 2 and the session database holds 99:

expression result
(SELECT max(id) FROM src) alone 2, qualified
recursive alias r, then (SELECT max(id) FROM src) 7002, qualified
recursive alias src, then (SELECT max(id) FROM src) 7099, unqualified
(SELECT max(id) FROM src), then recursive alias src 2007, qualified

The last row is the confirmation: the leak is forward-only, exactly as a set that is inserted into and never popped predicts. with_aliases is a mutable std::unordered_set<String> at AddDefaultDatabaseVisitor.h:126, inserted at :148, read at :274, with no erase or clear.

I am not fixing it in this PR, for two reasons.

It is not a regression. That same expression reads 7099 on pristine master too, so the value is unchanged by this change: previously nothing in UPDATE was canonicalized at all, so the sibling was unqualified for a broader reason. There is no shape where this PR makes an alias resolve worse than before.

It is pre-existing in shared machinery this PR does not touch. AddDefaultDatabaseVisitor.h is byte-identical to origin/master (md5 59cedddfbabfcd0bf0a8802a937b5d1a), and the defect is already reachable through the path master ships: on unpatched master, ALTER TABLE t UPDATE v = (WITH RECURSIVE src AS (...) SELECT max(id) FROM src) * 1000 + (SELECT max(id) FROM src) fails the mutation with Code: 81, UNKNOWN_DATABASE, while the same statement with a non-colliding alias name correctly gives 7002. Making the alias tracking stack-scoped changes a header constructed at 10 sites across 7 files, including CREATE VIEW, WindowView, IStorageCluster and SelectStreamFactory, from a PR whose changelog is about UPDATE.

An earlier review round raised the visitor-wide scope of this member as well; that is why the change constructs a separate visitor per expression rather than reusing one, which fixes the cross-expression case locally. The within-one-expression case above is the remaining part, and it belongs where the member lives.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6d86477ad with master 8cb46d93b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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

Object file sizes

65 object files changed (+62.35 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterUpdateQuery.cpp.o 100.86 KiB 163.64 KiB +62.78 KiB (+62.24%)

737 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

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

Job report

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 56769ea

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

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'in' (STID 0250-41a5) trunk bug, not PR-caused. A FutureSetFromSubquery reaches in before its set is built. Breadth over 30 days on this STID: 124 rows / 102 distinct PRs / 8 master, spanning 2026-07-08 to 2026-08-07, so the family is trunk-wide and independent of this branch. #102308 (external, open)
Sync - CH Inc sync (private, not actionable by me)

All 175 check-runs completed (157 success, 17 skipped, 1 failure); Config Workflow,
Finish Workflow and Mergeable Check all success. CIDB records 326,284 result rows across
160 checks on this commit, of which exactly 1 is FAIL (the row above).

#102308 ("Restore subquery plans after failed in-place set build") is the fix this family is
tracked against; it is still open, so it is linked here as the owner rather than falling through to
a fix task.

Session id: cron:our-pr-ci-monitor:20260807-130000

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️

Verified the root cause on master: execute() only calls setDatabase(table_id.database_name) at line 124, after the ON CLUSTER branch has already returned, and never runs AddDefaultDatabaseVisitor over predicate/assignments at all. So both exits really did resolve unqualified names against the session's database. The fix mirrors #113185's two call sites faithfully, and the forEachPointerToChild override is load-bearing rather than incidental — AddDefaultDatabaseVisitor replaces child nodes, and ASTUpdateQuery keeps predicate/assignments as separate pointers that also live in children, so without it a replaced child would leave those raw pointers at the old node.

One suggestion. The function now resolves the same database into two variables and uses a different one in each branch: resolved_table_id.getDatabaseName() in the ON CLUSTER block and table_id.getDatabaseName() in the local block. That's correct — the cluster branch returns before auto table_id = ... is reached, which is exactly why the earlier variable exists — but it reads like a duplicate and invites a later "simplification" that would break the early-return path. Worth a line at the second one, something like:

/// Same database as `resolved_table_id` above, resolved again here because the `ON CLUSTER`
/// branch returns before `table_id` is declared. Do not collapse the two.

Also worth confirming the local-path visitor block sits after the auto table_id = ... declaration and not before it; green CI answers this, but the diff anchor alone doesn't make the ordering obvious to a reader.

The merge-order note about #107486 is a good catch and applies to a few other in-flight PRs converging on this interpreter — coordinating the order is probably cheaper than rebasing twice.

`execute` resolves the database of the updated table into two variables and uses a
different one in each branch: `resolved_table_id` in the `ON CLUSTER` block and
`table_id` in the local block. That reads like a duplicate, so a later reader may
try to collapse the two, which would break the early-return path.

Two properties make them distinct, and neither is visible from the diff anchor:

  - the `ON CLUSTER` block returns before `table_id` is declared, so only the
    earlier variable exists at that point;
  - `tryResolveStorageID` returns an empty `StorageID` where `resolveStorageID`
    throws, which is why the earlier one is guarded by `if (resolved_table_id)`
    and the local path can dereference its result unconditionally.

Comment only; no behaviour change.
Inlining SQL user-defined functions before the `_row_exists` classification means a
function body of `0` asks for `ALTER DELETE`, not `ALTER UPDATE`. Nothing asserted
that: moving `UserDefinedSQLFunctionVisitor::visit` below the access-right
construction leaves every existing arm of this file green, and leaves the three
database-resolution tests of this branch green too.

The four new rows go in the file that already owns this contract, next to the
literal `_row_exists = 0` / `= 1` pair they mirror. The `1` body is a control: it
stays an update whichever order the inlining and the classification run in, so only
the two zero rows separate the orders.

Measured on a debug build, per binary with the build id asserted against
`SELECT lower(buildId())`. With the expansion below the classification the two zero
rows invert (delete-only user denied, update-only user allowed) and the runner
reports a diff at exactly those two reference lines, every other row unchanged.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim thanks, and thanks for re-deriving the root cause independently.

The comment. Added in 0c9f97c, close to your wording. I kept a second reason beyond the
early return, because it is the one a "simplification" would trip over even after moving code
around: the two calls are different functions. tryResolveStorageID returns an empty StorageID
where resolveStorageID throws (Context.cpp:7895 vs :7877, both reaching
resolveStorageIDImpl with nullptr vs &exc), which is why the earlier one is guarded by
if (resolved_table_id) and the local path dereferences its result unconditionally. Collapsing
them would either drop that guard or make an unresolvable target throw before the access check.

The ordering. It is after: table_id is declared at InterpreterUpdateQuery.cpp:156 and the
first local visitor is at :193. Rather than rely on that, I checked what happens if a later
reader moves it: the block does not compile, error: use of undeclared identifier 'table_id' at
the two visitor constructions. So the ordering is enforced by the compiler, not only by the tests.

The merge order. Enumerating all 1916 open PRs by changed file, then discarding by hunk line
and operation, four touch this interpreter or the visitor:

PR What it does here Interaction
107486 +55/-5 in execute, resolves the id up front and pins the database itself real conflict: merge-tree reports one, in InterpreterUpdateQuery.cpp, and zero against my base alone
110968 adds a partitions member to ASTUpdateQuery and pushes it into children no textual conflict, but see below
110073 adds a joinGet branch to AddDefaultDatabaseVisitor no conflict; different function
92323 rewrites the same access-construction block for case-insensitive identifiers conflict in this file; six of its seven are pre-existing against my base

107486 is the only one whose conflict I introduce, so my note was about the right PR. The order I
would suggest is 107486 first: it is +457 across 11 files against my +289, and it moves the
resolution to the top of execute, which my two call sites then sit inside rather than beside.
Rebasing mine onto it is a hunk-level move; the reverse asks its author to re-resolve a larger diff.

110968 is worth flagging even though it does not conflict. It adds partitions to
ASTUpdateQuery and into children, and it adds forEachPointerToChild to ASTAlterQuery.cpp
but not to ASTUpdateQuery.h. Whichever of the two lands second, the override this PR introduces has
to list partitions too, or a visitor replacing that child leaves the raw pointer at the old
node, which is exactly the case the override exists for. I am happy to take that line if I land
second.

One more thing in this push. clickhouse-gh[bot] asked for a privilege test and it was right.
Inlining SQL UDFs before the _row_exists split means a function body of 0 asks for
ALTER DELETE, and nothing asserted it: moving the expansion below the access-right construction
leaves all four tests green. Four rows now pin it in
04328_delete_from_alter_delete_privilege.sh, beside the literal pair they mirror. On that mutant
the two UDF-zero rows invert and the runner diffs exactly those two reference lines, every other
row unchanged. The 1 body is a control that is identical on both arms. Also fixed the changelog
entry to present tense per docs/changelog_entry_guidelines.md:48.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0c5f9c2

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04561_ie_join_storage_join trunk test defect, not this PR (bystander) #113840 (external, merged) - absent from the build tested here
Build (arm_release) / Post Hooks build-profile telemetry INSERT rejected (Code: 241), non-gating: Build (arm_release) itself is green a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

On the first row: 04561_ie_join_storage_join was added by #113753 (merged 12:48Z today) and its
serverError INCOMPATIBLE_TYPE_OF_JOIN arms do not hold under parallel replicas, so it went red on
master and on ~40 unrelated PRs within hours of landing. @PedroTadim fixed it in #113840 (merged
20:50Z). This PR's diff does not touch that test, and the fix is not in the tree that was tested
here: the job ran merge commit b20a0e09c9a5, whose copy of the test is byte-identical (md5
fba1812231fee9b5bf2f908a4f964f3a) to the pre-fix version and carries no no-parallel-replicas tag,
and this PR's base 16bd8e4947a0 is 402 commits behind #113840's merge commit. The row clears on the
next CI run over a newer base.

The Post Hooks row is the build-profile telemetry INSERT, not a test: Build (arm_release) itself
reports green, and the row is recorded with check_status = success, so it does not gate the PR. This
build already contains the merged retry fix #113409 (its ci/jobs/scripts/log_cluster.py carries both
data.seek(0) and retries=8), so that PR is deliberately not linked as the owner here - the
remaining rejections after it are tracked separately.

Session id: cron:our-pr-ci-monitor:20260808-003000

The test grew by 79 lines over the review rounds of this PR, roughly doubling
its work. Its passing runs in the flaky check already peak at 172.5s against
the 180s TEST_MAX_RUN_TIME_IN_SECONDS cap, and it tips over the cap under the
flaky check's repeated-run load.

The `long` tag suppresses exactly that duration failure
(tests/clickhouse-test:3567-3572) and cuts the flaky-check repeat count from
50 to 5 (:4386-4388, --long-test-runs-ratio 0.1). No assertion is weakened.

Requested by PedroTadim.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim added -- Tags: long to 04693_merge_table_function_in_mutation.sql in 1b2a219.

It suppresses the flaky-check duration failure (tests/clickhouse-test:3567-3572, gated on "long" not in self.tags) and cuts that job's repeat count from 50 to 5 (:4386-4388, ratio 0.1). No assertion changes.

One consequence worth stating: --no-long is also passed by the non-per-test llvm-coverage stateless jobs and by Fast test, so the test is now skipped there. It keeps running in the ordinary sanitizer stateless jobs and, five times instead of fifty, in the flaky check. Tell me if you would rather I trim the test's work instead.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1b2a219

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
Fast test / 02458_relax_too_many_parts trunk regression, not this PR #113045 (external, open)
Finish Workflow / Post Hooks consequence of the row above: Fast test failed, so every Bugfix validation job was dropped and none could validate the bug #113045 (external, open)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

02458_relax_too_many_parts fails with Code: 252 ... Too many parts (3 with average size of 451.00 B)
on INSERT INTO test VALUES (3, 'a'). That is the trunk regression from #109000 where a plain
INSERT ... VALUES fan-out makes MergeTreeSink::onStart throw on an early insert: 61 rows across 57
distinct PRs, 4 master runs and 6 different checks in 30 days. This PR adds -- Tags: long to one
unrelated stateless test and does not touch the insert path. @alexey-milovidov's #113045 ("Perform the
Too many parts check once per INSERT query") is the tracked fix and is open, so it owns both rows.

The second row is not a separate defect. new_tests_check.py reported
Bugfix validation per-arch jobs: [... DROPPED, DROPPED, SKIPPED, SKIPPED] - passed: none, and
concluded no per-arch job validated the bug. That is because Fast test went red first and the
validation matrix was dropped, not because the regression tests stopped proving the fix: on the
previous head 0c5f9c2886ba722, where Fast test passed, all four of this PR's tests
(04693_merge_table_function_in_mutation, 04811_..._on_cluster, 04812_..._udf,
04328_delete_from_alter_delete_privilege) were validated OK on both amd64 and aarch64 and
Bugfix validation (functional tests, amd64/aarch64) reported success. Both rows clear together on
the next run that gets a green Fast test.

Session id: cron:our-pr-ci-monitor:20260809-013000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6d86477

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.

CI is fully finished on this commit with no failed checks - every dispatched job
reported success, so there is nothing to assign an owner to.

Session id: cron:our-pr-ci-monitor:20260809-170000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit 9e886a2 Aug 9, 2026
180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants