Skip to content

Fix LOGICAL_ERROR when a column transformer sets an alias on an asterisk - #109223

Merged
alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/109214-column-transformer-alias-on-asterisk
Sep 21, 2026
Merged

alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/109214-column-transformer-alias-on-asterisk

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109214

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

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 (APPLY with a name prefix, or REPLACE) is applied to an expression that expands to an asterisk or COLUMNS matcher, for example SELECT * APPLY (x -> t.*, 'p_'). Such queries now return a clear BAD_ARGUMENTS error. Also fixes wrong column names when an APPLY name prefix and a second matcher appear in one SELECT, and makes the analyzer honour the name prefix consistently with the old analyzer.

Description

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted), STID 1493-3ccb) on the query SELECT 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::transform and ASTColumnsReplaceTransformer::transform call setAlias on the transformer's result node, but only ASTWithAlias nodes support aliases. When the APPLY lambda body (or the REPLACE replacement) expands to an ASTAsterisk / ASTQualifiedAsterisk / ASTColumnsMatcher, the default IAST::setAlias throws LOGICAL_ERROR. A setTransformerAlias helper now checks for ASTWithAlias first and otherwise throws BAD_ARGUMENTS, mirroring the existing precedent for asterisks with column aliases in CREATE VIEW.

That path is the old analyzer. The default analyzer silently dropped the APPLY name 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:

  • A name prefix must stay inside its own transformer chain. Matched column nodes are shared (one node per column), so publishing the prefixed name on the matched node leaked it into a later matcher: SELECT * APPLY (x -> x, 'p_'), * reported p_a p_a, and the same query with the two matchers swapped reported a p_a. The prefixed name now goes on a private copy. Values were never affected.
  • A chained prefix accumulates onto the previous transformer's display name (q_p_a, q_identity(a).1) rather than the original column name.

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

Version info

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

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "SELECT * APPLY (x -> compound_value.*, 'f_') FROM (SELECT 1 AS a) SETTINGS enable_analyzer=0" aborts every time (RC 134, SIGABRT).
b Root cause explained? ASTColumnsApplyTransformer::transform (and ASTColumnsReplaceTransformer::transform) call setAlias on the transformer result node. Only ASTWithAlias nodes support aliases; when the APPLY lambda body / REPLACE replacement expands to an ASTAsterisk/ASTQualifiedAsterisk/ASTColumnsMatcher, the default IAST::setAlias throws LOGICAL_ERROR -> server abort in debug/sanitizer builds. Old-analyzer path only.
c Fix matches root cause? Yes. A setTransformerAlias helper checks ASTWithAlias before calling setAlias, throwing a clear BAD_ARGUMENTS otherwise — directly at the throwing site, not a symptom guard.
d Test intent preserved / new tests added? New test 04401_columns_transformer_alias_on_asterisk asserts BAD_ARGUMENTS for all crash variants and keeps 3 positive cases (valid APPLY func/lambda + REPLACE) working.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 0c854c59): test FAILS, "server died", stack pins the abort to ASTColumnsApplyTransformer::transform L120 (setAlias). Post-fix binary (314fd246): 30/30 then 10/10 pass with randomization.
f Fix is general across code paths? Yes. All three setAlias call sites in this file (one in APPLY, two in REPLACE) route through the guard. Verified REPLACE (compound_value.* AS a) also crashed before and is fixed now. EXCEPT does not call setAlias.
g Fix generalizes across inputs? Yes. The guard is by node type, so it covers every non-aliasable expansion: plain *, qualified t.*, and COLUMNS(...) matcher — all three verified. Valid aliasable results (functions from APPLY (func), lambda expressions) are unaffected.
h Backward compatible? Yes. No setting, format, or on-disk change. Only converts a server abort / LOGICAL_ERROR into a user-facing BAD_ARGUMENTS for queries that never worked.
i Invariants and contracts preserved? Yes. setTransformerAlias calls node->setAlias(alias) unchanged for ASTWithAlias nodes (identical behavior for all previously-working queries); it only adds a pre-check that rejects nodes whose setAlias contract is "unsupported". No AST-structure or ownership invariant is touched.

Session id: cron:clickhouse-worker-slot-3:20260702-194800

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @evillique @george-larionov — could you review this? It converts a LOGICAL_ERROR (server abort in debug/sanitizer) into a clean BAD_ARGUMENTS when a column transformer that assigns a name (APPLY with a prefix, or REPLACE) is applied to an expression expanding to an asterisk / qualified asterisk / COLUMNS matcher. The fix guards the three setAlias call sites in ASTColumnsTransformers.cpp with an ASTWithAlias check.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0777b02]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer/legacy mismatches around named column transformers and closes the earlier gaps around bare matchers, untuple, and shared-node naming. One correctness issue remains in the new query-tree-to-AST path: valid APPLY prefixes containing quotes do not round-trip, so I would not approve the change as-is.

