Skip to content

Require a join subquery alias only when it removes a real ambiguity - #109368

Closed
alexey-milovidov wants to merge 74 commits into
masterfrom
joined-subquery-alias-only-on-collision
Closed

alexey-milovidov wants to merge 74 commits into
masterfrom
joined-subquery-alias-only-on-collision

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

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.

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 involving 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:

SELECT i_item_sk
FROM item, (SELECT iss.i_brand_id AS brand_id FROM store_sales, item AS iss ...)
WHERE i_brand_id = brand_id;   -- no shared column name -> no alias needed

Notes:

  • Validation in resolveJoin/resolveCrossJoin is moved to run after all table expressions of the join are resolved, so sibling columns are known when the collision is checked.
  • The change is purely permissive: it never turns a previously-succeeding query into an error. When the columns of any side cannot be determined it falls back to the old strict behavior.
  • Only the analyzer is affected; the deprecated non-analyzer path keeps the stricter behavior.

Changelog category (leave one):

  • Improvement

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

  • Documentation is written (mandatory for new features)

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

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

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5a23421]

Summary: ✅


AI Review

Summary

This PR relaxes joined_subquery_requires_alias in the analyzer so unaliased joined subqueries and table functions are rejected only when the missing alias would make one of their outputs unreachable. Most of the earlier binder gaps have been fixed, but the current collision set is still narrower than the real identifier binder for Nested prefixes, so the PR can still admit joins whose unaliased output is shadowed after resolution.

Findings

❌ Blockers

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:1004-1008, 5527-5560] validateJoinTableExpressionWithoutAlias still models sibling binders as a literal NameSet, but identifier resolution also binds the first part of flattened Nested-style columns through AnalysisTableExpressionData::canBindIdentifier and IdentifierResolver::tryResolveIdentifierAsNestedPrefix. A sibling table with t Nested(t UInt32, s String) still binds bare t, so SELECT t FROM na, (SELECT 1 AS t) now passes with joined_subquery_requires_alias = 1 even though the right-hand t remains unreachable without a table alias. The same hole also remains for QUERY / UNION siblings that project array columns like `n.x` and `n.y`, because getColumnsFromTableExpression records only the literal projection names, not the bindable prefix n.
    Suggested fix: when building sibling_columns, add every bindable first-part Nested prefix (or reuse the same binder predicate the analyzer uses during identifier resolution) instead of only full names and subcolumns, and extend 04502 with both the storage-backed and projection-backed repros.
Tests
  • ⚠️ [tests/queries/0_stateless/04502_joined_subquery_alias_only_on_collision.sql:339-363] The current regression file covers the dotted n.x collision, but not the bare-prefix shape that still binds through Nested resolution. Add a focused case for SELECT t FROM na, (SELECT 1 AS t) and a projection-backed variant such as SELECT n FROM (SELECT [1] AS \n.x`, ['a'] AS `n.y`) AS lhs, (SELECT 1 AS n)` so the relaxed check is proven against the same prefix binder the analyzer actually uses.
Final Verdict

Changes requested: the relaxed alias check still misses bindable Nested prefixes, so the PR can accept queries whose joined output remains unqualifiable.

LLVM Coverage Report

Measured on commit 5a23421.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 81.00% +0.10%

Changed lines: Changed C/C++ lines covered: 209/216 (96.76%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Outdated
Comment on lines +956 to +962
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))

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.

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:

  1. Dotted projection names are first-class identifiers (04259_cte_subquery_dot_column_leak.sql), yet this loop skips every output like b.id / n.x. That means SELECT \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.
  2. A sibling Nested prefix can bind a bare name without that exact string appearing in sibling_columns (02731_analyzer_join_resolve_nested.sql.j2 shows bare t resolving from t.t / t.s). So SELECT t FROM na, (SELECT 1 AS t) would also bypass ALIAS_REQUIRED, but the right-side t is 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

