Skip to content

Do not expand a WITH element into a subquery that does not see it when updating - #119630

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:update-cte-out-of-scope-database
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:update-cte-out-of-scope-database

Conversation

@groeneai

@groeneai groeneai commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fixed a standalone UPDATE ... SET reading the wrong table when a mutation expression names a table that a same-named WITH element hides, but which the subquery does not see because its own SETTINGS clause disables enable_global_with_statement. Such a name is a table name, and it is now resolved in the database of the updated table instead of the database of the session, so the statement no longer silently updates from a different table or fails with UNKNOWN_TABLE.

Description

A standalone UPDATE ... SET expands common table expressions before filling in the default database. The expansion never consulted enable_global_with_statement, so it also replaced the name inside a nested SELECT whose own SETTINGS clause disables enclosing-scope lookup. There the name is a table name, but the expansion left an ASTSubquery carrier, so AddDefaultDatabaseVisitor had no identifier to qualify: the command, stored as text, resolved it in the session database. ALTER TABLE ... UPDATE is correct here: it runs the expansion only on MODIFY QUERY.

The visitor now takes an optional context and applies each subquery's own SETTINGS clause to a copy while descending, as QueryTreeBuilder does for the analyzer (clamped, not rejected). Where the resulting enable_global_with_statement is false, the inherited CTEs are dropped, so the subquery's table names survive to be qualified; a clause on one arm of a UNION is read for that arm alone. Only InterpreterUpdateQuery's two call sites pass a context; the other eight callers are unchanged.

Present since bac3508 (v26.8.1.2041-lts), not in 26.6 or 26.7. Asked for by the review bot on #114908 (discussion_r3995813819), pre-existing there.

Not fixed here, and Data's contract now says so: a WITH expression alias is still substituted into a subquery that does not see it, so WITH [7] AS src SELECT (SELECT 2 IN src SETTINGS enable_global_with_statement = 0) reads the array where a plain SELECT reads the table, and CREATE VIEW persists that substitution. Dropping them needs more than this guard: with enable_scopes_for_with_statement = 0 they stay visible, decided by the scope that declared the alias, so a fix must track it per alias. Both are measured, and handled separately; #118983 is covered by #114908.

⚠️ Conflicts with my own #114908, which edits the same line of visit(ASTSelectQuery &); the second to merge needs only data -> scope there.


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

Version info

  • Backported to: 26.8.21.5

…n updating

A standalone `UPDATE ... SET` expands common table expressions before it fills
in the default database, so that a `WITH` alias is not qualified as if it were a
table. The expansion did not consult `enable_global_with_statement`: it replaced
the name in every nested `SELECT`, including one whose own `SETTINGS` clause
disables the lookup in enclosing scopes. There the name is a table name, and the
expansion left an `ASTSubquery` carrier in its place, so the identifier the
database had to be added to was gone. `ASTSubquery::formatImplWithoutAlias`
prints the bare `cte_name`, and `MutationCommand::parse` stores the command as
text, so the mutation named an unqualified table and the background thread
resolved it in the database of the session instead of the updated table's.

With a source table of the same name in both databases the update silently read
the wrong row; with no such table in the session database it failed with
`UNKNOWN_TABLE`. `ALTER TABLE ... UPDATE` was correct already, because it runs
the expansion only on `MODIFY QUERY`.

The visitor now takes an optional context and, while descending, applies each
subquery's own `SETTINGS` clause to a copy of it, exactly as `QueryTreeBuilder`
does for the analyzer: the clause is clamped rather than rejected so a subquery
cannot widen the reader's constraints, and the copy leaves the AST untouched.
When the resulting `enable_global_with_statement` is false, the inherited
elements are dropped for that subquery, so its table names survive to be
qualified. The elements a `SELECT` declares itself are registered afterwards and
are unaffected.

Only the two call sites in `InterpreterUpdateQuery` pass a context, so the other
eight callers of the visitor keep their exact behaviour.

`Data::literals` is deliberately left alone. With
`enable_scopes_for_with_statement = 0` a `WITH` expression alias is copied into
every child scope, so the analyzer resolves it whatever
`enable_global_with_statement` says; dropping it here would leave an identifier
for `AddDefaultDatabaseVisitor` to qualify as a table or dictionary name, which
was measured to turn a working `x IN lit` into `Unknown identifier 'db.lit'` and
`dictGet(dn, ...)` into `Dictionary ('dn') not found`.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 12, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex) plus my own cold pass over the
resulting code. The independent pass raised 0 findings; my pass raised 3 nits, no blocker and no
major, so nothing was bounced.

# Sev Finding Verdict Action
1 💡 The IN <element name> spelling of the same carrier (ApplyWithSubqueryVisitor.cpp:150) reads the map this fix clears, and has no arm of its own AGREE Not shipped as an eighth arm: one clear() serves both carriers, so they cannot diverge without an edit inside the visitor, and the test is kept to one case per scenario.
2 💡 The description said the standalone path resolved the name in "the background thread"; there the stored command text is re-parsed inside the statement AGREE Corrected in the description before publishing.
3 💡 The helper's doc comment runs to four lines AGREE Kept: the first two say why a name a subquery cannot see is a table name there.

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