Findings

⚠️ Majors

  • [src/Analyzer/ColumnTransformers.cpp:117] Preserving column_name_prefix in toASTImpl now exposes a broken printer path: ASTColumnsApplyTransformer::formatImpl and appendColumnName still emit the prefix without SQL escaping. A valid query like SELECT * APPLY (toString, 'x''y') FROM (SELECT 1 AS a) therefore serializes as invalid SQL (APPLY (toString(), 'x'y')), which breaks dump_ast / distributed-query round-trips and hits Inconsistent AST formatting in assertion builds. Suggested fix: escape the prefix with the normal SQL string-literal printer in both paths before relying on this round-trip.
Tests
  • ⚠️ Add a focused regression that uses a prefix containing ' and exercises the new dump_ast = 1 / query-tree-to-AST round-trip path.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix APPLY prefix escaping in the AST printer path, and add a regression with an embedded quote in the prefix.

LLVM Coverage Report

⚠️ No coverage measurement for commit 0777b02: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
…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]>
@groeneai
groeneai force-pushed the fix/109214-column-transformer-alias-on-asterisk branch from 9213084 to 81bdafb Compare July 3, 2026 00:04
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand) — analyzer follow-up
# Question Answer
a Deterministic repro? Yes. clickhouse-local -q "SELECT * APPLY (toString, 'f_') FROM (SELECT 1 AS a, 2 AS b) FORMAT TSVWithNames SETTINGS enable_analyzer=1" printed toString(a) toString(b) (prefix dropped) before the fix; now prints f_a f_b, matching enable_analyzer=0.
b Root cause explained? buildColumnTransformers (QueryTreeBuilder.cpp) built ApplyColumnTransformerNode from only the lambda/function and never copied the parser's column_name_prefix. The node had no field for it, resolveMatcher used only the lambda/function projection name, and toASTImpl could not reconstruct it. So APPLY (expr, 'prefix') (documented, working under the old analyzer) silently ignored the prefix under the default analyzer.
c Fix matches root cause? Yes. Carry column_name_prefix end to end: parser AST -> ApplyColumnTransformerNode (new field + ctor arg, plumbed through hash/equal/clone) -> resolveMatcher prepends it to the accumulated projection name -> toASTImpl restores it for round-trips.
d Test intent preserved / new tests added? Extended 04401_columns_transformer_alias_on_asterisk with an enable_analyzer=1 section asserting the prefix is applied for APPLY (func, 'f_'), APPLY (lambda, 'f_'), chained APPLY (p_) APPLY (q_), REPLACE, and an EXPLAIN QUERY TREE round-trip. The existing old-analyzer crash guards are unchanged.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 314fd246): the new enable_analyzer=1 assertions FAIL (diff shows toString(a), plus(a, 1), plus(plus(a, 1), 1), EXPLAIN 0). Post-fix binary (12ab4e8c): test passes 30/30 with randomization.
f Fix is general across code paths? Yes. Both APPLY variants (lambda and function) carry the prefix via the single ctor argument; resolveMatcher applies it in the one finalization point shared by both. The old-analyzer setAlias guard from the first commit still covers the asterisk-expansion crash on that path.
g Fix generalizes across inputs? Yes. Verified old-vs-new analyzer parity (name and value) across: single function/lambda prefix, chained uniform prefixes, EXCEPT+prefixed-APPLY, REPLACE+prefixed-APPLY, aggregate APPLY (sum, 's_'), qualified a.*, empty prefix, and multi-row tables. Exotic mixed prefix / no-prefix aggregate chains keep a pre-existing analyzer projection-name difference that exists without any prefix too; values are identical and those cases are not asserted.
h Backward compatible? Yes. No setting, format, or on-disk change. It makes the default analyzer match the documented old-analyzer naming that had been silently dropped; queries that worked keep working (parity verified).
i Invariants and contracts preserved? Yes. The prefix is prepended only when an APPLY transformer with a non-empty prefix executed (execute_apply_transformer && !prefix.empty()); otherwise the existing node_projection_names[0] path is untouched. updateTreeHashImpl / isEqualImpl now include the prefix so equal trees stay equal and differing prefixes hash apart. toASTImpl restores the prefix so QueryTree -> AST round-trips are stable.

