Skip to content

Add analyzer_alias_hides_table_name: let an alias hide the table name from a qualifier - #118399

Open
alexey-milovidov wants to merge 51 commits into
masterfrom
correlated-qualifier-hidden-by-alias-99310
Open

alexey-milovidov wants to merge 51 commits into
masterfrom
correlated-qualifier-hidden-by-alias-99310

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

SQL says an alias replaces the name of the table it stands for, so t.x inside ... FROM t AS c ... refers
to a table t of an enclosing query. ClickHouse also accepts the table's own name as a qualifier, which is
harmless while the name means nothing else in the query, but it silently changes what a correlated subquery
means:

CREATE TABLE t (id UInt64, grp UInt8, val UInt64) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, 1, 10), (2, 1, 20), (3, 1, 30);

SELECT count() FROM t WHERE EXISTS (SELECT 1 FROM t AS c WHERE c.grp = t.grp AND c.val > t.val);
-- 0, expected 2

t.grp and t.val bind to the aliased t AS c, so the correlated predicate becomes a comparison of the
inner row with itself - c.grp = c.grp AND c.val > c.val, never true - and the query answers 0 with nothing
to indicate it.

This adds analyzer_alias_hides_table_name, which selects the standard reading: the name of a table
expression that has an alias is hidden from a qualifier when an enclosing scope carries that name, for the
table and the database.table form alike. A qualifier that means nothing outside the subquery keeps
resolving to the aliased table expression either way, so the accepted spelling still works wherever it is
unambiguous.

An enclosing query counts only while it is not resolving its own join tree. A subquery that sits in a
FROM or JOIN of that query cannot read a column of its siblings - validateFromClause rejects such a
correlated column with Lateral joins are not supported - so there is no second reading to choose from
there, and the qualifier keeps addressing the aliased table expression. That also keeps the answer
independent of the order of the enclosing FROM, whose table expressions are registered one at a time.

The setting is off by default, deliberately. Three tests of the suite are written in exactly this
spelling and rely on the current resolution, two of them born from user issues: 00858_issue_4756 and
01103_distributed_product_mode_local_column_renames cover the distributed_product_mode = 'local' rewrite
of an IN subquery, whose fragments qualify a column of an aliased table by the table's own name, and
03148_asof_join_ddb_subquery does the same for an ASOF JOIN inside IN. Their correlated reading is not
supported as an IN or JOIN argument, so the standard resolution makes all three fail. Flipping the
default is therefore a compatibility decision - happy to do it in this PR (and update those three queries to
set the setting) if that is the call.

Closes: #99310

Changelog category (leave one):

  • Improvement

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

New setting analyzer_alias_hides_table_name. When enabled, the alias of a table expression hides the
table's own name from a qualifier whenever an enclosing query has a table expression addressed by that name,
as SQL requires, so SELECT count() FROM t WHERE EXISTS (SELECT 1 FROM t AS c WHERE c.grp = t.grp) is
correlated instead of comparing the inner row with itself. Off by default, which keeps the previous
resolution.


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

… table

SQL says an alias replaces the name of the table it stands for, so `t.x` inside `... FROM t AS c ...`
refers to a table `t` of an enclosing query. ClickHouse also accepts the table's own name as a
qualifier, which is harmless while the name means nothing else in the query, but it silently changes
what a correlated subquery means:

    SELECT count() FROM t WHERE EXISTS (SELECT 1 FROM t AS c WHERE c.grp = t.grp AND c.val > t.val);

`t.grp` and `t.val` bound to the aliased `t AS c`, which turns the correlated predicate into a
comparison of the inner row with itself - never true - so the query answered 0 instead of the
correlated count, with nothing to indicate it.

The name of a table expression that has an alias is now hidden from a qualifier when an enclosing scope
carries that name, as the standard requires, for the `table` and the `database.table` form alike. A
qualifier that means nothing outside the subquery keeps resolving to the aliased table expression, so
the accepted spelling still works wherever it is unambiguous, and
`analyzer_compatibility_qualify_aliased_table_by_name` restores the previous resolution for the
shadowed case as well.

