Skip to content

Scope WITH names to the SELECT that declares them when adding the default database - #114908

Merged
alexey-milovidov merged 44 commits into
ClickHouse:masterfrom
groeneai:groeneai/scope-with-aliases-per-select
Oct 2, 2026
Merged

alexey-milovidov merged 44 commits into
ClickHouse:masterfrom
groeneai:groeneai/scope-with-aliases-per-select

Conversation

@groeneai

@groeneai groeneai commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Scope WITH names to the SELECT that declares them when adding the default database.

AddDefaultDatabaseVisitor leaves the names of WITH RECURSIVE lists unqualified, but it kept them in one set for the whole visitor and never removed them, so a name declared in one SELECT suppressed qualification of a same-named table in a sibling UNION branch or a sibling subquery (#104972). Now the names are visible only in the declaring SELECT and its subqueries.

Following the review, the visitor does not imitate identifier resolution and does not read settings:

  • The full traversal runs after ApplyWithSubqueryVisitor, which already expands the common table expressions and decides, with the context, which references a CTE reaches (enable_global_with_statement per SELECT). So the full traversal only keeps the names of WITH RECURSIVE lists, 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 in QueryTreeBuilder/QueryAnalyzer. A copy of a body that ApplyWithSubqueryVisitor put in place of a reference (cte_name) is walked like the body of the nearest declaration.
  • ALTER TABLE ... UPDATE/DELETE now runs ApplyWithSubqueryVisitor with the context on the command expressions before qualifying, as lightweight UPDATE already does. Before, a CTE referenced from a subquery of a mutation was qualified as a table.
  • The narrow pass (after SQL UDF expansion and for stored metadata) runs without that expansion, so it keeps scoping all WITH names structurally, as before, now with the same body rules, and also passes the aliases of WITH expressions (WITH [7] AS x) down to nested SELECTs.

Known limits of ApplyWithSubqueryVisitor that 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-named WITH RECURSIVE, and an alias nested inside a WITH expression (tuple([7] AS x)) referenced from a nested SELECT of a mutation.

Closes: #104972

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 table names not being qualified with the database when a WITH name declared elsewhere in the same query happened to match them: a view whose UNION branch referenced a table with the name of a WITH RECURSIVE CTE of another branch could not be read from another database, and ALTER TABLE ... UPDATE with a common table expression referenced from a subquery failed with UNKNOWN_DATABASE or read a table of the session database.


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

🤖 Generated with Claude Code

Version info

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

groeneai and others added 4 commits August 14, 2026 13:28
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
measurements. Every verdict below is backed by a code citation or a measurement, not prose.

Round 4 findings

❌ recursive-visibility-boundary (blocker) - DISAGREE. Claim: every name under
WITH RECURSIVE is treated as visible throughout its definition and all descendants, so physical
seed tables stay unqualified and the setting is ignored. Two sub-claims, each refuted at a
necessary step:

  • Seed. The register-before-walk order is unchanged from master:
    git show <base>:AddDefaultDatabaseVisitor.h registers every recursive element name in a loop
    that runs before visitChildren(select), exactly as the new code does. The accompanying probe
    (direct 9, mutation UNKNOWN_DATABASE) therefore reproduces on master and is outside this
    diff. It was run only against the patched binary.
  • Setting. QueryAnalyzer.cpp:6804-6815 injects the recursive CTE name into the recursive
    member's own scope via expression_argument_name_to_node, so a self-reference resolves there and
    never reaches the parent-scope gate at :1380-1384. A recursive self-reference is
    setting-independent in the analyzer, which is what the unconditional recursive lookup mirrors.
    Implementing the prescription was tried and measured: it broke a non-colliding recursive CTE
    from 10 to Code: 60 UNKNOWN_TABLE, because a self-reference sits one ASTSelectQuery deeper
    than its declaration. Arm C23 is the preservation control for that shape.

❌ select-local-global-with (blocker) - DISAGREE, pre-existing, disclosed. The mechanism is
real and correctly described: the visitor reads enable_global_with_statement once per instance,
so a SELECT-local SETTINGS override is not honoured. It is not a regression here. Master tracks
only recursive aliases, so a plain CTE name is never recorded and is qualified unconditionally
whatever the setting says - the probe's mutation=2 is master's answer too. The visitor is also
structurally unable to honour a per-SELECT override: it is constructed once per expression from a
single ContextPtr by its 13 call sites, and ASTSelectQuery::settings() is an unapplied
ASTSetQuery - applying nested SETTINGS per scope is the analyzer's job
(QueryTreeBuilder.cpp:294-320), which runs after this AST pass. Honouring it is a separate
change; nothing in this changelog claims it.

⚠️ stale-recursive-comments (nit) - agreed, not blocking.
AddDefaultDatabaseVisitor.h:359 still reads /// This is WITH RECURSIVE alias. above a guard
that now also matches plain bindings. Pre-existing line, left as is rather than growing the diff;
happy to adjust it if a maintainer prefers. The second cited site is not in this diff.

Contract corrections made before publication

⚠️ Three defects in the PR description were found and fixed here: the arm count was stale (30 ->
the delivered 34, with the witness/control split recorrected to 11/23 from the measured
per-arm table), the mutant count understated (four -> seven, adding the property that pins the
setting check), and the setting-aware lookup - the whole of the final round - was undocumented.

💡 One requested changelog line was declined: a note that enable_global_with_statement = 0
behaviour changes. Measured against master it does not - the nested-reference arm returns 2 on
both binaries, and the arm's own classification is "passes on base, not a witness". The delta was
against an unpublished intermediate state, so the line would have been a false public claim. The
design is documented in the description instead.

Earlier rounds

Rounds 1-3 raised 7 findings, 4 agreed and fixed (WITH-element walk order, the expanded-CTE clone
mask, the setting-aware lookup, and an allocating noexcept destructor now using a node handle),
3 disagreed with evidence. Each fix is pinned by its own mutant.

Session id: cron:clickhouse-review-self-slot-58:20260814-225501

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b31ec2e]

