Skip to content

Analyzer: throw CYCLIC_ALIASES instead of hanging when an ALIAS column reads itself - #129640

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:analyzer-cyclic-alias-column-read
Nov 6, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:analyzer-cyclic-alias-column-read

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124850

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a query that never finished and used memory until the server was killed when it read an ALIAS column whose expression reads the column itself through a subcolumn, directly or through other ALIAS columns (for example c0 Nullable(IPv6) ALIAS c0.null). Such a read now fails with CYCLIC_ALIASES.

Description

On 26.10.2.103, CREATE TABLE t (x UInt8, c0 Nullable(IPv6) ALIAS c0.null) ENGINE = MergeTree ORDER BY x; SELECT c0 FROM t runs until the server is killed: max_execution_time, max_memory_usage and max_server_memory_usage do not stop it. Older releases reach it through ATTACH or table function structures. Found by La Casa Del Dolor on master: OOM in dmesg, a read of such a column of a refreshable materialized view through clusterAllReplicas.

Root cause: ALIAS expressions are resolved on first use (#123926). While c0.null is resolved, tryGetColumnNode("c0") is called again and returns the node being resolved, which then becomes part of its own expression (getSubcolumn(c0, 'null')). The query tree is cyclic and validateTreeSize walks it forever. A direct cycle (c0 ALIAS c0) overflows the stack instead.

Change: AnalysisTableExpressionData keeps the names of the ALIAS columns being resolved, and tryGetColumnNode throws Cyclic aliases: `c0` -> `c1` -> `c0` when one of them is requested again. A failed resolution leaves the column unresolved, with its scope and lambda recursion guard unwound, so a later reference in the same query (after if(0, c0, ...) drops the first error) resolves it again, and a real cycle fails again. Every cycle comes back through this lookup, so stored definitions, Merge, remote/cluster*, format and JOIN USING are covered. Subcolumn and Nested prefix lookups check the declared type before they resolve a candidate, so a probe that is not a reference (t while t UInt8 ALIAS t.x reads the column x of table t) is not a cycle.

#124850 rejects such definitions at CREATE/ALTER/ATTACH; whichever PR lands second adapts the ATTACH statements of the new test.

Validation: 05546_alias_column_reads_itself fails on master at its first read and passes 50/50 with randomized settings; the stateless tests with alias, subcolumn, Nested, DEFAULT, lambda or short-circuit in their names show no new failures.


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

Version info

  • Merged into: 26.11.1.1517-master (included in 26.11 and later)

groeneai and others added 2 commits November 5, 2026 22:31
…expression is resolved

An ALIAS column whose expression reads the column itself through a
subcolumn, e.g. `c0 Nullable(IPv6) ALIAS c0.null`, made a SELECT of it run
until the server was killed. On 26.10 such a column is accepted by CREATE
and ALTER; older releases reach it through ATTACH and table function
structures (format, remote). It was found by La Casa Del Dolor on master:
a read through clusterAllReplicas of a refreshable materialized view with
such a column OOM-killed the server.

ALIAS expressions are resolved lazily (ClickHouse#123926): tryGetColumnNode erases
the column from unresolved_alias_columns and calls the resolver, which
sets the node's expression and resolves it against the same table data.
Resolving `c0.null` calls tryGetSubcolumnInfo -> tryGetColumnNode("c0"),
which no longer finds the column unresolved and returns the node that is
being resolved; wrapExpressionNodeInSubcolumn then makes
getSubcolumn(<c0 node>, 'null') part of that node's own expression. The
query tree is cyclic, and validateTreeSize, an iterative DFS that
memoizes a node only after its children, grows its stack without bound.
Analysis is not cancellable, so max_execution_time, max_memory_usage,
max_server_memory_usage and KILL QUERY do not stop it. A direct cycle
(`c0 ALIAS c0`) overflows the stack in a recursive walker instead
(TOO_DEEP_RECURSION).

The resolver now pushes the column name to
AnalysisTableExpressionData::alias_columns_in_resolution before building
the expression and pops it on scope exit, and tryGetColumnNode throws
CYCLIC_ALIASES with the chain when a requested column is in that list.
The resolver captures the original data, which is also the alias
resolution data of every re-entrant lookup, so the check also works when
a copy of the data started the resolution (the JOIN USING projection
alias path); that is why it precedes the unresolved_alias_columns branch.
Every cycle (through subcolumns, other ALIAS columns, functions) comes
back through this lookup, so tables, Merge, remote/cluster*, format,
materialized views and stored definitions are all covered.

The definition-time check for such columns is ClickHouse#124850.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n throws

The CYCLIC_ALIASES check left the column half-resolved: tryGetColumnNode
erased it from unresolved_alias_columns before resolving, and the resolver
had already set the unresolved expression when the check threw. Constant
if/multiIf folding catches errors of the dead branch, so in
`SELECT if(0, c0, NULL), c0` the second reference got a node whose
expression was the unresolved identifier `c0.null` and the query failed
with UNSUPPORTED_METHOD instead of CYCLIC_ALIASES.

Now the resolver resets the expression unless it reached its end, and the
column is erased from unresolved_alias_columns only after the resolver
returns, so a later reference resolves it again and fails the same way.
The test gains the if/multiIf retries plus the format() and JOIN USING
shapes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
❌ A CYCLIC_ALIASES caught by constant if/multiIf dead-branch folding left the column half-resolved, so a later reference in the same query failed with UNSUPPORTED_METHOD AGREE, fixed: a failed resolution leaves the column unresolved; test statements added
💡 format() and the JOIN USING copy path were claimed but not in the test AGREE, fixed: one statement each
💡 The shortest-prefix subcolumn probe also throws for an alias a reading a.b.<dynamic> through another column a.b DISAGREE: needs a column named as a dotted extension of the alias, no realistic schema

Re-review of the fix: no findings.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: CREATE TABLE t (x UInt8, c0 Nullable(IPv6) ALIAS c0.null) ENGINE = MergeTree ORDER BY x; SELECT c0 FROM t in clickhouse local under a 6 GiB cgroup is OOM-killed in ~9 s on master; the CI shape (clusterAllReplicas over a refreshable MV) pins a server at its 16 GiB limit.
b Root cause explained? Lazy ALIAS resolution: the re-entrant tryGetColumnNode("c0") returns the node being resolved, getSubcolumn(c0, 'null') becomes part of its own expression, and validateTreeSize walks the cyclic tree forever.
c Fix matches root cause? Yes: the lookup that would close the cycle throws CYCLIC_ALIASES, so no cyclic tree is built; no walker is bounded.
d Test intent preserved / new tests added? New 05546_alias_column_reads_itself: direct, self through a subcolumn, remote(), a second reference after a constant if/multiIf dropped the first error, format(), JOIN USING, Merge, mutual cycle, and non-cycle guards (alias of an alias subcolumn, lambda argument named like the column).
e Both directions demonstrated? Master: 9 hang shapes OOM-killed, 5 direct cycles TOO_DEEP_RECURSION, the test fails at its first read. Fix: all CYCLIC_ALIASES in under a second, also for a second reference after if(0, c0, ...) / multiIf(0, c0, ...); test 50/50 with randomized settings.
f Fix is general across code paths? One check on every path that resolves an ALIAS expression: tables, remote/cluster*/format, Merge, refreshable MV, JOIN USING through a copy of the table data; each measured.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable(IPv6)/Nullable(String) .size/Nullable(UInt8)/UInt8/Tuple/Array, chains of length 1 to 3, MergeTree/Memory/Merge/MaterializedView.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; only reads that hung or overflowed the stack now fail with CYCLIC_ALIASES. 1297 stateless tests (alias, subcolumn, Nested, DEFAULT) show no new failure.
i Invariants and contracts preserved? The list of columns being resolved is LIFO (pushed before the expression is set, popped by SCOPE_EXIT, also on a throw); a failed resolution resets the expression and keeps the column in unresolved_alias_columns, so the next lookup resolves it again; on success the resolve-once-per-object contract is unchanged.

Session id: cron:clickhouse-impl-slot-40:20261105-225800

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @novikd, could you review this and add the can be tested label so CI runs? It makes the analyzer throw CYCLIC_ALIASES when an ALIAS column is requested again while its own expression is being resolved (e.g. c0 Nullable(IPv6) ALIAS c0.null), instead of building a cyclic query tree that validateTreeSize walks until the server is OOM-killed, as in the La Casa Del Dolor run linked in the description.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0d4643e]

Summary: ✅


AI Review

Summary

Reviewed #129640 at 0d4643e8c05db51cae12e88d2be571438b4507ea, including all prior discussion. The change rejects recursive ALIAS column expansion with CYCLIC_ALIASES and restores resolution state after discarded exceptions. No unresolved findings remain. The previous lambda-state finding is fixed and its thread has been resolved.

The new regression test passes in the fast-test report for this head. Focused local checks with the same head's binary also confirm the lambda and inner-alias retry cases succeed.

Final Verdict

✅ Approve — no new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 5, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Amazing finding, thank you!

@alexey-milovidov alexey-milovidov self-assigned this Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0d4643e8c with master c9e18d017 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 831894676; 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

7 object files changed (+40.52 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.62 MiB 1.65 MiB +20.90 KiB (+1.26%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/TableExpressionData.cpp.o 39.85 KiB 57.09 KiB +17.24 KiB (+43.27%)

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

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

Job report

…olves an ALIAS column

`tryGetSubcolumnInfo` and `tryResolveIdentifierAsNestedPrefix` called
`tryGetColumnNode`, which resolves the expression of an ALIAS column, for
every candidate before checking its type. When the candidate was an ALIAS
column whose resolution was already in progress, the new cycle check threw
`CYCLIC_ALIASES`, although the probe would have discarded the column.

Valid definitions that read 7 / 2 / 5 before this PR and threw afterwards:
`t UInt8 ALIAS t.x` in table `t` (table-qualified column), `a UInt8 ALIAS
t.x, t UInt8 ALIAS a`, `n.a UInt64 ALIAS length(n)` next to
`n.b Array(UInt8)` (Nested prefix), and `a String ALIAS toString(a.b.c)`
next to a `a.b JSON` column. The last two are accepted by CREATE TABLE.

The type of a column node is its declared type, so both probes now check it
on the node from `getColumnNodeMap` and call `tryGetColumnNode` only for a
column they return. A probe that does return the column still reaches the
cycle check, so the real cycles keep throwing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 8133b27: subcolumn and Nested prefix probes now check the declared type before they resolve an ALIAS column, and the test covers both table-qualified shapes and the Nested prefix.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…lumn

Since 8cdb747 a failed resolution of an ALIAS column leaves the column
unresolved, and the next lookup resolves it again. State of the failed attempt
survived into that retry in two places:

- `resolveLambda` erased the lambda from `lambdas_in_resolve_process` only on
  success, so the retry met the structurally equal lambda and threw
  `Recursive lambda`.
- The column's `IdentifierResolveScope` was reused with the aliases, the
  identifier lookups in progress and the identifier cache of the failed
  attempt, so an inner alias of the expression threw
  `MULTIPLE_EXPRESSIONS_FOR_ALIAS`.

The failure is visible when the cycle goes through a branch of `if`/`multiIf`
that is not taken, whose error the constant folding discards. For a definition
loaded by ATTACH, `a Int32 ALIAS if(0, b, 1)` with
`b Int32 ALIAS arraySum(arrayMap(z -> z + a, [2]))` reads `1 3` on master and
threw `Recursive lambda` here; `d Int32 ALIAS q + ((x + c) AS q)` with
`c Int32 ALIAS if(0, d, 1)` reads `1 16` on master and threw
`MULTIPLE_EXPRESSIONS_FOR_ALIAS`.

The lambda is now erased by `SCOPE_EXIT`, and a retry replaces the scope with
a fresh one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai from my understanding, CREATE TABLE t (x UInt8, c0 Nullable(IPv6) ALIAS c0.null) ENGINE = MergeTree ORDER BY x; this create should fail because it doesn't make sense for a column to reference itself in the alias expression

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, it should fail. That check is my #124850: with it on top of this PR, this CREATE fails with CYCLIC_ALIASES, and so do ALTER ... ADD COLUMN, a refreshable MV TO with that column list, and ATTACH, while c1 UInt8 ALIAS c0.null over a physical c0 still works.

This PR covers tables that already have such a column. 26.10.2.103 accepts the CREATE, and #124850 does not re-check stored metadata, so such a table still loads (measured with a table created on 26.10.2.103). Reading the column then runs until the server is OOM-killed (master: 10 s under a 6 GiB cgroup, max_execution_time = 2 does not stop it); with this PR it fails with CYCLIC_ALIASES.

I can move the CREATE check into this PR if you prefer one PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 78e4937 Nov 6, 2026
186 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
ClickHouse#129640 added the analyzer read-side guard and created its cyclic tables
with a full-definition ATTACH, which did not validate ALIAS columns. This
PR screens a full ATTACH like CREATE, so those ATTACH statements now fail
with CYCLIC_ALIASES and the reads of tables that can no longer be created
are removed; the non-cycle guards (`t_ok`, `t_probe`) still attach and
read the same values. The read-side guard remains for definitions stored
by older versions, which a stateless test cannot create.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
Since ClickHouse#129640 a read that closes an ALIAS cycle fails with CYCLIC_ALIASES
in the analyzer, including a cycle hidden in a SQL UDF of a table function
structure, which used to run the server out of memory. Following UDF
bodies at definition time therefore only moved that error earlier, and it
had to approximate the analyzer's binding of UDF parameters: a parameter
that receives a function composition (`negate | toString`) and shares its
name with a registered UDF was expanded as that UDF, so a valid structure
was rejected (master reads it).

Drop the UDF expansion and keep the subquery descent; `CREATE TABLE` and a
full `ATTACH` expand SQL UDFs before the check anyway. The UDF test now
checks that reading such a column fails with CYCLIC_ALIASES, and that the
composition case reads its value.

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). 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.

4 participants