Repository navigation
Require a join subquery alias only when it removes a real ambiguity - #109368
alexey-milovidov wants to merge 74 commits into
Conversation
`joined_subquery_requires_alias = 1` (the default) rejected every unaliased subquery, table function or union used in a multi-table join, even when the missing alias could not cause any ambiguity. That is stricter than necessary: an alias is only needed to qualify a column, so it matters exactly when the unaliased table expression exposes a column whose name also occurs in another table expression of the same join. `validateJoinTableExpressionWithoutAlias` now throws `ALIAS_REQUIRED` only on such a name collision (computed with the existing `getColumnsFromTableExpression` helper over the sibling table expressions), and otherwise allows the missing alias. Genuine ambiguities that involve non-sibling table expressions are still caught later by the normal `AMBIGUOUS_IDENTIFIER` resolution, exactly as they are for ordinary tables. This lets standard queries such as TPC-DS q14 (whose `cross_items` derived table has no correlation name) run without setting `joined_subquery_requires_alias = 0`. Validation in `resolveJoin` and `resolveCrossJoin` is moved to run after all table expressions of the join are resolved, so that sibling columns are known when the collision is checked. The change is purely permissive - it never turns a previously-succeeding query into an error - and only affects the analyzer; the deprecated non-analyzer path keeps the stricter behavior. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [5a23421] Summary: ✅
AI ReviewSummaryThis PR relaxes Findings❌ Blockers
Tests
Final VerdictChanges requested: the relaxed alias check still misses bindable LLVM Coverage ReportMeasured on commit 5a23421.
Changed lines: Changed C/C++ lines covered: 209/216 (96.76%) · Uncovered code |
| bool has_name_collision = false; | ||
| for (const auto & column_name : table_expression_columns) | ||
| { | ||
| /// Sub-columns (e.g. `x.size0`) are addressed with a dot and cannot collide with a bare identifier. | ||
| if (column_name.find('.') != std::string::npos) | ||
| continue; | ||
| if (sibling_columns.contains(column_name)) |
There was a problem hiding this comment.
This collision test is weaker than the analyzer's real identifier binder. It only compares literal names, but expression resolution also treats compound names and Nested prefixes as bindable identifiers.
Two concrete cases already exist in tree:
- Dotted projection names are first-class identifiers (
04259_cte_subquery_dot_column_leak.sql), yet this loop skips every output likeb.id/n.x. That meansSELECT \b.id` FROM t2_compat, (SELECT 1 AS `b.id`)would now passjoined_subquery_requires_alias = 1` even though the subquery column is not qualifiable at all. - A sibling
Nestedprefix can bind a bare name without that exact string appearing insibling_columns(02731_analyzer_join_resolve_nested.sql.j2shows baretresolving fromt.t/t.s). SoSELECT t FROM na, (SELECT 1 AS t)would also bypassALIAS_REQUIRED, but the right-sidetis still shadowed by the left table.
I think this check has to reuse the actual binding predicate (AnalysisTableExpressionData::canBindIdentifier / IdentifierResolver::tryBindIdentifierToTableExpression) instead of skipping dotted names and intersecting raw NameSets.
There was a problem hiding this comment.
🕵 This is now fixed in 8a1dce4 (the earlier dismissal is withdrawn — m-selmi confirmed the gap with a concrete silent-misbinding repro below). The collision test no longer skips dotted names, and QUERY/UNION projections contribute their sub-column names, so compound-name binders (Nested columns, sub-columns, Tuple elements) are covered by the check.
There was a problem hiding this comment.
This only fixed the dotted-name half of the original report. The current collision check still builds sibling_columns from the literal names returned by getColumnsFromTableExpression, and the TABLE / TABLE_FUNCTION path at src/Analyzer/Resolve/QueryAnalyzer.cpp:5497-5529 still inserts only full storage names (t.t, t.s, ...) plus subcolumns.
The real binder is still broader than that: AnalysisTableExpressionData::canBindIdentifier treats the first identifier part as bindable, and IdentifierResolver::tryResolveIdentifierFromStorage will still resolve bare t as a Nested prefix over t.t / t.s. So the Nested-prefix half of the original issue is still present on the current head:
CREATE TABLE na (x Int32, t Nested(t UInt32, s String)) ENGINE = MergeTree ORDER BY x;
SELECT t FROM na, (SELECT 1 AS t);joined_subquery_requires_alias = 1 now allows that query even though bare t still resolves to na.t, leaving the subquery output unreachable unless it has its own table alias. I think this helper still needs to add the storage-side first-part binders (or ask canBindIdentifier / tryBindIdentifierToTableExpression directly) and add this repro to 04502.
|
I looked into the AI "Request changes" review above — the concern that the collision heuristic in Case 1 — dotted name ( SELECT `b.id` FROM t2_compat, (SELECT 1 AS `b.id`);
-- returns 2 (the table subcolumn b.id) with setting = 1 (this PR), with = 0, and even with the subquery aliased AS subBare Case 2 — SELECT t FROM na, (SELECT 1 AS t);
-- returns [(1,'a')] (na.t) with setting = 1 (this PR) and with = 0 — identicalBare Structurally this is expected: So I'd read this as a design tradeoff rather than a correctness bug: keep the conservative raw-name heuristic, or strengthen it to reuse Sanity-checked on the current commit ( |
The relaxation implemented in this PR (requiring a join subquery alias only on a real column-name collision) lives in the new analyzer's `QueryAnalyzer.cpp` only; the old analyzer keeps the strict behavior and throws `ALIAS_REQUIRED` for every unaliased join subquery. The new test `04502_joined_subquery_alias_only_on_collision` therefore failed in the "old analyzer" stateless run, where the first no-collision query threw `ALIAS_REQUIRED`. Pin `SET enable_analyzer = 1` at the top of the test, matching the sibling test `01000_subquery_requires_alias`, so the feature-specific queries run under the analyzer that implements the relaxation regardless of the CI job's default. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109368&sha=9ac8fb212d27184bd7bbe5330cd1daa2216c3ef8&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ry-alias-only-on-collision
…as-only-on-collision
Address the review of #109368: `validateJoinTableExpressionWithoutAlias` only required an alias for an unaliased join subquery/table function when its output column name collided with an *ordinary* column of a sibling table expression. Virtual columns such as `_part` were ignored even though `initializeTableExpressionData` registers them as bindable names, so `SELECT _part FROM mt, (SELECT '' AS _part)` slipped past `joined_subquery_requires_alias = 1` and then bound `_part` to the left `MergeTree` virtual column, leaving the subquery output unreachable — a real ambiguity the relaxation was meant to keep rejecting. `getColumnsFromTableExpression` gains an opt-in `include_virtuals` parameter so only the collision check sees virtual columns; the shared `NATURAL JOIN` and `USING` callers keep their previous behavior. The comparison is asymmetric on purpose: the unaliased expression contributes only the columns it actually exposes as output (projection / physical), while its siblings also contribute virtual columns. Adding the virtuals of the unaliased expression as well would make the ubiquitous `_table` / `_database` virtuals collide on essentially every join and defeat the relaxation. The reverse orientation is still covered because the validation runs for each unaliased sibling in turn. Extended `04502_joined_subquery_alias_only_on_collision` with the `_part` virtual-column collision (now requires an alias), the aliased and `joined_subquery_requires_alias = 0` variants, and a non-colliding name that is still allowed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The join-alias collision check added in this PR compared the unaliased subquery / table function against its siblings including the siblings' virtual columns, but took only the physical / projection columns of the unaliased expression itself. As `clickhouse-gh` pointed out, that still misses a real ambiguity when the unaliased side is a table function that exposes virtual columns of its own: e.g. `SELECT _path FROM file(...), (SELECT '' AS _path) AS rhs` exposes the table function's virtual `_path`, which collides with the aliased sibling's `_path`, yet slipped past `ALIAS_REQUIRED`. Both sides now contribute their virtual columns to the collision check. The only exception is the ubiquitous `_table` / `_database` virtuals of the unaliased side: every table expression exposes them, so counting them would make an unaliased table function collide with every sibling (e.g. `SELECT number FROM t, numbers(3)`). They are dropped from the unaliased side only, so the reverse orientation is still covered by the siblings. Real (physical / projection) columns are collected first, so a real column that happens to be named like a universal virtual is still kept. Extends `04502_joined_subquery_alias_only_on_collision` with the table-function virtual-column collision (rejected) and the `_table` / `_database` exemption (allowed). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…collision check The join-alias collision check in `getColumnsFromTableExpression` collected a table function's columns with `GetColumnsOptions::AllPhysical`, but the binder `initializeTableExpressionData` registers table-function columns with `GetColumnsOptions::All` (which also includes `ALIAS` / `EPHEMERAL` columns). Table functions such as `merge` forward the `ALIAS` columns of their source tables, and a bare identifier can bind to them, so `SELECT z FROM merge(...), (SELECT 1 AS z) AS rhs` (where `z` is a forwarded `ALIAS` column) bypassed `ALIAS_REQUIRED` even though bare `z` binds to the table function and the subquery output is unreachable without an alias. Use `GetColumnsOptions::All` for the `TABLE_FUNCTION` case, matching the `TABLE` case and the binder, so the collision check compares the full bindable column set. Extended test `04502` with a `merge`-forwarded `ALIAS` column collision (throws), its aliased and no-collision variants (allowed). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…as-only-on-collision
Address review (clickhouse-gh): the setting text still described the pre-PR behavior of always forcing aliases. This PR only requires an alias for a joined subquery or table function when a missing alias would create a real ambiguity (a column-name collision with a sibling table expression). Update the description in `src/Core/Settings.cpp` and the autogenerated snapshot `docs/reference/settings/session-settings.mdx` accordingly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…pe expression alias `WITH` and projection aliases are pre-registered before the join tree is resolved and shadow join-tree columns by default (`prefer_column_name_to_alias = 0`), so an unaliased joined subquery whose output column matches such an alias is unreachable without a table alias: `WITH 1 AS x SELECT x FROM numbers(1), (SELECT 2 AS x)` binds bare `x` to the scope alias. `validateJoinTableExpressionWithoutAlias` now treats a collision with an in-scope expression alias like a sibling-column collision and throws `ALIAS_REQUIRED`.
…-only The deprecated pre-analyzer path (`enable_analyzer = 0`) still requires an alias for every joined subquery and table function in `JoinedTables::resolveTables`, so the `joined_subquery_requires_alias` description must not present the collision-based behavior as global. Also mention that in-scope expression aliases count as collisions.
…as-only-on-collision
|
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109368&sha=ea8c0f26f97b5a838442598c846acce74e9b3993&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The other red checks on this run are already tracked: the coverage-shard server abort cascade is the |
|
Investigated. Fix in a separate PR: #110637. Root cause is not specific to this PR. The literal token map used by It is a rare allocator address-reuse race (matches the 181/181 rerun result, and ASan never hits it due to quarantine). The fix erases any token-map entry at the address of such synthesized literals, restoring the pre-refactor behavior where token info lived on the object and died with it. |
`04502_joined_subquery_alias_only_on_collision.sql` described the
relaxation as living in the "new analyzer", which the style check now
flags: the analyzer has been the default since ClickHouse 24.3 and is
no longer new. Reword to match the PR description's own terminology
("the analyzer" / "the deprecated non-analyzer path").
…as-only-on-collision
|
Both are environment/harness defects, unrelated to this PR. 1.
|
|
Signature 1 is fixed in #115512: The same collision reaches users, so that PR also pins the two documented setups (the SeaweedFS catalog guide and the SeaweedFS connector page). Both run Signature 2 is unchanged: still on your call between extending one of #113428 / #114029 / #112393 and opening a fourth PR. |
test_database_iceberg_seaweedfs_catalog could fail during fixture setup with a Connection refused from wait_for_seaweedfs, which reads as "the Iceberg REST catalog never started". That reading is wrong: the catalog answered HTTP 200 on all 314 polls, and the Connection refused was only the final poll, issued after the container had already exited 255. weed mini derives its admin gRPC port as admin.port + 10000, i.e. 23646 + 10000 = 33646, which is inside the Linux ephemeral range (floor 32768). One of mini's own startup dials can therefore take 33646 as an outbound source port before the admin server binds it, and the listen fails with "bind: address already in use" (mini.go:1583). Admin is the only derived gRPC port above the floor: mini derives exactly five of them (master 19333, filer 18888, volume 19340, s3 18333, admin 33646), and WebDAV and Iceberg carry a null gRPC pointer so they derive nothing. The failure then masks itself. glog.Fatalf (mini.go:1598) skips defer close(allServicesReady), and ensureMiniTableBuckets, which creates -tableBucket=analytics, runs only after <-allServicesReady. So the Iceberg service keeps answering 200 while the analytics bucket is never created, and the fixture's "analytics" in buckets condition can never become true. Pinning -admin.port=12646 makes the derived port 22646: below the ephemeral floor, and below the 22768 cap SeaweedFS uses for this same problem in its own test port allocator (seaweedfs/seaweedfs#10209, which left the mini default alone). The default is still 23646 on tags 4.41, 4.42 and upstream master, so bumping the image does not help. -admin.ui=false does not help either: startMiniAdminWithWorker is launched unconditionally and miniEnableAdminUI only affects the welcome banner. Extending the fixture wait cannot help, because the container is dead and the bucket is never created. Validated by forcing the collision with docker run --sysctl net.ipv4.ip_local_port_range="33646 33646" on chrislusf/seaweedfs:4.41: without the pin the CI log reproduces verbatim at both mini.go:1583 and mini.go:1598 including the two-minute readiness gap, and the analytics bucket is never created; with the pin it is. A control run on the default range passes unpinned, so the harness is not trivially red. The integration test itself passes and its container log reports Admin UI: ...:12646, where the same run on unpinned master reports ...:23646. The other SeaweedFS entry point, ci/jobs/scripts/functional_tests/ setup_seaweedfs.sh, needs no change: it runs weed server, which has no admin server, and already pins ports deriving to 21111..21114. The same collision reaches users through the two documented setups, so they are pinned as well: the SeaweedFS catalog guide's docker-compose.yml and the SeaweedFS connector page's docker run. Both pin image :latest, and admin.port is still 23646 there. Their symptom is worse than the test's, because the bucket each page tells the reader to use is the one that is never created, while the container keeps answering HTTP 200: the guide's CREATE DATABASE against s3://analytics and the connector page's clickhouse bucket both fail against a container that looks healthy. Verified on chrislusf/seaweedfs:latest with the same forced collision, once per page: unpinned, neither "created bucket clickhouse" nor "created table bucket analytics" appears and the container exits 255; pinned, each bucket is created and the container reports Admin UI: ...:12646. Both snippets keep publishing only 8333 and 8181, so the pinned admin port stays inside the container. The eight locale copies of the guide are left alone: they are generated from the English source (docs/README.md), so editing them by hand would be overwritten. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109368&sha=4443610796f2ef985ff5615a261456a7ea4155ea&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%205%2F6%29 Related: ClickHouse#109368 Upstream: seaweedfs/seaweedfs#10838
A lambda used as an `ARRAY JOIN` expression becomes a `LambdaNode` whose `getResultType` returns an empty pointer until it is resolved, unlike `QueryNode`/`UnionNode`/`FunctionNode` which throw. The dotted-name collision check dereferenced it. Assume collision (strict `ALIAS_REQUIRED`) when the result type is empty, same as for the other unresolved carriers.
…adows the joined column `scope_alias_shadows_column` split every dotted name at the first dot, so a quoted alias whose full name contains a dot (e.g. `WITH 1 AS ``n.x```) was never found: identifier resolution treats such a name as a single part and binds it before the join tree, which made the joined output unreachable without a table-expression alias. Check the exact alias name first (with the same self-alias carveout) and only then fall back to the `alias.subcolumn` prefix logic.
…as-only-on-collision
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109368&sha=01998279bed976ac738c05beed23b2595cd706e2&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. This is unrelated to this PR (an analyzer-only change to join subquery alias validation — it cannot influence background merges/mutations). The stress job aborted on a logical error in a background merge: and the follow-up CIDB shows the same signature recurring on unrelated pull requests over the last 30 days (
One of the earlier occurrences hit it from Master has been merged into this branch in |
|
Fix is already in progress: #108550 (open). Same defect. The tracking issue you could not find is #108514 (open). Root cause of this occurrence, reproduced on pristine master: The aborting table is ORDER BY (key, toStartOfInterval(ts, toIntervalMinute(3)), ts)
TTL ts + INTERVAL 5 MINUTE GROUP BY key, toStartOfInterval(ts, toIntervalMinute(3))
SET ..., ts = min(toStartOfInterval(ts, toIntervalMinute(3)))
One correction to the Minimal reproducer, aborts on master with no stress harness: CREATE TABLE t (key UInt32, ts DateTime, value UInt32)
ENGINE = MergeTree PARTITION BY toYYYYMM(ts)
ORDER BY (key, toStartOfInterval(ts, toIntervalMinute(3)), ts)
TTL ts + INTERVAL 5 MINUTE GROUP BY key, toStartOfInterval(ts, toIntervalMinute(3))
SET value = sum(value), ts = min(toStartOfInterval(ts, toIntervalMinute(3)));
INSERT INTO t SELECT 1, toDateTime('2106-02-07 06:21:00') + number, 1 FROM numbers(170);
OPTIMIZE TABLE t FINAL;Gives exactly Three notes on the CI side:
One gap: none of #108550's tests use |
|
Signature 2 has a fixing PR: #116545 (open). Same defect, surfaced on a different report: the hung check wrote The de-aggregation is the part that carries over to this run: here the server was over its total limit rather than a per-user one, and a query that does not aggregate never reaches So no fourth PR on that reporting axis, which closes the question I left open here. One step of the chain I described above is not in that PR: |
…as-only-on-collision
|
@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too. |
novikd
left a comment
There was a problem hiding this comment.
If you really want to allow having table expressions in the JOIN, without an alias, QueryAnalyzer::validateJoinTableExpressionWithoutAlias is the wrong place for it.
The code looks hacky and overcomplicated.
The proper way would be to move the check to IdentifierResolver::tryResolveIdentifierFromJoin. There is already logic for disabmiguation of the identifier. Probably it should be improved to better handle the Expression lookup case.
]
| /// If the columns of any table expression cannot be determined, keep the strict behavior and require an alias. | ||
| if (columns_are_known) |
There was a problem hiding this comment.
IMHO, this whole PR looks like a hacky fix
|
Reimplemented as suggested in #109368 (review): the eager check in New PR: #117792 |
|
The separate fix you asked for here is #119116: |
joined_subquery_requires_alias = 1(the default) rejected every unaliased subquery, table function or union used in a multi-table join, even when the missing alias could not cause any ambiguity. That is stricter than necessary: an alias only serves to qualify a column, so it is only needed when the unaliased table expression exposes a column whose name also occurs in another table expression of the same join.validateJoinTableExpressionWithoutAliasnow throwsALIAS_REQUIREDonly on such a name collision (computed with the existinggetColumnsFromTableExpressionhelper over the sibling table expressions), and otherwise allows the missing alias. Genuine ambiguities involving non-sibling table expressions are still caught later by the normalAMBIGUOUS_IDENTIFIERresolution, exactly as they are for ordinary tables.This lets standard queries such as TPC-DS q14 (whose
cross_itemsderived table has no correlation name) run without settingjoined_subquery_requires_alias = 0:Notes:
resolveJoin/resolveCrossJoinis moved to run after all table expressions of the join are resolved, so sibling columns are known when the collision is checked.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
With
joined_subquery_requires_alias = 1(the default), the analyzer now rejects an unaliased subquery or table function in a join only when the missing alias would make one of its columns unreachable, for example because the name collides with another joined table expression or is shadowed by an in-scope alias; otherwise the query is allowed. If the analyzer cannot determine the exposed names up front, it keeps the old strict behavior. Unambiguous queries, such as some standard TPC-DS queries, no longer require adding an alias.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/109368]