Summary: ✅


AI Review

Summary

This PR narrows WITH-alias leakage to the declaring SELECT and fixes the mutation pre-expansion path, but two name-binding carriers still diverge from the contract it is trying to restore: persisted definitions still ignore per-SELECT visibility settings, and mutations still do not route joinGet through the new table-name qualification logic. Both issues change which object name gets stored or executed, so I cannot approve the current head.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:2011] and [src/Interpreters/InterpreterAlterQuery.cpp:570] still call ApplyWithSubqueryVisitor without a ContextPtr on persisted-definition paths. That drops getSubqueryContext entirely, so nested SETTINGS enable_global_with_statement = 0 (and session-sourced equivalents reached through the context) are ignored while the view or MODIFY QUERY body is canonicalized. The stored text can therefore capture a different binding than the live query and persist the wrong object name.
    Suggested fix: call the context-aware ApplyWithSubqueryVisitor::visit(..., getContext()) overload on these persistence paths as well, so each nested SELECT is expanded under the same visibility rules the analyzer applies live.
  • [src/Interpreters/InterpreterUpdateQuery.cpp:214] and [src/Interpreters/InterpreterAlterQuery.cpp:592] still stop after the full visit(...) traversal. The new joinGet handling lives only in visitTableExpressions() / visitFunctionTableNameArguments(), so UPDATE and ALTER ... UPDATE still leave joinGet's first table argument bare. That keeps the original mutation bug alive: the lookup can still resolve against the session/default database or fail with UNKNOWN_DATABASE instead of being pinned to the mutated table's database.
    Suggested fix: after the full traversal, run the narrow visitTableExpressions(...) pass on the same mutation expressions (or teach the full visit(ASTFunction &) path to qualify joinGet the same way).
Tests
  • ⚠️ The current regression set does not cover CREATE VIEW / ALTER ... MODIFY QUERY with nested SETTINGS enable_global_with_statement = 0, so the persisted-definition path above stays untested.
  • ⚠️ The current diff also has no UPDATE / ALTER ... UPDATE regression for joinGet, so the new joinGet carrier is only exercised on the narrow metadata-rewrite path.
