Skip to content

Do not expand a WITH expression alias into a subquery that hides it - #120026

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:with-expression-alias-out-of-scope
Sep 19, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:with-expression-alias-out-of-scope

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 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 bug where a standalone UPDATE ... SET substituted a WITH expression alias into a nested subquery that cannot resolve it. Where that name is a table name, the statement read the alias instead of the table, or silently succeeded where the equivalent SELECT raises UNKNOWN_IDENTIFIER.

Description

Follow-up to #119630, which fixed the CTE carrier. A standalone UPDATE ... SET expands WITH elements before the default database is filled in, and the expression-alias map was carried down unconditionally. So [7] AS src was substituted into a nested SELECT ... SETTINGS enable_global_with_statement = 0, where src names a table: it read the array, succeeding where a plain SELECT raises UNKNOWN_IDENTIFIER. Present since v26.8.1.2041-lts.

An expression alias is visible in one more way than a CTE: enable_scopes_for_with_statement = 0 copies the declaring select's aliases into every descendant scope, read by any select that disables it too. The descent now clears the inherited map where the reader disables enable_global_with_statement, then re-exposes a propagate-only map of those aliases where the reader disables the scopes too. Only InterpreterUpdateQuery's two calls pass a context; the other eight are unchanged.

Base vs fix: every arm red then green, two negative-control mutants, 50/50 randomized, 221 neighbours green.

Not fixed here, each measured:

  • ALTER TABLE ... UPDATE does not run this expansion; it diverges elsewhere, under statement-level enable_scopes_for_with_statement = 0.
  • Registration does not mirror the analyzer's alias collection, in two measured shapes: an alias nested inside a WITH expression (tuple([7] AS nested)) never enters the map, and a later sibling alias enters it only after earlier siblings are visited. Each makes the assignment read a same-named table where a plain SELECT reads the alias; both pre-existing. Fixing registration is not context-gated, so it would change what CREATE VIEW and MODIFY QUERY persist too, the question you reserved on Scope WITH names to the SELECT that declares them when adding the default database #114908. Tracked; say if you want them here.
  • A duplicate alias resolves to the last declaration at a rewritten site instead of raising MULTIPLE_EXPRESSIONS_FOR_ALIAS (pre-existing).

⚠️ Same lines as my open #114908; the second to land erases the new map in visitRecursiveWithElement too.

Why eight arms for ~20 lines of src/

Each arm kills a different plausible implementation; the value encodes which name won (100 the alias's array, 10 the table of the updated database, 1 the table of the session database, 0 the row was not updated). egws is enable_global_with_statement, esfws is enable_scopes_for_with_statement.

arm settings expected what it excludes
21 default; inner egws=0 10 the bug: master answers 100
22 statement esfws=0; inner egws=0 100 clearing the inherited aliases unconditionally (10)
23 statement esfws=0; inner egws=0, esfws=1 10 reading the setting from the declaring select only (100)
24 default; inner egws=0, esfws=0 10 reading it from the reading subquery only (100)
25 no table of that name UNKNOWN_IDENTIFIER the silent success: master sets v = 1
26 statement esfws=0; middle egws=0, esfws=1; inner egws=0, esfws=0 100 one map plus a classification flag instead of a propagate-only map (10)
27 nearer re-declaration under esfws=1 100 letting the nearer declaration replace the propagated one (1000)
28 arm 21's expression as an UPDATE ... WHERE conjunct row updated the second expansion call site: master leaves the row at 0

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

Version info

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

The expansion that runs before a mutation's default database is filled in
carried the sibling map, Data::literals, into every nested select
unconditionally. So a WITH expression alias was substituted even where the
analyzer would not resolve the name to it, and the name, which is a table
name there, never reached AddDefaultDatabaseVisitor: the standalone
UPDATE ... SET read the session database, or silently succeeded where both
sibling entrypoints raise UNKNOWN_IDENTIFIER.

The visibility rule differs by element kind, and for an expression alias it
is two-sided:

    visible(alias declared by D, referenced in S)
        = egws(S) or (not esfws(S) and not esfws(D))
    visible(CTE)
        = egws(S)

with egws = enable_global_with_statement (the parent-scope walk,
QueryAnalyzer.cpp:1395-1399) and esfws = enable_scopes_for_with_statement
(the compatibility copy, QueryAnalyzer.cpp:6513-6523). A CTE is never placed
in global_with_aliases, hence the single term, and hence the unconditional
clear on the subqueries map is right.

Propagation and visibility are independent: IdentifierResolveScope.cpp:27-33
copies global_with_aliases into every child scope whatever that scope does
with it, so an alias can be hidden at an intermediate select and resolve
again below it. Measured, with L1 declaring under esfws = 0, L2 at
egws = 0, esfws = 1 and L3 at egws = 0, esfws = 0: Code 47 at L2 and the
alias at L3. A flag on the visible map therefore cannot express this, since
clearing that map destroys the node L3 still needs. Hence a second,
AST-valued map, written only by a declaration made with the scopes disabled,
propagated untouched, never cleared, and merged back over the visible map
wherever a select disables them too. It overwrites rather than fills in: the
analyzer resolves the copy over a nearer scoped re-declaration (measured, the
outer alias wins, 100 against 1000).

Each test arm excludes one plausible wrong implementation, measured on this
branch point:

    arm  settings                                     pre  post
     21  default; inner egws=0                        100    10
     22  stmt esfws=0; inner egws=0                   100   100
     23  stmt esfws=0; inner egws=0, esfws=1          100    10
     24  default; inner egws=0, esfws=0               100    10
     25  no table of that name anywhere               v=1  Code 47
     26  three levels, hidden at the middle one       100   100
     27  nearer scoped re-declaration                1000   100

Arm 22 kills an unconditional clear (it would answer 10), 23 reading esfws
from the declaring select alone, 24 reading it from the referencing one
alone, 26 the single-map design, 27 filling in rather than overwriting. Arms
22 and 26 pass on both trees by construction: they are what a narrowing fix
must not break.
A standalone UPDATE runs the expansion twice, once over the predicate and once
over the assignments, and every expression alias arm the file already has is an
assignment arm. The predicate call is the structural sibling of the site the fix
is verified at, and it carries the same map.

Its observable is one no value arm can produce: with the array substituted the
conjunct 2 IN [7] is false and the row is left untouched at 0, while with the
alias hidden the identifier names the table of the updated database, which holds
2, so the conjunct is true and the row is updated.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 14, 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; 3 Gate B rounds, 2 findings, plus
4 nits from my own cold read; the final round on the frozen contract returned 0 findings).