Session id: cron:clickhouse-worker-slot-3:20260702-233000

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT 99 AS a, x.* APPLY (toString, 'f_') FROM (SELECT 1 AS a, 2 AS b) AS x (enable_analyzer=1) deterministically gave f_x.a; SELECT * APPLY (x -> x, 'p_') APPLY toString FROM (SELECT 1 AS a) gave toString(a).
b Root cause explained? Yes. (1) The prefix was applied to result_projection_names.back(), seeded from node_to_projection_name which qualifyColumnNodesWithProjectionNames sets to a qualified name (x.a) in a qualifying scope -> f_x.a. (2) An identity lambda leaves the resolved node pointing at the original matched node, already present in node_to_projection_name (so emplace was a no-op) and cached in resolved_expressions (read by resolveExpressionNode before the map) -> chained transformer saw the pre-prefix name.
c Fix matches root cause? Yes. (1) Accumulate the prefixed name from the short column_name in a separate variable. (2) insert_or_assign the map AND refresh the existing resolved_expressions entry for the reused node. No symptom-masking.
d Test intent preserved / new tests added? Yes. Existing cases unchanged. Added enable_analyzer=1 coverage: qualifying-scope short name (f_a not f_x.a), and chained-identity for both function and lambda forms (toString(p_a)).
e Both directions demonstrated? Yes. Built a pre-fix binary (Build ID 18f5722) and a fixed binary (48825ab). Pre-fix: f_x.a / toString(a). Fixed: f_a / toString(p_a).
f Fix is general across code paths? Yes. Both APPLY branches (LAMBDA and FUNCTION) flow through the single shared prefix/emplace block that was fixed. REPLACE is unaffected (no prefix).
g Fix generalizes across inputs? Yes. Verified chain orderings: APPLY toString APPLY (upper, 'p_') -> p_toString(a); APPLY (identity, 'p_') APPLY toString APPLY (upper, 'q_') -> q_toString(p_a); APPLY (x -> x, 'p_') APPLY (x -> x, 'q_') -> q_p_a. Non-prefixed transformers correctly reset the accumulator; standalone column refs (SELECT a, ...) are not contaminated by the map overwrite.
h Backward compatible? Yes. Projection-name-only change on the new analyzer that makes it match the legacy (enable_analyzer=0) semantics that were the intended behavior. No setting default, on-disk, wire, or metadata format change.
i Invariants and contracts preserved? Yes. node_to_projection_name and resolved_expressions stay consistent (both updated to the same value); result_projection_names.size() and the 1-projection-name invariant are unchanged; the overwrite is keyed by the specific reused node pointer, so it does not affect other nodes.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * APPLY (identity, 'p_') APPLY toString FROM (SELECT 1 AS a) and SELECT * APPLY (toString, 'f_') APPLY upper FROM (SELECT 1 AS a) with enable_analyzer=1 deterministically produce toString(p_a) / upper(f_a) on the pre-fix binary; legacy enable_analyzer=0 produces toString(identity(a)) / upper(toString(a)).
b Root cause explained? The earlier analyzer fix stored the prefixed display name into node_to_projection_name (and refreshed resolved_expressions) for every APPLY result, including freshly created function nodes. A later unprefixed APPLY f reads that cached name as its argument, so it formatted f(p_a) instead of f(<previous expr>), diverging from the legacy AST path.
c Fix matches root cause? Yes. Split the display name (keeps the accumulated prefix) from the chaining name (natural resolved name for a fresh node). The overwrite of node_to_projection_name / resolved_expressions is gated on node-pointer reuse, so it no longer rewrites a fresh function node's cached name.
d Test intent preserved / new tests added? Yes. 04401 now asserts the analyzer section matches the legacy section for function-form chains (upper(toString(a)), toString(identity(a))) and preserves the identity-lambda reuse case (toString(p_a)). No assertions weakened.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 48825ab) FAILS 04401 (upper(f_a) / toString(p_a)); fixed binary (8b87c12) PASSES, 30/30 with randomization and 5/5 with --no-random-*. Only the analyzer section changed; the legacy section already produced the correct values.
f Fix is general across code paths? Yes. The single accumulation site in resolveMatcher handles both APPLY forms (lambda and function) and chained transformers uniformly; the reuse gate is computed once per transformer iteration from the input node pointer, covering identity function, identity lambda, and wrapping function/lambda alike. No sibling code path carries this logic.
g Fix generalizes across inputs? Yes. Verified across chain shapes: prefixed-then-unprefixed (upper(toString(a))), unprefixed-then-prefixed (q_toString(a)), prefixed-prefixed (q_p_a, g_f_a), triple chains (q_toString(identity(a))), identity function vs identity lambda, and qualifying scope (short name f_a, not f_x.a). REPLACE and plain columns unaffected.
h Backward compatible? N/A. No setting default, on-disk/wire format, or validation change. This corrects analyzer projection-name output to match the legacy path for a feature added earlier in this same PR (never shipped).
i Invariants and contracts preserved? Yes. The invariant is legacy/analyzer parity of projection names, which is now restored for every chain shape. node_to_projection_name and resolved_expressions continue to map a node pointer to its correct display name; the fresh-node branch uses emplace (a fresh pointer is never already present), the reuse branch uses insert_or_assign to update the existing entry.