@clickhouse-gh clickhouse-gh Bot closed this Sep 12, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a547149]

Summary: ✅


AI Review

Summary

This PR makes standalone UPDATE run ApplyWithSubqueryVisitor with each nested SELECT's effective settings, which fixes the common-table-expression path where enable_global_with_statement = 0 used to leave a table name unqualified and then read from the session database. The focused stateless coverage is good, but the same invariant is still broken for inherited WITH <expr> AS alias rewrites in IN and dictGet*, so I cannot approve it yet.

PR Metadata
  • Changelog category is correct.
  • Changelog entry is otherwise clear, but it currently overstates the fixed carrier by saying a same-named WITH element. WITH <expr> AS alias inside IN / dictGet* is still unresolved, so the entry should say common table expression / CTE specifically unless that remaining carrier is fixed too.
Findings
  • ⚠️ [src/Interpreters/ApplyWithSubqueryVisitor.cpp:76-77, 161-182] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/119630#discussion_r3996990443] The new scope drop only clears inherited subqueries. visit(ASTFunction) still substitutes inherited literals into IN and dictGet*, so a standalone mutation like WITH [7] AS src SELECT (SELECT 2 IN src SETTINGS enable_global_with_statement = 0) still reads the hidden alias instead of the table or dictionary visible in that subquery. That leaves the same wrong-result / wrong-target mutation bug reachable on the literals carrier.
  • Suggested fix: track literals with the same effective-scope semantics as subqueries (including the declaring-scope behavior of enable_scopes_for_with_statement) and add one focused stateless IN or dictGet* regression, or explicitly scope the PR and changelog down to a CTE-only fix.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either close the remaining literals carrier in IN / dictGet*, or narrow the user-facing claim everywhere to a CTE-only fix so the PR no longer promises a broader invariant than the code actually enforces.

LLVM Coverage Report

Measured on commit a547149.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.30% 81.40% +0.10%