I looked into the AI "Request changes" review above — the concern that the collision heuristic in validateJoinTableExpressionWithoutAlias is weaker than the analyzer's real identifier binder (it skips dotted projection names and does not treat a sibling Nested prefix as bindable). That subset relationship is accurate, but I could not turn either flagged case into a wrong result: both behave exactly as joined_subquery_requires_alias = 0 already does today, with deterministic resolution.

Case 1 — dotted name (t2_compat(id Int, b Tuple(id Int))):

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 sub

Bare `b.id` binds to the table subcolumn regardless of the alias or the setting; the subquery's b.id is only ever reachable as sub.`b.id`. Nothing is newly misresolved — it's the same result the escape hatch already produces.

Case 2 — Nested prefix (na(x Int32, t Nested(t UInt32, s String))):

SELECT t FROM na, (SELECT 1 AS t);
-- returns [(1,'a')] (na.t) with setting = 1 (this PR) and with = 0 — identical

Bare t deterministically binds to the Nested column na.t, shadowing the subquery, exactly as = 0 does.

Structurally this is expected: validateJoinTableExpressionWithoutAlias only decides throw-vs-allow. When it allows, the query runs identically to joined_subquery_requires_alias = 0; it can only ever throw more than = 0, never resolve columns differently. So the heuristic's incompleteness cannot corrupt data — its only effect on the missed dotted/Nested cases is that those queries run (== 0) instead of erroring with ALIAS_REQUIRED, which matches the "ambiguities fall through to normal resolution" design stated in the PR description.

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 AnalysisTableExpressionData::canBindIdentifier / IdentifierResolver::tryBindIdentifierToTableExpression so dotted and Nested-prefix collisions also force the alias. Happy to implement the binder-based version if you'd prefer it — it's your call on your own PR.

Sanity-checked on the current commit (9ac8fb21, aarch64): the common bare-name collision still throws ALIAS_REQUIRED, a no-collision join is allowed, and the new test 04502_joined_subquery_alias_only_on_collision passes.

alexey-milovidov and others added 2 commits July 4, 2026 03:25
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits July 12, 2026 19:41
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits July 13, 2026 10:39
…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]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
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]>
@mintlify

mintlify Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 14, 2026, 6:19 AM

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

03443_projection_sparse failed with Cannot parse string 'sumState' as UInt64 ... While executing ValuesBlockInputFormat on INSERT INTO t_projection_sparse VALUES ('bb', initializeAggregation('sumState', 0::UInt64)) — the Values expression-template parser appears to have matched the aggregate-function-name literal against a UInt64 placeholder. CI's own randomized-settings diagnosis reran it 181 times with the same settings and all passed, so it is a rare transient race, not specific to this PR (the same signature hit #110188 on 2026-07-13). There is no tracking issue for it yet.

The other red checks on this run are already tracked: the coverage-shard server abort cascade is the EXCHANGE TABLES race #110133 (fixes in progress: #110048, #109747), test_replicated_table_structure_alter is #110036 (fix in progress: #110145), and the stress-test UBSan signed-integer overflow in the DateTime64 → Time conversion has fix #110451 in progress.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Fix in a separate PR: #110637.

Root cause is not specific to this PR. The literal token map used by ConstantExpressionTemplate (added when begin/end were removed from ASTLiteral) is keyed by raw ASTLiteral*. ParserCastOperator synthesizes the 0 in 0::UInt64 as a literal that survives into the AST but is never tokenized. It carries no map entry of its own, but the allocator can hand it a freed address whose stale entry (from the discarded 'sumState' string-literal probe that the cast operator tries first) still exists. ConstantExpressionTemplate then finds the stale span, positions the 0 placeholder over the 'sumState' text (template dump initializeAggregation('sumState', CAST(-dummy-0, 'UInt64'))), and a later row feeds 'sumState' into the UInt64 placeholder.

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").
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Both are environment/harness defects, unrelated to this PR.

1. Integration tests (amd_tsan, 5/6): test_database_iceberg_seaweedfs_catalog

