Skip to content

Fix wrong result for duplicate-named subquery columns wrapped in SELECT * - #107127

Open
groeneai wants to merge 32 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106923-subquery-duplicate-column-collision
Open

groeneai wants to merge 32 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-106923-subquery-duplicate-column-collision

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

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

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

Fixed a 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-matched RIGHT/FULL JOIN row 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`)) returns 0 2 0 instead of 7 2 0, which the unwrapped SELECT 7, * FROM ... returns. A non-matched RIGHT JOIN row shows the same problem:

SELECT * FROM (SELECT 1, * FROM (SELECT 2 AS x, 1) AS a RIGHT JOIN (SELECT 3 AS y) AS b ON y = x);
-- before: 1  0  1  3    after: 1  0  0  3 (same as the unwrapped query)

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 JOIN keys, 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). An APPLY output is an expression, not a starred column: SELECT * APPLY toString, 'r' AS `toString(a)` keeps both columns; a by-name read returns the first. LATERAL and correlated UNION subqueries follow the same rule: 05315_lateral_join_duplicate_projection_names now expects s.* to return both columns, and the test covers a scalar correlated union that failed with UNION_ALL_RESULT_STRUCTURES_MISMATCH.

It also fixes the wrapped FULL OUTER JOIN ... USING shape of #118986. Found by the AST-fuzzer correctness oracle.


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

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT * FROM (SELECT 1, * FROM (SELECT 2 AS x, 1) AS a RIGHT JOIN (SELECT 3 AS y) AS b ON y = x) returns 1 0 1 3 on master and 1 0 0 3 after the fix, deterministically with default settings.
b Root cause explained? Yes. The planner addresses a subquery output column by source_alias + "." + column_name only, with no positional discriminator. Two same-named subquery outputs therefore collapse to one identifier: the outer SELECT * matcher resolves both to a single ColumnNode, CollectTableExpressionData drops the duplicate name, and the second column's value is replaced by the first (the constant), so the non-matched join row keeps the literal instead of being defaulted.
c Fix matches root cause? Yes. It gives a subquery's duplicate-named output columns distinct internal identifiers (the missing discriminator), so the planner addresses each distinctly. It does not widen any check or hide the symptom downstream.
d Test intent preserved / new tests added? New test 04327_subquery_duplicate_column_name_constant_default added, covering the RIGHT/FULL JOIN cases, the no-join minimal case, non-constant duplicates, extra wrapping, harmless SELECT number, number, different-source t1.*/t2.*, by-name binding, and three redefinition cases (issue #14739) to confirm shadowing is preserved.
e Both directions demonstrated? Yes. The new test FAILS on the master baseline (1 0 1 3, 7 2 7) and PASSES with the fix (1 0 0 3, 7 2 0), 20/20 with randomization.
f Fix is general, not a narrow patch? Yes. The fix is at the analyzer source (subquery projection resolution), not at one crash site. A differential sweep of 1833 analyzer/subquery/join/matcher/union/CTE/alias tests (master baseline vs fixed) shows the only behavior change is the intended one. Equal-expression duplicates and explicit-alias redefinition are intentionally left unchanged.

Session id: cron:clickhouse-worker-slot-17:20260610-230711

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 SELECT * overwrites one value with the other. The fix gives such duplicates distinct internal identifiers in the analyzer while preserving the original display names; equal-expression duplicates and explicit-alias redefinition (#14739) are left unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d3f977]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 5/6) ERROR
Performance Comparison (arm_release, master_head, 6/6) ERROR

AI Review

Summary

PR #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 JOIN ... USING. No new actionable findings remain.

Missing context / blind spots
  • ⚠️ CI for head 5d3f97792fcb0aa81f9805affe3641a5eb8d3ef0 is still running. Local focused probes used the preceding commit's CI binary (f375458c71b181832721c966cfed11bcc62e47d2), so they do not validate the latest matcher fix. A completed current-head CI run would close this runtime validation gap.
Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit f33230e, addressing the three review comments)

# Question Answer
a Deterministic repro? Yes. Each gap reproduces on demand: CR1 SELECT * FROM (SELECT 7, * FROM (SELECT 2 AS x, materialize(0) AS \7`)) AS s(a, x, b)gave header7,x,7; CR2 SELECT * FROM (SELECT materialize(1), materialize(2) AS `1`)gave1,1; CR3 SELECT * FROM ((SELECT 7, * FROM (SELECT materialize(0) AS `7`)) UNION ALL (SELECT 9, * FROM (SELECT materialize(1) AS `9`)))gave7,7 / 9,9`.
b Root cause explained? Yes. CR1: display-name sidecar was recorded before resolveProjectionColumns applied the AS s(...) override, so it held stale names. CR2: the shadowing carveout fired for any later explicit alias, not only when the earlier column came from *. CR3: disambiguation was gated on QueryNode::isSubquery(), but union-branch query nodes are built with is_subquery=false, and a union exposes first-branch names, so an outer matcher collapsed the duplicates through the name-keyed column map.
c Fix matches root cause? Yes. CR1: skip disambiguation when an override alias list is pending (it already makes names unique). CR2: track a projection_from_matcher flag per output column and gate the carveout on the earlier occurrence being matcher-produced. CR3: disambiguate at the union level by renaming the first branch's duplicate columns + a UnionNode display-name sidecar, restored by the outer matcher. No symptom-masking.
d Test intent preserved / new tests added? Yes. The existing 04327 cases are unchanged and still pass. Added 8 regression cases covering all three gaps (alias-list x2, distinct/alias-first x2, union/double-wrap/equal-expr/nested-union x4), plus the existing #14739 shadowing and equal-expr cases continue to pass.
e Both directions demonstrated? Yes. Built debug locally; before the fix the three queries gave wrong output above, after the fix: CR1 -> a,x,b / 7,2,0; CR2 -> 1,2 (distinct) and 100,1,2 (alias-first); CR3 -> 7,0 / 9,1. Full 04327 test passes 10/10 deterministically.
f Fix is general, not a narrow patch? Yes. The union path mirrors the existing QueryNode disambiguation (same isSubquery gate, same display-name sidecar + restore mechanism) rather than special-casing the reported query. Equal-expression duplicates, nested-union first branches, and top-level (non-subquery) unions are all handled explicitly. Sanity-checked union/matcher/CTE/intersect queries and 02227_union_match_by_name.

Session id: cron:clickhouse-worker-slot-16:20260611-030000

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (round-2 fixes, commit 0850406)

# Question Answer
a Deterministic repro? Yes. R2-#1: SELECT COLUMNS('^7$') FROM (SELECT 7, * FROM (SELECT 2 AS x, materialize(0) AS \7`))returned one column (should be two: 7 and 0). R2-#2:SELECT * FROM (((SELECT 7, * FROM (SELECT materialize(0) AS `7`)) UNION DISTINCT (SELECT 8, 8)) UNION ALL (SELECT 9, 9))returned row7 7(should be7 0). R2-#3: SELECT * FROM ((SELECT number, number FROM numbers(2)) UNION ALL (SELECT 5, 6)) ORDER BY 1returned5 5(should be5 6`). All three fail on demand on the pre-fix binary.
b Root cause explained? R2-#1: display names were restored only after the name-sensitive isMatchingColumn filter ran, so a disambiguated column was matched/addressed under its internal name (7_1) not its display name. R2-#2: union output names come from the first branch recursively; when the first branch was itself a UnionNode, front()->as<QueryNode>() was null and the code bailed out, leaving the original collision. R2-#3: 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; the isEqual shortcut wrongly collapsed them.
c Fix matches root cause? Yes. R2-#1: build the internal->display map before the filter loop and evaluate isMatchingColumn on the display name; the column node keeps the internal name for the planner. R2-#2: descend the chain of first branches to the leaf QueryNode and rename the duplicate there, so it propagates up through every computeProjectionColumns(). R2-#3: drop the isEqual shortcut for unions; always disambiguate duplicate first-branch names.
d Test intent preserved / new tests added? Yes. Extended 04327 with: a COLUMNS('^7$') selection case + a COLUMNS('^7_1$') { serverError EMPTY_LIST_OF_COLUMNS_QUERIED } negative case (R2-#1); a nested-union value form + a DESCRIBE header form + a mixed-mode genuine-UnionNode case (R2-#2); the (number, number) UNION ALL (5, 6) value case (R2-#3). The round-1 reference line for the equal-expr-under-union query was corrected from the buggy 5 5 to 5 6. All round-1 regressions (#106923, #14739 shadowing, alias-list, distinct-dups, equal-expr collapse) preserved.
e Both directions demonstrated? Yes. Each repro from (a) fails on the pre-fix binary and passes on the fixed binary (Build ID 1730274d). Full 04327 passes 20/20 with randomization through clickhouse-test.
f Fix is general, not a narrow patch? Yes. R2-#1 fixes the matcher for all name-sensitive matchers (COLUMNS('...'), COLUMNS(a, b)), not just *. R2-#2 handles arbitrarily deep nested-union first branches via the descend loop, not just one level. R2-#3 covers any duplicate first-branch names under union regardless of expression equality. No new defensive guards mask an upstream bug; the changes target the resolution logic directly.

Session id: cron:clickhouse-worker-slot-6:20260611-045300

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (round 3, commit 149e9b3)

# Question Answer
a Deterministic repro? Yes. R3-#1: WITH t AS MATERIALIZED (SELECT 7, * FROM (SELECT 2 AS x, materialize(0) AS \7`)) SELECT * FROM t UNION ALL SELECT * FROM twithenable_materialized_cte=1->DESCRIBEheader7, x, 7_1(internal name leaked) andCOLUMNS('^7$')matched only one column. R3-#2:SELECT COLUMNS('^7$') FROM ((SELECT 7, * FROM (SELECT materialize(0) AS `7`)) UNION ALL (SELECT 9, * FROM (SELECT materialize(1) AS `9`)))builds the map fromUnionNode::computeProjectionColumns()`, which exercises the dangling keys.
b Root cause explained? R3-#2: the internal_name_to_display_name map stored std::string_view keys taken from the NamesAndTypes that UnionNode::computeProjectionColumns() returns by value (and, for R3-#1, from a materialized-CTE subquery), so the keys dangled once collect_internal_to_display returned. The QueryNode branch was safe only because getProjectionColumns() returns a reference. R3-#1: getMatchedColumnNodesWithNames restored display names for QueryNode/UnionNode table expressions but not for a TableNode. A reused MATERIALIZED CTE is a TableNode whose temporary storage columns are built from the (disambiguated) internal projection names, while the display-name sidecar lives on the resolved CTE subquery node, so the internal name 7_1 leaked into the public header.
c Fix matches root cause? Yes. R3-#2: the map now owns String keys/values (std::unordered_map<String, String>); display_name_of returns const String & into the owned map (or into the loop-scoped internal_name argument), so no view outlives its storage. R3-#1: added a TableNode branch that, for a materialized CTE, recovers the internal->display mapping from the resolved subquery node (QueryNode or UnionNode); the storage column names equal the subquery's internal projection names, so the keys match.
d Test intent preserved / new tests added? Yes. 04327 extended with four materialized-CTE regression queries: a SELECT * union value form, a DESCRIBE header form (asserts 7, x, 7, no 7_1), a COLUMNS('^7$') positive form (matches both 7 columns), and a COLUMNS('^7_1$') negative form (serverError EMPTY_LIST_OF_COLUMNS_QUERIED). No existing assertion was weakened.
e Both directions demonstrated? Yes. R3-#2 (UB) proven under an ASan build: reverting only the map back to std::string_view and rebuilding reproduces AddressSanitizer: heap-use-after-free (READ of 3 bytes inside a freed 144-byte region) on the union COLUMNS('^7$') query; with the owned-String fix the same query is ASan-clean and returns the correct 7 0 / 9 1. R3-#1 fails before the fix (header 7, x, 7_1; COLUMNS('^7$') one column) and passes after (header 7, x, 7; COLUMNS('^7$') -> 7 0; COLUMNS('^7_1$') -> EMPTY_LIST_OF_COLUMNS_QUERIED).
f Fix is general, not a narrow patch? Yes. R3-#2 fixes the lifetime at the source (the map now owns its data) rather than guarding any single call site, covering every branch that feeds it (QueryNode, UnionNode, materialized-CTE). R3-#1 handles the materialized-CTE surface for both QueryNode and UnionNode subqueries (not just the plain-query case). Full 04327 passes single + 20/20 with randomization; all prior regressions preserved (#106923, #14739 shadowing, alias-list, distinct duplicates, equal-expression collapse, union-by-position, nested union, COLUMNS); 02227_union_match_by_name and the single-node materialized_cte tests pass.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (round-4 review, head 1ec34aed)

# 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

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Round-5 fix (commit e38f44a) + arm_tidy build fix.

# Question Answer
a Deterministic repro? Yes. On pre-fix HEAD (1ec34ae), SELECT \7_1` FROM (SELECT 7, * FROM (SELECT materialize(0) AS `7`))returns0(binds the hidden disambiguated column) instead ofUNKNOWN_IDENTIFIER. Reproduces identically for a union subquery and a reused MATERIALIZED CTE (enable_materialized_cte=1`).
b Root cause explained? The disambiguation renames duplicate output columns to internal names (7 -> 7_1) in projection_columns. initializeTableExpressionData builds the table-expression column membership sets and node map from those internal names, and IdentifierResolver::tryResolveIdentifierFromStorage binds directly against them. The display-name sidecar was only consulted on the matcher path (SELECT * / COLUMNS()), so a direct identifier reference to the generated name 7_1 bound to the hidden column, violating the contract that generated names are not user-addressable.
c Fix matches root cause? Yes. The generated internal names are recorded as hidden_column_names in initializeTableExpressionData (via a shared buildSubqueryInternalToDisplayNameMap helper, also used by the matcher) and excluded from the column membership sets, so a direct lookup of 7_1 is not bindable and falls through to UNKNOWN_IDENTIFIER. The original name 7 still binds to the first occurrence; the generated names remain in the column-node map so the planner addresses each duplicate distinctly; typo correction no longer suggests them. Covers the plain subquery, union subquery, and reused materialized-CTE surfaces. The arm_tidy break (display_name_of returning const String& of a by-value parameter) is fixed by returning String by value.
d Test intent preserved / new tests added? Yes. Added 6 direct-identifier regression queries to 04327_subquery_duplicate_column_name_constant_default covering plain/union/materialized-CTE: each asserts SELECT \7`binds the first occurrence andSELECT `7_1`throwsUNKNOWN_IDENTIFIER`. All prior matcher/header/COLUMNS/union/materialized-CTE regressions are unchanged.
e Both directions demonstrated? Yes. Pre-fix: 7_1 binds (0) in all three forms. Post-fix (build cb0f9226): 7_1 -> UNKNOWN_IDENTIFIER in all three; 7 -> first occurrence (7 / 7,9 / 7). Full 04327 passes 50/50 with randomization; matcher path (SELECT * header 7,x,7, COLUMNS('^7$') matches both, COLUMNS('^7_1$') empty, typo hints exclude 7_1) all correct. Non-regression sweep (incl. 02476_analyzer_identifier_hints, 02227_union_match_by_name) green.
f Fix is general, not a narrow patch? Yes. The fix is at the single point where the addressable identifier namespace is built (initializeTableExpressionData + the membership sets), routed through one shared internal->display helper, so it covers every table-expression surface direct identifier resolution sees (subquery, union, materialized CTE) rather than patching one call site. It removes addressability of the generated names rather than guarding the symptom; the planner-facing internal names are untouched.