Changed lines: Changed C/C++ lines covered: 41/42 (97.62%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @evillique, could you review this? The CTE prepass in InterpreterUpdateQuery expanded a WITH element into a nested SELECT that does not see it (its own SETTINGS clause disables enable_global_with_statement), leaving an ASTSubquery carrier where a table identifier had to be qualified, so the stored mutation text resolved that table in the session's database. It now applies each subquery's own settings the way QueryTreeBuilder does, and drops only the inherited elements.

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 12, 2026
A subquery reads its own `SETTINGS` clause per select, so a trailing clause on
the last arm of a union applies to that arm alone: the arm carrying
`enable_global_with_statement = 0` resolves the reference as a table in the
database of the updated table, while the arm without it keeps reading the alias.

The two arms are weighted differently so that every misattribution answers its
own value, each measured: the clause read for the other arm gives 2007, for both
arms 2002, for neither 7007. On pristine master 1b86f9d (build id
e2b70dd96336dc77) the statement answers 7099, reading the table of the session
database, so the arm fails without this change.

The union node itself cannot carry the clause where a mutation expression sits:
only `ParserQueryWithOutput` parses a trailing `SETTINGS`, so a nested
`(SELECT ...) UNION ALL (SELECT ...) SETTINGS ...` is a syntax error, and at the
top level the clause reaches the context before any interpreter runs.
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a5471497c with master eac8fc376 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 68ce550b7; 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

12 object files changed (+24.87 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ApplyWithSubqueryVisitor.cpp.o 66.28 KiB 88.04 KiB +21.75 KiB (+32.82%)

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

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

Job report

scope_data = data;
scope_data->context = getSubqueryContext(ast, data.context);
if (!scope_data->context->getSettingsRef()[Setting::enable_global_with_statement])
scope_data->subqueries.clear();

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 only clears data.subqueries, but visit(ASTFunction) below still substitutes inherited data.literals for IN and dictGet. A standalone mutation like WITH [7] AS src SELECT (SELECT 2 IN src SETTINGS enable_global_with_statement = 0) will therefore still rewrite src to the hidden alias instead of the table that subquery actually sees, leaving the same wrong-result bug in this path. Please either gate the literals carrier with the same scope logic (taking enable_scopes_for_with_statement into account) or narrow the contract/comments to the table-CTE case only.

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.

Narrowed, in a5471497cf1d4: Data::context now states that inherited subqueries are dropped and inherited literals are substituted either way, and the three comments around it say CTE where they said element. Comments only, no behaviour change.

You are right about the carrier. ASTWithElement is the CTE form alone, since ParserWithElement falls through to ParserExpressionWithOptionalAlias for WITH <expr> AS <alias>, so the prose was narrower than it read, while visit(ASTFunction &) does still substitute an inherited alias into IN and dictGet.

I am not taking the other option here, because it is the guard I measured and reverted a few hours ago: enable_scopes_for_with_statement is answered by the scope that declared the alias, not by the one reading it, so a guard reading it from the subquery diverges in both mixed parent/child combinations. Doing it correctly needs the per-alias bookkeeping you describe, which is a second root cause.

It is also wider than this PR. InterpreterCreateQuery runs the same visitor with no context at all, so the substitution is persisted:

CREATE VIEW v AS WITH [7] AS src
    SELECT (SELECT toUInt8(2 IN src) SETTINGS enable_global_with_statement = 0) AS r;
SHOW CREATE VIEW v  -- ... toUInt8(2 IN ([7] AS src)) ...
SELECT r FROM v     -- 0, where the same statement as a plain query answers 1

That needs no non-default table setting, and DatabaseOnDisk / DatabaseReplicated run the visitor again over stored metadata, so a fix has to settle creation and reload together. Both carriers are being handled separately, and the description names them instead of leaving them implicit.

`Data::context` was documented as keeping "a `WITH` element" out of a subquery
that does not see it, but only the inherited `subqueries` are dropped. An
expression alias reaches `visit(ASTFunction &)` through `Data::literals` and is
still substituted into the `IN` and `dictGet` arguments there. `ASTWithElement`,
the class that prose named, is the common table expression alone, because
`ParserWithElement` falls through to an ordinary aliased expression for
`WITH <expr> AS <alias>`, so the text read wider than the code.

Both carriers are named now, and the two call-site comments say CTE where they
said element. Why `Data::literals` stays inherited is in 0772ae8; a gate
on the reading subquery's settings would be wrong as well, because
`enable_scopes_for_with_statement` is answered by the scope that declared the
alias, not by the one that reads it.

Comments only, no change in behaviour.
@clickhouse-gh clickhouse-gh Bot added comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 93d8d00 Sep 13, 2026
176 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Sep 13, 2026
…-aliases-per-select

Resolve the conflict in `ApplyWithSubqueryVisitor::visit(ASTSelectQuery &)` with ClickHouse#119630:
keep this branch's recursive-element dispatch and pass master's per-select `scope`
instead of `data` to both arms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE DATABASE db2;

-- same table name in both databases, different row
CREATE TABLE src (id UInt64) ENGINE = MergeTree ORDER BY id;          -- session database
INSERT INTO src VALUES (99);
CREATE TABLE db2.src (id UInt64) ENGINE = MergeTree ORDER BY id;      -- updated table's database
INSERT INTO db2.src VALUES (2);

CREATE TABLE db2.u (id UInt64, v UInt64) ENGINE = MergeTree ORDER BY id
    SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO db2.u VALUES (1, 0), (2, 0);

-- control: a name no WITH element hides resolves in the updated table's database
UPDATE db2.u SET v = (SELECT max(id) FROM src) WHERE id = 1;
SELECT v FROM db2.u WHERE id = 1;   -- 2

-- subject: the inner SELECT disables enclosing-scope lookup, so `src` is a table
-- name there and must resolve the same way
UPDATE db2.u SET v = (WITH src AS (SELECT 7 AS id)
                      SELECT (SELECT max(id) FROM src SETTINGS enable_global_with_statement = 0))
    WHERE id = 2;
SELECT v FROM db2.u WHERE id = 2;   -- 99 on 26.8.4.11, expected 2

-- Observed on v26.8.4.11-lts: 2 then 99 -- the hidden name read the session
-- database. Fixed on master by #119630 (2 then 2).

▶ Run on ClickHouse Fiddle

Results:

Backport the fix to 26.8.

CC component owner: @scanhex12 @Michicosun

Analysis metadata

comp-mutations · Severity P2 · Finding phase_d_pr119630

  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and 26.8 is the only branch that needs it. Measured here from ancestry rather than from a repro:

  • The commit clickgap bisected to (bac3508, Use the database of the updated table in the expression of an UPDATE #113748, merged 2026-08-09) is an ancestor of 26.8 (branch cut 2026-08-24) and of no other active release branch: 26.7, 26.6 and 26.3 were cut on 2026-07-22, 2026-06-23 and 2026-03-19, all before it. That is the ancestry form of the feature_absent verdict for those three.
  • The fix is not on 26.8: merge commit 93d8d00 is absent there, and tests/queries/0_stateless/05189_update_cte_out_of_scope_database.sql is a 404 at ref=26.8 while it is present on master.
  • Cherry-pick exposure is confined to the standalone UPDATE path: the new scope computation runs only when Data::context is set, and InterpreterUpdateQuery is the only caller that passes one, so the visitor's other callers take exactly the path they took before.

I do not open release-branch PRs by hand, so this is a label ask rather than a cherry-pick from me.

@PedroTadim, could you apply v26.8-must-backport here? 26.8 is the newest active release branch, so that label expands to exactly the one affected branch.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 7, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 7, 2026
Backport #119630 to 26.8: Do not expand a WITH element into a subquery that does not see it when updating
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 8, 2026
… a subquery that does not see it when updating
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-review-bot PR origin: review-bot finding on a groeneai PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants