Skip to content

Keep a Tuple element's Nullable in the merged JOIN USING key type - #118902

Merged
vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-join-using-merged-key-nullable-tuple-element
Sep 10, 2026
Merged

vdimir merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-join-using-merged-key-nullable-tuple-element

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

---8<--- PR BODY BELOW ---8<---

Related: #112951
Related: #117409

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

Requested by @ nickitat in #117409 (comment).

Projecting the USING key of an INNER or SEMI join whose keys have no least supertype throws, while
the same join without that projection answers correctly:

SELECT t
FROM (SELECT tuple(if(number = 0, NULL, CAST(1, 'Nullable(Int64)'))) AS t FROM numbers(2)) AS a
INNER JOIN (SELECT tuple(CAST(1, 'UInt64')) AS t) AS b USING (t);
-- Code: 349. Cannot convert NULL value to non-Nullable type

count() over that join answers 1 and ON a.t = b.t returns (1), so the row the projection failed on
is one the join drops.

The merged USING column is materialized by converting a whole key column to the type the analyzer
publishes, and it runs before the join filters anything, so that type has to hold every value the source
keys hold. resolveJoinUsing enforces that at the top level only: getMostSubtype drops the Nullable
of a Tuple element when the other side has none, which a top-level test cannot see, so the published type
was Tuple(UInt64).

I ask getMostSubtype for the merged type in its force_support_conversion mode, documented as "a type
which may be used to convert each argument to". The published type becomes Tuple(Nullable(UInt64)) and
the existing conversion becomes total. The key comparison keeps the default mode, which is what its
accurateCastOrNull needs: a key with no representation must be reported by a NULL of the whole key, not
of one element. The modes differ only where an element is Nullable on exactly one side.

Worth knowing: for such a key USING now publishes Tuple(Nullable(U)) where it published Tuple(U),
and the qualified columns of both sides agree on it. Master only since #112951, so no backport;
04669_join_key_no_supertype is unchanged. Passing false for the new argument reddens the new test.


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

The merged USING column is materialized by converting a whole key column to
the type the analyzer publishes for it, and that conversion runs before the
join filters anything: `buildJoinUsingCondition` registers a plain `_CAST`
into that type, and `convertToPhysical` places it in the pre-join DAG. The
published type therefore has to hold every value the source keys hold.

`resolveJoinUsing` applies that rule at the top level only, publishing
`makeNullable(subtype)` when either source key is Nullable. `getMostSubtype`
drops the `Nullable` of a Tuple element when the other side's element has
none, and that nullability is invisible to a top-level test, so for
`Tuple(Nullable(Int64))` joined against `Tuple(UInt64)` the published type
was `Tuple(UInt64)` and a NULL element failed the conversion:

    SELECT t
    FROM (SELECT tuple(if(number = 0, NULL, CAST(1, 'Nullable(Int64)'))) AS t FROM numbers(2)) AS a
    INNER JOIN (SELECT tuple(CAST(1, 'UInt64')) AS t) AS b USING (t);
    -- Code: 349. Cannot convert NULL value to non-Nullable type

`count()` over that same join answers 1 and `ON a.t = b.t` returns `(1)`, so
the row the projection failed on is one the join drops anyway.

Ask `getMostSubtype` for the merged USING type in its `force_support_conversion`
mode, whose documented contract is exactly "a type which may be used to convert
each argument to": the published type becomes `Tuple(Nullable(UInt64))` and the
existing conversion becomes total. The key comparison keeps the default mode,
which is what `predicateOperandsToCommonType`'s `accurateCastOrNull` needs, a
value with no representation being reported by a NULL of the whole key rather
than of one element. The two modes differ only where a Tuple element is
Nullable on exactly one side. On master the key site strips such elements
itself (`removeNullableInsideTuple`), so the two modes could also be one; the
parameter keeps each call site's target explicit and leaves the key path's
computation unchanged.

Related: ClickHouse#112951
Related: ClickHouse#117409
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026 •

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

