Skip to content

Fix AMBIGUOUS_COLUMN_NAME in a correlated subquery over a Nullable key whose isNull is an outer GROUP BY key - #132567

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-null-safe-join-key-name-collision
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-null-safe-join-key-name-collision

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129971
Related: #104350

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Since #129971 (master only, not in any release branch), this query fails:

SELECT a, (SELECT isNull(a))
FROM (SELECT toNullable(number) AS a FROM numbers(2)) AS o
GROUP BY a, isNull(a) WITH ROLLUP
SETTINGS group_by_use_nulls = 1;
-- Code: 352 ... different types: isNull(__table3.a) UInt8 ... isNull(__table3.a) Nullable(UInt8) (AMBIGUOUS_COLUMN_NAME)

With group_by_use_nulls = 0 it runs, but isNull(a) selected next to it reads 1 instead of the rolled-up 0 in the
grand-total row. It turned
test 04210 of #104350 red (CI report).

Root cause: #129971 joins the decorrelated subquery on its Nullable key with NullSafeEquals. JoinStepLogical
splits such a key into isNull(x) and if(isNull(x), d, assumeNotNull(x)) (or wraps it in tuple(x)), and these
took their default names. The outer side of that join is the stream after GROUP BY, which already has a column
isNull(__table3.a), so the join saw two columns of one name.

The change names these key expressions like TableJoin names its __wrapNullsafe wrapper: the default name unless an
input of the join already has it, then a _N suffix. Joins without such a collision keep identical names.

Validation: each query of the new test fails on master and passes with the fix (ROLLUP, CUBE, GROUPING SETS, EXISTS,
group_by_use_nulls = 0, both correlated_subqueries_default_join_kind values). The existing correlated-subquery,
null-safe-join and group_by_use_nulls tests pass, except 3 that need fixtures I do not have locally and fail the same
way on master. Ordinary expressions I tried do not take the if(...) or tuple(x) key names (the analyzer unwraps a
tuple in GROUP BY), so the test forges them, and an occupied _0, with the internal __actionName.

Reverting #129971 also removes the error, but brings back the wrong results it fixed (#112576).


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

groeneai and others added 2 commits November 18, 2026 02:23
Since ClickHouse#129971 the decorrelation join of a correlated scalar or EXISTS
subquery compares a Nullable correlated key with `NullSafeEquals`.
`JoinStepLogical` turns such a key into `isNull(x)` plus
`if(isNull(x), d, assumeNotNull(x))` (or `tuple(x)`), and these wrappers
took the default DAG name built from the key, e.g. `isNull(__table3.a)`.

The outer side of the decorrelation join is the stream after `GROUP BY`,
so it can already carry a column of that exact name: the GROUP BY key
`isNull(a)`. The join header then had two columns of one name:
- with `group_by_use_nulls = 1` and ROLLUP/CUBE/GROUPING SETS they differ
  in type (`Nullable(UInt8)` vs `UInt8`) and the query fails with
  `Code: 352 ... columns with identical name must have identical structure
  (AMBIGUOUS_COLUMN_NAME)`;
- with equal types the name-keyed lookup binds the synthesized key, so the
  outer `isNull(a)` of a ROLLUP subtotal row reads 1 instead of the rolled-up 0.