# Sev Finding Verdict Evidence / action
1 ❌ Registration keys on the direct WITH child, so an alias nested inside a WITH expression is never substituted and a same-named table is read (ApplyWithSubqueryVisitor.cpp:101,110) DISAGREE for this PR, mechanism AGREED Confirmed by measurement, and it is pre-existing: the diff does not touch registration, and both new branches can only act on aliases an enclosing select already registered, so master answers identically. Its remedy is not context-gated, so it would change what CREATE VIEW and MODIFY QUERY persist, the question reserved on #114908. Now stated in the description and tracked.
2 ❌ Each WITH child is descended into before its own alias is registered (:99 vs :110), so a subquery in an earlier element cannot see a later sibling's alias, where the analyzer collects the whole list first (QueryAnalyzer.cpp:6524) DISAGREE for this PR, mechanism AGREED Same root cause as #1 and same disposition: the loop and its order are not in this diff, and neither branch can see a not-yet-registered sibling in any settings regime. Seeding the list first would also drop the self-reference guard the current order gives for free. Tracked with #1.
3 💡 No test arm for the dictGet* consumer of the same map DISAGREE Both consumers (:178, :198) read the same map at the same point of the descent, so the pruning cannot be right for one and wrong for the other; a dictionary fixture adds no discrimination.
4 💡 The enable_global_with_statement = 1 plus reader-side enable_scopes_for_with_statement = 0 combination has no arm DISAGREE With the global lookup enabled neither branch fires, so that combination is byte-identical before and after this diff.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Both blockers concern pre-existing behaviour of the same function at a different site
(registration, not the descent this PR fixes); both are disclosed in the description with the
measurement, and both are put to you there rather than only listed.

Session id: cron:clickhouse-review-self-slot-58:20260914-151400

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

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [736e6af]

Summary: ✅


AI Review

Summary

This PR makes the UPDATE rewrite path respect WITH expression-alias visibility when nested subqueries disable enable_global_with_statement or re-expose aliases via enable_scopes_for_with_statement = 0. The new exported_literals split is directionally correct, but the fix is still incomplete for nested UNION/INTERSECT/EXCEPT subqueries because their query-level SETTINGS live on ASTSelectWithUnionQuery, which this walk still ignores.

Findings