Independent-model gate (codex) plus my own cold pass: 5 findings, 1 fix round.

# Sev Finding Verdict
1 ⚠️ Did not merge with master: conflict in JoinUtils.cpp against #117409, merged meanwhile AGREE, fixed @ c7a5e99. Re-measured against the current tip: merges clean, no churn in the touched files since the base
2 💡 The new JoinUtils.h paragraph restated removeNullableInsideTuple's doc, 7 lines above AGREE, fixed @ c7a5e99: cross-reference instead
3 💡 The commit message's key-path sentence was incomplete on the merged base AGREE, fixed @ c7a5e99
4 💡 JoinUtils.h reads as saying force mode keeps a Nullable element and that a key target must have none AGREE on wording, DISAGREE that it is wrong: JoinUtils.h:103 states that contract in the same words. The two targets differ: the equality-comparison target must have no Nullable element, the merged USING output target must keep one

I kept the parameter rather than always forcing and relying on the strip at the key site: on current
master both are behaviourally identical, but the second makes this correctness depend on a strip done in
another file for another reason.

Session id: cron:clickhouse-review-slot-9:20260908-210300

@clickhouse-gh clickhouse-gh Bot closed this Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c7a5e99]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer-side JOIN ... USING subtype fallback for tuple keys by preserving a one-sided tuple-element Nullable in the published merged-key type, so the pre-join cast used for the projected USING column no longer throws on rows the join would discard anyway. I did not find a correctness, safety, or performance issue in the updated flow: the projected-column cast stays separate from the actual join-key conversion, which still goes through the existing accurateCastOrNull path, and the new stateless test exercises the failing projection, side-qualified output, SEMI behavior, and an out-of-range element case.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit c7a5e99.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd, could you review this? resolveJoinUsing publishes getMostSubtype's result as the merged USING column type, but that subtype drops a Tuple element's Nullable when the other side has none, and the whole key column is converted into it before the join filters anything, so projecting the key threw Code: 349 on a row the join drops anyway. I ask getMostSubtype for the merged type in its force_support_conversion mode and leave the key comparison on the default mode.

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c7a5e9943 with master a63831d1f (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.

Compile time of recompiled translation units

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

Job report

@@ -0,0 +1,15 @@
A Tuple element that is Nullable on one side only
1
(1) Tuple(Nullable(UInt64))

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.

What type we had before change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Tuple(UInt64): getMostSubtype dropped the element Nullable because only the left key carried it.

On the statement this line comes from that type is not observable, because the conversion of the whole key column runs before the join filters anything, so it fails instead of printing a type (master fb2a5923):

SELECT t, toTypeName(t) FROM ... USING (t);
-- Code: 349. Cannot convert NULL value to non-Nullable type: while executing
-- 'FUNCTION _CAST(__table1.t, 'Tuple(UInt64)'_String) -> Tuple(UInt64)'

DESCRIBE (SELECT t FROM ... USING (t));
-- t    Tuple(UInt64)

The old type is reachable only when the key column happens to hold no NULL, and that case is the one behavior change here. Merged USING key type:

key types (left / right) master this PR
Tuple(Nullable(Int64)) / Tuple(UInt64), a NULL present Code: 349 Tuple(Nullable(UInt64))
the same types, no NULL in the data Tuple(UInt64) Tuple(Nullable(UInt64))
Tuple(Nullable(UInt64)) / Tuple(Nullable(Int64)) Tuple(Nullable(UInt64)) unchanged
ON a.t = b.t instead of USING Tuple(Nullable(Int64)) / Tuple(UInt64) unchanged

Row 2 is the same test query with tuple(CAST(number + 1, 'Nullable(Int64)')) on the left: identical result rows, only the element type gains Nullable. That fallback subtype for keys with no least supertype landed in #112951 on 2026-08-29 and is not in a release, so no released type changes. The old value cannot be pinned in the .reference (one binary per run); the bottom two rows are in the test as controls.

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.

For USING projection colum shouln't we alway use supertype, rather then subtype?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, and that is what happens today: resolveJoinUsing computes tryGetLeastSupertype(expression_types) first and publishes it whenever it resolves. The subtype is reached only under !common_type, which is the case #112951 added it for, so this PR does not change which of the two is chosen. It changes only what the fallback subtype looks like.

Published merged USING type, master 7d76bcdf (without this PR):

left / right key published type
Tuple(Nullable(Int32)) / Tuple(UInt32) Tuple(Nullable(Int64)) supertype; element Nullable kept, and SELECT t works with a NULL present
Tuple(Nullable(Int64)) / Tuple(UInt64), LEFT or FULL Code: 386 NO_COMMON_TYPE no supertype, and the fallback is INNER/SEMI only
Nullable(Int64) / UInt64 Nullable(UInt64) fallback, top-level Nullable kept; the query returns 1
Tuple(Nullable(Int64)) / Tuple(UInt64), INNER Tuple(UInt64) fallback, element Nullable dropped, hence the Code: 349

Row 2 is where the absence of a supertype is visible: with LEFT the fallback does not apply, so the query stops at cannot infer common type for Tuple(Nullable(Int64)) and Tuple(UInt64). getLeastSupertype refuses that pair with "there is no signed integer type, that can exactly represent all required unsigned integer values", and the analyzer asks for the plain supertype, not the Variant form if uses by default, so there is nothing to publish for it.

Rows 1 and 3 both keep nullability, row 4 is the only one that drops it, and this PR makes row 4 agree with them. So no subtype is published where a supertype exists.

The other option for row 4 is to refuse it too, back to NO_COMMON_TYPE for a Tuple key whose element is Nullable on one side only. count() over that join answers 1 today, so that turns a working query into an error, which is why I did not pick it. Happy to switch if you prefer the refusal.

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.

Why we edited getMostSubtype call then?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Because for this pair there is no supertype to publish, so the fallback is what produces the type, and that call is its only producer. tryGetLeastSupertype at QueryAnalyzer.cpp:5770 returns nullptr for Tuple(Nullable(Int64)) and Tuple(UInt64), the fallback at :5791 runs, and the argument I added changes what it yields from Tuple(UInt64) to Tuple(Nullable(UInt64)). The supertype-first order above it is untouched.

The helper has exactly two callers, with opposite requirements, and only the projection one is switched:

  • projection (resolveJoinUsing): the published type is materialized as a plain _CAST over the whole key column, before the join, before any row is dropped (cast_to_super, PlannerJoinsLogical.cpp:221-224), so it has to hold every source value. That is what the flag is documented to give: "returns type which may be used to convert each argument to" (getMostSubtype.h:14).
  • key comparison (predicateOperandsToCommonType, JoinStepLogical.cpp:781): unchanged, default mode, and it additionally strips Nullable from Tuple elements at :784, so a key value with no representation in the subtype becomes a top level NULL and matches nothing. The tree already keeps the two targets apart: the comment at :808 records that the projection casts cannot be reused as the key conversions.

With that one argument set back to false and nothing else changed, 4 of the 8 statements of the new test fail with Code: 349, while the 4 controls (count(), the ON form, out of range, Nullable on both sides) are unchanged.

The one other place this could be fixed is the projection cast itself: keep Tuple(UInt64) published and convert with accurateCastOrNull plus assumeNotNull. I did not take it because trackInputColumn walks exactly those type change nodes and throws LOGICAL_ERROR for any function other than toNullable, CAST and _CAST (optimizeJoin.cpp:1148).

If you prefer either of the alternatives, that one or the refusal from my previous comment, tell me which and I will switch.

@vdimir vdimir self-assigned this Sep 10, 2026
@vdimir
vdimir added this pull request to the merge queue Sep 10, 2026
Merged via the queue into ClickHouse:master with commit 67eb3ec Sep 10, 2026
174 of 344 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog 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