Session id: cron:clickhouse-worker-slot-7:20260611-082500

Comment thread src/Analyzer/QueryNode.h Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (round-6 fix, commit a26cd52)

# Question Answer
a Deterministic repro? Yes. SELECT m FROM (SELECT number, (number + 7, materialize(0)) IN (SELECT 7, * FROM (SELECT materialize(0) AS 7)) AS m FROM numbers(2)) ORDER BY number SETTINGS rewrite_in_to_join = 1, allow_experimental_correlated_subqueries = 1; failed every time on the pre-fix binary with Code: 47 UNKNOWN_IDENTIFIER __subquery_column_*.
b Root cause explained? The projection_column_display_names sidecar is parallel to projection_columns, but clearProjectionColumns() / resolveProjectionColumns() only mutated projection_columns, leaving a stale sidecar. The IN-to-join rewrite (resolveFunction) resolves the duplicate-name RHS subquery, then clears and re-resolves it under one generated __subquery_column_*. The stale sidecar made buildSubqueryInternalToDisplayNameMap map that generated name back to the old display name (7) and mark it hidden, so the rewritten SELECT __subquery_column_* could not resolve its own column.
c Fix matches root cause? Yes. Reset the sidecar in clearProjectionColumns() and resolveProjectionColumns(); compact it in lock-step with projection_columns in QueryNode/UnionNode::removeUnusedProjectionColumns. The legitimate disambiguation now records a fresh sidecar AFTER resolveProjectionColumns (disambiguateDuplicateProjectionColumnNames returns the names instead of setting them before resolve).
d Test intent preserved / new tests added? Preserved. Added 4 regression queries to 04327 exercising the IN-to-join rewrite over a duplicate-name subquery (IN, NOT IN, and a direct 7_1 reference). All prior regression cases unchanged.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID cb0f9226): repro returns UNKNOWN_IDENTIFIER. Post-fix binary (Build ID 9f79dffa): repro returns correct membership (1, 0 for IN; 0, 1 for NOT IN).
f Fix is general, not a narrow patch? Yes. Fixed in the QueryNode projection methods themselves, so every clear+re-resolve caller is covered, not just the IN-rewrite site (InjectRandomOrderIfNoOrderByPass uses the same pattern). The UnionNode pruning path is kept parallel too. Not a guard at the symptom site.

