Repository navigation
Add analyzer_alias_hides_table_name: let an alias hide the table name from a qualifier - #118399
alexey-milovidov wants to merge 51 commits into
Conversation
… 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]>
|
Workflow [PR], commit [79cbc33] Summary: ✅
AI ReviewSummaryThe PR adds the opt-in Findings
Tests
Final VerdictStatus: Make outer-alias type probing free of expression evaluation and persistent scope mutations, and add the focused regressions above. |
|
TL;DR: 1. Hiding is order-dependent inside FROM-clause subqueries.
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 returnsBoth spellings work identically today (verified live on current master: The same asymmetry applies to 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 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: |
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]>
analyzer_alias_hides_table_name: let an alias hide the table name from a qualifier
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes22 object files changed (+62.25 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units25 translation units recompiled, 149 s compile time in total, 25 of them have a recent master baseline. |
…r-hidden-by-alias-99310
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]>
|
🕵 The Master is merged and the order-dependence blocker is addressed in |
…r-hidden-by-alias-99310
`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]>
|
🕵 Addressed both AI-review blockers and pushed b26387b.
The two CI reds on the previous head are unrelated and tracked:
|
…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]>
…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]>
|
🕵 @groeneai, investigate the failure: The other reds of |
|
🕵 @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 This push merges |
|
The fix is already in progress in my PR #114995 (issue #90967). The full stack is in CIDB (STID #114995 locks the path list and replaces that |
…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]>
|
🕵 Thanks @groeneai. The |
…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]>
|
🕵 @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 |
|
The fix is my PR #129666 (open, CI green, waiting on review).
I checked the report's query on debug builds. When the |
…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]>
…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]>
…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]>
`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]>
…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]>
|
🕵 This push merges |
| 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; |
There was a problem hiding this comment.
[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.
SQL says an alias replaces the name of the table it stands for, so
t.xinside... FROM t AS c ...refersto a table
tof an enclosing query. ClickHouse also accepts the table's own name as a qualifier, which isharmless while the name means nothing else in the query, but it silently changes what a correlated subquery
means:
t.grpandt.valbind to the aliasedt AS c, so the correlated predicate becomes a comparison of theinner row with itself -
c.grp = c.grp AND c.val > c.val, never true - and the query answers 0 with nothingto indicate it.
This adds
analyzer_alias_hides_table_name, which selects the standard reading: the name of a tableexpression that has an alias is hidden from a qualifier when an enclosing scope carries that name, for the
tableand thedatabase.tableform alike. A qualifier that means nothing outside the subquery keepsresolving 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
FROMorJOINof that query cannot read a column of its siblings -validateFromClauserejects such acorrelated column with
Lateral joins are not supported- so there is no second reading to choose fromthere, 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_4756and01103_distributed_product_mode_local_column_renamescover thedistributed_product_mode = 'local'rewriteof an
INsubquery, whose fragments qualify a column of an aliased table by the table's own name, and03148_asof_join_ddb_subquerydoes the same for anASOF JOINinsideIN. Their correlated reading is notsupported as an
INorJOINargument, so the standard resolution makes all three fail. Flipping thedefault 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):
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 thetable'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)iscorrelated instead of comparing the inner row with itself. Off by default, which keeps the previous
resolution.
Workflow [PR]
Sync PR [sync-upstream/pr/118399]