Repository navigation
Hybrid SQL-standard short-name fallback for subquery columns - #107449
yakov-olkhovskiy wants to merge 20 commits into
Conversation
Add an opt-in compatibility setting,
`analyzer_enable_short_column_names_from_subquery` (default off), that
lets the outer query refer to a subquery / CTE projection column whose
canonical name is an unaliased qualified identifier such as `b.f1`
either by its dotted canonical name (existing ClickHouse behavior) or
by its short name `f1` (SQL-standard / PostgreSQL / MySQL / Oracle /
SQL Server behavior).
The fallback is strictly additive: the canonical projection name keeps
working in every case (`DESCRIBE`, `SELECT *`, result-set headers and
the wire protocol are unchanged), and a short name is registered only
when:
- the rightmost component is unique among sibling projections, and
- it does not collide with any other column's canonical name (an
explicit alias of the same name wins canonical resolution).
Resolves the well-known divergence from SQL-standard column naming
reported in:
- #87022
- #66133
- #94858
- #94558
Implementation lives entirely inside the analyzer: a per-table-expression
short-name index on `AnalysisTableExpressionData` is populated during
`initializeTableExpressionData` and consulted from
`tryBindIdentifierToTableExpression` and `tryResolveIdentifierFromStorage`
after canonical lookup misses. The index is empty unless the setting is
on, so the default-off path is a single `unordered_map::empty()` check.
Closes: #87022
Related: #66133
Related: #94858
Related: #94558
Co-authored-by: Yakov Olkhovskiy <[email protected]>
|
Workflow [PR], commit [7009a75] Summary: ❌
AI ReviewSummaryThis PR adds the opt-in Findings
Final VerdictI would not approve this as-is. The remaining short-name/projection-name interaction still produces ambiguous result headers for explicitly qualified references from sibling subqueries. |
Address AI review feedback on #107449 (#107449 (comment)): `WITH ... AS MATERIALIZED` rewrites the CTE reference into a `TableNode` backed by a `TemporaryTableHolder`, which goes through the table-node branch of `initializeTableExpressionData` rather than the QueryNode / UnionNode branch. The previous commit only populated `short_name_to_column_node` in the latter, so materialized CTEs were silently excluded from the new SQL-standard short-name fallback. Factor the population logic into `populateShortNameIndexForSubquery` and invoke it from both branches: - the QueryNode / UnionNode branch as before, against the eagerly built node map, - the table-node branch when `isMaterializedCTE()` is true, after triggering the lazy column-node-map populator. Regular tables and table functions are intentionally excluded — the setting's contract is 'from subquery', not 'rewrite every storage column'. Extend the stateless test to cover the three materialized-CTE shapes (short name in `WHERE`, outer alias + short name, canonical name still working). Co-authored-by: Yakov Olkhovskiy <[email protected]>
Mirrors the existing default-off assertion for #87022 with one per each of the other open issues this PR closes: - subquery (#66133), - 3-way self-join CTE (#94858), - and the materialized-CTE shape. This makes the regression-test contract symmetric: for every issue the PR claims to close, there's both a default-off assertion that the previously-failing query still fails with UNKNOWN_IDENTIFIER, and a setting-on assertion that it now succeeds. Also drops #94558 from the test header's 'Closes' list (it was already closed by upstream changes) and demotes its label in the existing dotted-projection-in-subquery case to 'related'. Reorganized the test layout: shared table fixture lifted out of the #94858 block so the same fixture serves both the default-off and setting-on assertions for that issue. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review feedback on #107449 (#107449 (comment)): the short-name fallback in `tryResolveIdentifierFromStorage` sat before `tryResolveIdentifierAsNestedPrefix`, so a subquery shaped like SELECT [1] AS `f1.x`, ['a'] AS `f1.y`, 42 AS `b.f1` would change resolution of outer `f1` from the existing Nested-prefix collapse (`Nested(x Array(UInt8), y Array(String))`) to the new short-name target (`b.f1`) when the setting is enabled. This violates the additive contract for the setting — enabling it must never change the resolution target of an identifier that already resolves successfully on master. Verified the regression with a focused reproducer before and after the fix: master / setting=0 → [(1,'a')] (Nested-prefix collapse) PR / setting=1 → 42 (short-name hijack — bug) fix / setting=1 → [(1,'a')] (Nested-prefix wins, additive) Move the short-name lookup to after `tryResolveIdentifierAsNestedPrefix` in the resolution order. The map is empty unless the opt-in setting is on, so the cold-path cost in the default-off case is unchanged. Add a focused regression test in `04339_short_column_names_from_subquery` asserting that with the setting on, outer `f1` against a projection list shaped like `f1.x Array(...), f1.y Array(...), b.f1 ...` still returns the Nested-prefix tuple array rather than `b.f1`'s value. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address the remaining additivity violations identified in the AI review on #107449: 1. Cross-join short-name vs Nested-prefix priority across siblings. Reproducer: `SELECT f1 FROM (SELECT 42 AS `b.f1`) l CROSS JOIN (SELECT [1] AS `f1.x`, ['a'] AS `f1.y`) r` returned `42` (left side's short-name) instead of the master result `[(1,'a')]` (right side's Nested-prefix collapse) under `single_join_prefer_left_table`. Fix: thread a `short_name_fallback_enabled` flag through `IdentifierResolver` and wrap `tryResolveIdentifierFromJoinTree` with two passes — pass 1 disables short-name so any canonical / subcolumn / Nested-prefix match anywhere in the join tree wins; pass 2 retries with short-name enabled only if pass 1 found nothing. The "cannot be resolved" throw inside `tryResolveIdentifierFromStorage` becomes a soft-fail in pass 1 so the retry actually runs; the throw fires normally on pass 2. 2. JOIN USING accepting a short-name-resolved column whose stored `getColumnName" still returned the dotted canonical name, then silently failing to merge left and right keys. Fix: `resolveJoin`'s USING branch installs a SCOPE_EXIT-guarded save/restore of the flag and resolves USING identifiers with short-name disabled. The query now fails with the master-equivalent `UNKNOWN_IDENTIFIER` from the USING handler instead of producing a wrong-shape result. 3. Predicate-level short-name binding propagating into `qualifyColumnNodesWithProjectionNames` and the qualifier-stripping logic in `tryResolveIdentifierFromStorage`, which could in theory over-qualify `SELECT *` headers and shift other projection names even when no query referenced the short name. Fix: drop the `canBindShortName` check from `tryBindIdentifierToTableExpression`. The predicate is for qualification decisions, not resolution; the resolver still consults short-name through `tryResolveIdentifierFromTableExpression` / `tryResolveIdentifierFromStorage`, both gated on `short_name_fallback_enabled`. Default-off is unaffected: the short-name index is empty, so the two-pass collapses to two cheap canonical-only attempts (pass 1 soft-fails, pass 2 throws the same error message users see today). Extend `04339_short_column_names_from_subquery` with focused regression tests for all three findings: cross-join Nested-prefix priority, JOIN USING short-name suppression, and `SELECT *` header stability. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review on PR #107449 (#107449 (comment)): the previous pass-1 soft-fail let an alias-qualified short-name lookup return null silently, which let an unrelated cross-join sibling that exposes a literal column with the same name hijack the resolution. Reproducer: SELECT q.f1 FROM (SELECT 1 AS `b.f1`) AS q CROSS JOIN (SELECT 2 AS `q.f1`) AS r SETTINGS analyzer_enable_short_column_names_from_subquery = 1; On master this query throws because q's alias-prefix branch can't find 'f1', and the throw kills cross-join sibling resolution. With the soft-fail this PR introduced, q quietly returned null, r's literal 'q.f1' column won, and the query returned 2 instead of 1 (the value of q.f1 resolved via short-name fallback to b.f1). Switch the two-pass implementation from "soft-fail when short-name is disabled" to "throw normally, but catch UNKNOWN_IDENTIFIER at the join-tree level when retry is allowed": - Removed the `!short_name_fallback_enabled -> return {}` branch in `tryResolveIdentifierFromStorage` so pass 1 produces the same master-equivalent throw it did before this PR. - `tryResolveIdentifierFromJoinTree` now wraps pass 1 in a try/catch that only intercepts UNKNOWN_IDENTIFIER and only when `retry_with_short_name_fallback` is true (i.e. the resolver entered with the fallback enabled — JOIN USING context, which enters with it disabled, doesn't get the retry). Pass 2 throws the same error normally if no resolution is found. - SCOPE_EXIT-guard the flag restore so any rethrow doesn't leak state. Default-off is byte-identical to master: pass 1 throws or returns null the way it does today, pass 2 (when reached) finds the same empty short-name index and produces the same outcome. Setting-on without a sibling literal column-name conflict is unchanged. Setting-on WITH the bot's reproducer now correctly returns the alias-qualified short-name target (1) instead of the sibling literal (2). Add focused regression tests covering both setting states for the exact reproducer. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review feedback on PR #107449: 1. Blocker: exception safety of `scope.join_using_columns` push/pop. `tryResolveIdentifierFromJoin` pushes a pointer to a stack-local `join_using_column_name_to_column_node` onto `scope.join_using_columns` before recursing into each side, and pops it only on normal return. The two-pass retry introduced earlier in this PR catches `UNKNOWN_IDENTIFIER` from deep inside that recursive call, which would let the pointer stay on `scope.join_using_columns` after the surrounding stack frame is gone — a use-after-free that `tryBindIdentifierToJoinUsingColumn` (called from `tryResolveIdentifierFromStorage`'s qualifier-stripping logic) would dereference during pass 2 or any later resolution. Fix: wrap the push/pop in `SCOPE_EXIT` so the pop runs on every code path, including the thrown-then-caught one. Record whether we pushed in a single boolean so the cleanup condition cannot drift from the push condition under any control flow. 2. Major: setting documentation overstated the implemented contract. The PR intentionally suppresses the short-name fallback during JOIN USING identifier resolution (because a USING list matches keys by `ColumnNode::getColumnName`, which still returns the canonical dotted name for a short-name-resolved column — allowing the fallback there would let USING accept mismatched left/right names and silently fail to merge them). Document that exclusion in both the setting description in `Settings.cpp` and the changelog entry in `SettingsChangesHistory.cpp`, and call it out explicitly in the PR description. Add a focused regression test that pushes the lambda's USING-map onto `scope.join_using_columns` and then throws inside the recursion via an alias-prefix miss with short-name disabled (pass 1). The query exercises the SCOPE_EXIT cleanup path on every CI run; under sanitizers (ASan/MSan) the dangling pointer would trip use-after-free without the fix. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Two minor cleanups requested in PR #107449 review: - The `tryBindIdentifierToTableExpression` predicate body no longer carries the standalone NOTE block explaining why short-name binding is intentionally not consulted there. The reasoning is already captured in the setting description and the header doc comment on `IdentifierResolver::short_name_fallback_enabled`; an in-code NOTE without surrounding code to anchor it just adds noise. - The `analyzer_enable_short_column_names_from_subquery` description no longer says "so the query behaves the same as master" — that phrasing only makes sense from inside a PR comparing to its base. Users reading the setting docs in a release see the setting as-is, with no "master" to compare against. Rephrase to state the behavior directly: `JOIN ... USING (f1)` against a short-name-only side raises `UNKNOWN_IDENTIFIER`. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ical Address AI review on PR #107449: the previous `rfind('.')` on the flattened canonical projection name happily split column names that legitimately contain a dot. For a join projecting `b.`f.1``, the canonical name flattens to `b.f.1` and the old code registered `1` as the fallback — exposing a meaningless short name and not exposing the real column `f.1`. Walk the underlying projection nodes to recover each projection's `ColumnNode::getColumnName` (the actual column name from inside the subquery, before the analyzer joined identifier parts with `.`) and verify it is a strict suffix of the canonical name preceded by `.`. Skip registration otherwise. This means: - `SELECT b.f1 FROM ... AS a JOIN ... AS b ON ...` → canonical `b.f1`, column.name `f1`, register short = `f1` (issue #87022 still works). - `SELECT b.`f.1` FROM ... AS a JOIN ... AS b ON ...` → canonical `b.f.1`, column.name `f.1`, register short = `f.1` (the actual column, not the rfind-induced `1`). - `SELECT 1 AS `b.f1`` (constant explicitly aliased with a dotted string) → not a ColumnNode → skip. The user picked the alias name; PostgreSQL doesn't expose `f1` as a short name for it either. For the materialized-CTE branch the storage snapshot's columns include appended virtual columns (`_part` etc.) after the regular projection columns, so `column_names_and_types.size()` exceeds the inner subquery's `projection_nodes.size()`. Iterate up to the smaller projection-node count and bail cleanly if a future change inverts that ordering. Source the projection nodes via `mat_table_node->getMaterializedCTESubquery()` (with a small helper that walks through nested unions to the first `QueryNode`). Add focused regression tests: - Quoted dotted column name from a join: canonical `b.f.1` keeps working; outer reference `f.1` (the actual column) now resolves; outer reference `1` (what the buggy split would have registered) correctly raises `UNKNOWN_IDENTIFIER`. Update the existing "alias-qualified short-name lookup is not hijacked by sibling literal column" assertion: the user-facing semantic for `SELECT q.f1 FROM (SELECT 1 AS `b.f1`) AS q CROSS JOIN (SELECT 2 AS `q.f1`) AS r` is now master-equivalent on both setting states — the explicit dotted alias `b.f1` does not gain a short-name `f1`, alias-qualified `q.f1` errors with `UNKNOWN_IDENTIFIER` (PostgreSQL behaves identically), and the cross-join sibling can no longer hijack it. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…-names-from-subquery-5b0c # Conflicts: # src/Core/Settings.cpp Co-authored-by: Yakov Olkhovskiy <[email protected]>
…-names-from-subquery-5b0c # Conflicts: # src/Analyzer/Resolve/IdentifierResolver.cpp Co-authored-by: Yakov Olkhovskiy <[email protected]>
Two fixes: 1. AI review on PR #107449: the short-name fallback was registering candidates for any projected `ColumnNode` whose `getColumnName` matched the canonical name's suffix, regardless of whether that canonical name came from an analyzer-synthesized qualifier or from an explicit user alias. After alias removal the two cases look identical at the projection-list level. As a result, queries like SELECT b.f1 AS `x.f1` FROM (SELECT 1 AS f1) AS b would silently expose `f1` (matching `x.f1`'s suffix against the resolved column.name `f1`), which violates the setting's "unaliased" contract. Worse, an explicit alias next to a real unaliased qualified sibling would ambiguity-cancel the legitimate short-name registration: SELECT b.f1 AS `x.f1`, c.f1 -- both register `f1` → killed Fix: in addition to verifying the column.name is a strict suffix of the canonical name preceded by `.`, verify that the qualifier prefix matches the resolved column's source. For an unaliased `b.f1`, the source's alias (or, for a CTE reference, its CTE name, or for an unaliased table its table name) equals the qualifier prefix. For an explicit alias like `b.f1 AS `x.f1``, the qualifier `x` won't match the source's alias `b`, and we skip registration. Added regression tests for both the standalone explicit-alias case and the sibling-ambiguity-cancellation case. 2. Fast test `02995_new_settings_history` regression after the master merge: the baseline TSV in that test was bumped to v26.6.1, and the test asserts that any new setting must appear in a `SettingsChangesHistory.cpp` block with version > 26.6. My setting was in the 26.6 block; move it to the 26.7 block where it now belongs. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…-names-from-subquery-5b0c Co-authored-by: Yakov Olkhovskiy <[email protected]>
…table Address AI review on PR #107449: the TableNode branch of safe_short_name compared only against `getStorageID().getTableName()`, missing two shapes the analyzer actually emits for unaliased qualified projections: 1. Materialized CTE references. `WITH cte AS MATERIALIZED (...)` is rewritten to an unaliased `TableNode` backed by a temporary holder whose `getStorageID().getTableName()` is the auto-generated `_data_<hash>`. The user-visible source name lives on `getMaterializedCTE()->cte_name`. Without that, a query like WITH src AS MATERIALIZED (SELECT 1 AS f1), q AS (SELECT src.f1 FROM src JOIN (SELECT 1 AS f1) r ON src.f1=r.f1) SELECT f1 FROM q; never registered the short name because the qualifier prefix `src` didn't match `_data_<hash>`. 2. Database-qualified table references. When two unaliased tables share the same name across databases, `qualifyColumnNodesWithProjectionNames` emits canonical names like `db1.t.f1`. The previous check only compared against the bare table name `t`, so the `db.t` qualifier prefix never matched. Accept both forms in the `TableNode` branch, plus the `getTemporaryTableName()` form for completeness. Added focused regression tests for both shapes. Co-authored-by: Yakov Olkhovskiy <[email protected]>
AI review on PR #107449 pointed out that the previous db.table regression test read back canonical dotted names directly, so the assertion would still pass even if the new `database_name + "." + table_name" branch in safe_short_name were removed — the test exercised the canonical-lookup path, not the new code (#107449 (comment)). Replace with the bot's suggested focused shape: two unaliased `dbN.t` sources in the inner FROM (which forces the analyzer to keep the canonical projection name in `db.table.column` form), but project only one of them. The outer short-name `f1` is then unambiguous and exercises the `db.table` source-name match directly. Without the new branch this assertion returns `UNKNOWN_IDENTIFIER`; with it, `f1` resolves via the short-name fallback to the projected db-qualified column (= 10). Verified the regression catch by temporarily removing the `db.table` branch locally — the new `SELECT f1 FROM (SELECT db04339_a.t.f1 FROM db04339_a.t, db04339_b.t)` correctly fails without it. Co-authored-by: Yakov Olkhovskiy <[email protected]>
CI failure on PR #107449 (stateless flaky check, amd_msan): the `04339` test creates two new databases (`db04339_a` / `db04339_b`) and the flaky check runs the same test ~50 times in parallel. Database names are GLOBAL across the server, so the parallel runs race on `CREATE DATABASE db04339_a` and one of them fails with `DATABASE_ALREADY_EXISTS`. The fix is to make those database names unique per test instance, which a pure-`.sql` test can't express without `Tags: no-parallel` (discouraged by AGENTS.md). Split the cross-database assertion into a sibling `.sh` test `04411_short_column_names_db_table.sh` that builds its database names from `${CLICKHOUSE_DATABASE}` (each test instance gets a unique per-test database, so `${DB}_a` / `${DB}_b` are also unique per instance — no parallel collision). The assertion itself is unchanged from the bot's suggested shape: two unaliased `dbN.t` sources force the canonical projection name to `db.table.column`, but project only one of them so the outer short-name `f1` is unambiguous and exercises the `db.table` source-name match in `safe_short_name`. `04339_short_column_names_from_subquery.sql` retains all the single-database assertions (which are safe under the flaky check because they use `currentDatabase()` tables only) and keeps a short pointer comment to the new `.sh` test. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Replace the .sh shell wrapper introduced in the previous commit with
a focused .sql test tagged no-parallel. The motivation: .sql tests
are much easier to debug locally (just clickhouse-client < file.sql,
no shell config sourcing, no ${CLICKHOUSE_DATABASE} substitution),
and Tags: no-parallel is exactly designed for cases like this one
where two side-by-side databases with the same table name are
genuinely required by the assertion. The AGENTS.md guidance to avoid
no-* tags 'unless strictly necessary' fits this case: cross-database
state IS the strict necessity here.
The assertion itself is unchanged from the bot's suggested shape:
two unaliased dbN.t sources in the inner FROM force the analyzer to
keep the canonical projection name in db.table.column form, but the
projection list selects only one of them, so the outer short-name
'f1' is unambiguous and exercises the db.table source-name match in
safe_short_name. Without that branch the assertion returns
UNKNOWN_IDENTIFIER; with it, the short name resolves to the
projected db-qualified column (= 10).
Update the pointer comment in 04339 to reference 04411.sql.
Co-authored-by: Yakov Olkhovskiy <[email protected]>
…-names-from-subquery-5b0c # Conflicts: # src/Core/Settings.cpp Co-authored-by: Yakov Olkhovskiy <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 170/187 (90.91%) · Uncovered code |
|
|
| /// | ||
| /// The map is empty unless `analyzer_enable_short_column_names_from_subquery` is on, | ||
| /// so there is no extra cost in the default-off case. | ||
| if (short_name_fallback_enabled && !result_expression && identifier_without_column_qualifier.getPartsSize() == 1) |
There was a problem hiding this comment.
The new short-name fallback lets alias-qualified lookups like l.f1 / r.f1 resolve when both joined subqueries expose only canonical dotted names (b.f1, d.f1), but the qualifier-stripping step below still decides whether it can shorten the projection name by calling tryBindIdentifierToTableExpressions, and that predicate deliberately ignores short-name candidates.
With a shape like:
WITH t1 AS (SELECT 1 AS f1), t2 AS (SELECT 2 AS f1)
SELECT l.f1, r.f1
FROM
(
SELECT b.f1
FROM t1 AS a
JOIN t1 AS b ON a.f1 = b.f1
) AS l
CROSS JOIN
(
SELECT d.f1
FROM t2 AS c
JOIN t2 AS d ON c.f1 = d.f1
) AS r
SETTINGS enable_analyzer = 1, analyzer_enable_short_column_names_from_subquery = 1;both identifiers resolve, but node_to_projection_name becomes f1, f1: the left side strips because it is preferred, and the right side also strips because tryBindIdentifierToTableExpressions("f1") cannot see that l already binds f1 via the new short-name map. That loses the distinction the user wrote and makes a wrapper query over this projection ambiguous.
Please keep the qualifier-stripping path aware of sibling short-name bindings (for example with a dedicated check used only while computing qualified_identifier, not by restoring short-name participation in the generic binding predicate that drove the earlier SELECT * regression).
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Fixed in #110746 |
Address AI review feedback on ClickHouse#107449 (ClickHouse#107449 (comment)): `WITH ... AS MATERIALIZED` rewrites the CTE reference into a `TableNode` backed by a `TemporaryTableHolder`, which goes through the table-node branch of `initializeTableExpressionData` rather than the QueryNode / UnionNode branch. The previous commit only populated `short_name_to_column_node` in the latter, so materialized CTEs were silently excluded from the new SQL-standard short-name fallback. Factor the population logic into `populateShortNameIndexForSubquery` and invoke it from both branches: - the QueryNode / UnionNode branch as before, against the eagerly built node map, - the table-node branch when `isMaterializedCTE()` is true, after triggering the lazy column-node-map populator. Regular tables and table functions are intentionally excluded — the setting's contract is 'from subquery', not 'rewrite every storage column'. Extend the stateless test to cover the three materialized-CTE shapes (short name in `WHERE`, outer alias + short name, canonical name still working). Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review feedback on ClickHouse#107449 (ClickHouse#107449 (comment)): the short-name fallback in `tryResolveIdentifierFromStorage` sat before `tryResolveIdentifierAsNestedPrefix`, so a subquery shaped like SELECT [1] AS `f1.x`, ['a'] AS `f1.y`, 42 AS `b.f1` would change resolution of outer `f1` from the existing Nested-prefix collapse (`Nested(x Array(UInt8), y Array(String))`) to the new short-name target (`b.f1`) when the setting is enabled. This violates the additive contract for the setting — enabling it must never change the resolution target of an identifier that already resolves successfully on master. Verified the regression with a focused reproducer before and after the fix: master / setting=0 → [(1,'a')] (Nested-prefix collapse) PR / setting=1 → 42 (short-name hijack — bug) fix / setting=1 → [(1,'a')] (Nested-prefix wins, additive) Move the short-name lookup to after `tryResolveIdentifierAsNestedPrefix` in the resolution order. The map is empty unless the opt-in setting is on, so the cold-path cost in the default-off case is unchanged. Add a focused regression test in `04339_short_column_names_from_subquery` asserting that with the setting on, outer `f1` against a projection list shaped like `f1.x Array(...), f1.y Array(...), b.f1 ...` still returns the Nested-prefix tuple array rather than `b.f1`'s value. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address the remaining additivity violations identified in the AI review on ClickHouse#107449: 1. Cross-join short-name vs Nested-prefix priority across siblings. Reproducer: `SELECT f1 FROM (SELECT 42 AS `b.f1`) l CROSS JOIN (SELECT [1] AS `f1.x`, ['a'] AS `f1.y`) r` returned `42` (left side's short-name) instead of the master result `[(1,'a')]` (right side's Nested-prefix collapse) under `single_join_prefer_left_table`. Fix: thread a `short_name_fallback_enabled` flag through `IdentifierResolver` and wrap `tryResolveIdentifierFromJoinTree` with two passes — pass 1 disables short-name so any canonical / subcolumn / Nested-prefix match anywhere in the join tree wins; pass 2 retries with short-name enabled only if pass 1 found nothing. The "cannot be resolved" throw inside `tryResolveIdentifierFromStorage` becomes a soft-fail in pass 1 so the retry actually runs; the throw fires normally on pass 2. 2. JOIN USING accepting a short-name-resolved column whose stored `getColumnName" still returned the dotted canonical name, then silently failing to merge left and right keys. Fix: `resolveJoin`'s USING branch installs a SCOPE_EXIT-guarded save/restore of the flag and resolves USING identifiers with short-name disabled. The query now fails with the master-equivalent `UNKNOWN_IDENTIFIER` from the USING handler instead of producing a wrong-shape result. 3. Predicate-level short-name binding propagating into `qualifyColumnNodesWithProjectionNames` and the qualifier-stripping logic in `tryResolveIdentifierFromStorage`, which could in theory over-qualify `SELECT *` headers and shift other projection names even when no query referenced the short name. Fix: drop the `canBindShortName` check from `tryBindIdentifierToTableExpression`. The predicate is for qualification decisions, not resolution; the resolver still consults short-name through `tryResolveIdentifierFromTableExpression` / `tryResolveIdentifierFromStorage`, both gated on `short_name_fallback_enabled`. Default-off is unaffected: the short-name index is empty, so the two-pass collapses to two cheap canonical-only attempts (pass 1 soft-fails, pass 2 throws the same error message users see today). Extend `04339_short_column_names_from_subquery` with focused regression tests for all three findings: cross-join Nested-prefix priority, JOIN USING short-name suppression, and `SELECT *` header stability. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review on PR ClickHouse#107449 (ClickHouse#107449 (comment)): the previous pass-1 soft-fail let an alias-qualified short-name lookup return null silently, which let an unrelated cross-join sibling that exposes a literal column with the same name hijack the resolution. Reproducer: SELECT q.f1 FROM (SELECT 1 AS `b.f1`) AS q CROSS JOIN (SELECT 2 AS `q.f1`) AS r SETTINGS analyzer_enable_short_column_names_from_subquery = 1; On master this query throws because q's alias-prefix branch can't find 'f1', and the throw kills cross-join sibling resolution. With the soft-fail this PR introduced, q quietly returned null, r's literal 'q.f1' column won, and the query returned 2 instead of 1 (the value of q.f1 resolved via short-name fallback to b.f1). Switch the two-pass implementation from "soft-fail when short-name is disabled" to "throw normally, but catch UNKNOWN_IDENTIFIER at the join-tree level when retry is allowed": - Removed the `!short_name_fallback_enabled -> return {}` branch in `tryResolveIdentifierFromStorage` so pass 1 produces the same master-equivalent throw it did before this PR. - `tryResolveIdentifierFromJoinTree` now wraps pass 1 in a try/catch that only intercepts UNKNOWN_IDENTIFIER and only when `retry_with_short_name_fallback` is true (i.e. the resolver entered with the fallback enabled — JOIN USING context, which enters with it disabled, doesn't get the retry). Pass 2 throws the same error normally if no resolution is found. - SCOPE_EXIT-guard the flag restore so any rethrow doesn't leak state. Default-off is byte-identical to master: pass 1 throws or returns null the way it does today, pass 2 (when reached) finds the same empty short-name index and produces the same outcome. Setting-on without a sibling literal column-name conflict is unchanged. Setting-on WITH the bot's reproducer now correctly returns the alias-qualified short-name target (1) instead of the sibling literal (2). Add focused regression tests covering both setting states for the exact reproducer. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Address AI review feedback on PR ClickHouse#107449: 1. Blocker: exception safety of `scope.join_using_columns` push/pop. `tryResolveIdentifierFromJoin` pushes a pointer to a stack-local `join_using_column_name_to_column_node` onto `scope.join_using_columns` before recursing into each side, and pops it only on normal return. The two-pass retry introduced earlier in this PR catches `UNKNOWN_IDENTIFIER` from deep inside that recursive call, which would let the pointer stay on `scope.join_using_columns` after the surrounding stack frame is gone — a use-after-free that `tryBindIdentifierToJoinUsingColumn` (called from `tryResolveIdentifierFromStorage`'s qualifier-stripping logic) would dereference during pass 2 or any later resolution. Fix: wrap the push/pop in `SCOPE_EXIT` so the pop runs on every code path, including the thrown-then-caught one. Record whether we pushed in a single boolean so the cleanup condition cannot drift from the push condition under any control flow. 2. Major: setting documentation overstated the implemented contract. The PR intentionally suppresses the short-name fallback during JOIN USING identifier resolution (because a USING list matches keys by `ColumnNode::getColumnName`, which still returns the canonical dotted name for a short-name-resolved column — allowing the fallback there would let USING accept mismatched left/right names and silently fail to merge them). Document that exclusion in both the setting description in `Settings.cpp` and the changelog entry in `SettingsChangesHistory.cpp`, and call it out explicitly in the PR description. Add a focused regression test that pushes the lambda's USING-map onto `scope.join_using_columns` and then throws inside the recursion via an alias-prefix miss with short-name disabled (pass 1). The query exercises the SCOPE_EXIT cleanup path on every CI run; under sanitizers (ASan/MSan) the dangling pointer would trip use-after-free without the fix. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Two minor cleanups requested in PR ClickHouse#107449 review: - The `tryBindIdentifierToTableExpression` predicate body no longer carries the standalone NOTE block explaining why short-name binding is intentionally not consulted there. The reasoning is already captured in the setting description and the header doc comment on `IdentifierResolver::short_name_fallback_enabled`; an in-code NOTE without surrounding code to anchor it just adds noise. - The `analyzer_enable_short_column_names_from_subquery` description no longer says "so the query behaves the same as master" — that phrasing only makes sense from inside a PR comparing to its base. Users reading the setting docs in a release see the setting as-is, with no "master" to compare against. Rephrase to state the behavior directly: `JOIN ... USING (f1)` against a short-name-only side raises `UNKNOWN_IDENTIFIER`. Co-authored-by: Yakov Olkhovskiy <[email protected]>
…ical Address AI review on PR ClickHouse#107449: the previous `rfind('.')` on the flattened canonical projection name happily split column names that legitimately contain a dot. For a join projecting `b.`f.1``, the canonical name flattens to `b.f.1` and the old code registered `1` as the fallback — exposing a meaningless short name and not exposing the real column `f.1`. Walk the underlying projection nodes to recover each projection's `ColumnNode::getColumnName` (the actual column name from inside the subquery, before the analyzer joined identifier parts with `.`) and verify it is a strict suffix of the canonical name preceded by `.`. Skip registration otherwise. This means: - `SELECT b.f1 FROM ... AS a JOIN ... AS b ON ...` → canonical `b.f1`, column.name `f1`, register short = `f1` (issue ClickHouse#87022 still works). - `SELECT b.`f.1` FROM ... AS a JOIN ... AS b ON ...` → canonical `b.f.1`, column.name `f.1`, register short = `f.1` (the actual column, not the rfind-induced `1`). - `SELECT 1 AS `b.f1`` (constant explicitly aliased with a dotted string) → not a ColumnNode → skip. The user picked the alias name; PostgreSQL doesn't expose `f1` as a short name for it either. For the materialized-CTE branch the storage snapshot's columns include appended virtual columns (`_part` etc.) after the regular projection columns, so `column_names_and_types.size()` exceeds the inner subquery's `projection_nodes.size()`. Iterate up to the smaller projection-node count and bail cleanly if a future change inverts that ordering. Source the projection nodes via `mat_table_node->getMaterializedCTESubquery()` (with a small helper that walks through nested unions to the first `QueryNode`). Add focused regression tests: - Quoted dotted column name from a join: canonical `b.f.1` keeps working; outer reference `f.1` (the actual column) now resolves; outer reference `1` (what the buggy split would have registered) correctly raises `UNKNOWN_IDENTIFIER`. Update the existing "alias-qualified short-name lookup is not hijacked by sibling literal column" assertion: the user-facing semantic for `SELECT q.f1 FROM (SELECT 1 AS `b.f1`) AS q CROSS JOIN (SELECT 2 AS `q.f1`) AS r` is now master-equivalent on both setting states — the explicit dotted alias `b.f1` does not gain a short-name `f1`, alias-qualified `q.f1` errors with `UNKNOWN_IDENTIFIER` (PostgreSQL behaves identically), and the cross-join sibling can no longer hijack it. Co-authored-by: Yakov Olkhovskiy <[email protected]>
This is a hybrid solution: it preserves ClickHouse's current projection-naming behavior exactly as-is, and additionally lets the outer query refer to a subquery / CTE projection column by its short name, the way the SQL standard and every other major engine (PostgreSQL, MySQL, Oracle, SQL Server) do. Both ways of addressing the column work in parallel.
In ClickHouse today, the reproducer from #87022 fails:
The CTE's projection column is named
b.f1(the analyzer keeps the full dotted form), soWHERE f1 = 1cannot resolve. Workarounds users have to fall back to today areWHERE `b.f1` = 1orSELECT b.f1 AS f1— both surprising. The standard says the implicit column name is justf1(the rightmost component).This PR adds a new opt-in compatibility setting:
analyzer_enable_short_column_names_from_subquery(defaultfalse).When on, the outer query can refer to the column by either name:
b.f1(existing behavior, unchanged),f1(new),t3.f1(new).The fallback is strictly additive:
DESCRIBE,SELECT *, result-set headers, and the wire protocol are byte-identical.<source>.<short>only when (a) the short name is unique among sibling projections, and (b) it does not collide with any other column's canonical name. An explicit alias of the same short name always wins canonical resolution.unordered_map::empty()check on the cold miss path of identifier resolution.Scope limitation: the short-name fallback does NOT apply while resolving
JOIN USINGcolumn lists. A USING list matches keys byColumnNode::getColumnName, which still returns the canonical (dotted) name for a short-name-resolved column, so allowing the fallback there would makeUSINGaccept mismatched left/right names and silently fail to merge them. The fallback is suppressed in USING context —JOIN ... USING (f1)against a side that only exposesf1via this fallback raisesUNKNOWN_IDENTIFIERexactly as on master. Use an explicitAS f1alias or the canonical dotted name for that form.The same fix closes the related issues #66133 (subquery on the right side of a JOIN) and #94858 (3-way self-join inside a CTE). #94558 was closed by upstream changes already and is kept as a
Related:reference (its CROSS JOIN shape is also handled by the new fallback).Implementation lives entirely inside the analyzer:
AnalysisTableExpressionDatagains a per-table-expressionshort_name_to_column_nodemap plustryGetShortNameColumnNode/canBindShortNameaccessors.QueryAnalyzer::initializeTableExpressionDatapopulates it forQueryNode/UnionNodetable expressions when the setting is on, and also forTableNodes that represent materialized CTEs (theWITH ... AS MATERIALIZEDrewrite path).IdentifierResolver::tryResolveIdentifierFromStorageconsults it after the existing canonical / subcolumn / Nested-prefix lookups miss.IdentifierResolver::tryResolveIdentifierFromJoinTreewraps the join-tree walk in a two-pass: pass 1 disables short-name so any canonical / Nested-prefix match anywhere in the tree wins; pass 2 retries with the fallback enabled only when pass 1 found nothing. Pass 1'sUNKNOWN_IDENTIFIERthrow (which preserves master's "alias-prefix miss kills sibling resolution" semantics) is caught at the join-tree level and converted into a pass-2 retry; theJOIN USINGpush/pop intryResolveIdentifierFromJoinis wrapped inSCOPE_EXITso the catch can't leave a dangling pointer onscope.join_using_columns.resolveJoindisables the fallback for the duration ofJOIN USINGidentifier resolution, via the sameSCOPE_EXIT-guarded flag.04339_short_column_names_from_subquery.{sql,reference}, covers all the issue reproducers, the additive guarantees, the materialized-CTE path, the conflict / ambiguity matrix, cross-join Nested-prefix precedence, alias-qualified short-name lookup vs sibling literal columns, theJOIN USINGexclusion, and the exception-safe push/pop path forscope.join_using_columns. For each open issue it closes, there are now symmetric default-off (serverError UNKNOWN_IDENTIFIER) and setting-on (succeeds and returns the expected row) assertions.Closes: #87022
Closes: #66133
Closes: #94858
Related: #94558
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add the opt-in setting
analyzer_enable_short_column_names_from_subquery(defaultfalse). When enabled, an outer query may refer to a subquery / CTE / materialized-CTE projection column whose canonical name is an unaliased qualified identifier likeb.f1either by its dotted canonical name (existing behavior) or by its SQL-standard short namef1. The canonical name keeps working in every case; the short name is purely additive and is registered only when unambiguous and non-colliding. The fallback does not apply while resolvingJOIN USINGcolumn lists — use an explicitASalias or the canonical dotted name for that form.