Skip to content

Do not treat an equated INNER JOIN key as an ambiguous identifier - #109366

Merged
alexey-milovidov merged 16 commits into
masterfrom
inner-join-equi-key-not-ambiguous
Jul 31, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
inner-join-equi-key-not-ambiguous

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Resolves an unqualified column reference that binds to both sides of an INNER JOIN when the two columns are equated by a top-level equals conjunct of the ON condition, instead of throwing AMBIGUOUS_IDENTIFIER.

Motivation: for SELECT id FROM a INNER JOIN b ON a.id = b.id the join guarantees a.id = b.id on every output row, so id is not really ambiguous. Previously this only "worked" by accident when single_join_prefer_left_table = 1 silently picked the left side for a single join; with the setting disabled, or in a multi-way join whose later ON equates the exposed column by name on both sides - e.g. ... t1 INNER JOIN t2 ON t1.id = t2.id INNER JOIN t3 ON t1.id = t3.id, or a top-level identifier consumed by a later USING - the same query failed. The reference is now resolved to the left side - exactly the value single_join_prefer_left_table already produced - so the change only turns a previously-thrown ambiguity into that same result and never changes a query that already succeeded.

The relaxation is deliberately narrow and value-safe:

  • only unqualified (one-part) identifiers, so qualified and subcolumn name resolution is unaffected;
  • only INNER joins (an outer join can leave the non-preserved side default/NULL on unmatched rows);
  • only equalities reachable through a chain of and (an equality under or does not guarantee equal values);
  • only a direct equals of the two resolved columns in that join's ON (not a.id = b.id + 1, etc.). It does not chase a transitive equivalence class across the left subtree, so a multi-way chain whose later ON equates a key that is not the exposed left representative - e.g. ... t1 INNER JOIN t2 ON t1.id = t2.id INNER JOIN t3 ON t2.id = t3.id, where the left subtree exposes id as t1.id but the second ON names t2.id - stays ambiguous by design.
  • only an equality that is a property of the join itself, so an unqualified reference written inside the very ON that equates it - e.g. ... INNER JOIN t3 ON id = t3.id - is not covered and stays ambiguous as before: picking a side there would change the join condition rather than only the projected column (resolved to the right side the condition becomes trivially true). Such a reference keeps working only in the single-join case through single_join_prefer_left_table = 1, which is untouched.

02372_analyzer_join, 02374_analyzer_join_using and 03716_multiple_joins_using_top_level_identifier documented the old behavior and are updated. 04501_inner_join_key_column_not_ambiguous is added covering the new behavior, each guard rail (non-key columns, OR, LEFT JOIN, qualified/subcolumn identifiers, the transitive multi-way chain above, and a reference inside its own ON still raise AMBIGUOUS_IDENTIFIER), and the mixed-type equi-key semantics: the reference keeps the raw left type, identical to what single_join_prefer_left_table = 1 has always produced, in contrast to the common-type projection of USING.

Changelog category (leave one):

  • Improvement

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

An unqualified reference to an INNER JOIN key that is equated in the ON condition (e.g. SELECT id FROM a INNER JOIN b ON a.id = b.id) is no longer reported as an ambiguous identifier, since both sides are guaranteed to carry the same value.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.559 (included in 26.8 and later)

An unqualified column that resolves to both sides of an `INNER JOIN` was
reported as `AMBIGUOUS_IDENTIFIER` whenever `single_join_prefer_left_table`
could not silently pick a side - for example with that setting disabled, or in
a multi-way join. But when the two columns are equated by a top-level `equals`
conjunct of the `ON` condition, every joined row carries the same value on
both sides, so an unqualified reference is not actually ambiguous.

`tryResolveIdentifierFromJoin` now resolves such a reference to the left side,
exactly as `single_join_prefer_left_table` already did, so this only turns a
previously-thrown ambiguity into the same result the default already produced.
The relaxation is limited to `INNER` joins (an outer join may leave the
non-preserved side default or NULL on unmatched rows) and to equalities
reachable through a chain of `and` (an equality under `or` does not guarantee
equal values).

Existing tests `02372_analyzer_join`, `02374_analyzer_join_using` and
`03716_multiple_joins_using_top_level_identifier` documented the old behavior
and are updated accordingly; `04501_inner_join_key_column_not_ambiguous` is
added for the new behavior and its guard rails.

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 [65b641f]

Summary: ✅


AI Review

Summary