Session id: cron:clickhouse-worker-slot-1:20260703-031100

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * APPLY (x -> *, 'f_') FROM (SELECT 1 AS a) SETTINGS enable_analyzer=1 returned f_a (wrongly accepted); the multi-column form returned UNSUPPORTED_METHOD; REPLACE (COLUMNS('a') AS a) returned a. All should be BAD_ARGUMENTS.
b Root cause explained? In resolveMatcher, a named transformer whose expression is a bare matcher/asterisk is resolved into a ListNode; the block only rejected size != 1 and flattened node_list_nodes[0]. On a one-column input it renamed the single reused column (f_a); on multi-column it hit the generic UNSUPPORTED_METHOD. Neither mirrors the legacy path, which rejects with BAD_ARGUMENTS when setTransformerAlias runs on a non-aliasable asterisk node.
c Fix matches root cause? Yes. Reject up front, before the matcher is expanded: for a prefixed APPLY when the lambda body is a MatcherNode, and for REPLACE when the replacement expression is a MatcherNode, throw BAD_ARGUMENTS. This is the analyzer-side equivalent of the legacy setTransformerAlias guard.
d Test intent preserved / new tests added? Yes. 04401 gains enable_analyzer=1 negative coverage for every case (one-column and multi-column APPLY/REPLACE over *, t.*, COLUMNS(...)), plus a positive x -> tuple(*) case in both sections to guard against over-rejection. Prior positive cases unchanged.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID 8b87c12) accepts/misreports; fixed binary (57dcee9) rejects with BAD_ARGUMENTS. Full .sql output matches the reference on the fixed binary and differs on the pre-fix binary.
f Fix is general across code paths? Yes. Both named-transformer sites are covered: the prefixed-APPLY lambda branch and the REPLACE branch. The function-form APPLY expression is never a bare matcher, so it needs no guard.
g Fix generalizes across inputs? Yes. Verified for *, qualified t.*, and COLUMNS('a'); for one-column and multi-column inputs; and for both APPLY-lambda and REPLACE. Over-rejection boundary checked: a matcher nested in a function (x -> tuple(*), x -> [*]) and untuple stay accepted, matching the legacy path.
h Backward compatible? Yes. This tightens the default analyzer to match the long-standing legacy-analyzer BAD_ARGUMENTS behavior for a query shape that either errored differently or silently renamed a column. No setting/format change; no SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. The guard runs before node is mutated, so the downstream size != 1 / single-projection-name invariants are unchanged for all still-valid inputs. The rejection is a plain early throw with no state left behind.

Session id: cron:clickhouse-worker-slot-2:20260703-044900

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 247a715)

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_analyzer=1; SELECT * APPLY (x -> untuple(x), 'f_') FROM (SELECT (1,2) AS a) throws UNSUPPORTED_METHOD ("resolved as list node with size 2. Expected 1") every time; the old analyzer returns f_a.1 f_a.2.
b Root cause explained? untuple resolves to a ListNode of tupleElement calls (one per tuple field). resolveMatcher's named-APPLY path only handles a single result node: the size != 1 branch throws UNSUPPORTED_METHOD. The legacy analyzer instead expands each element and prefixes the short column name (f_a.1, f_a.id), so the new analyzer diverged from the PR's old/new parity invariant.
c Fix matches root cause? Yes. In the size != 1 block, when the result is an untuple expansion (every element is tupleElement(arg, const_name)) and this is the terminal transformer, expand the list into sibling projection columns named <prefix><short_column>.<field> (field taken from the constant second arg, exactly as the legacy path builds it). Not a bounds-widening or tag band-aid.
d Test intent preserved / new tests added? Preserved. 04401 gains enable_analyzer=1 coverage for unnamed/named/multi-column/function-form untuple plus a chained-after-untuple negative (serverError UNSUPPORTED_METHOD). Old-analyzer section unchanged; existing untuple/projection/transformer tests still pass.
e Both directions demonstrated? Yes, at the real test-harness level (not just clickhouse local). Pre-fix binary (Build ID 57dcee9): 04401 FAILS with the cited UNSUPPORTED_METHOD. Fixed binary (Build ID c6d5741): PASSES, 20/20 with randomization.
f Fix is general across code paths? Yes. The single ListNode expansion site in resolveMatcher is where every named APPLY result funnels (both LAMBDA and FUNCTION forms), so both APPLY (x -> untuple(x), 'f_') and APPLY (untuple, 'f_') are covered. No sibling site duplicates this logic.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified parity for unnamed tuples (f_a.1), named tuples (f_a.id), multi-column matchers (f_a.1 f_a.2 f_b.1 f_b.2), 3-field and mismatched-arity tuples, and function-form untuple. Non-tuple input still errors identically in both analyzers (untuple argument must have compound type, from resolveFunction, unchanged).
h Backward compatible? Yes. No setting default, on-disk/wire format, or replication metadata changed. The change only makes the new analyzer accept a query the old analyzer already accepted, converging behavior (no SettingsChangesHistory.cpp entry needed).
i Invariants and contracts preserved? Yes. The matcher output list / result_projection_names count invariant is upheld: k tupleElement nodes are pushed as k sibling nodes with k names (k-1 in the loop + the last via the existing loop tail), so resolveExpressionNodeList sees matching node/name counts. The expansion fires only when untuple is the terminal transformer, so a chained transformer still hits the unchanged size != 1 throw, matching the old analyzer's rejection of chained untuple.

