Skip to content

Fix views and mutations reading a table instead of an alias declared inside a WITH expression - #123774

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/with-expression-descendant-alias-inline
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/with-expression-descendant-alias-inline

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 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 CREATE VIEW, CREATE MATERIALIZED VIEW, ALTER TABLE ... MODIFY QUERY and ALTER TABLE ... UPDATE treating an alias declared inside a WITH expression (for example WITH tuple([7] AS s) AS w) as a table name when a nested SELECT uses it on the right side of IN: the statement failed with UNKNOWN_IDENTIFIER, or read a table with the same name instead of the alias.

Description

On 26.8 and 26.3, CREATE VIEW v AS WITH tuple([7] AS s) AS w SELECT (SELECT toUInt8(7 IN s)) AS r stores s as <db>.s. Without a table s it fails with UNKNOWN_IDENTIFIER; with one, the view returns 0 while the same query run directly returns 1. A materialized view, MODIFY QUERY and ALTER TABLE ... UPDATE behave the same.

On master this also fails 05237_with_expression_alias_scope_descendant on every run under a Replicated database (failing job): replay reprocesses the definition the DDL log keeps after SQL UDF expansion.

Root cause: ApplyWithSubqueryVisitor registers only the alias of a direct WITH child (w, not s), and the full AddDefaultDatabaseVisitor traversal then qualifies every name left in place. The narrow pass after SQL UDF expansion (#114908) already follows the analyzer.

Change: ApplyWithSubqueryVisitor registers every alias a WITH expression declares at any depth, except inside a lambda or a subquery, as soon as its node is visited, and inlines it (7 IN ([7] AS s)), as it has inlined a top-level alias since #100042. A name a nested SELECT or a lambda declares itself wins, also for a top-level alias. The narrow pass uses the same helper. AddDefaultDatabaseVisitor now also counts an alias inside a table function argument as the select's own, as the analyzer does, also without WITH. As for a top-level alias, a use before the declaration is not inlined, and CREATE VIEW / MODIFY QUERY expand without a context, so enable_global_with_statement = 0 in a nested SELECT does not stop the inlining there.

Validation: 05237 gets back the mutation arms, plus view, materialized view, MODIFY QUERY, same-expression and shadowing arms; master fails 8 of them. 50/50 randomized runs, 10/10 under --replicated-database, no new failures among 595 neighbour tests.

Overlaps textually with open #120778, #122362 and #120089.


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

groeneai and others added 6 commits October 3, 2026 13:56
…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 ClickHouse#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 ClickHouse#114908 rework, each on
its own row, and a hand-written view arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y are visited

An alias inherited from an enclosing `WITH` was substituted even into a nested
select that declares the same alias itself, where the analyzer resolves the
local one. A non-CTE `WITH` child was visited as a whole before its aliases
were registered, so a later part of the same expression did not see one.

Test arms: a materialized view and `MODIFY QUERY`, a later part of the same
`WITH` expression, and nested selects that shadow a descendant or a top-level
alias.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…TH` alias

A nested select's `ARRAY JOIN` and `JOIN ... ON` aliases were not counted as its own, so an inherited alias still replaced them.
A lambda body got the inherited aliases unchanged, so one was substituted over a lambda parameter or a body alias of the same name.
Add a stack check to the recursive alias walk.
Test arms: `ARRAY JOIN`, `JOIN ... ON`, a lambda parameter and a lambda-body alias that bind the same name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The analyzer puts the aliases inside a table function's arguments into the select scope,
so `ApplyWithSubqueryVisitor` now counts them among a nested select's own aliases, and
`AddDefaultDatabaseVisitor::collectAliases` descends into those arguments (not into the
table alias) so the dropped name stays bare. Both must change together, otherwise the
name is either inlined or qualified as a table. 05237 gains a table function shadow arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The analyzer stops collecting aliases at a lambda, also inside a table
function argument, but `collectAliases` walked into it there. A
lambda-body alias then left an unrelated table name bare in a stored
view, so the view read that name from the reader's current database.
Take the argument aliases with `forEachExpressionAlias`, as the visitor
does.

Adds a test arm read through `USE system`, and moves the own-alias scan
above the comment that describes the `scope_data` block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop a comment that restates its call and shorten the visitWithExpression comment to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

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

Pre-publication review by an independent model (engine: codex; 9 findings over 5 rounds).

# Sev Finding Verdict Evidence / action
1 ❌ A nested SELECT that declares the same alias itself got the inherited WITH alias inlined AGREE, fixed @ 662acfc its own aliases hide the inherited one
2 ❌ A scalar subquery later in the same WITH expression did not see an earlier alias AGREE, fixed @ 662acfc each alias is registered right after its node is visited
3 ⚠️ CREATE MATERIALIZED VIEW and MODIFY QUERY were untested AGREE, fixed @ 662acfc test arms added
4 ❌ Aliases in ARRAY JOIN / JOIN ... ON lost to the inherited alias AGREE, fixed @ fe01bc5 they hide it too
5 ❌ A same-named lambda parameter got the alias substituted (BAD_ARGUMENTS) AGREE, fixed @ fe01bc5 lambda parameters and lambda-body aliases hide it
6 ❌ Aliases in table function arguments lost to the inherited alias AGREE, fixed @ 0d66faa the visitor and collectAliases both take them
7 ❌ A lambda alias inside a table function argument left a table name bare AGREE, fixed @ cc8bfa1 the lambda keeps its aliases; the test arm reads through USE system
8 ❌ Two different aliases with the same name in one WITH expression: the last one wins DISAGREE the analyzer rejects that input (MULTIPLE_EXPRESSIONS_FOR_ALIAS); master's rule for a top-level alias is the same
9 ❌ A CTE and an expression alias with the same name: the stored view takes the CTE, the live query the alias DISAGREE visit(ASTFunction &) checks CTEs before aliases in lines this PR does not touch; master stores the same CTE for this query, and for a top-level alias too

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

Session id: cron:clickhouse-review-slot-9:20261003-221100

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE VIEW v AS WITH tuple([7] AS nested) AS wrapper SELECT (SELECT toUInt8(7 IN nested) * 100 + toUInt8(5 IN nested) * 10) AS r with a table nested holding 5 returns 10 on master (live query 100); the unmodified 05237 under --replicated-database fails with exactly the CI diff every run.
b Root cause explained? ApplyWithSubqueryVisitor registered only the alias of a direct WITH child, so an alias declared deeper in the expression was left as an identifier, and the full AddDefaultDatabaseVisitor traversal qualified it as <db>.nested. The narrow pass after SQL UDF expansion already used the analyzer's wider rule, so a Replicated replay of its output re-qualified the name.
c Fix matches root cause? Yes. The visitor that decides which WITH names a reference reaches now applies the same rule as the narrow pass and the analyzer, through one shared helper; no guard at the qualification site, no test tag.
d Test intent preserved / new tests added? Yes. 05237 keeps its 8 arms, gets back the 4 mutation/off arms removed in the #114908 rework, and adds view, materialized view, MODIFY QUERY, same-expression, shadowing (nested SELECT, ARRAY JOIN, JOIN ... ON, table function argument, lambda parameter and body) and table-function-lambda arms (33 rows).
e Both directions demonstrated? Yes. Master reads the table (or the inherited alias) on 8 rows, plus view and stored alias is bare under --replicated-database; the fix matches all 33 rows. A mutant per mechanism turns exactly its own rows red.
f Fix is general across code paths? Yes. Every caller of the visitor gets it; measured CREATE VIEW, CREATE MATERIALIZED VIEW, MODIFY QUERY, ALTER TABLE ... UPDATE and the Replicated replay. The narrow pass and AddDefaultDatabaseVisitor::collectAliases use the same helper.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: tuple and array wrappers, lambda and subquery boundaries (still tables, each guarded by a mutant), enable_global_with_statement = 0 (still a table), 50/50 randomized runs. Column type wrappers do not apply to an alias-name rule.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; new definitions store the inlined alias, the form a top-level alias has had since #100042; already stored <db>.name text is not rewritten.
i Invariants and contracts preserved? Yes. Each alias is registered right after its node is visited, so a use before the declaration is unchanged (forward-reference shapes store byte-identical text); an alias a select, a lambda parameter or a lambda body declares hides an inherited one, so the stored text equals the live query; an exported alias still wins under enable_scopes_for_with_statement = 0.

Session id: cron:clickhouse-impl-slot-6:20261003-204800

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [83a4678]


AI Review

Summary

This PR fixes a real class of persisted-query alias-resolution bugs around descendant aliases inside WITH expressions, and the added coverage closes several important regressions. I still see one remaining correctness hole: when enable_scopes_for_with_statement = 0, a lambda-local binding can still be overridden again after the visitor descends into a nested SELECT, so the stored query can diverge from live analyzer resolution.

Findings
  • ❌ Blockers
    • [src/Interpreters/ApplyWithSubqueryVisitor.cpp:118] Lambda shadowing is only removed from literals, not from exported_literals. Under enable_scopes_for_with_statement = 0, a nested SELECT inside that lambda re-imports the outer exported alias at src/Interpreters/ApplyWithSubqueryVisitor.cpp:216, so persisted views / MODIFY QUERY / mutations can still inline the parent WITH alias instead of the lambda-local binding.
    • Suggested fix: erase the shadowed names from both maps when building lambda_data, and add a stateless case where a nested SELECT inside the lambda reads the lambda-local name.
Tests
  • ⚠️ tests/queries/0_stateless/05237_with_expression_alias_scope_descendant.sh covers default-scope shadowing and enable_global_with_statement = 0, but it does not cover enable_scopes_for_with_statement = 0 with a nested SELECT inside a lambda, which is the path that still looks uncovered.
Final Verdict

Changes required.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 3, 2026
This was referenced Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants