Repository navigation
Use the database of the updated table in the expression of an UPDATE - #113748
Conversation
`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.
Internal second-model review (click to expand)An independent model reviewed this change against the code on disk, without access to the ❌ A SQL user-defined function in the update expression was not canonicalized. ❌ Expanding a function whose call is the whole predicate needed a pointer-repair hook. ❌ A user-defined function name is global, so those arms collided with concurrent copies of the ❌ The assignments half of the clustered substitution had no witness anywhere in the corpus.
💡 💡 A reviewer proposed also teaching the shared visitor to scope the alias bookkeeping it keeps. 💡 A reviewer proposed passing the substituted expression through the same helper used for the Corrections to the review's own earlier claims. A figure from an earlier internal round ("23 of |
Pre-PR validation gate (click to expand)
Mutants: fifteen, each reddening only the arms it should. Reverting the predicate visits reddens the predicate and Regression: a slice of 85 stateless tests, every member of which mentions 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 Session id: cron:clickhouse-review-slot-9:20260806-225600 |
|
cc @yariks5s @CurtizJ, could you review this? An |
|
Workflow [PR], commit [6d86477] Summary: ✅
AI ReviewSummaryThis PR mirrors Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 44/46 (95.65%) · Uncovered code |
| /// expressions it walked, and the two expressions have separate scopes. | ||
| if (update_query.predicate) | ||
| { | ||
| AddDefaultDatabaseVisitor visitor(getContext(), table_id.getDatabaseName()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes65 object files changed (+62.35 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units14 translation units recompiled, 58 s compile time in total, 14 of them have a recent master baseline. |
CI finish ledger - 56769eaEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All 175 check-runs completed (157 success, 17 skipped, 1 failure);
Session id: cron:our-pr-ci-monitor:20260807-130000 |
|
@groeneai 🕵️ Verified the root cause on master: One suggestion. The function now resolves the same database into two variables and uses a different one in each branch: /// 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 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.
|
@PedroTadim thanks, and thanks for re-deriving the root cause independently. The comment. Added in The ordering. It is after: The merge order. Enumerating all 1916 open PRs by changed file, then discarding by hunk line
107486 is the only one whose conflict I introduce, so my note was about the right PR. The order I 110968 is worth flagging even though it does not conflict. It adds One more thing in this push. |
CI finish ledger - 0c5f9c2Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
On the first row: The 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.
|
@PedroTadim added It suppresses the flaky-check duration failure ( One consequence worth stating: |
CI finish ledger - 1b2a219Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The second row is not a separate defect. Session id: cron:our-pr-ci-monitor:20260809-013000 |
…r-update-query-merge-database-substitution
CI finish ledger - 6d86477Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this commit with no failed checks - every dispatched job Session id: cron:our-pr-ci-monitor:20260809-170000 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
UPDATEand lightweightDELETEreading 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 themergetable 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
tindb1, asrcin bothdb1and 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'ssrc. The same happens with a plain identifierFROM src, in the assignments, and forDELETEatlightweight_delete_mode = 'lightweight_update'.InterpreterUpdateQuery::executehad two exits and neither substituted a database, so every unqualified name resolved against whatever current database the interpreting context held. ForcingALTER ... UPDATEthroughtryRewriteToLightweightUpdatereaches the sameupdateLightweightyet resolves in the table's own database.The fix mirrors the two calls of
InterpreterAlterQuery: the narrowsubstituteDatabaseInTableFunctionsin theON CLUSTERbranch, and, past the replicated-database branch, expanding common table expressions then the full visitor.InterpreterDeleteQueryneeds 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 touchingUPDATEand lightweight updates show no regression, all three files fail onmasterand pass with the change, and each mutant reddens only its own arms.Inlining SQL user-defined functions before the
_row_existssplit means a UDF expanding to0asks forALTER DELETE, notALTER UPDATE, asALTERalready does after the same expansion. The value gate is unchanged and no grant permits anything it did not before.An unqualified
UPDATE ... ON CLUSTERnow dispatches the database of the initiator, matchingALTER. #107486 pins the same database, so whichever lands second needs a rebase.Version info
26.8.1.1038(included in26.8and later)