Session id: cron:clickhouse-worker-slot-2:20260703-063600

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET enable_analyzer=1; SELECT * APPLY identity APPLY (untuple, 'q_') FROM (SELECT (1, 2) AS a) produced q_a.1 q_a.2 (Build ID c6d5741); should be q_identity(a).1 q_identity(a).2 per the legacy path.
b Root cause explained? The untuple special-case in resolveMatcher built each element name as apply_column_name_prefix + column_name + '.' + field, using the original short column name. It ignored apply_prefixed_projection_name, the display-name accumulator prior transformers update, so a chained untuple hardcoded q_a.N instead of following the node feeding untuple.
c Fix matches root cause? Yes. Base each element on apply_prefixed_projection_name (the accumulated display name) instead of the original short column_name. Untuple is the terminal transformer, so the accumulator holds exactly the pre-untuple display name.
d Test intent preserved / new tests added? Yes. 04401 gains a chained-untuple regression under both enable_analyzer=0 and =1 (q_identity(a).N, q_p_a.N), both sections asserting identical output (parity). Prior cases unchanged.
e Both directions demonstrated? Yes, Build-ID-verified. Pre-fix (c6d5741): both chains give q_a.N. Post-fix (23357d2): q_identity(a).N / q_p_a.N, matching enable_analyzer=0. Test FAILs before / PASSes after (20/20 runs, deterministic + randomized).
f Fix is general across code paths? Yes. This is the single site that names untuple-expanded elements. The direct-untuple case (accumulator = short column name) is unchanged; only the chained case is corrected. No sibling path builds these names.
g Fix generalizes across inputs? Yes. Verified parity for longer/nested chains (q_r_p_a.N, q_identity(identity(a)).N), function-form and prefix-form chains, named-field tuples (q_p_a.id/q_p_a.v), 3-field tuples, and multi-column inputs (q_p_a.N q_p_b.N). Direct untuple stays f_a.N.
h Backward compatible? N/A behavior-wise (both prior behaviors were buggy/inconsistent). This makes enable_analyzer=1 match the long-standing enable_analyzer=0 naming; no setting default, on-disk, or wire format changes.
i Invariants and contracts preserved? Yes. node/name count invariant into resolveExpressionNodeList is unchanged (only the name string changes). The untuple branch still requires is_last_transformer; node_to_projection_name per-element entries still use the same per-element name. The old/new analyzer parity invariant this PR upholds is restored for chained untuple.

Session id: cron:clickhouse-worker-slot-0:20260703-090000

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * REPLACE (untuple(a) AS a) FROM (SELECT (1, 2) AS a) SETTINGS enable_analyzer=1 throws UNSUPPORTED_METHOD ("resolved as list node with size 2") on the pre-fix binary, every run.
b Root cause explained? The untuple list-expansion branch in QueryAnalyzer::resolveMatcher was gated on execute_apply_transformer && !prefix.empty(). A named REPLACE sets execute_replace_transformer instead, so it skipped the expansion and hit the size != 1 throw, while the legacy path (ASTColumnsReplaceTransformer::transform + ActionsVisitor::doUntuple) expands to a.1, a.2.
c Fix matches root cause? Yes. The guard now also fires for execute_replace_transformer; no separate code path.
d Test intent preserved / new tests added? Yes. Added enable_analyzer=0/=1 REPLACE-untuple cases to 04401 (anon fields, named fields, other-columns-preserved, target-vs-source base). No existing assertion weakened.
e Both directions demonstrated? Yes. Pre-fix (Build ID 23357d2) 04401 FAILS; fixed (1f0b2f5) PASSES 20/20 randomized + 5/5 deterministic.
f Fix is general across code paths? Yes. The APPLY and REPLACE untuple cases now share the single expansion branch. The sibling bare-matcher rejection (both APPLY and REPLACE) is unchanged and still fires before expansion.
g Fix generalizes across inputs? Yes. Verified anonymous 2/3-field tuples (a.1 a.2 a.3), explicitly named fields (a.id a.v), multi-column input (other cols preserved), and target-vs-source naming (REPLACE (untuple(b) AS a) -> a.1 a.2, uses the target a not the source b). A transformer chained after untuple stays rejected in both analyzers.
h Backward compatible? Yes. No setting, format, or metadata change. This only makes enable_analyzer=1 accept a query the old analyzer already accepts (old/new parity), producing identical output.
i Invariants and contracts preserved? Yes. The node/name count invariant for resolveExpressionNodeList is preserved (k-1 nodes pushed in the loop, last via the loop tail, k names in result_projection_names), same as the existing APPLY-untuple expansion. apply_prefixed_projection_name (empty prefix for REPLACE) yields the target column name as the element base.