Ordinary joins never hit this because their inputs are `__tableN.`-qualified
columns. Name the three wrappers like `TableJoin`'s `__wrapNullsafe` does:
keep the default name unless an input of the join's DAG has it, then
append `_<i>`. Plans without a collision keep byte-identical names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The earlier queries of 05828 collide only with the `isNull(x)` key, so a
regression in the naming of the `if(isNull(x), d, assumeNotNull(x))` value
key, of the `tuple(x)` wrap, or of the `_N` suffix loop would go unnoticed.
Ordinary expressions do not take those names, so the new queries forge an
outer `GROUP BY` key with the internal `__actionName`: one named like the
`if` key, one like the `tuple` key, and one occupying `isNull(x)_0` next to
the colliding `isNull(x)` key. Each fails on master (Code 352) and fails
again when only its own naming path is reverted to the default name (or,
for the loop, to an unchecked `_0`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding over 2 rounds) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ Only the isNull key collision was tested; the if and tuple key names and the _N loop were not AGREE, fixed @ 261735f 3 queries forge those names with __actionName; each fails on master and under a mutation of only its own path
2 💡 The helper repeats TableJoin's makeColumnNameUnique scheme DISAGREE that function is file-static over ColumnsWithTypeAndName; these are ActionsDAG inputs
3 💡 The forged names hard-code __table3 noted, not blocking a renumbering only makes those 3 queries stop colliding; they cannot fail falsely

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261118-030700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The query in the description throws Code: 352 (isNull(__table3.a) as UInt8 and Nullable(UInt8)) on every run on master 9b10750; with group_by_use_nulls = 0 the grand-total row's isNull(a) reads 1 on every run.
b Root cause explained? JoinStepLogical gave the null-safe key wrappers (isNull(x), if(isNull(x), d, assumeNotNull(x)), tuple(x)) their default names. Since #129971 the decorrelation join uses such keys, and its outer input (the stream after GROUP BY) already has a GROUP BY key column of the same name, so the join header holds two columns of one name: different types throw, equal types bind the wrong one.
c Fix matches root cause? Yes. The join no longer names a key it synthesizes like one of its inputs (default name, else a _N suffix), as TableJoin does for __wrapNullsafe. No guard at the throw site, no setting change.
d Test intent preserved / new tests added? New stateless test 05828_correlated_subquery_null_safe_key_name_collision: 6 queries of user-reachable shapes, plus 3 that forge the if, tuple and occupied _0 names with the internal __actionName; no existing test changed.
e Both directions demonstrated? Yes. Runner: [ FAIL ] with Code: 352 against a master server, [ OK ] against the fix. Per query on master: 8 throw, 1 returns a wrong value; on the fix all 9 equal an uncorrelated oracle over materialize(). Each forged-name query also fails under a mutation of only its own naming path (unchecked _0, default if name, default tuple name). The first parent of #129971 runs the first 6, so #129971 introduced both symptoms. 50/50 randomized runs OK.
f Fix is general across code paths? All three wrappers (isNull, the if value key, tuple) use one helper in addJoinPredicatesToTableJoin, which every null-safe join goes through (scalar and EXISTS decorrelation, LATERAL, the restore join, ordinary <=> joins). Of the other nodes the join adds, assumeNotNull and the default constant are never outputs, and the casts are not added for decorrelation keys (both sides have the outer column's type).
g Fix generalizes across inputs (params/datatypes/wrappers)? ROLLUP, CUBE, GROUPING SETS; group_by_use_nulls 0 and 1; scalar and EXISTS; both join kinds. Key types Nullable(UInt64), LowCardinality(Nullable(UInt32)), Nullable(Date) fail on master and pass with the fix; Nullable(String) uses the tuple key, which only a forged name reaches (tested).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or serialization change. Names change only when they would collide: EXPLAIN actions = 1 of the null-safe joins in 05224_null_safe_join_fixed_keys is byte-identical before and after.
i Invariants and contracts preserved? Invariant: a key the join synthesizes never shares its name with an input of the join's DAG (which holds both sides' inputs). Two non-input nodes of one name are the same function of the same inputs, so they are left alone. The suffix loop terminates (finitely many inputs).

Session id: cron:clickhouse-impl-slot-5:20261118-024900

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [261735f]

Summary: ✅


AI Review

Summary

The PR prevents synthesized null-safe join keys from shadowing input expressions, fixing exceptions and incorrect results for correlated subqueries over ROLLUP, CUBE, and GROUPING SETS. Reviewed head 261735fa26e58feb5a097c629e2bc9db428c8dc9 and all prior discussion; no actionable findings. The new nine-query regression test and existing null-safe join tests pass in Fast test.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 261735fa2 with master 3634df08e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.84 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 8.7 s 17.1 s +9.8 s (+134%)
Compile time of recompiled translation units

7 translation units recompiled, 33 s compile time in total, 7 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants