Repository navigation
Do not expand a WITH expression alias into a subquery that hides it - #120026
alexey-milovidov merged 3 commits into
Conversation
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.
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260914-151400 |
|
Workflow [PR], commit [736e6af] Summary: ✅
AI ReviewSummaryThis PR makes the Findings❌ Blockers
Tests
Final VerdictChanges requested. The per-select setting cases look covered, but nested union-level LLVM Coverage ReportMeasured on commit 736e6af.
Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · Uncovered code |
| if (data.context) | ||
| { | ||
| scope_data = data; | ||
| scope_data->context = getSubqueryContext(ast, data.context); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units16 translation units recompiled, 113 s compile time in total, 16 of them have a recent master baseline. |
791cb23
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a bug where a standalone
UPDATE ... SETsubstituted aWITHexpression 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 equivalentSELECTraisesUNKNOWN_IDENTIFIER.Description
Follow-up to #119630, which fixed the CTE carrier. A standalone
UPDATE ... SETexpandsWITHelements before the default database is filled in, and the expression-alias map was carried down unconditionally. So[7] AS srcwas substituted into a nestedSELECT ... SETTINGS enable_global_with_statement = 0, wheresrcnames a table: it read the array, succeeding where a plainSELECTraisesUNKNOWN_IDENTIFIER. Present sincev26.8.1.2041-lts.An expression alias is visible in one more way than a CTE:
enable_scopes_for_with_statement = 0copies 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 disablesenable_global_with_statement, then re-exposes a propagate-only map of those aliases where the reader disables the scopes too. OnlyInterpreterUpdateQuery'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 ... UPDATEdoes not run this expansion; it diverges elsewhere, under statement-levelenable_scopes_for_with_statement = 0.WITHexpression (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 plainSELECTreads the alias; both pre-existing. Fixing registration is not context-gated, so it would change whatCREATE VIEWandMODIFY QUERYpersist 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.MULTIPLE_EXPRESSIONS_FOR_ALIAS(pre-existing).visitRecursiveWithElementtoo.Why eight arms for ~20 lines of
src/Each arm kills a different plausible implementation; the value encodes which name won (
100the alias's array,10the table of the updated database,1the table of the session database,0the row was not updated).egwsisenable_global_with_statement,esfwsisenable_scopes_for_with_statement.egws=010100esfws=0; inneregws=010010)esfws=0; inneregws=0, esfws=110100)egws=0, esfws=010100)UNKNOWN_IDENTIFIERv = 1esfws=0; middleegws=0, esfws=1; inneregws=0, esfws=010010)esfws=11001000)UPDATE ... WHEREconjunct0Workflow [PR]
Sync PR [sync-upstream/pr/120026]
Version info
26.10.1.224-master(included in26.10and later)