Repository navigation
Conversation
…CT * A subquery whose projection has two output columns with the same name but backed by different expressions (for example the outer SELECT 1 literal colliding with a starred inner column also named 1, exposed via *) corrupts values when the subquery is wrapped in an outer SELECT *. The planner addresses a subquery's output column purely by source_alias + "." + column_name, with no positional discriminator. So the two same-named outputs collapse to one column identifier: the outer matcher resolves both to a single ColumnNode, only one identifier is registered for that name, and the second column's value is replaced by the first (often a constant). The reported case is a non-matched RIGHT JOIN row whose constant left column kept its literal value instead of being defaulted. Fix: when a subquery has duplicate projection column names backed by non-equal expressions, give the later occurrences unique internal names so the planner assigns each a distinct identifier, while keeping the original user-visible display names (the correct output legitimately has duplicate display names). Two cases are intentionally left untouched: equal expressions with the same name (SELECT number, number), which collapse harmlessly, and a later explicit alias that redefines a same-named starred column (SELECT *, expr AS c), which is intentional shadowing. Closes: ClickHouse#106923 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-17:20260610-230711 |
|
cc @qoega (reported) @KochetovNicolai @novikd — could you review? A subquery with two output columns of the same name backed by different expressions collapses to one column identifier in the planner (no positional discriminator), so wrapping it in an outer |
|
Workflow [PR], commit [5d3f977] Summary: ❌
AI ReviewSummaryPR #107127 preserves distinct values in duplicate-named subquery columns by separating internal identifiers from display names. The previous findings are addressed in the current code, including qualified matcher expansion over Missing context / blind spots
Final Verdict✅ Approve. |
…duplicate-name disambiguation Three gaps in the duplicate-named subquery column fix (PR ClickHouse#107127): 1. A pending column alias list (... AS s(a, b, c)) is applied by resolveProjectionColumns after disambiguation recorded display names, so the recorded names were the stale pre-override ones. Such a list already makes every name unique, so skip disambiguation when it is pending. 2. The shadowing carveout skipped any later explicit alias, even when the earlier same-named column was not produced by a matcher. It now applies only when the earlier occurrence came from a * expansion (ClickHouse#14739), so SELECT 1, 2 AS `1` is disambiguated while SELECT *, x AS c stays shadowed. A projection_from_matcher flag is tracked during projection resolution. 3. A union used as a subquery exposes its names from the first branch, so an outer SELECT * collapsed duplicate-named union columns. The first branch's duplicate columns are renamed to unique internal names and the originals kept as display names on the UnionNode, restored by the outer matcher (mirrors the QueryNode path). Top-level unions are untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit f33230e, addressing the three review comments)
Session id: cron:clickhouse-worker-slot-16:20260611-030000 |
Three follow-up correctness gaps in the duplicate-named subquery column
disambiguation:
1. COLUMNS()/matcher vs internal names. The display names were restored only
after the name-sensitive matcher filter ran, so a column renamed to a unique
internal name (e.g. `7_1`) was matched and addressed under that internal name
instead of its display name. Now the internal->display map is built before the
filter loop and `isMatchingColumn` is evaluated on the display name, while the
column node keeps its internal name for planner resolution. So
`COLUMNS('^7$')` selects both `7` columns and `7_1` is not user-addressable.
2. Nested union first branch. A union's output names come from its first branch
recursively; when that first branch is itself a union, the previous code bailed
out (`front()->as<QueryNode>()` was null), leaving the original collision and
wrong values. Now descend the chain of first branches to the leaf QueryNode and
rename the duplicate there; the rename propagates up through every enclosing
computeProjectionColumns().
3. Equal first-branch expressions under UNION. A union names columns from the
first branch but maps values by position across all branches, so equal
first-branch expressions do not make duplicate positions interchangeable.
Dropped the isEqual shortcut for unions: `(SELECT number, number) UNION ALL
(SELECT 5, 6)` now returns 5, 6 instead of 5, 5.
Extended 04327 with COLUMNS()-matcher, nested-union value + DESCRIBE header,
mixed-mode genuine-UnionNode, and equal-expr-under-union regression cases.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (round-2 fixes, commit 0850406)
Session id: cron:clickhouse-worker-slot-6:20260611-045300 |
Two follow-up issues from the round-2 fix: Own String keys/values in the internal->display name map. The union and materialized-CTE branches feed the map from temporaries (UnionNode::computeProjectionColumns() returns NamesAndTypes by value), so the previous std::string_view keys dangled once the collecting lambda returned, a heap-use-after-free under ASan in the union-subquery COLUMNS() path. Restore display names for materialized-CTE table expressions. A reused MATERIALIZED CTE is a TableNode whose temporary storage columns carry the internally disambiguated names; the display-name sidecar lives on the resolved CTE subquery node. Recover the mapping from it so the user-visible header keeps the original duplicate names and a name-sensitive matcher addresses them, with the generated internal name staying unaddressable. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (round 3, commit 149e9b3)
Session id: cron:clickhouse-worker-slot-1:20260611-061800 |
The round-2 chain-descent in disambiguateDuplicateUnionProjectionColumnNames
descends through a first branch that is itself a UnionNode to the leaf
QueryNode, so the mixed-mode genuine nested-union case (e.g.
((A UNION DISTINCT B) UNION ALL C) with A producing duplicate names) already
keeps both display names and does not leak the internal 7_1 name. The existing
mixed-mode test only checked values; add DESCRIBE + COLUMNS('^7$') /
COLUMNS('^7_1$') header forms to lock in the non-regression.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (round-4 review, head
|
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | The reported symptom does NOT reproduce on head. The bot R4-#1 comment is anchored to commit f33230e9 (round 1), where the union disambiguation did if (!first_branch) return; for a UnionNode first branch. On head the round-2 chain-descent (0850406c) walks to the leaf QueryNode, so DESCRIBE/COLUMNS over the genuine mixed-mode nested union return both 7 display names deterministically (verified every run). |
| b | Root cause explained? | At f33230e9, a first branch that was itself a UnionNode was skipped (bare return), so the outer union never set a display sidecar and the inner 7_1 could surface. Round-2 replaced that with a while (branch->as<UnionNode>()) branch = branch_queries.front(); descent to the leaf; the outer union snapshots that leaf (still named 7,7 at that point), finds the duplicate, renames it to 7_1, sets the sidecar, and the rename propagates up through computeProjectionColumns(). |
| c | Fix matches root cause? | N/A code-wise: behavior is already correct on head, so no code change is made (no-speculative-change rule). The PR adds only the header-checking regression the bot correctly identified as missing. |
| d | Test intent preserved / new tests added? | Added 4 queries for the genuine nested-UnionNode mixed-mode first branch: a value form, a DESCRIBE header form, COLUMNS('^7$') (matches both), and COLUMNS('^7_1$') ({ serverError EMPTY_LIST_OF_COLUMNS_QUERIED }, internal name unaddressable). The prior mixed-mode test checked values only; this locks in the header non-regression. |
| e | Both directions demonstrated? | Pre-fix direction shown against the round-1 code the bot reviewed: at f33230e9 the UnionNode first branch hit if (!first_branch) return; and was not disambiguated. Post-fix (0850406c onward, incl. head): DESCRIBE -> 7,7; COLUMNS('^7$') -> 1 2 / 7 0 / 9 1; COLUMNS('^7_1$') -> EMPTY_LIST_OF_COLUMNS_QUERIED. Full 04327 test passes 30/30 with randomization. |
| f | Fix is general, not a narrow patch? | The round-2 chain-descent already generalizes to arbitrarily deep first-branch union chains (S2/S3/4-level forms verified). All prior regressions preserved (#106923 1 0 0 3, #14739 shadowing, alias-list, distinct-dups, equal-expr collapse, R2-#3 union 5 6, R3 materialized-CTE, COLUMNS) and 02227_union_match_by_name passes. |
Session id: cron:clickhouse-worker-slot-12:20260611-070600
…esolution Round-5 review (clickhouse-gh[bot]) found that the duplicate-name disambiguation fixed only matcher expansion (SELECT *, COLUMNS()). Direct identifier resolution still bound the generated internal name: a query like `SELECT \`7_1\` FROM (SELECT 7, * FROM (SELECT materialize(0) AS \`7\`))` resolved to the hidden second column, violating the contract that generated names such as `7_1` are not user-addressable. tryResolveIdentifierFromStorage binds against the table-expression projection_columns, which carry the disambiguated internal names; the display-name sidecar was only consulted on the matcher path. Record the generated internal names as hidden_column_names in initializeTableExpressionData (via a shared buildSubqueryInternalToDisplayNameMap helper, also used by the matcher) and keep them out of the column membership sets. A direct reference to the original name still binds to the first occurrence; a reference to the generated name is an unknown identifier. The generated names stay in the column-node map so the planner addresses each duplicate distinctly, and typo correction no longer suggests them. Covers the plain subquery, union subquery, and reused materialized-CTE surfaces. Also fix the arm_tidy build break: display_name_of returned const String& of a by-value parameter (bugprone-return-const-ref-from-parameter, fatal under -warnings-as-errors); return String by value. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateRound-5 fix (commit e38f44a) + arm_tidy build fix.
Session id: cron:clickhouse-worker-slot-7:20260611-082500 |
The duplicate-name disambiguation stores the original display names in a projection_column_display_names sidecar parallel to projection_columns. clearProjectionColumns() and resolveProjectionColumns() only touched projection_columns, leaving a stale sidecar behind. The IN-to-join rewrite (resolveFunction) resolves a duplicate-name RHS subquery, then clears and re-resolves it under a single generated __subquery_column_*; the stale sidecar made buildSubqueryInternalToDisplayNameMap map that generated name back to the old display name and mark it hidden, so the rewritten SELECT __subquery_column_* could not resolve its own column (UNKNOWN_IDENTIFIER). Reset the sidecar in clearProjectionColumns() and resolveProjectionColumns(), and compact it in lock-step with projection_columns in QueryNode/UnionNode::removeUnusedProjectionColumns. The legitimate disambiguation now records the fresh sidecar after resolveProjectionColumns (disambiguateDuplicateProjectionColumnNames returns the names instead of setting them before resolve). InjectRandomOrderIfNoOrderByPass uses the same clear+re-resolve pattern and is covered too. Repro (was UNKNOWN_IDENTIFIER): SELECT (number + 7, materialize(0)) IN (SELECT 7, * FROM (SELECT materialize(0) AS `7`)) FROM numbers(2) SETTINGS rewrite_in_to_join = 1, allow_experimental_correlated_subqueries = 1; Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (round-6 fix, commit a26cd52)
Verification: full Session id: cron:clickhouse-worker-slot-6:20260611-102800 |
…ckHouse#114505 The same duplicate-name check for `WITH t(a, a)` and `AS t(a, a)` column alias lists landed on master in ClickHouse#114505 at both `QueryTreeBuilder` sites, so this branch keeps master's version instead of its own helper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-subquery-duplicate-column-collision
Correlated `UNION` subqueries are disambiguated like uncorrelated ones, but no test exercised it. The scalar correlated union here fails with `UNION_ALL_RESULT_STRUCTURES_MISMATCH` when the first branch's repeated name is left as is, and returns one row per outer row with the change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-subquery-duplicate-column-collision # Conflicts: # src/Analyzer/Resolve/IdentifierResolver.cpp # src/Analyzer/Resolve/QueryAnalyzer.cpp
Delete comments that narrate the new code's design; keep the non-obvious invariants (planner column identity, union positional mapping, materialized CTE storage names, matcher/transformer display names) as one or two lines. 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) over four rounds of this update; the last round, on the final head, reported 0 findings.
Severity: ❌ blocker / |
CI finish ledger - 7f0e76cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All check runs completed. The other three Session id: cron:our-pr-ci-monitor:20261009-070003 |
…heck `* APPLY f` lists `f(c)` expressions, so a later `expr AS `f(c)`` is a second column, not a redefinition of a starred one (ClickHouse#14739). It now gets a unique internal name like the explicit `f(c), expr AS `f(c)`` pair, and an outer `SELECT *` keeps both values. Found by the AST fuzzer oracle on ClickHouse#126056. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)This update adds one commit: the
Severity: ❌ blocker / |
With a USING join in scope, `updateMatchedColumnsFromJoinUsing` corrects the
type of each column a qualified matcher (`s.*`, `s.COLUMNS(...)`) expands by
resolving `s.<column name>`. For the generated internal name of a
disambiguated duplicate (`s.q_1`) that lookup is refused because the name is
not user-addressable, so the whole query failed with UNKNOWN_IDENTIFIER:
SELECT s.* FROM (SELECT materialize(7) AS q, * FROM (SELECT materialize(0) AS q, 1 AS k)) AS s
INNER JOIN (SELECT 1 AS k) AS t USING (k)
A generated name cannot be named in USING either, so such a column is never a
USING key: skip the lookup and keep its own type, as for any other non-key
column. The result is now `7 0 1` (master returns `7 7 1`).
Reported by clickhouse-gh[bot] in
ClickHouse#107127 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 5d3f977Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261016-070011 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a wrong result when a subquery has two output columns with the same name backed by different expressions (for example a constant column colliding with a starred column of the same name) and the subquery is wrapped in an outer
SELECT *. Previously one column's value (often a constant) overwrote the other; for a non-matchedRIGHT/FULL JOINrow this kept the constant's literal value instead of the default.Description
Closes #106923. Related #118986.
On 26.9.9.28,
SELECT * FROM (SELECT 7, * FROM (SELECT 2 AS x, materialize(0) AS `7`))returns0 2 0instead of7 2 0, which the unwrappedSELECT 7, * FROM ...returns. A non-matchedRIGHT JOINrow shows the same problem:Root cause: the planner addresses a subquery's output column by
source_alias + "." + column_name, with no positional discriminator, so two same-named columns of one subquery collapse into one column identifier and one value overwrites the other.Fix: when a subquery has duplicate projection names backed by different values, the later occurrences get unique internal names (
q->q_1), so the planner assigns each a distinct identifier. The user-visible display names are preserved. Name-based analyzer decisions (matchers, column qualification,NATURAL JOINkeys, identifier lookup, hints) use the display names; only the column node keeps the internal name. Two cases are unchanged: equal expressions over the same source (SELECT number, number), and a later explicit alias that redefines a same-named starred column (SELECT *, expr AS c, intentional shadowing, #14739). AnAPPLYoutput is an expression, not a starred column:SELECT * APPLY toString, 'r' AS `toString(a)`keeps both columns; a by-name read returns the first.LATERALand correlatedUNIONsubqueries follow the same rule:05315_lateral_join_duplicate_projection_namesnow expectss.*to return both columns, and the test covers a scalar correlated union that failed withUNION_ALL_RESULT_STRUCTURES_MISMATCH.It also fixes the wrapped
FULL OUTER JOIN ... USINGshape of #118986. Found by the AST-fuzzer correctness oracle.Workflow [PR]
Sync PR [sync-upstream/pr/107127]