The catalog was never down. GET localhost:30160/v1/config returned 200 on all 314 polls (0 non-200). What the fixture never saw is the analytics bucket; the Connection refused in the traceback is just the final poll, after the container had already exited. This is a SeaweedFS bug.

From _instances-gw0/docker.log inside the logs.tar.gz artifact:

E0819 04:00:13.399354 mini.go:1583 Admin server error: failed to start worker gRPC server:
    failed to listen on port 33646: listen tcp :33646: bind: address already in use
F0819 04:02:13.607964 mini.go:1598 Admin server readiness check failed:
    admin server did not become ready at http://0.0.0.0:23646 after 240 attempts
seaweedfs-1 exited with code 255

weed mini derives the admin gRPC port as admin.port + GrpcPortOffset = 23646 + 10000 = 33646 (weed/command/mini.go:57,543-544 at tag 4.41, which the compose file pins). 33646 is inside the Linux ephemeral range (ip_local_port_range floor 32768), so one of mini's own startup dials can take it as an outbound source port before the admin server binds it. Upstream diagnosed that same race for weed mini in seaweedfs/seaweedfs#10209 but fixed it only in their test port allocator; the hard-coded default in mini.go still sits above the floor.

The bucket then goes missing because glog.Fatalf skips the defer close(allServicesReady), so ensureMiniTableBuckets (which creates -tableBucket=analytics, and runs only after <-allServicesReady) never runs. The Iceberg service itself was ready at 04:00:13, hence 200 forever with no bucket. The 240 x 500 ms readiness budget from 04:00:13.4 expires at 04:02:13.4, matching the Fatalf timestamp.

Fix in this repo is one line in tests/integration/compose/docker_compose_iceberg_seaweedfs_catalog.yml: pass an explicit -admin.port below 22768 so the derived gRPC port stays under the ephemeral floor. I will open that PR, and file the upstream issue with this reproducer.

2. Stress test (arm_tsan): not a deadlock

No TSAN report and no signal because nothing crashed. The server was over its own memory limit for the last 13 minutes of the run:

05:41  current RSS: 54.49 GiB, maximum: 49.32 GiB
05:53  current RSS: 49.67 GiB, maximum: 49.19 GiB

clickhouse-server.stress.log carries 101257 MEMORY_LIMIT_EXCEEDED lines. Every prepare_for_hung_check query returned Code: 241, so stress.py took its generic except Exception path and set have_long_running_queries = True. The hung check then died inside create_common_database before checking anything: the server threw 241 out of a connection handler (ServerErrorHandler: Code: 241 ..., 05:53:55.440) in the same second the runner's request aborted with [Errno 104] Connection reset by peer, and ConnectionResetError is not an HTTPError, so that retry loop does not cover it. With res != 0 and have_long_running_queries both true, the row is written as Hung check failed, possible deadlock found.