❌ Blockers

  • [src/Interpreters/ApplyWithSubqueryVisitor.cpp:76] UNION ... SETTINGS ... keeps query-level settings on ASTSelectWithUnionQuery.settings_ast, not on a child ASTSelectQuery. The new context-aware path only reads ASTSelectQuery::settings(), and nested union nodes still come through visit(ASTPtr &, ...) without ASTSelectWithUnionQuery-specific handling, so a mutation subquery written as (SELECT ... UNION ALL SELECT ...) SETTINGS enable_global_with_statement = 0 will still substitute an outer WITH alias that the subquery is supposed to hide. Suggested fix: route nested ASTSelectWithUnionQuery through a context-adjusting overload that reads settings_ast, then let child ASTSelectQuery nodes clamp on top of that context.
Tests
  • Add a focused regression where the hidden-reader subquery is written as (... UNION ALL ...) SETTINGS enable_global_with_statement = 0; that is the carrier the current tests do not cover. A matching enable_scopes_for_with_statement = 0 arm would keep the new exported_literals path covered too.
Final Verdict

Changes requested. The per-select setting cases look covered, but nested union-level SETTINGS still bypass the new visibility logic and leave a supported subquery shape incorrect.

LLVM Coverage Report

Measured on commit 736e6af.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · 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 14, 2026
if (data.context)
{
scope_data = data;
scope_data->context = getSubqueryContext(ast, data.context);

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.

enable_global_with_statement and enable_scopes_for_with_statement can also live on the surrounding ASTSelectWithUnionQuery: UNION ... SETTINGS ... keeps the clause on settings_ast, not on any child ASTSelectQuery. This new path only adjusts the context in visit(ASTSelectQuery, ...), and nested union nodes still arrive through visit(ASTPtr &, ...), which never dispatches ASTSelectWithUnionQuery specially. So a mutation expression like (SELECT ... UNION ALL SELECT ...) SETTINGS enable_global_with_statement = 0 will still keep the outer WITH alias visible and rewrite the wrong AST. Please route nested ASTSelectWithUnionQuery through a context-aware overload that reads settings_ast, then let the per-arm ASTSelectQuery visits clamp on top of that context.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured on this head (Build-ID 7d749c1e28aca6ab4c0e5fccab903e7788341d88) and on its merge base (a93f49069ef1af55a5c31b50b1735b31adf19cc0), rather than read off the code.

1. A union-level SETTINGS clause cannot be spelled where a mutation expression's subquery sits. (SELECT ...) UNION ALL (SELECT ...) SETTINGS enable_global_with_statement = 0 is rejected with Code: 62 ... Expected one of: UNION, EXCEPT, INTERSECT, alias, AS in all four positions available to it: a FROM subquery, a scalar subquery, an IN subquery, and a mutation expression. The same nesting without the clause parses and answers 3, so the nesting is not what is refused. ParserSelectWithUnionQuery has no SETTINGS handling, and the only writer of ASTQueryWithOutput::settings_ast is ParserQueryWithOutput.cpp:229-235, i.e. the top level of a query with output. EXPLAIN AST agrees: Set is a direct child of SelectWithUnionQuery only for a top-level parenthesised union, and there the clause reaches the query context through InterpreterSetQuery.cpp:203-206 instead of being read per subquery.

2. The spelling in the comment lands on the last arm, and this PR is what fixes it. For SELECT ... UNION ALL SELECT ... SETTINGS enable_global_with_statement = 0, EXPLAIN AST puts Set under the second SelectQuery, which is exactly what getSubqueryContext reads. Oracle: [7] AS src declared one select above the reader, a table src holding 2 in the updated database and 99 in the session database, arms weighted 10000/1000/100 and 100/10/1 so each arm's winner is visible separately.

base a93f4906 this head 7d749c1e
that spelling through the standalone UPDATE, session database != updated database 10100, both arms substituted the alias 10010
the identical expression as a plain SELECT in the updated database 10010 10010
the identical expression as a plain SELECT in the session database 10001 10001
no clause anywhere (control) 10100 10100

So the union carrier is the one this PR corrects, not one it misses.

3. The missing dispatch is inert. visit(ASTSelectWithUnionQuery &, const Data &) is for (auto & child : ast.children) visit(child, data);, which is what the generic visit(ASTPtr &, ...) branch already does for a union node. Without a reachable settings_ast there, routing it separately changes no result.

I am therefore not adding the requested arm: the shape it names can only assert SYNTAX_ERROR, a parser property this PR does not touch, and the parseable per-arm shape reads the same getSubqueryContext that the id = 8 arm (union, clause per arm) and the id = 21 to id = 27 arms (expression alias, including both mixed enable_scopes_for_with_statement combinations) already assert.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 791cb23 Sep 19, 2026
177 of 349 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Sep 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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