This PR narrows INNER JOIN ambiguity handling so that a bare identifier resolving to both sides is accepted only when the current ON condition directly equates the two resolved columns, and the final version also covers the isNotDistinctFrom (<=>) case. I re-checked the current code, tests, prior review threads, and current PR description, and the remaining edge cases raised earlier are either fixed in code or now explicitly documented and regression-tested as out of scope.

Final Verdict

✅ No new findings. The implementation matches the narrowed contract, the focused regression coverage is adequate for that scope, and current CI is green.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
alexey-milovidov and others added 7 commits July 3, 2026 23:00
The flaky check for the changed test `02374_analyzer_join_using` failed
with "Test runs too long (> 180s)": across 173 randomized runs the average
was ~58s but a tail reached ~197s, i.e. specific randomized MergeTree
storage settings (direct I/O thresholds, uncompressed cache, part storage,
prewarm, etc.) pushed individual debug runs past the 180s limit.

The test only exercises analyzer `JOIN` / `USING` identifier resolution and
join value semantics; the storage engine is incidental. Switching the three
tables from `MergeTree` to `Memory` removes the MergeTree-settings
randomization that drives the slow tail while keeping the output identical:
the `CREATE TABLE` statements sit before the `{ echoOn }` marker so they are
never echoed into the reference, and every query uses `ORDER BY ALL`, so row
sets and ordering are unchanged (verified: `MergeTree` and `Memory` produce
byte-identical results for the test queries). The `.reference` is therefore
unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109366&sha=823a06f7ab937f8bfd09e1024d11a33e5dbd4be9&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new test `04501_inner_join_key_column_not_ambiguous` documents behavior
that is specific to the new analyzer (an equated `INNER JOIN` key is not an
`AMBIGUOUS_IDENTIFIER`, while non-equated columns, `OR` conditions, and outer
joins still are). The "old analyzer" stateless job runs with
`enable_analyzer = 0`, where these queries resolve differently and do not throw
`AMBIGUOUS_IDENTIFIER`, so the `-- { serverError AMBIGUOUS_IDENTIFIER }`
expectations failed (3 out of 3 reruns).

Add `SET enable_analyzer = 1;` at the top of the test, matching the sibling
analyzer tests this PR already touches (`02372_analyzer_join`,
`02374_analyzer_join_using`), so the test always exercises the new analyzer
regardless of the job's default. The reference output is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109366&sha=5f98e8723f258ea37d813e553b7299664a560dd7

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The template expands to ~180 queries; under sanitizers with the flaky
check's 50 parallel reruns a single run can exceed the 180 second limit
("Test runs too long"). The sibling 02372_analyzer_join, with the same
4x4 join-matrix shape, already carries the `long` tag for this reason.
The flaky check exempts `long`-tagged tests from the run-time limit
(tests/clickhouse-test, FailureReason.TOO_LONG), so this fixes the only
PR-specific CI failure while preserving all coverage and the reference.

#109366
The review asked for a focused mixed-type regression that proves the
resulting identifier semantics. The semantics are deliberate: for
mixed-type equi-keys the unqualified reference resolves to the raw left
column - the same value and type that the default
`single_join_prefer_left_table = 1` has always produced for a single
join - and not a USING-like common-type projection. The new queries pin
`toTypeName(id)` to the left type (`UInt8`) for the relaxation path,
show it is identical to the pre-existing single-join default, cover the
multi-way join where `single_join_prefer_left_table` never applied,
and contrast with `USING (id)`, which keeps exposing the common-type
(`UInt16`) projection.

#109366
The `various_checks.sh` style check now rejects the phrases "new analyzer"
and "new query analyzer" in comments and docs (the analyzer is enabled by
default since ClickHouse 24.3 and is no longer new). The comment in
`04501_inner_join_key_column_not_ambiguous.sql` used "the new analyzer";
reword it to "the analyzer". "the old analyzer" is left as-is (the check
only forbids the "new" forms).