Session id: cron:clickhouse-worker-slot-4:20260703-100700

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
… 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).
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

The only real failure at the previous head (0752f03b) was Fast test / 02122_join_group_by_timeout. Finish Workflow was the aggregator downstream of it, and the rest of the matrix was dropped behind that red.

That test asserted query_duration 1 and printed query_duration 0: a max_execution_time 1 query was cancelled before 1000 ms had elapsed. It is not reachable from this PR (analyzer columns-transformer code plus its own test, which passed at that head in 350 ms), and #114559 fixes it on master. I merged master to pick that up.

I also pinned SET enable_analyzer = 1 in the test. When the old-analyzer arm was dropped in August the file was left setting the mode nowhere, so Stateless tests (amd_llvm_coverage, old analyzer, ...) would have run its analyzer-specific naming cases through the legacy expansion, which substitutes the lambda argument only in children of the lambda body. Measured on master 261c959b:

SELECT * APPLY (x -> x, 'p_') FROM (SELECT 1 AS a)
enable_analyzer=0: Code: 47. Missing columns: 'x' while processing 'SELECT x AS p_a FROM (SELECT 1 AS a)'
enable_analyzer=1: a / 1

Those jobs never ran at the previous head, so this had not surfaced yet. The INSERT arm still covers the original abort with the mode pinned, because an INSERT column list expands the transformers outside the query tree.