Verification: full 04327 passes single + 50/50 with randomization. Non-regression sweep (03583_rewrite_in_to_join, 0331*/0341*/0344*/0354*_analyzer_correlated_subqueries*, 02911/03023 remove-unused, 02227_union_match_by_name) all pass; the single failure in the sweep was 03644_object_storage_correlated_subqueries, which needs S3/MinIO (not configured on the local repro server) and is unrelated. clang-tidy-21 clean on the three changed C++ TUs (bugprone-return-const-ref-from-parameter etc.).

Session id: cron:clickhouse-worker-slot-6:20260611-102800

groeneai and others added 5 commits October 9, 2026 03:27
…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]>
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]>
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ❌ 05315_lateral_join_duplicate_projection_names (from master) expected s.* to collapse a LATERAL subquery's duplicate names, while correlated unions were still excluded AGREE, fixed correlated query and union subqueries follow the same rule; 05315 now expects both columns; a scalar correlated union arm covers the union side
2 ⚠️ Equal expressions over two identical table expressions on the two sides of an outer JOIN still collapsed (numbers(1, 1) RIGHT JOIN numbers(1, 1) ON 0) AGREE, fixed the exemption also requires both columns to read the same table expression
3 ⚠️ WITH t(a, a) column list was not checked for duplicates AGREE, fixed by master #114505 this branch carries no copy of the check
4 ⚠️ Parallel-replicas INSERT SELECT forwards the analyzer aliases without dedup DISAGREE not reproduced: both parallel_replicas_local_plan values return 1 2 3, and the forwarded aliases are unique
5 ❌ A later expr AS name shadowing a starred column is lost DISAGREE the shadowing carveout renames nothing, so that query is analysed exactly as on master and returns the same result
6 ❌ A recursive CTE seed with a repeated name throws DISAGREE the same Code: 44 on master; the seed's storage code is outside this diff, and no wrong result is returned
7 ⚠️ 04327 does not pin join_use_nulls DISAGREE the stress check reports only server death and hung queries, and the query that throws under join_use_nulls=1 is the unwrapped control, which this PR does not change

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7f0e76c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 2/4) / Build ClickHouse master-side build break, not from this PR (which changes src/Analyzer only): src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25:11: error: use of undeclared identifier 'FifoQueue', the only error in the shard, in a file this PR does not touch. 19 true-master commits and 79 PRs fail this shard since 2026-10-09 00:35Z #124798 (external, open)
Finish Workflow / Post Hooks new_tests_check.py cascade of the row above: both functional Bugfix validation jobs were DROPPED (Dropped due to previous failure [Build (arm_tidy, 2/4)]), so no per-arch validation could run #124798 (external, open)
Mergeable Check, PR praktika rollups of the rows above (Failed: Workflow Post Hook,Build (arm_tidy, 2/4), Dropped: 101), no independent failure #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