This surfaced on the `CH Inc sync` job (private sync PR
ClickHouse/clickhouse-private#63276), whose merge with private master
brought in the wording rule that the public PR's older merge-base predated.

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

clickhouse-gh Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR only relaxes the analyzer's AMBIGUOUS_IDENTIFIER handling so an unqualified column that is an equated key of an INNER JOIN resolves to the left side instead of erroring — a pure identifier-resolution change with no effect on the execution hot path, and it only runs for JOIN queries. The single flagged item, ClickBench Q4, has no join at all, so the diff cannot plausibly move its timing; the -24.7% delta falls within master's current variance band (201.5-294.0 ms) and was correctly held at no_change as run-to-run noise. The deterministic envelope suppression is consistent with the diff, and no cross-query pattern applies.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 03393864-3c7b-48f8-96d0-db14ae9fd42d
  • MIRAI run: c22fdf92-50e1-4fbb-87ac-8845fbdd7516
  • PR check IDs:
    • clickbench_719227_1785268660
    • clickbench_719240_1785268660
    • clickbench_719246_1785268660
    • tpch_adapted_1_official_719261_1785268660
    • tpch_adapted_1_official_719283_1785268660
    • tpch_adapted_1_official_719297_1785268661

…d identifiers

The equi-key relaxation in `innerJoinKeyColumnsAreEquated` was applied to every
ambiguous JOIN identifier lookup, not just the unqualified (one-part) column
references it is meant for. For a storage that exposes subcolumns as `ColumnNode`
(`supportsSubcolumns` is true), a compound identifier could bind to a left
subcolumn and a right column at the same time; when the `ON` condition equated
those two candidates, the relaxation silently resolved the ambiguity to the left
side instead of raising `AMBIGUOUS_IDENTIFIER`, changing qualified/subcolumn name
resolution semantics.

Gate the branch on `identifier_lookup.identifier.isShort()` so it only fires for
truly unqualified identifiers, matching the advertised behavior.

Reproducer (with `single_join_prefer_left_table = 0`), previously resolved to the
left subcolumn, now correctly raises `AMBIGUOUS_IDENTIFIER`:

    CREATE TABLE t_sub (p Tuple(q Int64)) ENGINE = Memory;
    CREATE TABLE p (q Int32) ENGINE = Memory;
    SELECT p.q FROM t_sub INNER JOIN p AS pr ON t_sub.p.q = pr.q;

Covered by a new case in `04501_inner_join_key_column_not_ambiguous`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 17, 2026 15:14
…ated INNER JOIN key relaxation

The equated `INNER JOIN` key relaxation (`innerJoinKeyColumnsAreEquated`)
matches a direct `equals` of the two resolved columns in the nearest join's
`ON`; it does not chase a transitive equivalence class across the left
subtree. So a multi-way chain whose later `ON` equates a key that is not the
exposed left representative - e.g.

    SELECT id FROM t1
    INNER JOIN t2 ON t1.id = t2.id
    INNER JOIN t3 ON t2.id = t3.id

with `single_join_prefer_left_table = 0`, where the left subtree exposes `id`
as `t1.id` but the second `ON` names `t2.id` - still (correctly) raises
`AMBIGUOUS_IDENTIFIER`, because `t1.id = t3.id` is not directly present.

This narrows the PR's claim to the implemented scope rather than expanding the
feature to full equivalence-class tracking (which would be a much larger,
riskier change). No source behavior changes: this commit only adds regression
coverage to `04501_inner_join_key_column_not_ambiguous` for the transitive
chain (stays ambiguous) and for the sibling shape whose later `ON` equates the
exposed representative `t1.id` directly (resolves), and rewords the PR
description accordingly.

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

Copy link
Copy Markdown
Member Author

@groeneai, please investigate these two CI failures on this PR and provide fixes in separate PRs. Both are unrelated to this change (it only touches IdentifierResolver.cpp and four JOIN tests) — both reproduce on master and across many other PRs, and neither has a tracking issue yet.

  1. Stateless tests (amd_tsan, parallel) — 04625_hash_table_sizes_stats_table_expression_modifiers: the no-final branch reports no-final-prealloc 0 instead of the expected 650000, i.e. the hash-table size statistics were not collected/applied for the non-FINAL query. play.clickhouse.com shows this failing on master (pull_request_number = 0, 2026-07-24 and 2026-07-26) and on ~12 unrelated PRs over the last few days.
    Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109366&sha=${SHA}&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29

  2. Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) — Server died with Logical error: '!part.empty()' (STID: 2735-47bf), which in turn broke 03304_fill_virtual_columns. This exact logical error recurs on master in the same job (2026-07-23 … 2026-07-25) and in the AST fuzzer across many PRs.
    Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109366&sha=${SHA}&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%202%2F3%29

If a fix for either is already in progress, please link it here.

The remaining two reds — Stress test (arm_asan_ubsan) (Cannot start clickhouse-server) and Upgrade check (amd_release) (Failed to read version metadata for part … Cannot parse input) — are the known corrupted txn_version.txt problem tracked by #111053, with #111922 already open for it.

@groeneai

Copy link
Copy Markdown
Collaborator

Both are already owned, so no new PRs from me.

1. 04625_hash_table_sizes_stats_table_expression_modifiers - fix in progress in your own #111502.

