Skip to content

Fix MULTIPLE_EXPRESSIONS_FOR_ALIAS on SELECT * over JOIN under parallel replicas - #104303

Closed
devcrafter wants to merge 15 commits into
masterfrom
fix-pr-multiple-expr-alias-on-join
Closed

devcrafter wants to merge 15 commits into
masterfrom
fix-pr-multiple-expr-alias-on-join

Conversation

@devcrafter

@devcrafter devcrafter commented May 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix MULTIPLE_EXPRESSIONS_FOR_ALIAS when serializing a QueryNode whose projection has duplicated column names (e.g. SELECT * over a JOIN) for distributed dispatch.


Partial progress on #74324.

QueryNode::toASTImpl always emits AS <name> for every projection. After createUniqueAliasesIfNecessary qualifies tables as __tableN, a SELECT * over a JOIN produces __table1.a AS a, __table3.a AS a — duplicate alias, two different expressions — which the analyzer rejects when re-resolving the dispatched AST on a remote replica.

Fix: skip the alias only when the projection column name is duplicated within the same projection.

Verification (debug build, parallel replicas enabled):

  • new test 04209_pr_join_using_alias_collision: 100/100
  • 00597_push_down_predicate_long: 100/100 (removed from parallel_replicas_blacklist.txt)

02559_multiple_read_steps_in_prewhere was also listed under #74324 but fails on a different PREWHERE alias-substitution pattern; left blacklisted.

…llel replicas

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

clickhouse-gh Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [184113a]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
02971_functions_to_subcolumns_variant FAIL cidb
02999_scalar_subqueries_bug_1 FAIL cidb
03285_analyzer_extract_common_expr_bug FAIL cidb
02116_tuple_element_analyzer FAIL cidb
03702_optimize_inverse_dictionary_lookup_composite_and_layouts FAIL cidb
03448_analyzer_array_join_alias_in_join_using_bug FAIL cidb
03454_global_join_index_subqueries FAIL cidb
01754_cluster_all_replicas_shard_num FAIL cidb
04101_common_expression_single_arg_collapse FAIL cidb
00409_shard_limit_by FAIL cidb
113 more test cases not shown
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR targets MULTIPLE_EXPRESSIONS_FOR_ALIAS for SELECT * over JOIN under parallel replicas, but the current head (184113a) disables projection-alias emission in QueryNode::toASTImpl instead of narrowing the fix to the collision case. That changes the QueryNode -> AST contract globally and can alter column-name semantics during distributed re-analysis.

Findings

❌ Blockers

  • [src/Analyzer/QueryNode.cpp:509] The whole projection_columns alias-assignment block is commented out, so aliases are dropped for every query, not just duplicate-source SELECT */JOIN projections. resolveProjectionColumns and setProjectionAliasesToOverride still define required output names (including subquery column alias overrides and generated unique aliases), but those names are no longer serialized back to AST. This can make remote/distributed re-analysis observe different projection names than the analyzed query tree.
    Suggested fix: restore alias emission and suppress AS <name> only for the specific conflicting duplicate-source ColumnNode case.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Re-enable alias emission in QueryNode::toASTImpl and keep suppression narrowly scoped to true duplicate-source collisions.
  2. Add focused regression coverage for alias-override round-trips (e.g., subquery column alias lists / generated unique aliases), not only the SELECT */JOIN case.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 7, 2026
@devcrafter
devcrafter marked this pull request as draft May 7, 2026 14:28
@devcrafter
devcrafter marked this pull request as ready for review May 11, 2026 17:46
@devcrafter
devcrafter requested review from novikd May 11, 2026 17:46
@novikd novikd self-assigned this May 12, 2026
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request May 17, 2026
Address reviewer feedback by moving the `PREWHERE` half of the fix out
of `queryNodeToDistributedSelectQuery` and into the analyzer itself.

The original PR postprocessed the AST after `queryNodeToDistributedSelectQuery`
to clear aliases from constraint clauses. Reviewers (ClickHouse#103806 review threads
at `Utils.cpp:214`, `:223`, `:267`) flagged the approach as a "mechanical
fixup of something already broken" and asked for a deeper fix in the query
tree. This commit implements that.

Root cause (traced in `QueryAnalyzer::resolveQuery`):