Two existing tests are written in the shadowed spelling and rely on the previous resolution -
`00858_issue_4756` and `03148_asof_join_ddb_subquery`, whose correlated reading is not supported yet as
an `IN` or `JOIN` argument - so both now set that setting for the query in question.

Closes: #99310

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79cbc33]

Summary: ✅


AI Review

Summary

The PR adds the opt-in analyzer_alias_hides_table_name setting to preserve correlated references when an inner table has an alias. The earlier findings are addressed, but the new outer-alias type probe evaluates unused expressions and changes analyzer state, causing otherwise valid queries to fail. Request changes.

Findings

⚠️ Majors

  • src/Analyzer/Resolve/QueryAnalyzer.cpp:1626: Speculative type lookup must not affect query execution or resolution state. tryGetTypeOfOuterExpressionAlias runs ordinary alias resolution in the live inner scope before checking whether the alias provides the requested suffix. With t(val UInt64) containing 10, 20, and 30, all three cases below succeed with the setting disabled but fail when enabled:

    WITH number + 1 AS t
    SELECT number IN (SELECT t.val FROM t AS c)
    FROM numbers(1)
    SETTINGS analyzer_alias_hides_table_name = 1;
    -- Expected: 0. Actual: NOT_IMPLEMENTED for a correlated IN subquery.
    
    WITH intDiv(1, 0) AS t
    SELECT (SELECT count() FROM t AS c WHERE t.val > 15)
    SETTINGS analyzer_alias_hides_table_name = 1;
    -- Expected: 2. Actual: ILLEGAL_DIVISION from the unused alias.
    
    WITH x AS t
    SELECT (SELECT tuple(5 AS x), tuple(6 AS x), count()
            FROM t AS c WHERE t.val > 15)
    SETTINGS analyzer_alias_hides_table_name = 1;
    -- Expected: ((5),(6),2). Actual: MULTIPLE_EXPRESSIONS_FOR_ALIAS.

    The probe leaves correlated-column registrations and transitive alias-use records behind, and can execute constant expressions or scalar subqueries. Restoring only the outer alias's used_alias_names entry does not undo these effects. Use non-evaluating type inspection with isolated resolution state.

Tests
  • ⚠️ Add regression coverage for unused throwing aliases, false correlation in an IN subquery, and transitive alias-use bookkeeping. All three failures were reproduced with the PR-head fast-test binary. The existing 05872_correlated_qualifier_hidden_by_non_constant_expression_alias and 05460_correlated_qualifier_hidden_by_expression_alias tests pass locally and match their reference outputs, so they do not cover these failures.
Final Verdict

Status: ⚠️ Request changes

Make outer-alias type probing free of expression evaluation and persistent scope mutations, and add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: tableNameIsHiddenByAlias reads the enclosing scope's table_expression_node_to_data, which is filled one FROM element at a time, so inside a FROM-clause subquery the hiding depends on the left-to-right position of the sibling table in the enclosing FROM: one order silently keeps the old resolution, the reversed order turns a previously-working, self-contained subquery into a NOT_IMPLEMENTED exception. Head 553cc8660aca, hand-traced (no CI build yet) plus live pre-PR baselines.

1. Hiding is order-dependent inside FROM-clause subqueries.