The culprit is the randomized max_bytes_before_external_group_by. The run on 3a472ad9 minimized to --max_bytes_before_external_group_by 43754681, the master run on 10116111 (2026-07-26 02:18) to 67836231, the earlier master run on 9a5b5235 to 52303827. Once the aggregation spills to disk the hash-table-stats collection stops for that query, so AggregationPreallocatedElementsInHashTables reads 0. Only the no-final line flips because the FINAL query aggregates 520e3 groups instead of 650e3, so its state stays under the randomized threshold and it still preallocates.

#111502 pins max_bytes_before_external_group_by=0 and max_bytes_ratio_before_external_group_by=0 in the test's settings array, which covers exactly this shape, and 04625 is OK on every shard of its own run 955837af. 30d CIDB for the test name: 18 hits over 14 distinct PRs plus 3 on master, all the same one-line diff.

2. Logical error '!part.empty()' (STID 2735-47bf) - a tracking issue does exist, #110133. Your search missed it because the reported label is a CI-reporter misattribution, not the real message.

ci/jobs/scripts/log_parser.py names the failure from the first Logical error... match in the server log. In the coverage 2/3 log for 3a472ad9 there are exactly two matches. Line 67639 is an SQL comment echoed back by executeQuery inside an ordinary handled TYPE_MISMATCH exception from 04367_lambda_arg_backquoted_dot_no_logical_error.sql (14:31:44). Line 120039 is the only genuine abort (14:36:56):

Logical error: 'Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64''
FunctionBinaryArithmetic.h:3360 -> IFunction.h:532 executeImplDryRun
  -> ActionsDAG.cpp:1286 executeActionForPartialResult -> :1568 evaluatePartialResult -> :1402 updateHeader
  -> ExpressionTransform::transformHeader -> InterpreterSelectQuery::executeImpl
query_id 91fd5b25-2c1d-466c-9b66-406bfb11ad3d, query: SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1)

That query is 03915_exchange_tables_race: EXCHANGE TABLES swaps n between Int256 and Float64 while the SELECT is being planned. Server died and the 03304_fill_virtual_columns ERROR are collateral of that single abort; servers 1 and 2 have zero <Fatal> lines.

Fixes in progress: #110048 (yours, read consistency for renamed or exchanged tables - the root cause), #109747 (guard in partial-result evaluation), #111708 (the reporter misattribution itself, so the label stops hiding the real message).

Do not conflate this STID with 5217-5b3d / 5217-505b on the ParallelReplicas coverage job: different root cause (unknown-stream throw), issue #110518, fix #111689.

Address review: `innerJoinKeyColumnsAreEquated` only recognized `equals`,
but a null-safe equality `<=>` (`isNotDistinctFrom`) is a join-key carrier
for the planner as well - see the `equals`/`isNotDistinctFrom` handling in
`PlannerJoins.cpp`. As a result `SELECT a FROM t1 INNER JOIN t2 ON t1.a <=> t2.a`
still threw `AMBIGUOUS_IDENTIFIER` with `single_join_prefer_left_table = 0`,
even though every surviving row carries the same value on both sides.

`isNotDistinctFrom` is in fact a stronger guarantee than `equals` here: a
surviving row has either the same non-NULL value or `NULL` on both sides, so
resolving the unqualified reference to the left side is exactly as safe.

Adds regressions to `04501_inner_join_key_column_not_ambiguous`: a direct
`<=>` key, the same inside an `and` chain mixed with a plain `equals`
conjunct, and a negative case pinning that a non-key column stays ambiguous
under a null-safe join key.
…pe as ambiguous

`innerJoinKeyColumnsAreEquated` matches an `equals`/`isNotDistinctFrom` of the two
already resolved columns, so a reference written inside the very `ON` that equates it,
as in `... INNER JOIN t3 ON id = t3.id`, is not covered: at that point that side of the
equality is still the identifier being resolved, and picking a side would change the join
condition itself (resolved to the right side it becomes trivially true), so the "both sides
carry the same value" justification does not apply.

Confirmed by experiment that this shape throws `AMBIGUOUS_IDENTIFIER` both in the multi-way
form (regardless of `single_join_prefer_left_table`) and in the single-join form with
`single_join_prefer_left_table = 0`, exactly as before this change; the single-join form with
`single_join_prefer_left_table = 1` keeps working. All four cases are now pinned in
`04501_inner_join_key_column_not_ambiguous`.
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.50% +0.10%

Changed lines: Changed C/C++ lines covered: 31/33 (93.94%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jul 31, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 31, 2026
Merged via the queue into master with commit 2258505 Jul 31, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the inner-join-equi-key-not-ambiguous branch July 31, 2026 22:43
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants