Skip to content

Hybrid SQL-standard short-name fallback for subquery columns - #107449

Closed
yakov-olkhovskiy wants to merge 20 commits into
masterfrom
cursor/short-column-names-from-subquery-5b0c
Closed

yakov-olkhovskiy wants to merge 20 commits into
masterfrom
cursor/short-column-names-from-subquery-5b0c

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

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:

WITH t1 AS (SELECT 1 AS f1, 2 AS f2),
     t2 AS (SELECT 1 AS f1, 5 AS f2),
     t3 AS (SELECT b.f1, b.f2 FROM t1 AS a JOIN t2 AS b ON a.f1 = b.f1)
SELECT * FROM t3 WHERE f1 = 1;
-- => Unknown expression identifier `f1` ... (UNKNOWN_IDENTIFIER)

The CTE's projection column is named b.f1 (the analyzer keeps the full dotted form), so WHERE f1 = 1 cannot resolve. Workarounds users have to fall back to today are WHERE `b.f1` = 1 or SELECT b.f1 AS f1 — both surprising. The standard says the implicit column name is just f1 (the rightmost component).

This PR adds a new opt-in compatibility setting:

  • analyzer_enable_short_column_names_from_subquery (default false).

When on, the outer query can refer to the column by either name:

  • canonical name b.f1 (existing behavior, unchanged),
  • short name f1 (new),
  • via outer alias + short name: t3.f1 (new).

The fallback is strictly additive:

  • The canonical projection name stays the same — DESCRIBE, SELECT *, result-set headers, and the wire protocol are byte-identical.
  • The short name is registered for a projection <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.
  • The short-name map is empty unless the setting is on, so the default-off path is a single unordered_map::empty() check on the cold miss path of identifier resolution.

Scope limitation: the short-name fallback does NOT apply while resolving JOIN USING column lists. A USING list matches keys by ColumnNode::getColumnName, which still returns the canonical (dotted) name for a short-name-resolved column, so allowing the fallback there would make USING accept 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 exposes f1 via this fallback raises UNKNOWN_IDENTIFIER exactly as on master. Use an explicit AS f1 alias 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:

  • AnalysisTableExpressionData gains a per-table-expression short_name_to_column_node map plus tryGetShortNameColumnNode / canBindShortName accessors.
  • QueryAnalyzer::initializeTableExpressionData populates it for QueryNode / UnionNode table expressions when the setting is on, and also for TableNodes that represent materialized CTEs (the WITH ... AS MATERIALIZED rewrite path).
  • IdentifierResolver::tryResolveIdentifierFromStorage consults it after the existing canonical / subcolumn / Nested-prefix lookups miss.
  • IdentifierResolver::tryResolveIdentifierFromJoinTree wraps 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's UNKNOWN_IDENTIFIER throw (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; the JOIN USING push/pop in tryResolveIdentifierFromJoin is wrapped in SCOPE_EXIT so the catch can't leave a dangling pointer on scope.join_using_columns.
  • resolveJoin disables the fallback for the duration of JOIN USING identifier resolution, via the same SCOPE_EXIT-guarded flag.
  • A new test, 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, the JOIN USING exclusion, and the exception-safe push/pop path for scope.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):

  • Improvement

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 (default false). When enabled, an outer query may refer to a subquery / CTE / materialized-CTE projection column whose canonical name is an unaliased qualified identifier like b.f1 either by its dotted canonical name (existing behavior) or by its SQL-standard short name f1. 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 resolving JOIN USING column lists — use an explicit AS alias or the canonical dotted name for that form.

Open in Web Open in Cursor 

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7009a75]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) FAIL cidb, issue
Stress test (arm_debug) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) ERROR
LLVM Coverage DROPPED

AI Review

Summary

This PR adds the opt-in analyzer_enable_short_column_names_from_subquery fallback so outer scopes can resolve subquery / CTE projection columns like b.f1 by f1 while keeping the canonical dotted names available. Most of the earlier additivity and materialized-CTE issues are fixed in the current head, but one header-stability gap remains for explicit alias-qualified short-name lookups from sibling subqueries.

Findings

⚠️ Majors

  • src/Analyzer/Resolve/IdentifierResolver.cpp:748 Alias-qualified short-name references from multiple sibling subqueries can both collapse to the same projection name. Once l.f1 / r.f1 resolve through the new fallback, the qualifier-stripping logic still asks tryBindIdentifierToTableExpressions whether bare f1 is already taken, but that predicate intentionally ignores short-name bindings. The result is duplicate f1 headers instead of preserving the user's explicit qualification, and a wrapper query over that projection becomes ambiguous. The fix should make the projection-name shortening path see sibling short-name bindings without reintroducing short-name participation into the generic binding predicate used by SELECT *.
Final Verdict

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

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 14, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review June 14, 2026 22:28
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
cursoragent and others added 2 commits June 15, 2026 04:55
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]>
Comment thread src/Core/Settings.cpp Resolved
cursoragent and others added 2 commits June 16, 2026 02:25
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
cursoragent and others added 2 commits June 16, 2026 15:41
…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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…-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]>
cursoragent and others added 4 commits June 26, 2026 18:05
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 170/187 (90.91%) · Uncovered code

Full report · Diff report

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ alexey-milovidov
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

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.

@novikd

novikd commented Aug 19, 2026

Copy link
Copy Markdown
Member

Fixed in #110746

@novikd novikd closed this Aug 19, 2026
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements

Projects

None yet

5 participants