Final Verdict

❌ Changes requested — the remaining persistence-path and mutation-path gaps still store or execute the wrong table binding.

LLVM Coverage Report

Measured on commit b31ec2e.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 116/119 (97.48%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ALTER TABLE other_db.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 with a table named src in both the session database and other_db. No randomization, no timing, no retries; every arm runs on a fresh clickhouse local --path. Issue #104972's own repro is equally deterministic.
b Root cause explained? Yes. AddDefaultDatabaseVisitor::visit(ASTSelectQuery &, ASTPtr &) inserted a WITH RECURSIVE alias into with_aliases, a set that lives for the whole visitor instance with zero erase/clear call sites, and never restored it on leaving that SELECT's subtree. visit(const ASTTableIdentifier &, ASTPtr &) consults the set to skip qualification, so an alias declared in one subquery kept suppressing qualification for identifiers the visitor saw afterwards. Forward-only, which is the signature: a colliding sibling placed second returns the correct value.
c Fix matches root cause? Yes: the alias bookkeeping is given the scope discipline it lacked. A stack of scopes (one pushed per ASTSelectQuery subtree, RAII so throw-safe) replaces the flat sets, so a name is resolved to the binding actually in effect, and a plain alias is registered only after its own element is visited. No widened bound, no no-random-* tag, no reduced dataset, no guard at the failure site. Seven mutants across the four review rounds confirm each half and the registration order are load-bearing; the first three: emptying the restore reverts all 9 witnesses to their exact master values; registering plain aliases up front regresses the plain-CTE self-shadowing case; dropping the non-recursive walk breaks a globalized UNION branch with UNKNOWN_IDENTIFIER. A later element makes the enclosing-scope lookup conditional on enable_global_with_statement: without that setting a plain WITH name is not visible outside its own SELECT (InterpreterSelectQuery.cpp:621, executeQuery.cpp:1613, QueryAnalyzer.cpp:1380-1384 all skip or clear parent-CTE lookup), so searching every enclosing scope claimed a name was an alias where the resolver reads a table. The recursive lookup stays unconditional because a recursive element's self-reference lives in a nested SELECT of the declaring one. A further mutant, reverting only the plain-lookup restriction, returns that arm to the pre-fix value while leaving all three suites byte-identical.
d Test intent preserved / new tests added? New test 04800_recursive_cte_alias_scope_in_mutation (34 arms: 11 witnesses, 23 preservation controls). No existing test weakened, removed or retagged. Tagged no-old-analyzer with its reason: a background mutation selects its analyzer from the background context (MutationsInterpreter.cpp:119-125, context from Context::createCopy(getBackgroundContext())), so no session SET and no statement SETTINGS can reach the ALTER ... UPDATE arms; verified the tag SKIPs on an old-analyzer server and that the same file WITHOUT the tag still FAILs there. No expected-error annotation anywhere: the fix turns errors into values, so pinning one would risk locking in a regression. Four arms added for the setting (C20-C23), both directions on the same shape. Their expected values come from a hand-qualified equivalent and a no-CTE rewrite that return identical results on the pre-fix and fixed binaries, so nothing was learned from the fix. Classified honestly: C20 passes on master, so it is a regression guard for a later review round rather than a witness for the PR, and it is pinned by its own mutant; C23 is a preservation control.
e Both directions demonstrated? Yes, on Build-ID-asserted binaries (fix 4fe61e45c80927f2f14b999b8e62f8cbd4043db4, master 8a40589d95bc507bf6a50c45cc4d12a36b1a69f5; SELECT lower(buildId()) checked against each binary before every verdict). On master: UNKNOWN_DATABASE on the ALTER path, 7099 instead of 7002 through UPDATE ... SET, 105 instead of 8 across UNION branches, UNKNOWN_TABLE on the #104972 view. With the fix all pass. The whole test file also reddens on master and on all three mutants. For the setting arms: with enable_global_with_statement = 0 the pre-fix binary returns the enclosing CTE's value and the fixed one returns the table's, matching both a direct top-level SELECT of the same expression (which runs no qualification pass) and a hand-qualified read.
f Fix is general across code paths? The change is in the visitor, so all 13 construction sites are fixed at once rather than one call site being guarded. Sites exercised by an arm: InterpreterAlterQuery, InterpreterUpdateQuery (predicate and assignments), InterpreterCreateQuery (view), SelectQueryDescription (materialized view), and executeDDLQueryOnCluster via 02028_add_default_database_for_alterquery_on_cluster. The remaining sites are constructed with only_replace_in_join / only_replace_current_database_function or are table-function-only, so they cannot reach the changed lines with a CTE shape; their existing tests stay green.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: this is AST alias bookkeeping, not data typing. The axis that applies is AST shape, and the matrix covers JOIN table expressions, the second argument of IN, INTERSECT, three-level nesting, WHERE/GROUP BY/ORDER BY of the declaring SELECT, UNION branch 2 into branch 3, outer-to-inner visibility, the same name at two nesting levels, a materialized view, a merge() table function, a WITH element that is a literal rather than an ASTWithElement, and plain vs recursive. Boundaries: no WITH at all, one element, two same-named elements.
h Backward compatible? Yes. No setting is added and no default changes, so no SettingsChangesHistory.cpp entry is required; the fix only starts honouring the existing enable_global_with_statement (default true), whose default path is unchanged. Two behaviours change, both of them the buggy shapes: an identifier outside a recursive alias's scope that shares its name used to be left unqualified and is now qualified, and with the setting disabled a plain WITH name in a nested SELECT now resolves to the table, which is what the resolver does with it. The first was order-dependent and errored outright on the ALTER path; the second contradicted the setting's documented meaning. Neither can have been a relied-upon contract. Not a deliberate break.
i Invariants and contracts preserved? The invariant is stated in the source: 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. Restore happens in a destructor, so it holds on early-return and throw paths (the visitor throws from identifier and dictionary-loader paths). The visitor runs single-threaded per query, so no concurrency contract is involved, and no data-structure invariant is touched. with_aliases stays mutable and the methods stay const, matching the class's existing contract; the guard holds a reference into the visitor, whose lifetime strictly encloses it. The mask's restore now moves a detached node back instead of inserting a fresh one, so the destructor allocates nothing and cannot throw from a noexcept context; measured with a counting allocator over 200 set sizes (0 allocations on restore, against a positive control where a plain insert allocates).

Verification: new test 50/50 green under randomization, 8/8 green with 8 copies running concurrently (no no-parallel tag), and the named carrier tests 03215_view_with_recursive, 03237_create_table_select_as_with_recursive, 00652_mutations_default_database, 00751_default_databasename_for_view, 02028_add_default_database_for_alterquery_on_cluster all pass.

Session id: cron:clickhouse-impl-self-slot-57:20260814-114400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @davenger, could you review this? AddDefaultDatabaseVisitor kept WITH RECURSIVE alias names in one instance-wide set with no erase, so an alias declared in one subquery suppressed default-database qualification for every later identifier, including a real table: this replaces the set with a per-SELECT scope stack, walks the non-recursive WITH list too, and consults enclosing scopes for a plain name only when enable_global_with_statement is set.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 15, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b31ec2e92 with master 8de7a5fd4 (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.

Object file sizes

11 object files changed (+255.21 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterCreateQuery.cpp.o 1.01 MiB 1.05 MiB +39.90 KiB (+3.85%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterAlterQuery.cpp.o 391.04 KiB 429.27 KiB +38.24 KiB (+9.78%)
src/CMakeFiles/dbms.dir/Databases/DatabaseOnDisk.cpp.o 483.80 KiB 519.81 KiB +36.01 KiB (+7.44%)
src/CMakeFiles/dbms.dir/Interpreters/MutationsInterpreter.cpp.o 898.81 KiB 933.87 KiB +35.06 KiB (+3.90%)
src/CMakeFiles/dbms.dir/Storages/IStorageCluster.cpp.o 297.19 KiB 330.98 KiB +33.79 KiB (+11.37%)
src/CMakeFiles/dbms.dir/Interpreters/InterpreterUpdateQuery.cpp.o 177.01 KiB 210.69 KiB +33.68 KiB (+19.03%)
src/CMakeFiles/dbms.dir/Storages/SelectQueryDescription.cpp.o 112.89 KiB 145.14 KiB +32.25 KiB (+28.57%)

719 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

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

Job report

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6364057

CI has fully finished on this head. The praktika PR report is green (159 OK / 18 skipped of 177,
no ERROR or FAIL node); Config Workflow and Finish Workflow are both green.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable)

CH Inc sync is the only non-green check and is the one exempt disposition. Coverage is real:
Stateless tests (arm_asan_ubsan, targeted) 350 passed and all five flaky check jobs green at
50/50 each.

Session id: cron:our-pr-ci-monitor:20260815-160000

@groeneai groeneai added the groeneai-origin-self PR origin: self-found defect (impact-bar validated) label Aug 19, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1058 1124 +6.3% <0.0001 The two tests disagree and the measurements were noisy on both sides. CPU time is flat, and this plain SELECT never reaches the default-database visitor that the PR rewrites.
⚠️ 30 not_sure 230 280 +21.7% <0.0001 The +21.7% is a wall-clock change only. CPU is flat, the PR median of 280 ms sits inside master's recent 195–293 ms range, and the PR only touches DDL and mutation name qualification, which this SELECT does not run.
⚠️ 31 not_sure 268 323 +20.5% <0.0001 Suppressed correctly: the PR median of 323 ms is inside master's recent range and CPU is flat. No changed code path runs for this SELECT, so there are no grounds to contest it.

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
  • StressHouse run: 1e611ea4-156c-40aa-9644-1be7c470f84d
  • MIRAI run: 956a8df8-bdfc-497a-a199-ac57004db57e
  • PR check IDs:
    • clickbench_2789202_1790885305
    • clickbench_2789305_1790885316
    • clickbench_2789417_1790885323
    • tpch_adapted_1_official_2789533_1790885335
    • tpch_adapted_1_official_2789666_1790885356
    • tpch_adapted_1_official_2789780_1790885411

…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 01f91cc

CI 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; Config Workflow, Style check and
Finish Workflow all green; no non-green check-run conclusion; praktika result_pr.json reports
the root as OK with all 174 nodes in {OK, SKIPPED} (153 OK / 21 SKIPPED). Gate (c) met at 50 min
since the last completion. Exactly one parent workflow run at this head, so the check-run rollup is
admissible.

One clarification, because a raw CIDB query at this commit is not empty: the 4 non-green CIDB rows
are all Performance Comparison (arm_release, master_head, N/6) per-query verdicts with
test_status = unstable and check_status = success (codecs_float_insert #4 and
timeseries_to_grid_scalar_add #1, each an ::old/::new pair). unstable is a performance delta
reported for a human to read rather than a job failure, and the matching praktika nodes read OK.
That count is a real filtered subset rather than an empty query: the unfiltered control at the same
commit returns 301,017 rows. Nothing to own.

Skip audit: every one of the 21 skips carries a self-describing reason (6 not labeled with 'pr-performance', 3 reused from cache, 3 no integration tests updates, 3 No tests selected for this change, 2 Not affected by the changed files and not required, 2 not labeled with 'ci-toolchain', plus singletons). No silent scope loss.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master

Merged 573230bfe668dad. One conflict, in src/Interpreters/AddDefaultDatabaseVisitor.h: the fix for #94894 (34c2a4733ea, c7b99e9e982) added an expression_aliases set, cleared and collected per select query, while this branch replaces with_aliases with a per-select scope stack. Both are kept, since they are separate namespaces read at different sites. The only lines dropped from master's side are the three this branch already replaces: the with_aliases member with its population and its lookup, the inline constructor, and visitChildren(select).

The expression_aliases collect had to move above the WITH walk. Git's textual resolution leaves it below, and this branch descends into the WITH elements at that point, so the right argument of an IN inside a WITH element resolves to a table instead of to the alias:

CREATE VIEW v AS WITH ((7 IN ((7, 8) AS src)) AND (7 IN src)) AS flag SELECT toUInt64(flag) AS s

binary s stored
master 82cfa6a421bb9c1 1 7 IN (src)
this branch 1 7 IN (src)
this branch, textual resolution 0 7 IN (<db>.src)

05024_mv_alias_in_where_in passes on all three, so no test in the tree covered that shape. C30 in 04800 is the arm that fails on the third binary, and C31 pins that a name in the same position which is not an alias is still qualified.

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`.
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 27, 2026
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9ac16f0

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Equal values are not contiguous within the range assumed to be sorted (STID 2508-348f) trunk logical error, not this diff. The aborting query is SELECT count() FROM (SELECT DISTINCT s FROM dist_distinct__fuzz_4 ORDER BY s ASC LIMIT 100) with optimize_distinct_in_order = 1, and the fuzzer-generated dist_distinct__fuzz_4 is Distributed declaring s UInt8 over the String table t_distinct of 04870_distinct_merge_over_distributed, so the shards' sort order is not the declared type's order. 14 rows over 14 PRs in 30 days #118445 (external, open)
Mergeable Check, PR praktika rollups of the row above, no independent failure #118445
Sync - CH Inc sync (private, not actionable by me)

Bugfix validation (functional tests, amd64/aarch64) is not a row here: both jobs are green, and the stored FAIL leaves are the invert_bugfix_validation_status inversion, which stores a changed test that passed on master HEAD as a failure.

Session id: cron:our-pr-ci-monitor:20261001-060329

alexey-milovidov and others added 3 commits October 1, 2026 07:58
…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]>
@alexey-milovidov alexey-milovidov changed the title Scope WITH aliases to the SELECT that declares them when adding the default database Scope WITH names to the SELECT that declares them when adding the default database Oct 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit 80893cc Oct 2, 2026
149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
alexey-milovidov pushed a commit that referenced this pull request Oct 4, 2026
…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]>
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up as asked in #114908 (comment): the aliases a WITH expression declares at any depth (stopping at lambdas and subqueries, as the analyzer collects them) are registered by #123774, which is now part of #123790.

The remaining case is CREATE VIEW and ALTER TABLE ... MODIFY QUERY expanding the definition without a context, so an inherited WITH name is still substituted into a subquery with enable_global_with_statement = 0. I will open it on top of #123790 once that is merged.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov the CREATE VIEW / MODIFY QUERY half of this follow-up is still open: #123790 landed with the CI change only, and its src/ part is now #124021, which widens the gap.

Measured on #124021's CI build (bd5e6d36, build_amd_binary) and on master eef0f171, with a table src holding 5 (100 = the alias was read, 10 = the table):

definition query view, master view, #124021
WITH [7] AS src SELECT (SELECT toUInt8(7 IN src) * 100 + toUInt8(5 IN src) * 10 SETTINGS enable_global_with_statement = 0) AS r 10 100 100
the same with WITH tuple([7] AS src) AS w 10 10 100
the same through ALTER TABLE ... MODIFY QUERY 10 10 100
the same under SET enable_global_with_statement = 0 instead of the clause 10 10 100

On #124021 the nested alias is stored as 7 IN ([7] AS src), as the direct one already is on master: both persisting call sites still expand without a context, and #124021 now registers the nested alias on that path too. The fix is to pass the creating context at InterpreterCreateQuery.cpp (fresh definitions only, not for a parameterized view or a WITH RECURSIVE) and at MODIFY QUERY, the same two lines #122362 changes.

Should the context go into #124021, or should I open it as a separate PR once #124021 and #122362 land?

valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 13, 2026
…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]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 13, 2026
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]>
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-self PR origin: self-found defect (impact-bar validated) 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.

with_aliases scope contamination causes table references to not be qualified in sibling UNION branches

4 participants