CI is running on 378733bc.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0777b02e3 with master 305623c72 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of cb26a48e3; 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 (+29.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.44 MiB 1.45 MiB +18.87 KiB (+1.28%)

716 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

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

Job report

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 378733b

CI is fully finished and green on this head: 174/174 checks completed, 156 pass, 18 skipped, 0 failures. Config Workflow, Fast test, Style check, Mergeable Check and Finish Workflow all pass, and CIDB records no failing test row for this PR. There is nothing to own, so the ledger table is empty.

For continuity with the previous ledger: the 02122_join_group_by_timeout red at 0752f03b is owned by #114559, which this branch now contains, and this head additionally pins SET enable_analyzer = 1 in 04401_columns_transformer_alias_on_asterisk.sql. The PR is MERGEABLE / CLEAN.

Session id: cron:our-pr-ci-monitor:20260907-000027

@alexey-milovidov alexey-milovidov self-assigned this Sep 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, resolve conflicts.

groeneai and others added 2 commits September 13, 2026 16:08
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved and pushed as 4a46126; GitHub reports the PR MERGEABLE again.

Only src/Analyzer/Resolve/QueryAnalyzer.cpp conflicted, at two points where master and this branch each added lines: the checkMaterializedCTESubqueryIsNotCorrelated helper (#108883) and the node_to_projection_name seed in the APPLY lambda branch (#118825). I kept both. The seed publishes the matched column's pre-transformer name, which is what a later bare matcher reads, so it does not compete with the prefixed name this branch publishes on a private clone further down. The branch delta came through the merge unchanged: the 174 changed lines of that file are set-identical before and after the resolution.

Validating the merge also surfaced a naming bug this branch had introduced, which I fixed in the same push. SELECT * APPLY (x -> (x AS z)), * FROM (SELECT 1 AS a) printed z z, renaming the second untransformed * as well, and swapping the two matchers printed a z; master prints z a. An identity lambda resolves back to the very node the matcher handed it, and that node is shared with every other expression in the query, so an alias inside the lambda body leaked onto it. The private-copy condition now triggers when the name changes rather than only when an APPLY prefix is set, and 04401 covers both projection orders plus prefix together with alias.

Verified on a debug build of the merged tree: 04401 green on 3 runs, and 05142_apply_lambda_join_using_projection_name, 01470_columns_transformers, 01470_columns_transformers2, 02339_analyzer_matcher_basic, 03631_select_replace_comprehensive all green.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
groeneai and others added 2 commits September 13, 2026 18:10
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 21, 2026
Merged via the queue into ClickHouse:master with commit 8b017d7 Sep 21, 2026
177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — this PR looks backward incompatible but is categorized as Bug Fix (user-visible misbehavior in an official stable release).

Why: QueryAnalyzer.cpp:3095 makes the APPLY name prefix the result projection name, changing SQL-visible output column names for existing queries under the default analyzer (26.7: toString(a); this build: p_a). The consequence is not cosmetic: a materialized view whose target table carries the old name is rejected with THERE_IS_NO_COLUMN, and REPLACE (COLUMNS('b') AS a) went from returning a correct row to BAD_ARGUMENTS. Both verified against a 26.7.1.1 binary.

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I measured the three claims before answering, against official builds 26.7.8.15 and 26.8.4.10 and master 26.10.1.383, which contains this PR (merged into 26.10.1.371). All three reproduce, default settings, clickhouse local:

Query 26.7.8.15 and 26.8.4.10 master 26.10.1.383
SELECT * APPLY (toString, 'p_') FROM (SELECT 1 AS a) column toString(a) column p_a
SELECT * APPLY (x -> x, 'p_') FROM (SELECT 1 AS a) column a column p_a
MV TO dst AS SELECT * APPLY (toString, 'p_') FROM src, with dst column named toString(a) INSERT writes 1 row Code: 8 THERE_IS_NO_COLUMN
SELECT * REPLACE (COLUMNS('b') AS a) FROM (SELECT 1 AS a, 2 AS b) names a b, values 2 2 Code: 36 BAD_ARGUMENTS
SELECT * APPLY (x -> t.*, 'p_') FROM (SELECT 1 AS a) AS t column a, prefix ignored Code: 36 BAD_ARGUMENTS

Two corrections to the framing:

  1. The rename is confined to the two-argument APPLY (<func or lambda>, '<prefix>') form, which the docs do not describe (apply_modifier.mdx and select/index.mdx document APPLY(func) only). Every documented form is byte-identical on both arms: APPLY(toString), APPLY(x -> x + 1), REPLACE(a + 1 AS a), COLUMNS('a') APPLY(toString) APPLY(length).

  2. REPLACE (COLUMNS('b') AS a) was accepted by accident rather than by design, so I am not filing it as a separate regression. On 26.7.8.15, COLUMNS('a|b') and * AS a already failed with Code: 1 UNSUPPORTED_METHOD ("resolved as list node with size 2"), COLUMNS('zzz') with size 0, and that exact query already threw Code: 49 LOGICAL_ERROR through the AST path (EXPLAIN AST optimize = 1, default settings). A bare matcher is also not an expression alias, which is what REPLACE documents. The single-column match was the one shape that slipped through the "expected exactly 1" branch.

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 enable_analyzer = 0 is rejected from 26.9 on. The nearest precedents both went under Backward Incompatible Change: #96194 (new validation rejecting previously working input) and #82838 ("This change is potentially backward incompatible", on a formatter fix).

@alexey-milovidov you merged this, and the category is yours to settle rather than mine or a bot's: do you want Backward Incompatible Change? If yes, I will edit the body to the entry below and leave the label to you, since I do not run label commands. If you would rather keep Bug Fix, I will leave the body as it is.

Under the mandatory analyzer, SELECT * APPLY (<func>, '<prefix>') now names the result column <prefix> plus the short column name (p_a) instead of ignoring the prefix (toString(a)), so a materialized view or target table keyed on the old name has to be updated. REPLACE (<matcher> AS col) and APPLY (x -> <matcher>, '<prefix>') are now rejected with BAD_ARGUMENTS; previously they threw LOGICAL_ERROR or silently dropped the prefix.

@fm4v

fm4v commented Sep 28, 2026

Copy link
Copy Markdown
Member

@groeneai is it true? Prepare detailed answer.
Backward incompatible: the analyzer now honours the APPLY (expr, 'prefix') name prefix, so output column names change from the expression name to <prefix><column> (toString(a) -> p_a). Queries, views and materialized-view target tables that depend on the old names must be updated - a materialized view whose target table was created from the old names is rejected with THERE_IS_NO_COLUMN, and because the prefix uses the unqualified column name, a named APPLY over a JOIN of two table expressions that share a column name now yields duplicate output names (CREATE TABLE ... AS SELECT fails with ILLEGAL_COLUMN). Also: REPLACE (<matcher> AS col) and APPLY (x -> <matcher>, 'prefix') are now rejected with BAD_ARGUMENTS even when the matcher expands to exactly one column, where the analyzer previously returned a result. Fixes the LOGICAL_ERROR ("Can't set alias of ... of QualifiedAsterisk") on the legacy analyzer and INSERT column-list expansion paths.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@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 26.8.4.10 and 26.9.5.2 (before this PR) and master 26.10.1.903 (after it), with default settings, in clickhouse local.

Claim Verdict Measured
Names change toString(a) -> p_a True Only the two-argument APPLY (<func or lambda>, '<prefix>') form, over *, t.* and COLUMNS(...). APPLY (toString) still gives toString(a). The docs describe only the one-argument form.
An MV over a target with the old names is rejected with THERE_IS_NO_COLUMN Partly Only when the MV is created on 26.10: CREATE MATERIALIZED VIEW ... TO dst fails with Code: 8. An MV that already exists is not rejected (see below).
A named APPLY over a JOIN sharing a column name gives duplicate names, and CTAS fails with ILLEGAL_COLUMN True SELECT * APPLY (toString, 'p_') FROM t1 JOIN t2 ON t1.a = t2.a: toString(a), toString(t2.a) -> p_a, p_a. CREATE TABLE ... AS SELECT and CREATE VIEW fail with Code: 44 ("Cannot add column p_a: column with this name already exists"). The SELECT itself still runs. USING (k) with a shared non-key column behaves the same way.
REPLACE (<matcher> AS col) and APPLY (x -> <matcher>, 'prefix') are now BAD_ARGUMENTS even for one column True REPLACE (COLUMNS('b') AS a), REPLACE (t.* AS a), APPLY (x -> t.*, 'p_') and APPLY (x -> COLUMNS('a'), 'p_') used to return a row and now fail with Code: 36. With two or more columns they already failed, and only the code changed (Code: 1 UNSUPPORTED_METHOD -> Code: 36). APPLY (x -> t.*) without a prefix is unchanged.
Fixes the LOGICAL_ERROR on the INSERT column-list path True INSERT INTO t (* APPLY (x -> t.*, 'p_')) VALUES ... and INSERT INTO t (* REPLACE (COLUMNS('b') AS a)) VALUES ...: Code: 49 -> Code: 36.
... and on the legacy analyzer Not in 26.10 26.9 rejects enable_analyzer = 0 and 26.10 ignores it. The old interpreter can still be reached through EXPLAIN AST optimize = 1: Code: 49 -> Code: 36. The quoted message is the 26.7 wording; 26.8 and 26.9 print Can't set alias 'p_a' of t.*.

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:

  • MV, with TO dst or with an inner table, defined as SELECT * APPLY (toString, 'p_') FROM src: INSERT INTO src VALUES (2) succeeds, but the MV writes '' instead of '2' into toString(a). MV inserts match target columns by name and fill the missing ones with defaults (InsertDependenciesBuilder.cpp: MatchColumnsMode::Name, then addMissingDefaults). The result is silent data loss, not an error.
  • Plain view: every read fails, SELECT * included, with Code: 47 UNKNOWN_IDENTIFIER ("Unknown expression identifier toString(a)"), because the stored column list no longer matches the query.
  • INSERT INTO ... SELECT maps columns by position and is not affected.

Removing the prefix on the old version fixes both, and it changes nothing there because the prefix has no effect. After ALTER TABLE mv MODIFY QUERY SELECT * APPLY (toString) FROM src and CREATE OR REPLACE VIEW on 26.9, the MV writes correct values and the view reads on master. Candidates can be listed before upgrading. The stored DDL prints the one-argument form as APPLY toString, so this query matches only the two-argument form, and it also shows the stored column names:

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 enable_analyzer = 0 stores the prefixed name (p_a). I created one on 26.8 with a session-level enable_analyzer = 0: on 26.9 it writes '', and on master it writes the value.

Suggested entry with these corrections:

The analyzer now honours the name prefix of the two-argument APPLY (<func>, '<prefix>') form, so output column names change from the expression name to <prefix><column> (toString(a) -> p_a). Queries that depend on the old names must be updated. A view created with such a query before the upgrade fails on read, and a materialized view keeps accepting inserts but writes default values into target columns that carry the old names. Before upgrading, remove the prefix from these queries; with the analyzer it has no effect in older versions. Because the prefix uses the unqualified column name, a named APPLY over a JOIN of two table expressions that share a column name now yields duplicate output names (CREATE TABLE ... AS SELECT fails with ILLEGAL_COLUMN). REPLACE (<matcher> AS col) and APPLY (x -> <matcher>, '<prefix>') are now rejected with BAD_ARGUMENTS, including when the matcher expands to exactly one column, which previously returned a result. Also fixes a LOGICAL_ERROR ("Can't set alias ...") in EXPLAIN AST optimize = 1 and in INSERT column-list expansion.

Do you want me to put this entry into the PR body under Backward Incompatible Change? The changelog script reads the body, not the label. The pr-bugfix label would need your hand.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 30, 2026
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]>
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-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

Logical error: Can't set alias of A of B (STID: 1493-3ccb)

6 participants