* When resolving `PREWHERE cond` where `cond` is a projection alias, the
  analyzer deep-clones the alias body and registers the clone's root in
  `scope.aliases.node_to_remove_aliases` (see line ~1135 of
  `QueryAnalyzer.cpp`). The clone's *descendants*, which carry the inner
  aliases (e.g. `cond1`, `cond2`) from the original projection body, are
  not registered.
* `PREWHERE` then deep-clones the tree a second time so that
  `ReplaceColumnsVisitor` can rewrite types for `JOIN USING` without
  leaking back into the projection. After this clone the originally-
  registered node is no longer in the query tree, while the new clone's
  root carries the `cond` alias and is unregistered.
* The cleanup loop at line ~5840 calls `removeAlias` on each registered
  node non-recursively, so the projection's inner aliases get cleared
  while `PREWHERE`'s do not. When the AST is shipped to a remote replica
  under `parallel_replicas_local_plan = 0` the receiver sees the same
  alias bound to two different bodies and throws
  `MULTIPLE_EXPRESSIONS_FOR_ALIAS`.

Fix:

1. Make alias removal recursive in `QueryAnalyzer.cpp`: walk each
   registered node top-down and clear aliases on every descendant,
   stopping at `QUERY` / `UNION` / `LAMBDA` boundaries (those are
   separate scopes that handle their own cleanup).
2. Register the post-clone `prewhere_node` in `node_to_remove_aliases`
   so the recursive walk reaches its inner aliases.

`Utils.cpp` no longer touches `PREWHERE` / `WHERE` / `HAVING` /
`QUALIFY`. The empirical check in the issue thread showed only `PREWHERE`
ever triggered the asymmetry; the rest of the constraint clauses were
dead code in the postprocess and are dropped together with it.

The duplicate-projection-alias dedup remains in
`queryNodeToDistributedSelectQuery` for now: it covers case 2 of the
regression test (`SELECT *` over a self-join with overlapping column
names) and a different root cause is being addressed in ClickHouse#104303 by
@devcrafter. Once that lands the dedup here can be removed.

Verified locally with the new binary against the regression test
`04145_multiple_expressions_for_alias_parallel_replicas` and the
original repro from ClickHouse#74324; both pass. Existing alias tests
(`00057_join_aliases`, `00138_table_aliases`,
`00157_aliases_and_lambda_formal_parameters`) remain green.

Refs ClickHouse#74324
Refs ClickHouse#103806 (comment)
Refs ClickHouse#104303

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Analyzer/QueryNode.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 95.00% (19/20) · Uncovered code

Full report · Diff report

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

It'd be better to find out the reason for such kind of clushes.

Comment thread src/Analyzer/QueryNode.cpp Outdated
Comment on lines +531 to +533
auto [it, inserted] = first_column_by_name.try_emplace(column_name, current_column);
if (!inserted && it->second->getColumnSourceOrNull() != current_column->getColumnSourceOrNull())
continue;

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.

It does not look like a good solution because it does not fix the query sent, but it "supresses" an error on the shard.
What is the reason that different expressions have the same aliases?

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.

It doesn't suppress error on the shard, it doesn't allow generating the same aliases for different columns.

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.

The another question - why should we generate here aliases?

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.

projection_columns aliases are currently dropped for every query here because the whole alias-assignment block is disabled.

That changes more than the SELECT */JOIN collision case. projection_columns is also where override aliases are stored (for example, subquery column alias syntax via setProjectionAliasesToOverride). Those names are not guaranteed to exist as node aliases, so without this block they are lost during QueryNode -> AST serialization.

As a result, distributed/parallel-replica re-analysis can observe different projection names than the analyzed query tree contract.

Can we keep alias emission and only suppress it for the conflicting duplicate-source case, instead of disabling aliases globally?

ast_with_alias->setAlias(projection_columns[i].name);
}
}
// if (!projection_columns.empty())

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.

projection_columns alias emission is disabled for all projections here because the entire block is commented out.

That changes behavior beyond the SELECT */JOIN collision case: alias override paths (for example setProjectionAliasesToOverride used for subquery column alias lists and generated unique aliases) still populate projection_columns, but those names are no longer serialized into the dispatched AST. Remote re-analysis can then observe different projection names than the analyzed query tree.

Can we restore alias emission and only suppress AS <name> for the narrow conflicting duplicate-source ColumnNode case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants