Repository navigation
Fix LOGICAL_ERROR when a column transformer sets an alias on an asterisk - #109223
alexey-milovidov merged 19 commits into
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260702-194800 |
|
cc @evillique @george-larionov — could you review this? It converts a |
|
Workflow [PR], commit [0777b02] Summary: ✅
AI ReviewSummaryThis PR fixes the analyzer/legacy mismatches around named column transformers and closes the earlier gaps around bare matchers, Findings
Tests
Final Verdict
LLVM Coverage Report |
…fix in the analyzer Two related column-transformer issues: 1. Old analyzer crash. APPLY (with a name prefix) and REPLACE assign an alias to their result node. Only ASTWithAlias nodes support aliases, so when the transformer expression expands to an asterisk / qualified asterisk / COLUMNS matcher (e.g. SELECT * APPLY (x -> t.*, 'p_')), the default IAST::setAlias threw a LOGICAL_ERROR and aborted the server in debug/sanitizer builds. Reject such queries with a clear BAD_ARGUMENTS. Found by the AST fuzzer (STID 1493-3ccb). 2. New (default) analyzer dropped the APPLY name prefix. APPLY (expr, 'p_') is documented and works under the old analyzer (result named p_ + column name), but the analyzer never carried column_name_prefix from the parser into ApplyColumnTransformerNode, so the prefix was silently ignored (e.g. SELECT * APPLY (toString, 'f_') produced toString(a) instead of f_a). Carry the prefix QueryTreeBuilder -> ApplyColumnTransformerNode -> resolveMatcher / toASTImpl so the projection name matches the old analyzer. Closes: ClickHouse#109214 Co-Authored-By: Claude Opus 4.8 <[email protected]>
9213084 to
81bdafb
Compare
Pre-PR validation gate (click to expand) — analyzer follow-up
Session id: cron:clickhouse-worker-slot-3:20260702-233000 |
…e names The new-analyzer APPLY name-prefix support added earlier in this PR took the prefix base from node_to_projection_name, which qualifyColumnNodesWithProjectionNames may set to a qualified name (t1.a) in a scope that requires qualification. The legacy AST path prefixes ASTIdentifier::shortName(). So `t1.* APPLY (toString, 'f_')` in a qualifying scope produced f_t1.a instead of f_a. Fix: accumulate the prefixed display name from the short column name, independent of the (possibly qualified) node_to_projection_name value. The prefix also failed to reach a chained transformer when the first transformer was an identity lambda (`APPLY (x -> x, 'p_') APPLY toString` gave toString(a), not toString(p_a)): the identity lambda leaves the resolved node pointing at the original matched node, which is already present in both node_to_projection_name and resolved_expressions, so an emplace did not update the name. Overwrite both maps when the resolved node pointer is reused. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260703-004300 |
…sion, not the prefix alias
The earlier analyzer fix stored the prefixed display name (f_a, p_a) into
node_to_projection_name for every APPLY result, including freshly created
function/lambda nodes. A later unprefixed APPLY then formatted its argument
from that prefix alias instead of the actual previous expression, so the
analyzer diverged from the legacy AST path for function-form chains:
SELECT * APPLY (identity, 'p_') APPLY toString -> toString(p_a) (analyzer)
-> toString(identity(a)) (legacy)
SELECT * APPLY (toString, 'f_') APPLY upper -> upper(f_a) (analyzer)
-> upper(toString(a)) (legacy)
Split the two roles:
- Terminal display name of this column keeps the accumulated prefix (f_a, q_p_a).
- The name a chained transformer observes for this node is the natural resolved
name for a freshly created node (toString(identity(a))), matching the legacy
path. Only a reused node (an identity lambda x -> x that resolves back to the
original matched node, which has no legacy equivalent) carries the accumulated
prefix forward, so a chained transformer still sees toString(p_a) there.
The overwrite of node_to_projection_name / resolved_expressions is now gated on
node-pointer reuse, so it no longer rewrites the cached name of a fresh function
node. The short-name accumulator for qualified scopes (f_a, not f_x.a) is kept.
Regression coverage in 04401 asserts the analyzer section matches the legacy
section for both function-form chains and the identity-lambda reuse case.
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260703-031100 |
…BAD_ARGUMENTS The default analyzer accepted a named transformer whose expression is a bare matcher/asterisk (APPLY (x -> *, 'prefix'), APPLY (x -> COLUMNS(...), 'prefix'), REPLACE (COLUMNS(...) AS a)): on a one-column input it renamed the reused column (f_a), and on a multi-column input it threw a generic UNSUPPORTED_METHOD. The legacy analyzer rejects all of these with BAD_ARGUMENTS (setAlias on a non-aliasable asterisk node). Reject them in resolveMatcher before the matcher is expanded, when the lambda body (for a prefixed APPLY) or the REPLACE replacement is itself a MatcherNode. A matcher nested inside a function (x -> tuple(*)) is not a bare matcher and stays allowed, matching the legacy path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260703-044900 |
A named APPLY over untuple (SELECT * APPLY (x -> untuple(x), 'f_')) resolved to a ListNode of tupleElement calls, one per tuple field, and the matcher rejected it with a generic UNSUPPORTED_METHOD (size != 1). The legacy analyzer instead expands each element with the prefix applied to the short column name (f_a.1, f_a.id). Expand the list into sibling projection columns to match, but only when untuple is the terminal transformer (a transformer chained after untuple is rejected by both analyzers). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit 247a715)Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260703-063600 |
…y name A named untuple chained after an earlier transformer prefixed each output element from the original short column name (q_a.N), diverging from the legacy path which uses the accumulated display name of the node feeding untuple. Base the element names on apply_prefixed_projection_name so chained forms come out as q_identity(a).N / q_p_a.N (matching enable_analyzer=0), while a direct untuple stays f_a.N. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260703-090000 |
The untuple list-expansion special-case in QueryAnalyzer::resolveMatcher only ran for execute_apply_transformer, so a named REPLACE over untuple such as SELECT * REPLACE (untuple(a) AS a) FROM (SELECT (1, 2) AS a) fell through to the size != 1 UNSUPPORTED_METHOD throw under enable_analyzer=1, while enable_analyzer=0 accepted it and expanded to a.1, a.2 (ActionsVisitor::doUntuple aliases the untuple to the REPLACE target name). Relax the guard to also fire for execute_replace_transformer. For REPLACE the prefix is empty and the display-name accumulator holds the replaced column name, so the element names come out as the REPLACE target base (a.1, a.id), matching the old analyzer. The is_last_transformer gate is unchanged: a transformer chained after untuple is rejected by both analyzers. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260703-100700 |
… tuples The named-untuple expansion only ran when untuple resolved to a multi-element list (node_list_nodes_size != 1). A single-field tuple resolves to a one-element list, so it skipped the expansion and the generic single-node path dropped the field suffix: APPLY (untuple, 'f_') over Tuple(id UInt8) produced f_a instead of f_a.id, and REPLACE (untuple(a) AS a) produced a instead of a.id. The legacy transformer path (ActionsVisitor::doUntuple) keeps the field suffix for every tuple, including single-field ones (see 02890_untuple_column_names). Drop the size != 1 requirement; the isUntupleExpansion guard (every element is tupleElement(arg, const)) already restricts this to genuine untuple results, so the expansion now covers one-element tuples too. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Dropping the old-analyzer arm in 0752f03 left the file setting enable_analyzer nowhere, so the "old analyzer" stateless variant (Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, ...), which runs on pull requests) ran its analyzer-specific naming cases under the legacy expansion. The legacy path substitutes the lambda argument only in children of the body, so a root identity lambda is left as the identifier x: SELECT * APPLY (x -> x, 'p_') FROM (SELECT 1 AS a) Code: 47. Missing columns: 'x' while processing: 'SELECT x AS p_a FROM (SELECT 1 AS a)' (UNKNOWN_IDENTIFIER) measured on master 261c959 with --enable_analyzer=0; the same queries return the expected rows with --enable_analyzer=1. The INSERT arm keeps covering the original abort: an INSERT column list expands the transformers outside the query tree, so it still reaches the legacy helper with the mode pinned to 1 (verified: it aborts on master, passes here).
|
The only real failure at the previous head ( That test asserted I also pinned Those jobs never ran at the previous head, so this had not surfaced yet. The CI is running on |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes7 object files changed (+29.41 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units32 translation units recompiled, 262 s compile time in total, 32 of them have a recent master baseline. |
CI finish ledger - 378733bCI is fully finished and green on this head: 174/174 checks completed, 156 pass, 18 skipped, 0 failures. For continuity with the previous ledger: the Session id: cron:our-pr-ci-monitor:20260907-000027 |
|
@groeneai, resolve conflicts. |
…ransformer-alias-on-asterisk One conflicted file, src/Analyzer/Resolve/QueryAnalyzer.cpp, resolved as a union of two independent additions at the same two insertion points. Anonymous namespace: master's checkMaterializedCTESubqueryIsNotCorrelated (ClickHouse#108883) and this branch's isUntupleExpansion / getTupleElementName helpers. Kept both, master's first. resolveMatcher LAMBDA branch: master's node_to_projection_name.emplace seed (ClickHouse#118825) and this branch's BAD_ARGUMENTS guard for a prefixed APPLY whose lambda body is a bare matcher. Kept both, the guard first so the rejected query does not register a projection name on its way out. The seed publishes the pre-transformer name of the matched column, which is what a later bare matcher must still see; the prefixed name is published on this chain's private clone further down, so the two writes do not compete. Verified the branch delta to that file is unchanged by the resolution: the 174 changed lines of git diff <merge-base>..HEAD are set-identical to git diff origin/master..<resolved>. Co-Authored-By: Claude Opus 5 <[email protected]>
`SELECT * APPLY (x -> (x AS z)), * FROM (SELECT 1 AS a)` printed `z, z`: the second, untransformed `*` was renamed too. Reversing the two matchers printed `a, z`, so the result depended on projection order. Master prints `z, a`. An identity lambda resolves back to the very node the matcher handed it, and getMatchedColumnNodesWithNames hands out one node per column without cloning, so that node is shared with every other expression in the query. The private-copy condition covered only a non-empty APPLY prefix, while an alias in the lambda body produces a chain-local name the same way, and publishing it with insert_or_assign overwrote the name the later bare matcher reads. Condition on the name having changed rather than on the prefix being non-empty, which covers both sources. Regression arms for the aliased identity lambda in both projection orders, and for prefix plus alias together (`p_a, a`). Co-Authored-By: Claude Opus 5 <[email protected]>
|
Conflicts resolved and pushed as Only Validating the merge also surfaced a naming bug this branch had introduced, which I fixed in the same push. Verified on a debug build of the merged tree: |
Review feedback asked whether the private copy added in 4a46126 leaks the post-alias display name into a chained transformer, so that `SELECT * APPLY (x -> (x AS z)) APPLY toString FROM (SELECT 1 AS a)` reports `toString(z)` where it used to report `toString(a)`. Measured on debug builds of this branch and of master: both print `toString(z)`, and the legacy expansion rejects that query with UNKNOWN_IDENTIFIER because a root identity lambda is not substituted there. Nothing regressed, the two chained shapes were simply uncovered, so pin them. Also assert the prefix on the query tree to AST conversion directly. Dropping `ast_apply_transformer->column_name_prefix` from ApplyColumnTransformerNode::toASTImpl turns both EXPLAIN arms red, so the new one has a live oracle. Co-Authored-By: Claude Opus 5 <[email protected]>
`applyColumnsReplaceTransformer` calls `setTransformerAlias` from two places: once for a plain identifier, once for a column that already carries an alias. Only the identifier branch had a test, so reverting the second call to a bare `setAlias` left the suite green while a debug build still aborted there. A prefixed `APPLY` leaves every expanded column aliased, so a `REPLACE` keyed on that generated name takes the aliased-column branch. Measured on a debug build of today's master snapshot (195780d) the new arm exits 134, and on this branch it is BAD_ARGUMENTS. Co-Authored-By: Claude Opus 5 <[email protected]>
| ast_apply_transformer->lambda = lambda_expression.toAST(options); | ||
| } | ||
|
|
||
| ast_apply_transformer->column_name_prefix = column_name_prefix; |
There was a problem hiding this comment.
toASTImpl now preserves APPLY's column_name_prefix, but the AST printer that serializes that field still emits it without SQL escaping (ASTColumnsApplyTransformer::formatImpl / appendColumnName build , '<raw prefix>') directly in src/Parsers/ASTColumnsTransformers.cpp). Because the parser accepts an arbitrary string literal here, a valid query such as SELECT * APPLY (toString, 'x''y') FROM (SELECT 1 AS a) now formats as invalid SQL (APPLY (toString(), 'x'y')) on dump_ast / distributed-query round-trips, and assertion builds trip Inconsistent AST formatting. If this PR is going to route prefixed APPLY through toAST, it needs the prefix escaped in both printer paths and a regression with an embedded quote.
There was a problem hiding this comment.
The escaping defect is real. I am fixing it in its own PR: #119851 (quoteString for the prefix, backQuoteIfNeed for the applied function name, plus the embedded-quote regression, including your exact query).
Two corrections to the attribution, measured on debug builds of today's master snapshot (195780d646b8d, build id cbab6a4b4c4e...) and of this head (0777b02e, build id ec193ed5...), both binaries run identically:
| query | master | this head |
|---|---|---|
SELECT * APPLY (toString, 'x''y') FROM (SELECT 1 AS a) |
exit 134, Inconsistent AST formatting |
exit 134, same |
formatQuerySingleLine('SELECT * APPLY (toString, ''x''''y'') FROM t') |
SELECT * APPLY (toString, 'x'y') FROM t |
identical |
| re-parsing that output | Code: 62, SYNTAX_ERROR |
Code: 62 |
So the unescaped prefix is pre-existing, not introduced here. ASTColumnsApplyTransformer::formatImpl is reached from the statement's own formatting, so formatQuery already returns unparseable SQL and an assertions build already aborts, with or without this PR. That is also why the quote case does not become newly reachable on dump_ast: EXPLAIN QUERY TREE ... dump_ast = 1 over that query exits 134 on both binaries, the outer statement mangling the text before the query tree is involved.
Your premise about the routing is right, though, and that part is this PR. Without a quote:
EXPLAIN QUERY TREE run_passes = 0, dump_tree = 0, dump_ast = 1 SELECT * APPLY (toString, 'f_') FROM (SELECT 1 AS a)
master: SELECT * APPLY toString() /* prefix silently dropped */
this head: SELECT * APPLY (toString(), 'f_')
Once the prefix survives toAST, the printer owes it escaping. Agreed.
Why a separate PR rather than a commit here: the lines are src/Parsers/ASTColumnsTransformers.cpp:43 and :56, and this PR touches 7 files, none of them in src/Parsers/. Those same two lines are rewritten by my other open PR #114205, whose head commit is a maintainer's own master merge, so I do not push to that branch; changing them here would put two of my own open PRs in conflict on the same lines. appendColumnName deliberately stays raw in #119851: its output is a column name that is never parsed back, so quoting there would rename user-visible columns for every prefixed APPLY.
There was a problem hiding this comment.
🕵 Closing the loop: the escaping fix landed on master on 2026-09-14 as #119851 (commit 6340fd2912f0, merged in cc102704b1bf). ASTColumnsApplyTransformer::formatImpl now emits the prefix through quoteString and the applied function name through backQuoteIfNeed, and SELECT * APPLY (toString, 'x''y') round-trips instead of tripping Inconsistent AST formatting. appendColumnName deliberately stays raw, since its output is a column name that is never parsed back.
This branch is behind that commit (its merge base is master of 2026-09-13 15:23 UTC), but the two changes do not interact textually — this PR touches no file under src/Parsers/ — and the merge is clean. 04401_columns_transformer_alias_on_asterisk prints no formatted AST, so the printer change cannot drift its reference.
|
@groeneai @alexey-milovidov — this PR looks backward incompatible but is categorized as Why: Suggested category: |
|
I measured the three claims before answering, against official builds
Two corrections to the framing:
The conclusion still stands: the entry is written in fix voice and does not warn an upgrader that output column names change. Its "consistently with the old analyzer" clause also no longer tells a reader anything observable, since @alexey-milovidov you merged this, and the category is yours to settle rather than mine or a bot's: do you want
|
|
@groeneai is it true? Prepare detailed answer. |
|
@fm4v Mostly true, but the materialized view sentence needs correcting: an MV that already exists is not rejected after the upgrade. It silently writes defaults. I checked each sentence against official
Existing views and materialized views. I created them on 26.9.5.2 (26.8.4.10 behaves the same) and then opened the same data directory with master:
Removing the prefix on the old version fixes both, and it changes nothing there because the prefix has no effect. After SELECT database, name, create_table_query FROM system.tables
WHERE engine IN ('View', 'MaterializedView') AND match(create_table_query, 'APPLY \\(')Reverting the rename would not remove the hazard, only move it. An MV created under Suggested entry with these corrections:
Do you want me to put this entry into the PR body under |
The analyzer names a matched column whose bare name also binds to another table expression, an alias or an ARRAY JOIN expression with a qualified projection name (`r.a`), and an unprefixed `APPLY f` wraps that name (`toString(r.a)`). ClickHouse#109223 made the analyzer honor the `APPLY` name prefix, but seeded the prefixed name from the short column name, so `l.a` and `r.a` of a join both became `f_a`. Two different columns under one name then collide wherever the name is the key: `SELECT * FROM (...)` over the query reads the first `f_a` twice (wrong result, issue ClickHouse#122327 and the AST fuzzer "Subquery wrap oracle mismatch" on ClickHouse#121339 and in two other PRs), two different constants under one name fail the block structure check with `Code: 352 AMBIGUOUS_COLUMN_NAME`, and `remote()` over such a query fails with `Code: 44`. Seed the prefixed name from the column's projection name instead: `f_r.a`, the same base `*` and `APPLY f` use, and the same base a chained prefix after an unprefixed transformer already had (`q_toString(r.a)`). Names change only where the unprefixed name is already qualified: joins, a SELECT alias equal to a column name, an ARRAY JOIN clash and `tuple.*` (`f_tup.x`); a plain single-table `*` keeps `f_a`. A `REPLACE` result keeps the replaced column's name, so a `REPLACE (untuple(a) AS a)` expansion resets the accumulator to it (`a.1`, not `r.a.1`). The new test covers JOIN USING/ON, two tables, three joins, qualified and tuple matchers, join_use_nulls, a lambda, chained prefixes, named untuple and COLUMNS, with single-table and REPLACE controls. 04401 now expects `f_x.a` for a column qualified by a clashing SELECT alias, like its unprefixed `toString(x.a)`. Closes ClickHouse#122327 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #109214
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
LOGICAL_ERROR("Can't set alias of ... of QualifiedAsterisk", server abort in debug and sanitizer builds) when a column transformer that assigns a name (APPLYwith a name prefix, orREPLACE) is applied to an expression that expands to an asterisk orCOLUMNSmatcher, for exampleSELECT * APPLY (x -> t.*, 'p_'). Such queries now return a clearBAD_ARGUMENTSerror. Also fixes wrong column names when anAPPLYname prefix and a second matcher appear in oneSELECT, and makes the analyzer honour the name prefix consistently with the old analyzer.Description
Found by the AST fuzzer (
AST fuzzer (amd_debug, targeted), STID1493-3ccb) on the querySELECT DISTINCT * APPLY (x -> compound_value.*, 'f_') FROM test_table__fuzz_23 FINAL PREWHERE ...:report https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109082&sha=62139e418dccb913277c31a483b2547ed4e230e7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Root cause of the abort:
ASTColumnsApplyTransformer::transformandASTColumnsReplaceTransformer::transformcallsetAliason the transformer's result node, but onlyASTWithAliasnodes support aliases. When theAPPLYlambda body (or theREPLACEreplacement) expands to anASTAsterisk/ASTQualifiedAsterisk/ASTColumnsMatcher, the defaultIAST::setAliasthrowsLOGICAL_ERROR. AsetTransformerAliashelper now checks forASTWithAliasfirst and otherwise throwsBAD_ARGUMENTS, mirroring the existing precedent for asterisks with column aliases inCREATE VIEW.That path is the old analyzer. The default analyzer silently dropped the
APPLYname prefix instead, so it also had to learn the old analyzer's naming, and the same bare-matcher case had to be rejected there.Two further naming cases fixed while implementing that:
SELECT * APPLY (x -> x, 'p_'), *reportedp_a p_a, and the same query with the two matchers swapped reporteda p_a. The prefixed name now goes on a private copy. Values were never affected.q_p_a,q_identity(a).1) rather than the original column name.Workflow [PR]
Sync PR [sync-upstream/pr/109223]
Version info
26.10.1.371-master(included in26.10and later)