resolveCrossJoin resolves the table expressions left to right, and each one is registered into scope.table_expression_node_to_data only at the tail of its own resolveQueryJoinTreeNode call (QueryAnalyzer.cpp:5249, the map's sole insertion is at :3892). The new scan walks exactly that map, so a derived table resolved before the sibling t does not see it, while one resolved after does:

SELECT * FROM t, (SELECT count() FROM t AS c WHERE t.grp = 1) x; -- t already registered: hidden, t.grp correlates from the FROM clause -> "Lateral joins are not supported" (NOT_IMPLEMENTED)
SELECT * FROM (SELECT count() FROM t AS c WHERE t.grp = 1) x, t; -- map still empty: not hidden, keeps the old resolution and silently returns

Both spellings work identically today (verified live on current master: t.grp binds to t AS c, the derived table returns 3). That a correlated column in a FROM-clause subquery resolves through this parent chain and then throws NOT_IMPLEMENTED is also verified live: SELECT * FROM t, (SELECT t.grp FROM system.one) x gives Lateral joins are not supported. Correlated column 't.grp' is found in the FROM clause.

The same asymmetry applies to JOIN (resolveJoin resolves left then right) and to a materialized CTE referenced after t in the FROM list, where the correlated verdict is Materialized CTE cannot be correlated (UNSUPPORTED_METHOD).

2. The scan counts scopes the subquery cannot correlate with, and it fires transitively.

Inside a FROM-clause derived table there is no second reading of t.grp — lateral references are rejected — so by the PR's own rule ("the accepted spelling still works wherever it is unambiguous") the qualifier arguably should keep resolving to the aliased table there. The effect also reaches deeper scopes: this works today (returns 1) but the EXISTS is fully self-contained, and after the PR the sibling t of the enclosing query hides the name two scopes down and makes it an unsupported lateral reference:

SELECT x.c FROM t, (SELECT count() AS c FROM t2 WHERE EXISTS (SELECT 1 FROM t AS c1 WHERE t.grp = c1.grp)) x;

A possible shape: stop the walk when it crosses a scope boundary that correlated resolution cannot cross, so hiding only considers names the qualifier could actually reach.

Settled negative while checking: SELECT t.val FROM t AS c, t2 AS t already binds t2 AS t (the alias wins over the hidden name in the same scope) on current master, so the same-scope alias-steals-name case does not change.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 6, 2026
Three tests turned out to be written in the shadowed spelling and to rely on the previous resolution,
two of them born from user issues: `00858_issue_4756` and
`01103_distributed_product_mode_local_column_renames` cover the `distributed_product_mode = 'local'`
rewrite of an `IN` subquery, whose fragments qualify a column of an aliased table by the table's own
name, and `03148_asof_join_ddb_subquery` does the same for `ASOF JOIN` inside `IN`. Their correlated
reading is not supported as an `IN` or `JOIN` argument, so the standard resolution makes them fail.

That makes flipping this resolution a compatibility decision rather than a bug fix, so the standard
reading moves behind `analyzer_alias_hides_table_name`, off by default, and the three tests are left
untouched. The setting is named for what it enables rather than for what it restores, since the
behaviour it selects is not the default one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Resolve a qualifier that a table alias hides to the enclosing query's table Add analyzer_alias_hides_table_name: let an alias hide the table name from a qualifier Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79cbc3367 with master 022011d08 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

22 object files changed (+62.25 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/IdentifierResolver.cpp.o 538.34 KiB 574.07 KiB +35.73 KiB (+6.64%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.78 MiB 1.79 MiB +18.34 KiB (+1.01%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 3 commits September 11, 2026 09:29
Master renamed `query_plan_optimize_join_order_use_cd_a_conflict_detector` and
`query_plan_optimize_join_order_use_cd_c_conflict_detector` to
`query_plan_optimize_join_order_use_conflict_detector_a` and
`query_plan_optimize_join_order_use_conflict_detector_c` in the 26.9 section of
`SettingsChangesHistory`, and merging master next to an entry added in the same
place brought the old names back alongside the new ones. Neither setting exists
under the old name, so remove the two stale records.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`tableNameIsHiddenByAlias` walked every enclosing scope's
`table_expression_node_to_data`, but that map is filled one table expression at
a time while the join tree is being resolved, so for a subquery sitting in the
enclosing `FROM` or `JOIN` the answer depended on which side of the subquery the
sibling was written on:

    SELECT * FROM t, (SELECT count() FROM t AS c WHERE t.grp = 1) AS x;
    SELECT * FROM (SELECT count() FROM t AS c WHERE t.grp = 1) AS x, t;

The first saw `t` and made `t.grp` a correlated column of the `FROM` clause,
which `validateFromClause` rejects with `Lateral joins are not supported`; the
second kept the previous resolution. The effect also reached deeper scopes, so a
fully self-contained `EXISTS` two levels down could start failing because of a
sibling of the enclosing `FROM`.

A subquery in a `FROM` or `JOIN` cannot read a column of its siblings at all, so
there is no second reading to choose from there and the qualifier keeps
addressing the aliased table expression. Skip an enclosing scope while it is
resolving its own join tree, which is exactly the state in which its name set is
half filled, and the decision no longer depends on the order of the `FROM`.

The test covers both orders of a comma join and of a `JOIN`, and the transitive
case through a nested `EXISTS`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_tsan) red on 07a8465f is unrelated to this change: the server failed to restart with Missing columns: 'id' while processing 'SELECT id FROM test_1.t1' when attaching a fuzzed table whose CONSTRAINT contains a subquery over another table, i.e. #114918. Fixes are already in flight (#114923 and #112992), so nothing to do here. The setting added by this PR is off by default and cannot affect that job.

Master is merged and the order-dependence blocker is addressed in c7faea4e36c8.

alexey-milovidov and others added 3 commits September 12, 2026 17:30
`master` bumped the version to `26.10`, so the records this branch put in
an older block now sit in the block of a released version. The
`settings_changes_history` style check requires every record a change
touches to be present under the current version block: otherwise
`compatibility` attributes the new default to the wrong release.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e pruning

Two paths still read the name of an aliased table expression as a qualifier while
`analyzer_alias_hides_table_name` hides it elsewhere, so enabling the setting could still pick the
wrong scope.

The qualifier of a matcher (`t.*`, `t.COLUMNS(...)`, `db.t.*`) is resolved as an expression first and
as a table expression afterwards, and the `TABLE_EXPRESSION` branch of
`tryResolveIdentifierFromTableExpression` accepted the hidden inner name unconditionally. The setting
therefore changed `t.col` but kept the old meaning of `t.*` in the very same query. `tableNameIsHiddenByAlias`
now also answers for a table expression lookup, where the whole identifier is the qualifier, and both
that branch and the matching `tryBindIdentifierToTableExpression` branch consult it, including the
visible name of a `MaterializedCTE`. Once the inner name is hidden there is nothing left to expand -
a parent scope is not searched for the table expressions of an ordinary subquery - so the matcher
reports `UNKNOWN_IDENTIFIER`, which is what a hidden name means.

`qualifierBindsToJoinSubtree`, which `analyzer_compatibility_prefer_alias_over_subcolumn` uses to
restrict resolution to one side of a `JOIN`, treated the hidden name as a qualifier too. With both
settings enabled it pruned the side that carries a valid same-scope `Tuple` subcolumn `t.id`, found no
local match on the side it kept, and resolved the identifier from an enclosing scope instead. The new
setting only removes the inner-table interpretation; it must not let a parent scope beat a
current-scope column. The helper now consults the same rule for table names, database-qualified names
and visible `MaterializedCTE` names; an alias still binds as before.

`05103_correlated_qualifier_hidden_by_alias` covers the four matcher spellings, the alias and the
unambiguous name as matcher qualifiers, the unchanged default, and the two-setting `JOIN` case.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed both AI-review blockers and pushed b26387b.

  1. Qualified matchers. tableNameIsHiddenByAlias now answers for a TABLE_EXPRESSION lookup too (there the whole identifier is the qualifier, so the lookup passes its own size as identifier_column_qualifier_parts). The TABLE_EXPRESSION branch of tryResolveIdentifierFromTableExpression consults it for the one-part table name, for database.table and for the visible MaterializedCTE name, and tryBindIdentifierToTableExpression got the same check so binding agrees with resolution. t.*, t.COLUMNS('val'), db.t.* and db.t.COLUMNS('val') inside ... FROM t AS c ... are now UNKNOWN_IDENTIFIER with the setting on, as the review asked; an alias-spelled qualifier and a name nothing else carries are unaffected.

  2. JOIN-side pruning. qualifierBindsToJoinSubtree takes the whole IdentifierLookup and consults the same rule before matching a table name, a database-qualified db.table, or a visible MaterializedCTE name. The alias check sits above it and is untouched. A hidden name now binds to neither side, both sides are tried, and a valid current-scope subcolumn wins instead of falling through to an enclosing correlated reference.

05103_correlated_qualifier_hidden_by_alias covers the four matcher spellings, the alias and the unambiguous name as matcher qualifiers, the unchanged default, and the two-setting JOIN case (the left side carries a Tuple column named like the table aliased on the right): it answers 3 where the pruned resolution answered 0. The test passes locally, as do 02339_analyzer_matcher_basic, 00467_qualified_names and the prefer_alias family.

The two CI reds on the previous head are unrelated and tracked:

alexey-milovidov and others added 2 commits September 25, 2026 06:02
…r-hidden-by-alias-99310

# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
`tableNameIsHiddenByAlias` skipped every enclosing scope whose join tree was
still in `table_expressions_in_resolve_process`. That set is still non-empty
while the `ON` expression of a `JOIN` is resolved, although both sides are
registered by then, so under `analyzer_alias_hides_table_name` a subquery in
`ON` kept binding the hidden name to the aliased inner table and silently
compared the inner row with itself.

Skip the scope only while it is not resolving a `JOIN ... ON` expression
(`resolving_join_on_expression`). A correlated subquery in `ON` is not
supported yet, so such a query now reports `NOT_IMPLEMENTED`, the same as the
query written with the outer table aliased, instead of answering 0.

Addresses the review thread on
#118399

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits September 26, 2026 23:23
…r-hidden-by-alias-99310

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…e CTE

A materialized CTE is registered in `table_expression_node_to_data` under an
internal temporary table name, so `tableNameIsHiddenByAlias` never matched an
enclosing `WITH t AS MATERIALIZED (...) SELECT ... FROM t` by its visible name,
and `analyzer_alias_hides_table_name = 1` kept the self-comparison reading of
`t.x` inside `... FROM t AS c ...`. Compare against `MaterializedCTE::cte_name`
as the current-scope qualifier paths already do, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: 05237_with_expression_alias_scope_descendant in Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118399&sha=3bd27f1433afa637fd3e02d0ee157e00f5ad05dc&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2%29) and provide a fix in a separate PR. If the fix is already in progress, link it here. The view row gives 10 instead of 100 and the stored definition is not bare; it fails in dozens of unrelated PRs in this DBReplicated job since 2026-10-03.

The other reds of 3bd27f14 are fixed on master, which I merged in 0ca7c8cb: the stress-test server restart failure on 05315_mongodb_connection_options_secrets (NAMED_COLLECTION_DOESNT_EXIST, fixed by ce46692c/7a3da7c0) and 05213_timeseries_metric_families_target under parallel replicas (#123763).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118399&sha=aff8601d0a19a6b0e85fd47c3f0229f377e690ee&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. It is AddressSanitizer: attempting double-free in a DistrOutStrProc thread (sending data of a Distributed insert). The report omits the stack trace, and I found no open issue for it. This PR only changes identifier resolution under analyzer_alias_hides_table_name, which is off by default.

This push merges master and addresses the matcher review thread (0cbfa11).

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress in my PR #114995 (issue #90967).

The full stack is in CIDB (STID 3448-4fc3). Both DistrOutStrProc threads are DistributedSink::runWritingJob writing to local shards of an object-storage table. Each one builds its sink in StorageObjectStorage::createSink, which reads the path list and then calls configuration->setPaths(paths) on the configuration shared by the table. Two concurrent std::vector assignments free the same buffer. TSan reports the same race as STID 3437-4705, also on master on 2026-11-03.

#114995 locks the path list and replaces that getPaths/setPaths pair in createSink with a single locked allocation of the write path. Its CI is green, and it is waiting on review. The failure is not related to this PR.

alexey-milovidov and others added 2 commits November 5, 2026 18:38
…lve `ALIAS` columns when probing outer readings

`tableExpressionDataCanReadIdentifier` checked a competing reading of the qualifier in an enclosing table
through `tryGetColumnNode` and `tryGetSubcolumnInfo`. Those resolve the expression of an `ALIAS` column,
so an unused `ALIAS` column named like the table (e.g. one calling `dictGet` of a dropped dictionary) made
the query fail only because `analyzer_alias_hides_table_name` was enabled. The check now reads the declared
types from the column node map without resolving any expression.

It also missed the `Nested` value that `tryResolveIdentifierAsNestedPrefix` reconstructs from flattened
`Array` columns: for an outer table with `t Nested(val UInt64)`, `t.*` in a subquery over `t AS c` still
expanded the inner table. Such a prefix now counts as a reading, under the same conditions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. The test_read_temporary_tables_on_failure failure on 0cbfa11 is fixed by #129151, which is already merged. This push (4c7f1dc) merges master to pick that fix up and addresses the two review threads from 2026-11-04 (reconstructed Nested prefixes, and unresolved storage ALIAS columns). The thread about non-constant expression aliases (checking their type would require resolving outer aliases eagerly in QueryAnalyzer) is still open for a human decision.

alexey-milovidov and others added 2 commits November 7, 2026 03:05
…ted `Nested` prefix when probing outer readings

`tableExpressionDataCanReadIdentifier` tried to reconstruct a `Nested` prefix even when a declared column
of that name exists, unlike `tryResolveIdentifierFromStorage`. With a scalar column `t` and an array
column `t.val` in an enclosing table, `t.*` in `FROM t AS c` was considered to have a competing reading,
the name was hidden, and the qualifier resolved to the scalar, throwing `UNSUPPORTED_METHOD`. Now, if a
column or subcolumn exists, it alone decides whether there is a usable reading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118399&sha=4c7f1dc0fc711071ed57fe2fa869fef475d00838&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The fuzzer hit Cannot convert nested result of function plus with type Decimal(35, 7) to the expected result type Variant(...) on a UNION ALL of a Join table and a MergeTree table. This does not involve identifier qualifiers, so it is unrelated to this PR. It looks like #129666 is the fix (that PR links this very report).

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

The fix is my PR #129666 (open, CI green, waiting on review).

DataTypeDecimal::equals compares only the scale, so addConvertingToCommonHeaderActionsIfNeeded does not convert the Join branch, whose b Decimal(35, 7) is equals to the common Decimal(38, 7), and the union header keeps Decimal(35, 7). ExecutableFunctionVariantAdaptor rebuilds plus from that runtime type and gets Decimal(35, 7), which is not an alternative of the declared Variant(DateTime('America/New_York'), Decimal(38, 7)). #129666 adds a CAST to the common type for such a branch.

I checked the report's query on debug builds. When the Join table yields no rows at runtime, master aborts with this exact message at FunctionVariantAdaptor.cpp:221, and the #129666 CI build gets past plus (it then throws a catchable Code: 153 division by zero from cos(a / b)). With the reproduce block's data, both builds stop earlier at the DateTime rows with a catchable Code: 43 (DateTime + Decimal), so the block alone does not reproduce the abort.

…s the scan of enclosing scopes

`tableNameIsHiddenByAlias` treated a lambda argument that binds the first part of a
qualified identifier but has no subcolumn for the rest the same as an absent argument,
and continued to scan the enclosing scopes. The normal lookup throws
`UNKNOWN_IDENTIFIER` there instead (see `tryResolveIdentifierFromCompoundExpression`),
so a table of a farther scope is unreachable and must not hide the inner name:

    WITH t -> (SELECT count() FROM t AS c WHERE t.val > 15) AS f SELECT f(1) FROM t

`expressionArgumentReadingOfIdentifier` now distinguishes an absent binding from one
that blocks further lookup, and the scan stops with "not hidden" in the latter case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 5 commits November 10, 2026 02:02
…r a farther table

`tableNameIsHiddenByAlias` treated an outer carrier that binds the qualifier of a matcher but
cannot be expanded (a scalar lambda argument, constant alias, column or `ARRAY JOIN` output) as
absent, and continued to a farther table of the same name, which then hid the inner table:

    WITH t -> (SELECT t.* FROM t AS c ORDER BY val LIMIT 1) AS f SELECT f(1) FROM t

threw `UNSUPPORTED_METHOD`. `resolveQualifiedMatcher` resolves the qualifier as an expression
first and stops at the nearest binding, so the farther table is never reached. The carriers now
report a tri-state `OuterReading`; a scope that has a blocking carrier and no readable one stops
the scan with "not hidden".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of the lookup

`tableNameIsHiddenByAlias` let any readable carrier of an enclosing scope hide the
name, even when a scalar carrier of the same scope binds the qualifier first, e.g.
`WITH 1 AS t SELECT (SELECT t.* FROM t AS c ...) FROM t` threw `UNSUPPORTED_METHOD`.
Now the carriers of a scope are probed in the order `QueryAnalyzer::tryResolveIdentifier`
tries them - lambda arguments, expression aliases, `ARRAY JOIN` outputs, columns, then
table names, with `prefer_column_name_to_alias` moving the aliases after the columns -
and the first group that binds the identifier decides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`tableNameIsHiddenByAlias` merged the readings of all columns of an enclosing
join tree with "readable wins", which differs from the actual lookup: when both
sides of a `JOIN` bind the identifier, the left side wins with
`single_join_prefer_left_table` (or for a `USING` column), otherwise the
identifier is ambiguous, and with `prefer_column_name_to_alias` an expression
alias takes over. Walk the join tree the way `tryResolveIdentifierFromJoinTreeNode`
does, so the column the lookup actually binds decides, and fall back to the
expression alias when the join tree is ambiguous.

Add `05621_correlated_qualifier_matcher_shadowed_by_joined_column` for the
left-side preference in both directions and for the alias takeover.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 14, 2026 05:23
…er probe

The probe of `analyzer_alias_hides_table_name` treated two sides of a `JOIN`
that both bind the identifier as ambiguous unless the left side wins by
`single_join_prefer_left_table` or `USING`. But `tryResolveIdentifierFromJoin`
and `tryResolveIdentifierFromCrossJoin` also pick one side when the resolved
columns are equal (the same column of two equal table expressions, such as two
references to one table or two equal subqueries) and, for an unqualified
identifier, when the `ON` condition of an `INNER JOIN` equates them. The false
ambiguity let a scalar expression alias take over under
`prefer_column_name_to_alias`, so the inner table stayed visible and `t.*`
silently read it instead of the outer `Tuple` column.

The probe now tracks the table expression that binds the identifier on each
side and resolves these cases to the left side, as the lookup does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ARRAY JOIN` in the qualifier probe

The probe of `analyzer_alias_hides_table_name` now treats columns equated by
`isNotDistinctFrom` (`<=>`) in the `ON` condition of an `INNER JOIN` as equal,
like `innerJoinKeyColumnsAreEquated` does, and evaluates the outputs of an
`ARRAY JOIN` at its position in the join tree, as `tryResolveIdentifierFromArrayJoin`
does, instead of letting them precede the whole join tree. An `ARRAY JOIN` output
below a `JOIN` now competes with the columns of the other side of that `JOIN`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
`vectorSimilarityIndexValidator` checked `hnsw_max_connections_per_layer` (M)
and `hnsw_candidate_list_size_for_construction` (ef_construction) only through
usearch's `index_config_t::validate()`, which requires M >= 2 and has no upper
bound. Usearch gives every graph node 2 * M level-0 neighbour slots and
allocates + zeroes them for each added vector (`node_make_`), so M = 2994230
costs 22.84 MiB per indexed row. That memory comes from usearch's mmap-backed
tape allocator and the build loop makes no throwing tracked allocation, so
building such an index never hits `max_server_memory_usage`: the kernel OOM
killer kills the server first. The AST fuzzer reaches it by mutating these two
arguments to `rand() % 2^22 + 1` (`QueryFuzzer::fuzzIndexDeclaration`), seen as
`OOM in dmesg` with invoking thread `VectorSimIndex` on PR ClickHouse#118399 (1f3ca7f)
and PR ClickHouse#115453 (9dca955).

Reject M > 512 and ef_construction > 3200 when an index is defined. These are
Lucene's limits (`Lucene99HnswVectorsFormat.MAXIMUM_MAX_CONN = 512`,
`MAXIMUM_BEAM_WIDTH = 3200`); at M = 512 a node costs ~4 KiB, and every in-tree
test and doc example stays far below (max M 200, max ef_construction 512).

The check is skipped on ATTACH, like the `bloom_filter` validation, so a table
created before this change still loads and its index can be dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 19, 2026 01:25
…he lookup does

An `ARRAY JOIN` output that binds the identifier by its whole name now keeps
the `ARRAY JOIN` node as its source, so the probe can recognize it as an
equated key of an enclosing `INNER JOIN`, as `innerJoinKeyColumnsAreEquated`
does. The first output that binds the identifier decides, as in
`tryResolveIdentifierFromArrayJoin`, instead of letting a later readable
output win over an earlier blocking one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 26.11 release branch has been cut and `master` is 26.12 now, so the new setting belongs to 26.12.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…rovides the rest of the identifier

Under `analyzer_alias_hides_table_name`, an expression alias of an enclosing query that is not a constant
counted as another reading of `t.val` whatever its type, so an unrelated `number + 1 AS t` or a `Tuple`
without `val` made the identifier fail with `UNKNOWN_IDENTIFIER` instead of keeping the inner-table spelling.

The alias table stores the expressions as written, so the type of such an alias is not known there.
`tableNameIsHiddenByAlias` now asks `QueryAnalyzer` for it: `tryGetTypeOfOuterExpressionAlias` resolves the
alias exactly as the parent lookup would resolve it once the name is hidden, so the answer does not depend on
the order in which the enclosing query resolves its expressions, and no expression is resolved that the
previous behaviour did not resolve. Asking for the type is not recorded as a use of the alias.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 This push merges master and addresses the last open review thread (non-constant expression aliases, 79cbc33), so the full CI suite, which was skipped because of that thread, can run. It also moves analyzer_alias_hides_table_name to 26.12 in the settings history, since the 26.11 branch has been cut (bdc14b9).

identifier_resolve_context.allow_to_check_database_catalog = false;

IdentifierLookup alias_lookup{Identifier(std::vector<std::string>{alias_name}), IdentifierLookupContext::EXPRESSION};
auto resolved_alias = tryResolveIdentifierFromAliases(alias_lookup, alias_scope, identifier_resolve_context).resolved_identifier;

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.

[Major] Keep the alias-type probe free of expression evaluation and scope mutations

tryResolveIdentifierFromAliases performs real expression resolution in lookup_scope, even when the resulting scalar type makes tableNameIsHiddenByAlias discard the alias. This can change a query that never uses the alias. Reproduced with the fast-test binary for 79cbc336730a:

CREATE TABLE t (val UInt64) ENGINE = Memory;
INSERT INTO t VALUES (10), (20), (30);

WITH number + 1 AS t
SELECT number IN (SELECT t.val FROM t AS c)
FROM numbers(1)
SETTINGS analyzer_alias_hides_table_name = 1;

This throws NOT_IMPLEMENTED for a correlated IN subquery. Disabling the setting, or renaming only the unused alias to x, returns 0. Resolving number during the probe invokes checkCorrelatedColumn, which adds it to the inner query's correlated columns; discarding the scalar alias does not undo that mutation. The scope guard only restores one entry in used_alias_names.

The same probe also evaluates unused expressions: WITH intDiv(1, 0) AS t SELECT (SELECT count() FROM t AS c WHERE t.val > 15) SETTINGS analyzer_alias_hides_table_name = 1 throws ILLEGAL_DIVISION instead of returning 2. Transitive alias-use tracking leaks too: WITH x AS t SELECT (SELECT tuple(5 AS x), tuple(6 AS x), count() FROM t AS c WHERE t.val > 15) succeeds with the setting disabled but throws MULTIPLE_EXPRESSIONS_FOR_ALIAS when enabled.

Please make type probing non-evaluating and isolate its resolution state, including correlated-column and transitive alias-use bookkeeping. Add focused regressions for these unused-alias cases; checking the suffix after full resolution is too late.

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

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated EXISTS subquery on same table silently returns wrong result (0 instead of correct count)

3 participants