Repository navigation
Scope WITH names to the SELECT that declares them when adding the default database - #114908
alexey-milovidov merged 44 commits into
Conversation
AddDefaultDatabaseVisitor records WITH RECURSIVE aliases in `with_aliases` and
consults that set to avoid qualifying a name that denotes a CTE rather than a
table. The set was shared by the whole visitor instance and had no erase or
clear call site, so an alias declared inside one SELECT kept suppressing
qualification for every identifier the same visitor saw afterwards, including a
genuine physical table. The leak was forward-only: a colliding name before the
CTE was unaffected.
Consequences, with a table named `src` in both the session database and the
updated table's database:
ALTER TABLE other.t UPDATE v = (WITH RECURSIVE src AS (SELECT 7 AS id)
SELECT max(id) FROM src) * 1000 + (SELECT max(id) FROM src) WHERE id = 1
failed with UNKNOWN_DATABASE, because the second `src` was left unqualified and
the mutation runs in a background thread with no current database. The same
expression through UPDATE ... SET silently read the session's `src`. A view
whose UNION branch referenced such a table was stored unqualified and could not
be read from another database (issue ClickHouse#104972).
The invariant now enforced: an alias suppresses qualification only within the
subtree of the SELECT that declares it, and within its own definition only when
the CTE is recursive.
Two coupled parts. A WithAliasesScope guard saves and restores the set around
each ASTSelectQuery subtree walk; restoring in a destructor keeps that correct
on early-return and throw paths. And the WITH list is now walked in the
non-recursive case too: a recursive alias is registered up front, since a
recursive CTE may reference itself, while a plain alias is registered only after
its own element has been visited, mirroring
ApplyWithSubqueryVisitor::visit(ASTSelectQuery &), so inside a plain CTE's
definition the name still denotes the table. The non-recursive case is needed
because ApplyWithGlobalVisitor copies a first branch's WITH list into later
UNION branches without the RECURSIVE flag, and those branches were previously
carried by the leak itself. Neither part is correct alone: without the second, a
globalized branch loses the alias it needs; registering plain aliases up front
instead breaks a plain CTE's own definition.
Fixing the visitor rather than a call site covers all 13 construction sites at
once. The change only narrows when suppression applies, so it can never leave
unqualified something that was qualified before.
Closes: ClickHouse#104972
`ApplyWithSubqueryVisitor` runs before `AddDefaultDatabaseVisitor` on the `ALTER ... MODIFY QUERY` and `CREATE MATERIALIZED VIEW` paths, and replaces a reference to a `WITH` element with a copy of its body tagged with the element's name. It leaves the `WITH` list in place, so the name was still registered as an alias and suppressed qualification of a same-named physical table inside that copy. A non-recursive `WITH` element cannot reference itself, so inside a copy of its body the name denotes the table again. This is what a plain top-level `SELECT v FROM (WITH src AS (SELECT max(id) AS v FROM src) SELECT v FROM src)` does, on a path that never reaches this visitor. Track the non-recursive subset of the aliases and drop the name while walking a copy tagged with it. The recursive case is unchanged: there the alias does refer to the element. Tracking only the non-recursive aliases matters because the prepass expands recursive references too, so un-suppressing on the tag alone would qualify away a recursive element's own self-reference. Also pin `enable_analyzer` in the test, which the old analyzer cannot run.
The previous round tracked the aliases in two flat sets, so two declarations of the same name in nested scopes collapsed into one entry. Walking a copy of a non-recursive element's body then erased the name outright instead of revealing the binding of the enclosing scope, and a same-named outer recursive alias stopped suppressing qualification: with a physical table of that name present, storing such a query as a view changed its result from 6 to 1. Replace the sets with a stack of scopes, innermost last. A name is looked up outwards from the innermost scope, and inside an expanded copy only the binding that is in effect is masked, for the duration of that walk. The binding in effect can be declared by an enclosing scope rather than the innermost one, so the lookup has to search outwards: with the innermost scope alone, a plain alias referenced from a nested SELECT loses its expansion and the query fails with UNKNOWN_IDENTIFIER. Test 04800 gains the nested-shadow arm and the nested-reference arm. Both pass on master, which never had the guard, so they are preservation controls; each is pinned by its own mutant. The test is also tagged no-old-analyzer: a background mutation selects its analyzer from the background context, so the session setting cannot reach the ALTER ... UPDATE arms, and WITH RECURSIVE needs it.
A WITH name declared in an enclosing SELECT is only visible inside a nested one when enable_global_with_statement is set: the interpreter skips ApplyWithAliasVisitor and ApplyWithGlobalVisitor without it, and the analyzer clears allow_to_check_cte for parent scopes. Searching every enclosing scope unconditionally therefore claimed a name was an alias where the resolver reads a table, leaving it unqualified. A mutation over a table in another database then read the session's table instead of its own. A recursive name stays visible in its own definition whichever way the setting is set, because that definition is a nested SELECT of the declaring one, so it is looked up before the setting is consulted. Restricting the plain lookup alone kept the recursive self-reference working; restricting both broke a non-colliding recursive CTE outright. Restore the masked binding with a node handle so the destructor moves the existing node back instead of inserting a fresh one. unordered_set::insert allocates, and an allocation failure escaping a noexcept destructor terminates the process. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (independent cold review + adversarial gate, 4 rounds)An independent model reviewed this diff cold, then adjudicated its findings against the recorded Round 4 findings❌
❌
Contract corrections made before publication
💡 One requested changelog line was declined: a note that Earlier roundsRounds 1-3 raised 7 findings, 4 agreed and fixed ( Session id: cron:clickhouse-review-self-slot-58:20260814-225501 |
|
Workflow [PR], commit [b31ec2e] Summary: ✅
AI ReviewSummaryThis PR narrows Findings❌ Blockers
Tests
Final Verdict❌ Changes requested — the remaining persistence-path and mutation-path gaps still store or execute the wrong table binding. LLVM Coverage ReportMeasured on commit b31ec2e.
Changed lines: Changed C/C++ lines covered: 116/119 (97.48%) · Uncovered code |
Pre-PR validation gate (click to expand)
Verification: new test 50/50 green under randomization, 8/8 green with 8 copies running concurrently (no Session id: cron:clickhouse-impl-self-slot-57:20260814-114400 |
|
cc @pufit @davenger, could you review this? |
The Style check rejects `#include <Core/Settings.h>` in a header: `AddDefaultDatabaseVisitor.h` is included by ten translation units, so pulling the generated settings header in there inflates build time repo-wide. Reading `enable_global_with_statement` needs the full settings header, so the constructor moves to a new `AddDefaultDatabaseVisitor.cpp` along with the include and the `extern const SettingsBool` declaration. Every user of the class is a `.cpp`, so nothing needs the constructor inline. Pure code move, no behaviour change: the test output is byte-identical to the previous head (35 lines) and still differs from the merge base, which fails with UNKNOWN_DATABASE.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+255.21 KiB total), 0 added.
719 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 units18 translation units recompiled, 132 s compile time in total, 18 of them have a recent master baseline. |
The setting was read once from the visitor's context, so a SELECT that sets it in its own SETTINGS clause was canonicalized as if it had not. With the statement setting on and an inner SELECT turning it off, an enclosing plain name was still treated as an alias and left unqualified, and the mutation then failed with UNKNOWN_DATABASE instead of reading the updated table's own table. The analyzer decides this per scope: tryResolveIdentifierInParentScopes consults scope.context, which QueryTreeBuilder builds by applying each SELECT's SETTINGS. Keep the clauses reaching a SELECT on its scope and replay them against the context, so a repeated setting takes its last value and compatibility, which derives this one without naming it, is honoured. Only the settings that can decide inheritance are collected: a clause of a view being stored may hold a query parameter, which has no value yet. The recursive lookup stays unconditional. A recursive name is visible in its own definition whichever way the setting is set, because that definition is a nested SELECT of the declaring one; gating it broke a self-referencing CTE under a statement-level 0. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - 6364057CI has fully finished on this head. The praktika
Session id: cron:our-pr-ci-monitor:20260815-160000 |
The private CI's flaky check fails a test outright when a single run goes past 180 seconds, and only for tests that are not tagged `long` (see `tests/clickhouse-test`). This file runs past it under ASan with S3 storage and metadata in Keeper, where every statement pays an object-storage round trip, so the check reports it as a failure instead of running the repetitions it exists for.
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes how AddDefaultDatabaseVisitor qualifies table names for WITH and CTE scoping, which only runs for CREATE VIEW, materialized views, SQL UDF expansion and ALTER/UPDATE mutations. It also expands CTEs in ALTER UPDATE/DELETE commands. None of this runs for the plain ClickBench SELECTs, so the Q30 regression (+21.7%) is downgraded to not sure. Its PR median is still inside master's recent range, and CPU time did not change. Q28 (+6.3%, the two tests disagree) and Q31 (+20.5%, suppressed as inside master's normal range) show the same pattern: slower by wall-clock time with flat CPU, which points to the test hosts rather than the code. Nothing here needs action from the author. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…er SELECT A nested `SETTINGS profile = '...'` sets `enable_global_with_statement` without naming it, because a profile stands for a group of settings. `appendSettings` collected only the two settings by name, so such a clause reached `evaluateWithAliasInheritance` as no change at all and the pass fell back to the enclosing decision. With a profile that turns the setting off, a plain `WITH` name in a nested `SELECT` was then left unqualified on the mutation and view paths, so the stored query read the session database or failed with UNKNOWN_DATABASE instead of the updated table's own database. Measured on the ALTER ... UPDATE path with a profile that turns the setting off: the value the visitor produced disagreed with the value the same expression returns when run directly, and the mutation failed with `Code: 81 UNKNOWN_DATABASE`. `profile` is carried through the filter and the replay now runs on a `Context` copy via `applySettingsChanges`, which is the path `QueryTreeBuilder` takes when it applies the clause for real, so the pass and the resolver agree on what the clause means. An unresolvable profile is caught like a value that does not convert, leaving the enclosing decision in place. Reported by clickhouse-gh[bot] on ClickHouse#114908.
CI finish ledger - 01f91ccCI is fully finished at this commit and no check failed, so no ledger row is owed. Evidence: 173 unique check runs, none queued or in progress; One clarification, because a raw CIDB query at this commit is not empty: the 4 non-green CIDB rows Skip audit: every one of the 21 skips carries a self-describing reason (6 Session id: cron:our-pr-ci-monitor:20260824-120000 |
Conflict in `src/Interpreters/AddDefaultDatabaseVisitor.h`. Master's fix for issue ClickHouse#94894 (34c2a47, c7b99e9) added an `expression_aliases` set, cleared and collected per select query, so that an identifier in the right argument of `IN` which is an expression alias is not qualified as a table name. This branch replaces the flat `with_aliases` set with a per-select scope stack for `WITH` aliases. Both are kept: they are separate namespaces read at different sites, `expression_aliases` in `visit(ASTFunction &)` for the `IN` argument and the scope stack in `visit(const ASTTableIdentifier &)`. Dropped from master's side are only the three things this branch already replaces: the `with_aliases` member with its population and its lookup, the inline constructor, and `visitChildren(select)`. The `expression_aliases` save, collect and restore is placed above the `WITH` walk so that it still runs before any descent into the children, which its comment states and which the textual merge would otherwise have broken.
The qualification pass collects the expression aliases of a select query before descending into its children, and this branch descends into the `WITH` elements of that same query, so the order of the two steps is now load-bearing. Reversing them makes the right argument of an `IN` inside a `WITH` element resolve to a table instead of to the alias, which `C30` returns as 0 rather than 1. Neither `04800` nor `05024` had an arm for that shape, so the whole suite stayed green. `C31` is the acceptance arm: a name in the same position that is not an alias must still be qualified, so a wider guard cannot pass unnoticed.
Merged masterMerged The
Session id: cron:clickhouse-maint-slot-20:20260826-120010 |
`evaluateWithAliasInheritance` replays the `SETTINGS` clause of the `SELECT` being visited onto a copy of the context. It caught an `Exception` from `applySettingsChanges` and returned the enclosing decision instead. Let the exception propagate, as the reviewer asked. The catch changed the outcome of exactly one shape: a `CREATE VIEW` whose inner `SETTINGS` clause holds an unbound query parameter on one of the three names `appendSettings` collects. With the catch the view was stored and then could not be read (`Code: 51`, against a literal control that returns a row); without it the `CREATE` reports `Code: 70`. Every other shape already failed downstream with the same code in both arms, in a mutation expression and in a stored view body alike: an unresolvable `profile` gives `Code: 180`, a non-convertible value `Code: 467`.
…-aliases-per-select
CI finish ledger - 9ac16f0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20261001-060329 |
…ion pass Inside a recursive member the name of the recursive element references the element at any depth, also in a nested `SELECT` that stops inheriting with `enable_global_with_statement = 0`. The full traversal does this through `BodyWalk`, but the narrow pass (`visitTableExpressions`) cleared every inherited `WITH` name at such a `SELECT` and qualified the self-reference as a table of the creating database. With the setting off in the session, `CREATE VIEW ... WITH RECURSIVE src AS (SELECT 1 AS id UNION ALL SELECT id + 1 FROM (SELECT id FROM src) WHERE id < 4) ...` failed with `UNKNOWN_TABLE` or stored `d1.src` and read the table (4) where the live query builds 1..4 (10), and the same arm of `05099_recursive_cte_alias_scope_in_mutation` (`C36`) read the table once mutations ran the narrow pass. The narrow pass now keeps the names of the recursive members it is inside visible in a nested `SELECT` that does not inherit, and walks the copy of a recursive body that `ApplyWithSubqueryVisitor` substituted for a reference (an `ASTSubquery` with `cte_name`, printed as the bare name) as that element's body, so the in-memory definition of the creating session agrees with the stored text. Test: `05316_with_recursive_nested_member_alias_scope_view`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Address review: ClickHouse#114908 (comment) (thread on `AddDefaultDatabaseVisitor.h:567`). The full `AddDefaultDatabaseVisitor` traversal, which `ALTER TABLE ... UPDATE` and standalone `UPDATE` use, leaves the first argument of `joinGet` alone, and a mutation is executed later in a context whose current database is unrelated to the query's: `ALTER TABLE d1.t UPDATE v = joinGet(src, 'v', id)` failed with `UNKNOWN_DATABASE` or read another database's `src`, with or without any `WITH` involved. Run the narrow pass after the full traversal in both entrypoints, as `CREATE` does for a stored definition, so `joinGet` is qualified with the database of the updated table under the same `WITH` alias scoping as the other carriers. Test: `05315_with_alias_scope_join_get_mutation`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Address the review of novikd: `AddDefaultDatabaseVisitor` no longer imitates the analyzer's identifier resolution, and it no longer reads `enable_global_with_statement`, `compatibility`, `profile` or `readonly` from `SETTINGS` clauses. The full traversal runs after `ApplyWithSubqueryVisitor` has expanded the common table expressions, and that visitor already decides with the context which references a CTE reaches. So the full traversal leaves only the names of `WITH RECURSIVE` lists unqualified, as before, but now scoped to the select query that declares them and its subqueries. A sibling `UNION` branch or a sibling subquery no longer inherits them, which is ClickHouse#104972. Inside the body of an ordinary element, and inside the seed of a recursive one, the element's own name is a table. A copy of a body that `ApplyWithSubqueryVisitor` left in place of a reference (`cte_name`) is walked like the body of the nearest declaration. `ALTER TABLE ... UPDATE/DELETE` now expands the CTEs of the command expressions with the context before qualifying, as lightweight `UPDATE` already does, so a CTE referenced from a subquery of a mutation is no longer qualified as a table. The narrow pass, which runs without that expansion (after SQL UDF expansion and on stored metadata), keeps scoping all `WITH` names structurally, now with the same body rules, and also inherits the aliases of `WITH` expressions into nested select queries. Removed: the per-scope settings replay, the `ApplyWithSubqueryVisitor` change for recursive members, the `joinGet` qualification in mutations, and the tests for them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ryVisitor `ApplyWithSubqueryVisitor` registered as a substitutable literal only the alias of a direct `WITH` child, so in `WITH tuple([7] AS nested) AS wrapper` it registered `wrapper` but not `nested`. A nested `SELECT` using `7 IN nested` then kept the identifier, and the full `AddDefaultDatabaseVisitor` traversal, which treats every name left in place as a table, qualified it as `<db>.nested`. A view, a materialized view, `MODIFY QUERY` and `ALTER TABLE ... UPDATE` with that shape read a same-named table instead of the alias, or failed with `UNKNOWN_IDENTIFIER` (reproduced on 26.8.2.7 and 26.3.33.24). The narrow pass that repairs a definition after SQL UDF expansion already takes the aliases at any depth of a `WITH` expression, not inside a lambda or a subquery, like the analyzer. A `Replicated` database writes that repaired text into the DDL log and every replica processes it again through the full pipeline, which re-qualified the alias. This made `05237_with_expression_alias_scope_descendant` fail on every run under `--replicated-database`. Register every such alias right after the expression is visited, as the direct child's alias was before, so it is inlined (`7 IN ([7] AS nested)`) the way a top-level alias has been since #100042. The rule now lives in one helper, `ApplyWithSubqueryVisitor::forEachWithExpressionAlias`, which the narrow pass also calls. The test gets back the mutation arms removed in the #114908 rework, each on its own row, and a hand-written view arm. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Follow-up as asked in #114908 (comment): the aliases a The remaining case is |
|
@alexey-milovidov the Measured on #124021's CI build (
On #124021 the nested alias is stored as Should the context go into #124021, or should I open it as a separate PR once #124021 and #122362 land? |
…nt-subquery-loading-dependency" This reverts commit 659cc1c, reversing changes made to f75df10. Conflicts resolved by removing only what ClickHouse#114923 added: the narrow qualification pass in AddDefaultDatabaseVisitor.h is removed together with the parts ClickHouse#114908 later added inside it; InterpreterCreateQuery.cpp keeps the expansion bound of ClickHouse#122362 on the neighbouring call; the string overload of qualifyDictionaryNameWithDatabase in ExternalDictionariesLoader is kept, because the dictionary usage record of ClickHouse#121567 is built on it. 04908_constraint_subquery_loading_dependency.sh (edited by ClickHouse#124408) is deleted with the rest of the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the revert, the only caller of `addWithAliases` passes `only_recursive_with_hides_table = true`, so `collectWithExpressionAliases` is never called and `with_expression_aliases` is never written: `isExpressionAlias(name)` equals `expression_aliases.contains(name)` on every remaining path. Remove the parameter, the member and both helpers (added by ClickHouse#114908 for the removed pass); the full traversal behaves as before. The second sentence of the comment on the string overload of `qualifyDictionaryNameWithDatabase` named the removed metadata-load caller. 05233_udf_expansion_with_alias_scope (ClickHouse#114908) and 05317_udf_dictget_alias_column_lightweight_delete (ClickHouse#123563, issue ClickHouse#123489) test the qualification of the names a SQL UDF brings into a CREATE, which the revert removes; both fail on the revert commit and are deleted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Scope
WITHnames to theSELECTthat declares them when adding the default database.AddDefaultDatabaseVisitorleaves the names ofWITH RECURSIVElists unqualified, but it kept them in one set for the whole visitor and never removed them, so a name declared in oneSELECTsuppressed qualification of a same-named table in a siblingUNIONbranch or a sibling subquery (#104972). Now the names are visible only in the declaringSELECTand its subqueries.Following the review, the visitor does not imitate identifier resolution and does not read settings:
ApplyWithSubqueryVisitor, which already expands the common table expressions and decides, with the context, which references a CTE reaches (enable_global_with_statementperSELECT). So the full traversal only keeps the names ofWITH RECURSIVElists, scoped. Inside the body of an ordinary element, and inside the seed of a recursive one, the element's own name is a table, as inQueryTreeBuilder/QueryAnalyzer. A copy of a body thatApplyWithSubqueryVisitorput in place of a reference (cte_name) is walked like the body of the nearest declaration.ALTER TABLE ... UPDATE/DELETEnow runsApplyWithSubqueryVisitorwith the context on the command expressions before qualifying, as lightweightUPDATEalready does. Before, a CTE referenced from a subquery of a mutation was qualified as a table.WITHnames structurally, as before, now with the same body rules, and also passes the aliases ofWITHexpressions (WITH [7] AS x) down to nestedSELECTs.Known limits of
ApplyWithSubqueryVisitorthat this PR does not change (same behavior as on master): a CTE that refers to a later CTE of the same list, a CTE body that the analyzer resolves at the reference while the expansion binds it at the declaration, an enclosing plain CTE expanded into the recursive members of a nested same-namedWITH RECURSIVE, and an alias nested inside aWITHexpression (tuple([7] AS x)) referenced from a nestedSELECTof a mutation.Closes: #104972
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed table names not being qualified with the database when a
WITHname declared elsewhere in the same query happened to match them: a view whoseUNIONbranch referenced a table with the name of aWITH RECURSIVECTE of another branch could not be read from another database, andALTER TABLE ... UPDATEwith a common table expression referenced from a subquery failed withUNKNOWN_DATABASEor read a table of the session database.Workflow [PR]
Sync PR [sync-upstream/pr/114908]
🤖 Generated with Claude Code
Version info
26.10.1.1313-master(included in26.10and later)