All check runs completed. The other three arm_tidy shards, Fast test and Style check passed. 101 jobs were dropped behind the shard 2/4 failure, so the functional test matrix and Bugfix validation have not run on this head yet.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

This update adds one commit: the #14739 shadowing exception no longer treats * APPLY f outputs as starred columns. The independent review (engine: codex) of that commit on the full PR reported 0 findings; my own review found one nit.

# Sev Finding Verdict Evidence / action
1 💡 The exception checks only for an APPLY transformer, so an identity APPLY (x -> x), whose output is the starred column itself, is treated like any other APPLY Noted, not changed no known use; the alternative (deciding on the resolved node) is unstable under constant folding

Severity: ❌ blocker / ⚠️ major / 💡 nit.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5d3f977

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6, 6/6) job timeout (7200 s), not from this PR: one of the shard's two Check CI Log cluster probes (setup_log_cluster.sh) blocked about 3645 s on the overloaded CI Logs cluster before any perf query ran, so the job was killed mid-run with no verdicts. Same on dozens of PRs and master between 01:40Z and 05:30Z #126217 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126217 (the owner of the rows above)

Session id: cron:our-pr-ci-monitor:20261016-070011

This branch has not been deployed

No deployments
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-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Non-matched RIGHT JOIN row carries the outer SELECT's constant column (not defaulted) when the join is wrapped in a subquery

5 participants