The label is wrong, but the row is not noise: it is a real memory-exhaustion signal wearing the wrong name. Over 30 days, of 1250 rows named exactly Hung check failed, possible deadlock found, only 17 contain Found hung queries. I have three open PRs on this reporting axis already (#113428, #114029, #112393) and would rather extend one than open a fourth. Say so if you would prefer a separate PR.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Signature 1 is fixed in #115512: -admin.port=12646 on the weed mini line, so the derived admin gRPC port is 22646 instead of 33646. Filed upstream as seaweedfs/seaweedfs#10838.

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 mini on image: latest, where the default is still 23646, and there the bucket each page tells the reader to create never appears while the container keeps answering 200.

Signature 2 is unchanged: still on your call between extending one of #113428 / #114029 / #112393 and opening a fourth PR.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 20, 2026
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.
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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:

Logical error: Sort order of blocks violated for column number 1, left: UInt64_4294966996, right: UInt64_4294966860. Chunk 0, rows read 280.
  src/Processors/Transforms/CheckSortedTransform.cpp:45
  ...
  src/Storages/MergeTree/MergeTreeBackgroundExecutor.cpp:383

and the follow-up Cannot start clickhouse-server / Check failed are downstream of that abort.

CIDB shows the same signature recurring on unrelated pull requests over the last 30 days (Stress test (arm_debug) / Stress test (arm_asan_ubsan)):

day PR
2026-08-21 #109368 (this one)
2026-08-11 #113575
2026-08-09 #101783
2026-08-06, 2026-08-05 #103182
2026-08-03 #110002
2026-07-27 #111990
2026-07-24 #111464

One of the earlier occurrences hit it from MutateTask (PartMergerWriter::mutateOriginalPartAndPrepareProjections), so it is the merge/mutation output that is mis-sorted, not the query path. I could not find an open tracking issue for it — it looks like it still needs one.

Master has been merged into this branch in 430202274baf, so the next CI run is on a fresh base.

@groeneai

Copy link
Copy Markdown
Collaborator

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 01763_long_ttl_group_by.sql's (its UUID 8f90028c-... resolves to comment: 01763_long_ttl_group_by.sql-test_3 in the err log). That schema assigns a sorting-key column from a GROUP BY TTL:

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

TTLAggregationAlgorithm writes the aggregated ts back without re-sorting, so a rewritten row can sort below an untouched one. The reported values confirm it: 4294966860 is 3-minute aligned (a post-SET value), 4294966996 is not (an untouched row), and column number 1 is the toStartOfInterval key.

One correction to the 2^32 reading: the near-max values are not a truncating narrowing, they are the trigger. max(ts) + INTERVAL 5 MINUTE overflows UInt32 (measured: 4294967029 + 300 wraps to 33), so a row near the DateTime maximum is judged expired while its neighbours are not. That partial group expiry is what interleaves aggregated and untouched rows. Ordinary timestamps do not reproduce it.

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 left: UInt64_4294966996, right: UInt64_4294966860. Dropping only ts = min(...) from the SET, keeping value = sum(value), makes it pass on the same data, which isolates the sort-key assignment as the cause.

Three notes on the CI side:

One gap: none of #108550's tests use toStartOfInterval or DateTime-max data, so this overflow-driven partial-expiry variant is not directly covered there. I will add it.

@groeneai

Copy link
Copy Markdown
Collaborator

Signature 2 has a fixing PR: #116545 (open). Same defect, surfaced on a different report: the hung check wrote possible deadlock found without ever reading system.processes, because its own queries were refused Code: 241 while the server was over a memory limit. It de-aggregates the startup probe and the processlist count, and replaces the bare except: in prepare_for_hung_check that turns "I could not tell" into "yes" with no log line.

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 CurrentMemoryTracker::check() at all, so no memory setting has to be lifted for it.

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: create_common_database retries only on a non-200 status, so a connection-level failure is re-raised past its loop and ends the run before the check starts. It belongs with #116545 and I will add it there rather than open a new PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Comment on lines +1097 to +1098
/// If the columns of any table expression cannot be determined, keep the strict behavior and require an alias.
if (columns_are_known)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

IMHO, this whole PR looks like a hacky fix

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reimplemented as suggested in #109368 (review): the eager check in QueryAnalyzer::validateJoinTableExpressionWithoutAlias is removed and ALIAS_REQUIRED is raised from IdentifierResolver::tryResolveIdentifierFromJoin / tryResolveIdentifierFromCrossJoin only when an identifier is actually ambiguous and one of the candidates comes from an unaliased subquery or table function (plus the equivalent check for *).

New PR: #117792

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The separate fix you asked for here is #119116: geohashesInBox now observes max_execution_time and KILL QUERY while it expands one row, at the same 65,536-unit granularity the other functions use. It does not change the hung check that surfaced on this PR, whose box is reversed and so expands to zero items; the shape the fix reaches is one legal box under the 10,000,000-item cap.

This branch was successfully deployed

1 active deployment
staging - docs — 5a234212 Deployed Aug 30, 2026 by mintlify[bot]
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-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants