Repository navigation
Conversation
An ALIAS column whose expression reads its own subcolumn, e.g. `c5 String ALIAS c5.size` (or `` `c5.size` ``), was accepted by CREATE, ALTER, full ATTACH and table function structures. The definition-time cycle check (`detectRecursiveDefaultCycles`) binds an identifier to a column only by its whole name, and the analyzer pass that validates the defaults resolves `c5.size` over a dummy storage where `c5` is a plain column. On read, the analyzer resolves `c5.size` through `tryGetSubcolumnInfo` to the ALIAS column node being resolved and wraps that node in `getSubcolumn`, so the node becomes its own descendant. `validateTreeSize` then walks the cycle forever and its stack grows through implicit allocations that the memory limit does not refuse: `SELECT c0` from such a table, or `SELECT c0 FROM format(CSV, 'c0 Int32, c5 String ALIAS c5.size', '1')`, runs the server out of memory (found by BuzzHouse on PR ClickHouse#109377). Through a second ALIAS column (`b String ALIAS a, a String ALIAS toString(b.size)`) the same cycle overflows the stack in `QueryExpressionsAliasVisitor`. Add `ColumnsDescription::checkAliasColumnsAreNotCyclic`: the ALIAS columns of a table, with an edge from ALIAS `X` to ALIAS `Y` when `X` reads `Y` by name or through a subcolumn bound the way `tryGetSubcolumnInfo` binds it (the column of that name, else the first `.`-prefix column whose type has the rest as a subcolumn), must form no cycle. Only ALIAS expressions are expanded into the query tree, so references to physical, DEFAULT and MATERIALIZED columns are not edges, and the existing DEFAULT cycle rule is unchanged. The DFS of `detectRecursiveDefaultCycles` is factored out and shared. The check runs where a user-supplied definition is accepted: column lists and table function structures in `getColumnsDescription` (mode CREATE), full ATTACH / `AS src` / `CLONE AS src` in the fresh-definition block of `getTablePropertiesAndNormalizeCreateQuery`, and the whole post-ALTER metadata in `validateCreateQuery`. Stored metadata is not screened on replay; a table stored with such a column by an older version keeps loading, rejects further ALTERs until the alias is removed (`MODIFY COLUMN ... REMOVE ALIAS`), and still cannot be read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`RequiredSourceColumnsVisitor` masks a lambda parameter only by its exact name, while the analyzer binds an identifier to a lambda argument by its full name or by its first part, before table columns. With a dotted parameter (`` `x.foo` -> `x.foo`.hash ``) the body reference leaked and was bound to the table column `x`, so a valid definition was rejected as `x -> x`. The check now collects names with its own walk: an identifier whose name or first part is a parameter of an enclosing lambda is not a table read, subqueries are not descended into. In-expression aliases (`expr AS b`) are deliberately not masked: under `prefer_column_name_to_alias = 1` the analyzer reads the table column `b` first, and such a definition overflows the stack on read (SIGSEGV on master with an ALIAS column `b` reading `a.size`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings over a full pass and one delta recheck) plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261009-065200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261009-044400 |
|
Workflow [PR], commit [cfce14f] Summary: ✅
AI ReviewSummaryReviewed Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings. |
| NameSet dependencies; | ||
| if (auto it = alias_to_expression.find(vertex); it != alias_to_expression.end()) | ||
| { | ||
| collectAliasDependenciesFromAST(it->second, alias_names, dependencies); |
There was a problem hiding this comment.
Nice refactor of the DFS, but this still leaves the existing DEFAULT/MATERIALIZED cycle detector blind to subcolumn self-reads. collectAliasDependenciesFromAST only adds an edge when the identifier text exactly matches a column name, so cases like a DEFAULT a.size, a MATERIALIZED a.null, or b DEFAULT toString(a.size), a DEFAULT b still contribute no dependency back to a.
Nothing else in validateDefaultsWithAnalyzer repairs that: it analyzes against a fake table where a exists as a source column, and elsewhere we already normalize subcolumn reads back to their top-level column for dependency tracking (MaterializedColumnDependencies does this with replaceSubcolumnsToGetSubcolumnFunctionInQuery). Could we make detectRecursiveDefaultCycles use the same subcolumn-aware collection/binding as checkAliasColumnsAreNotCyclic, so the fix applies consistently to all column-expression kinds?
There was a problem hiding this comment.
I left the DEFAULT/MATERIALIZED rule unchanged: such a cycle through subcolumns only makes an INSERT that omits every member fail with UNKNOWN_IDENTIFIER (same on master), and 04040_defaults_dependency_order expects that table (test_circ_tuple) to be created. #127018 extends that check to compound subcolumn references.
CI finish ledger - 7b7562bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 163 check runs completed. The other three Session id: cron:our-pr-ci-monitor:20261009-090003 |
…-subcolumn # Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp
CREATE and ALTER reject any subquery in a column default (`hasSubqueryInTree`), but a full-definition `ATTACH`, `AS` and `CLONE AS` skip that validation, so the ALIAS cycle check is the only screen there. Skipping subqueries let `a String ALIAS toString((SELECT b.size)), b String ALIAS a` through, and reading `a` then grows memory until the process is OOM-killed (also with a `FROM` in the subquery, and for `a ALIAS toString((SELECT a.size))`). Identifiers inside subqueries now count as reads of the table. This is stricter than the analyzer only when the subquery reads a column of another table named like an ALIAS column of this one, a definition CREATE rejects anyway. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A table function structure is parsed without the SQL UDF substitution a
CREATE TABLE or a full-definition ATTACH applies, so an ALIAS that reads
itself inside a UDF body passed the cycle check. With
prefer_column_name_to_alias = 1 the default expression validation accepts
such a structure too, and a UDF whose body is a scalar subquery also hides
the subquery from that validation:
CREATE FUNCTION h AS () -> (SELECT a.size);
SET prefer_column_name_to_alias = 1;
SELECT a FROM format(CSV, 'i Int32, a String ALIAS toString(h())', '1');
grows memory until the process is OOM-killed (master too). A plain
`() -> a.size` ends in TOO_DEEP_RECURSION.
The check now expands SQL UDFs in a copy of each ALIAS expression before
collecting the names it reads. The stored expression is unchanged, so
DESCRIBE still shows the UDF call, and a non-cyclic UDF alias (also one with
a subquery body) reads as before. As for a subquery in a full-definition
ATTACH, a UDF subquery that reads a same-named column of its own FROM now
counts as a read of the table; CREATE TABLE rejects that definition anyway
(a subquery in a default), and skipping such subqueries would let
`(SELECT a.size FROM numbers(1))` through, which is OOM-killed on read.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes7 object files changed (+22.82 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units1154 translation units recompiled, 8135 s compile time in total, 1154 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Expanding SQL UDFs with UserDefinedSQLFunctionVisitor before collecting the names an ALIAS reads substitutes whole-name parameters only, so a parameter used with a subcolumn stayed behind as a name of its own: - with `review_size = (x) -> x.size`, the structure `a String ALIAS toString(review_size(b)), b String ALIAS toString(a.size)` lost the edge from `a` to `b`, and `SELECT a FROM format(CSV, ...)` is OOM-killed (master too); - with `f = (a) -> a.size`, `s String, a String ALIAS toString(f(s))` was rejected with CYCLIC_ALIASES, because `a.size` was bound to the column `a`. The check now handles a SQL UDF call the way the analyzer resolves it, as a lambda applied to the call arguments: the arguments are read in the calling scope, and the body is read with the UDF parameters masked like lambda parameters. A call of a parameter whose argument is a lambda calls that lambda (already read where it is passed), not a registered UDF of the same name; with any other argument the name is looked up as a UDF, as the analyzer does. A UDF that is already being entered is not entered again. The check no longer needs a context. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@KochetovNicolai a scope question, since the bot keeps finding UDF corners here. To catch cycles hidden in SQL UDFs of table function structures (OOM-killed on master too), the check follows UDF calls as lambdas. It still over-approximates the analyzer's binding in contrived cases: for example, a lambda argument that the UDF never calls, and that reads the |
| } | ||
| } | ||
|
|
||
| for (const auto & child : node->children) |
There was a problem hiding this comment.
This recursive walk flattens every identifier under a scalar subquery into an outer-table read, because it descends into the subquery AST without preserving the subquery's own alias / FROM scope. That makes fresh-definition ATTACH reject safe aliases whenever the inner query reuses the same name, for example:
ATTACH TABLE db.t
(
a UInt64 ALIAS (SELECT a FROM (SELECT 1 AS a))
) ENGINE = Memory;At read time the inner a resolves inside the subquery, but collectNamesReadFromTable records it here and checkAliasColumnsAreNotCyclic turns it into a self-edge on a, so the definition now fails with CYCLIC_ALIASES. Could we preserve subquery binding here (or at least stop counting names proven local to the subquery) instead of treating every nested identifier as an outer dependency?
There was a problem hiding this comment.
Not changed: the walk cannot see a subquery's FROM columns without the catalog, and skipping subqueries with a FROM would let a full ATTACH accept a String ALIAS toString((SELECT b.size FROM numbers(1))), b String ALIAS a again (master accepts it). The rejected shape cannot be created on master either (CREATE refuses a subquery in an ALIAS with Code 116), so only a hand-written full ATTACH reaches it.
…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]>
…-subcolumn # Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp
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]>
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]>
|
Answering my own question above: I dropped UDF bodies from the check in 45a7ecf. Since #129640 such a cycle fails with |
An identifier that is neither a column nor a subcolumn can still read columns: the analyzer rebuilds `n` from every `Array` column `n.<suffix>` (`IdentifierResolver::tryResolveIdentifierAsNestedPrefix`). The cycle check ignored that, so `a Array(Tuple(x UInt64)) ALIAS n, n.x Array(UInt64) ALIAS a.x` was accepted and failed only on read. Add the edges to the `ALIAS` columns `n.<suffix>` when the name does not bind to a column or subcolumn, which keeps the analyzer's precedence (an exact column `n` wins). Compound suffixes (`n.b.c`) are followed as with the default `analyzer_compatibility_allow_compound_identifiers_in_unflatten_nested = 1`: a stored definition is read under any session's settings, and such a table fails every default read with `CYCLIC_ALIASES`. Only a table function structure of that shape queried with the setting disabled is now rejected where master reads it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #109377
Related: #129640
Related: #110435
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE,ALTER, fullATTACHand table function structures now reject anALIAScolumn that reads its own subcolumn, directly or through otherALIAScolumns (for examplec String ALIAS c.size), withCYCLIC_ALIASES. Before, such a definition was accepted and failed only when the column was read.Description
On master,
CREATE TABLE t (x UInt8, c0 Nullable(IPv6) ALIAS c0.null) ENGINE = Memoryis accepted, andSELECT c0 FROM tfails withCYCLIC_ALIASES(#129640). On 26.10.2.103 the same read runs the server out of memory. Found by BuzzHouse:OOM in dmesgon #109377. Such a definition should fail atCREATE.Root cause: the definition-time cycle check binds an identifier to a column only by its whole name, so
c0.nullis not seen as readingc0.Change:
ColumnsDescription::checkAliasColumnsAreNotCyclicbuilds the graph ofALIAScolumns, with an edge when an expression (subqueries included) reads anotherALIAScolumn by name, through a subcolumn (bound the waytryGetSubcolumnInfobinds it) or as a member of aNestedprefix, and rejects a cycle with the existing DFS (factored out ofdetectRecursiveDefaultCycles, whoseDEFAULTrule is unchanged). It runs for column lists and table function structures, fullATTACH/AS/CLONE AS, and the post-ALTERmetadata.05546_alias_column_reads_itself(#129640) now expectsCYCLIC_ALIASESat its cyclicATTACHstatements.SQL UDF bodies are not followed: a cycle hidden in one fails with
CYCLIC_ALIASESwhen the column is read. Metadata already stored with such a column still loads and fails the same way on read; furtherALTERs on it are rejected untilMODIFY COLUMN ... REMOVE ALIAS.#127018 makes the existing
DEFAULTcycle check follow compound subcolumn references such asc0.null; that check does not run for a fullATTACH, this one does.Validation: the new test
05339_alias_column_cyclic_subcolumnand the adapted05546fail on master;05339_alias_column_cyclic_subcolumn_udfchecks the read of UDF-hidden cycles; randomized runs pass; stateless tests that useALIASor SQL UDFs show no new failures.Workflow [PR]
Sync PR [sync-upstream/pr/124850]