Skip to content

Fix the JOIN key conversion to a common subtype for a Tuple key with Nullable elements - #117409

Merged
nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-join-key-common-subtype-tuple-nullable-element
Sep 8, 2026
Merged

nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-join-key-common-subtype-tuple-nullable-element

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117102
Related: #112951

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

An INNER JOIN on Tuple keys whose integer elements differ in signedness returned a row count depending
only on join_algorithm: 1 for the three hash algorithms, 2 for partial_merge and
full_sorting_merge. Reachable since #112951, on master only, hence Not for changelog; before it the
query was rejected.

Root cause: getMostSubtype keeps the element nullability, so the accurateCastOrNull target is
Nullable(Tuple(Nullable(UInt64))), where a genuine source NULL lands inside the tuple, not at the top
level. Only the hash family looks there, folding those elements into its null-key map; the merges strip
only the top level and compare the nested tuples, where NULL equals NULL.

The fix removes the Nullable wrappers of the target's elements, so both a genuine NULL and an
out-of-range element are reported at the top level, the only representation a merge algorithm can handle,
its input being sorted by the key. All five now agree on 1 row, the semantics
04669_join_key_no_supertype already declares ("NULL and out-of-range elements do not match").

Three narrowings and one residual. A Join table engine keyed on Tuple(Nullable(T)) is rejected as
before #112951: its prebuilt hash table cannot be re-keyed. A Tuple(LowCardinality(Nullable(T)))
element, reachable at default settings, is refused during analysis with NO_COMMON_TYPE, NULL-free data
included: that cast has no
accurateOrNull exemption and throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN instead. A key-value storage
keyed on Tuple(Nullable(T)) loses the direct algorithm, which needs the right key in the
storage's own type. The residual: with one type on both sides the fallback never fires, so
ON toNullable(a.t) = toNullable(b.t) still gives hash 1 and the merges 2, which predates #112951.
Stopping that fold would settle all four, but the semantics quoted above is the declared one.

A new stateless test covers all five algorithms, USING, LowCardinality elements and null-safe
comparison; reverting one line reddens exactly the two merge arms.


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

groeneai and others added 2 commits August 31, 2026 19:38
…Nullable elements

A JOIN on `Tuple` keys whose integer elements have different signedness returned a
different number of rows depending only on `join_algorithm`: 1 row for `hash`,
`parallel_hash` and `grace_hash`, but 2 for `partial_merge` and `full_sorting_merge`.

The keys are converted to the type of the values that they have in common with
`accurateCastOrNull`. `getMostSubtype` keeps the element nullability when both sides
are nullable, so the conversion target was `Nullable(Tuple(Nullable(UInt64)))`.
`createTupleWrapper` reports an inexact element conversion in the outer null map,
but when the target element is itself `Nullable` a genuine source NULL is left in
place of the element instead, and the top level stays non-NULL.

Only the hash family notices a NULL in that position: `extractNestedColumnsAndNullMap`
folds the nullable elements of a top-level `Nullable(Tuple)` key into its null-key map.
The merge algorithms strip only the top-level `Nullable` and then compare the nested
tuples with `IColumn::compareAt`, where a NULL element is equal to a NULL element.

Remove the `Nullable` wrappers of the elements of the conversion target, so both a
genuine NULL and an element outside the common range are reported at the top level
of the key column. That is the representation every algorithm already handles, and
the only one the merge algorithms can handle: their inputs are sorted by the key,
and a key that is NULL only in a nested element is not ordered to the edge of a
block the way a top-level NULL is, so a folded null map could not be searched.
This also unifies the case of nullable tuple elements with the case of
non-nullable ones, which was already correct.

The hoist is placed before the `is_prebuilt_hash_join` guard so that guard, the two
storage guards below it and the cast all see the same type; otherwise a prebuilt
hash table could be probed with a key of a different type. The element names are
carried over because `accurateCastOrNull` matches the elements of two named `Tuple`s
by name and unnamed ones by position.

The element stripping is not moved into `tryGetCommonSubtypeForJoinKeys` itself: that
function also feeds `QueryAnalyzer::resolveJoin`, which sets the type of the USING key
column of the result, and `buildJoinUsingCondition` casts the input columns to that
type with a plain cast over all rows, which would throw on a NULL element.

Closes: ClickHouse#117102

Co-Authored-By: Claude Opus 5 <[email protected]>
The conversion target of the preceding commit has non-`Nullable` `Tuple` elements. For
a source element `LowCardinality(Nullable(T))` that arms a throw that could not happen
while the target element was `Nullable`: the element wrapper of `createTupleWrapper`
goes through `prepareUnpackDictionaries`, which sets `skip_not_null_check` when the
source dictionary is nullable and the target is not, and then throws
`CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` for a dictionary that contains a NULL. The
ordinary `Nullable` element path has an `accurateOrNull` exemption there; the
`LowCardinality` one does not, and it discards the null map, so the NULL could not
reach the outer null map even without the throw. A JOIN of
`Tuple(LowCardinality(Nullable(UInt64)))` and `Tuple(LowCardinality(Nullable(Int64)))`
keys therefore failed at run time as soon as either side held a NULL element.

Refuse that shape in `tryGetCommonSubtypeForJoinKeys` instead, which reports it as
`NO_COMMON_TYPE` when the query is analyzed rather than when the data happens to
contain a NULL. The predicate is consulted on the original argument types, before the
`recursiveRemoveLowCardinality` normalization strips the evidence. Refusing in that
function rather than at the call site also keeps ON and USING in agreement, because
`QueryAnalyzer::resolveJoin` reads the same function to type the USING result column.

The refusal is narrow: only a `Tuple` element that is `LowCardinality` over a nullable
dictionary is rejected. A non-nullable `LowCardinality` element keeps taking the
fallback, and so does a `LowCardinality` or `Nullable` wrapper around the whole key,
which is not converted element-wise.

The test arm for a `LowCardinality` element used to hold no NULL, so it exercised the
element wrapper without reaching the null handling it exists for. It is replaced by a
pair of rejection arms and by an arm with a non-nullable `LowCardinality` element,
which fails if the refusal is ever widened.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 31, 2026
@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): two approach passes before any code was
written, then one full review pass, one fix round, one delta recheck and one recheck of the final
description.

# Sev Finding Verdict Evidence / action
1 ❌ Making the converted tuple element non-nullable arms a throw: an accurateCastOrNull of a LowCardinality(Nullable(T)) element to a non-nullable element raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN instead of reporting the NULL at the top level (FunctionsConversion.cpp:2856-2895) AGREE, fixed @ 89488ac The ordinary Nullable sibling at :2988-2999 exempts accurateOrNull precisely so createTupleWrapper can propagate the NULL outward; the LowCardinality branch does not, and discards the null map. Reproduced before fixing: Code: 349 on all five algorithms, rows on the base build. Such a key is now refused in tryGetCommonSubtypeForJoinKeys, so ON and USING both report NO_COMMON_TYPE during analysis rather than throwing on the first NULL row. The old arm for that type held only the value 1, so it exercised the wrapper and never the NULL it exists for; it is replaced by two rejection arms and a non-nullable LowCardinality arm that reddens if the refusal is ever widened
2 ⚠️ A key-value storage keyed on Tuple(Nullable(T)) loses the direct algorithm, an undisclosed narrowing AGREE, disclosed Confirmed: the storage-preservation condition compares the right key against the subtype, which no longer matches, so that key becomes a derived cast and tryDirectJoin declines it. Now stated in the description. The join still runs and returns the same rows, by a hash algorithm
3 ⚠️ The same finding asked for either preserving the direct lookup or rejecting the shape outright, with a test DISAGREE Preserving it means leaving the storage key uncast, and tryDirectJoin compares types modulo the top-level wrapper only, so it would then accept and hand getByKeys a probe of a different type than the storage primary key, which is the Primary key type mismatch the surrounding comment exists to prevent. Rejecting outright turns a correct answer into an error, a larger narrowing than the one flagged. The fixture also needs a single-column Tuple key with Nullable elements on a key-value storage, which the cited evidence does not show is constructible
4 💡 The description claimed a Nullable(Tuple(Nullable(T))) key still diverges, but all five algorithms return one row for it AGREE, corrected Measured on the mixed-signedness shape, which does take this fallback and is fixed. The residual needs one type on both sides, where no conversion happens at all; there it measures as hash 1 against 2 for both merge algorithms. The sentence now says so
5 💡 LowCardinality(Nullable(<int>)) is unreachable at default settings, allow_suspicious_low_cardinality_types being off DISAGREE That setting is a column-declaration guard: it is read only by validateDataType, whose message is Creating columns of type ... is prohibited by default, and the repository documents it as validated during CREATE TABLE and ALTER TABLE only. tuple(toLowCardinality(CAST(NULL, 'Nullable(UInt64)'))) in a plain SELECT measures as Tuple(LowCardinality(Nullable(UInt64))) and threw with no setting changed. The test needs the setting only because it spells the type with an explicit CAST
6 💡 The description ended with an open request to switch approaches AGREE, removed Replaced by a decision. The alternative lever is still named, with the reason for not taking it: 04669_join_key_no_supertype and ComparisonTupleEliminationPass both already state the semantics implemented here

My own review contributed one fix (the commit messages left about sixteen literal ClickHouse names
unbackticked, against the repository rulebook, which predates this branch by seven months) and four
findings I declined: the two branches of removeNullableInsideTuple that today's only caller cannot
reach stay, because making the helper partial over its declared input to delete two lines would be
worse; the Join table engine narrowing is stated in the description instead of pinned by new DDL in an
otherwise self-contained test; the rejection arms spell the refused type with a CAST and so carry
allow_suspicious_low_cardinality_types, although the same element type is reachable without it; and
the arm checking the USING result value runs one algorithm rather than five.

Also noticed and deliberately not chased: accurateCastOrNull on a LowCardinality(Nullable(T))
argument throws rather than returning NULL, which is arguably wrong on its own. It is pre-existing, it is
a different root cause in a shared conversion path with its own contract, and finding 1 does not depend
on changing it.

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

Session id: cron:clickhouse-review-slot-10:20260831-200004

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79d30bc]

Summary: ✅


AI Review

Summary

This PR fixes the tuple-key subtype fallback used by JOIN planning so hash and merge algorithms agree when nullable integer tuple elements are converted with accurateCastOrNull. The remaining issue is that JOIN ... USING still exposes the pre-fix nullable tuple subtype on the analyzer side, so the merged key's type contract is still inconsistent with the new execution semantics.

Findings

⚠️ Majors

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:5775-5778] USING still stores the merged key type straight from tryGetCommonSubtypeForJoinKeys, while the execution path now strips inner Nullable wrappers in src/Processors/QueryPlan/JoinStepLogical.cpp:783-792. For Tuple(Nullable(UInt64)) vs Tuple(Nullable(Int64)), the join keys are matched as Nullable(Tuple(UInt64)), but the exposed USING column stays Tuple(Nullable(UInt64)). That leaks stale nullability into downstream type inference and user-visible typing even though rows with NULL elements no longer survive the join. Suggested fix: normalize the subtype with JoinCommon::removeNullableInsideTuple in QueryAnalyzer::resolveJoinUsing before the existing top-level makeNullable step, and keep the merged USING key type aligned with the actual join-key conversion.
Tests
  • ⚠️ Extend tests/queries/0_stateless/05054_join_key_common_subtype_tuple_nullable_element.sql.j2 with a USING arm that prints toTypeName(t) for the mixed-signedness nullable-tuple case. The current new test only checks the value, so it misses the analyzer-side type mismatch.
Final Verdict

⚠️ Changes requested. The execution-side fix looks coherent, but USING is still only half-updated because the analyzer keeps publishing the old nullable tuple subtype.

LLVM Coverage Report

Measured on commit 79d30bc.

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

Changed lines: Changed C/C++ lines covered: 26/27 (96.30%) · 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 Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on 5/5 algorithms, no randomization and no server needed: clickhouse local running the issue's query with join_algorithm varied prints 1 for hash/parallel_hash/grace_hash and 2 for partial_merge/full_sorting_merge. Recorded before any source edit.
b Root cause explained? Yes. getMostSubtype keeps element nullability, so the key conversion target is Nullable(Tuple(Nullable(UInt64))); for a Nullable target element accurateCastOrNull reports a genuine source NULL as an element NULL, not at the top level. extractNestedColumnsAndNullMap folds those element null maps for the hash family, while the merge engines strip only the top level and ColumnNullable::compareAt(NULL, NULL) == 0. Confirmed by EXPLAIN actions = 1, which shows the cast target change from Nullable(Tuple(Nullable(UInt64))) to Nullable(Tuple(UInt64)).
c Fix matches root cause? Yes. It normalizes the conversion target so a NULL is reported at the top level, the one representation every algorithm and the merge sort order already handle. Where that normalization cannot be represented, namely a LowCardinality element over a nullable dictionary, the conversion is refused when the query is analyzed instead of throwing later on whichever row happens to hold a NULL. Not a widened bound, no-random-* tag, size reduction, or defensive check at a crash site. The merge cursors are deliberately not patched: the folded predicate is not monotone in the sort order they require, so the derived null map could not be searched.
d Test intent preserved / new tests added? No existing test weakened or removed, and no .reference file modified anywhere in the diff. New stateless SQL test with per-algorithm arms, an in-range matching row in every arm so a drop-all-rows mutation cannot pass, and two null-safe arms pinning the boundary the fix must not cross.
e Both directions demonstrated? Yes. Before: 1/1/1/2/2. After: 1/1/1/1/1. Plus two independent mutation controls, each on its own Build-ID-verified binary: reverting only the one-line hoist reddens exactly the partial_merge and full_sorting_merge arms (and the full_sorting_merge USING arm), leaving all three hash arms byte-identical; reverting only the LowCardinality refusal reddens the rejection arms with Expected server error code: 386 but got: 349. A third control corrupts the serverError annotations to a different code and confirms the test reddens, so those arms are checked rather than decorative.
f Fix is general across code paths? Yes. Fixed at the single conversion site rather than at either consumer, so all five algorithm families are corrected at once; parallel_full_sorting_merge shares MergeJoinTransform with full_sorting_merge. Both prepared-storage carriers were traced rather than assumed, and each changes for this key shape: a Join table engine keyed on Tuple(Nullable(T)) is rejected as it was before the feature, and a key-value storage keyed that way declines direct and runs a hash algorithm instead. Both are stated in the description. 00561_storage_join, 04659_storage_join_mixed_on_expression and 04669_join_key_no_supertype pass unchanged, since none of them uses this key shape. extractNestedColumnsAndNullMap is intentionally untouched, so IN and DISTINCT semantics for this shape are provably unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Test matrix: mixed signedness, same-type control, USING, LowCardinality elements, null-safe IS NOT DISTINCT FROM, and boundary values (NULL, 1, UInt64 max, Int64 -1). The two LowCardinality cases differ and both are asserted: an element over a nullable dictionary is refused by type with NO_COMMON_TYPE, because converting it to a non-Nullable element cannot report the NULL at the top level, and a non-nullable LowCardinality element still takes the fallback and returns its row. Additionally measured by hand: a named tuple key matches and behaves identically to master; a multi-element tuple with a partial NULL matches nothing on all three families; a nested tuple is still rejected NO_COMMON_TYPE. Scalar keys are untouched, since the helper returns non-Tuple types unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed, so no SettingsChangesHistory.cpp entry is needed; no serialization or on-disk format change; nothing deleted. The affected feature is master only: tryGetCommonSubtypeForJoinKeys is absent from 26.3, 26.6, 26.7 and 26.8, and master is 26.9.1. Hence changelog category Not for changelog.
i Invariants and contracts preserved? Yes. The Tuple(Nullable(T)) NULL-matching contract (ComparisonTupleEliminationPass.cpp, "join algorithms consider only NULLs on the top level") concerns keys with no top-level Nullable; the fix changes neither their type nor any algorithm, and the null-safe tuple(...) wrap reaches this code with allow_conversion_to_subtype = false so it never reaches the helper. Pinned by two new test arms and by 03214_join_on_tuple_comparison_elimination_bug passing unchanged. The hoist sits before the is_prebuilt_hash_join guard so that guard, the two storage guards and the cast all see the same type, which is what keeps a prebuilt hash table from being probed with a differently-typed key. The helper is a pure function over DataTypePtr, so no lifetime, resource or concurrency surface is touched.

Session id: cron:clickhouse-impl-slot-7:20260831-185600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @davenger, could you review this? The common-subtype conversion for Tuple join keys left the elements Nullable, so accurateCastOrNull reported a genuine source NULL inside the tuple rather than at the top level. Only the hash family looks there, so partial_merge and full_sorting_merge matched NULL against NULL and returned a different row count; the fix strips the element Nullable from the conversion target.

Comment thread src/Interpreters/JoinUtils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79d30bc98 with master 55c256363 (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, 1774 s compile time in total, 158 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 89488ac

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases trunk-wide rather than specific to this branch. The test collects parallel-replicas statistics off the query plan, which only the analyzer builds, so on the old-analyzer lane it collects none #117364 (external, merged 2026-08-31T22:05:00Z), verified by content to be absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) job-level container-memory abort with no failing test assertion: the shard's nested containers breach the /docker cgroup leaf, which ci/jobs/integration_test_job.py then reports #117411 / #117412 (external, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) pre-existing fixture, not this diff: all 288 flagged lines are Code: 16 ... Unexpected const virtual column: _table (NO_SUCH_COLUMN_IN_TABLE) from MutatePlainMergeTreeTask, an intentional background-mutation error that 04510_mutation_query_plan_only_virtual_columns produces on purpose and the upgrade log scan does not yet allowlist #117218 (mine, open)

None of the rows above is caused by this pull request.

On the 03707_autopr_unsupported_cases row: #117364 forces the analyzer in the test itself. compare
reports this head diverged from its merge commit c9ed88dbecbb, and the added SET enable_analyzer=1;
is absent from the test file at this head, with a pre-fix negative control. I am not merging master
here purely to re-run CI: the /docker row and the upgrade-check row cannot clear that way, so the
merge would not turn this head green and would only add review load.

Session id: cron:our-pr-ci-monitor:20260901-040000

@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 4, 2026
@rschu1ze
rschu1ze requested a review from nickitat September 7, 2026 08:38

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

lgtm

if (auto subtype = JoinCommon::tryGetCommonSubtypeForJoinKeys(left_type, right_type))
{
/// A converted key must report a NULL at the top level; see `removeNullableInsideTuple`.
subtype = JoinCommon::removeNullableInsideTuple(subtype);

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.

removeNullableInsideTuple is only applied in the physical join-key cast path. QueryAnalyzer::resolveJoinUsing still calls tryGetCommonSubtypeForJoinKeys directly at src/Analyzer/Resolve/QueryAnalyzer.cpp:5775-5778, so INNER / SEMI JOIN ... USING (t) on Tuple(Nullable(UInt64)) vs Tuple(Nullable(Int64)) still publishes the merged key as Tuple(Nullable(UInt64)) instead of the post-fix common subtype Tuple(UInt64).

That leaves the USING output type out of sync with the new matching semantics: the join keys are rewritten to accurateCastOrNull(..., Nullable(Tuple(UInt64))) here, but downstream type inference still sees nullable tuple elements (toTypeName(t), overload selection on t.1, INSERT ... SELECT compatibility, etc.). Please normalize the subtype in QueryAnalyzer as well, before makeNullable, and extend this new USING test with a toTypeName(t) assertion so the analyzer-side half does not regress.

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.

Checked this at source and on A/B binaries. The structural observation is right: there are two callers of tryGetCommonSubtypeForJoinKeys, and removeNullableInsideTuple is applied only at the JoinStepLogical one. The consequence does not follow, so I am not changing the analyzer here.

This diff touches no analyzer file, so the USING type it publishes is whatever #112951 already published. Measured on master 26.9.1.1 without the fix versus this branch, INNER JOIN ... USING (t) on Tuple(Nullable(UInt64)) vs Tuple(Nullable(Int64)):

  • toTypeName(t): Tuple(Nullable(UInt64)) on both, for hash, partial_merge, full_sorting_merge and grace_hash.
  • toTypeName(t.1): Nullable(UInt64) on both.
  • EXPLAIN header=1: __table1.t Tuple(Nullable(UInt64)) on both, so the declared type already matches the runtime header. The cast shows up only under Join conditions:.
  • INSERT INTO dst (t Tuple(UInt64)) SELECT t FROM ... USING (t): master fails with Code: 349 CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN, this branch inserts (1).

So of the three downstream effects listed, the two type ones are unchanged, and the one that is observable is repaired by this PR rather than broken by it.

On being out of sync with the matching semantics: that is not specific to tuples. For a plain Nullable(UInt64) vs Nullable(Int64) USING key, which this diff cannot reach, both binaries publish Nullable(UInt64) while no NULL row survives the INNER JOIN. QueryAnalyzer.cpp:5776-5778 widens by the source key's nullability by design, and normalizing only the Tuple case would create that asymmetry rather than remove it. Whether the widening should be tightened is a question about #112951's output typing, not about this fix.

I am not adding the toTypeName(t) assertion either. It would pin a type this PR provably does not move, and if that widening is ever tightened the assertion would fail as though this fix had caused it. The base-versus-branch equality above is the stronger guarantee, and it is recorded here.

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.

@groeneai sounds like a problem. pls reproduce and fix.

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.

Reproduced. The problem is not the published type on its own, it is the cast that materializes the merged USING column, and it fails on master without this PR (26.9.1.1):

-- returns 1
SELECT count() 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);

-- the same join, projecting the USING key
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: while executing
-- 'FUNCTION _CAST(__table1.t, 'Tuple(UInt64)'_String) -> Tuple(UInt64)'. (CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN)

ON a.t = b.t returns (1) on that data, SEMI LEFT JOIN ... USING (t) throws the same 349, and enable_analyzer = 0 gives TYPE_MISMATCH. tryGetCommonSubtypeForJoinKeys has 0 occurrences on 26.8 and 26.7, so this arrived with the fallback.

Mechanism: getMostSubtype drops the Nullable of an element when the other side has none, so resolveJoinUsing publishes Tuple(UInt64) (QueryAnalyzer.cpp:5775-5778), and buildJoinUsingCondition materializes the merged column with a plain _CAST into it over the unfiltered key column (PlannerJoinsLogical.cpp:220-224). A key with no representation in the subtype cannot match, so the join has to drop that row rather than fail its cast. The matching path already gets this right, converting with accurateCastOrNull into makeNullable(subtype). is_nullable at :5777 is a top-level test, which is why a plain Nullable(Int64) vs UInt64 key is shielded by that makeNullable and a tuple is not.

It also answers the review bot: publishing Tuple(UInt64) while a key holds a NULL element is exactly the configuration that throws above, so normalizing the analyzer's subtype as proposed would extend this to the key shape #117102 reports.

I am fixing it and will link the fix here. This PR does not reach it, since its only change to tryGetCommonSubtypeForJoinKeys is the LowCardinality(Nullable(...)) refusal and this shape has no LowCardinality, so it does not need to wait for that fix.

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.

Fixed in #118902.

getMostSubtype drops a Tuple element's Nullable when the other side's element has none, and
resolveJoinUsing publishes that subtype as the merged USING type while its is_nullable shield tests
the top level only. The merged column is then materialized by converting the whole key column into that
type before the join filters anything, so a NULL element has nowhere to go and the conversion throws. The
PR asks getMostSubtype for the merged type in its existing force_support_conversion mode, so the
published type becomes Tuple(Nullable(UInt64)) and the conversion becomes total. The key comparison keeps
the default mode, which is what its accurateCastOrNull needs.

Two things worth knowing: the fallback is reachable only since #112951, so nothing released is affected and
no backport applies; and for such a key USING now publishes Tuple(Nullable(U)) where it published
Tuple(U).

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79d30bc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log pre-existing background-mutation retry loop, not this diff: all 32803 bytes of flagged lines are one shape, Code: 47 ... Unknown expression identifier 'b'. Maybe you meant: ['a']. In scope b, b. from MutatePlainMergeTreeTask on ...::all_1_1_1_2, the empty-part revival arm of the 04653_mutation_rewrite_stale_part_column_type test; 33 PRs carry it in 7 days, 0 true-master rows #118499 (mine, open)
Mergeable Check aggregator; its own message is Failed: Upgrade check (amd_release), so it carries no separate failure #118499 (mine, open)
PR praktika aggregator of the same job #118499 (mine, open)

CI ran on the master merge pushed to this branch at 2026-09-08T03:46:07Z, so the failing head is
current with master.

Session id: cron:our-pr-ci-monitor:20260908-103036

@nickitat
nickitat added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 97f5e09 Sep 8, 2026
344 of 345 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 8, 2026
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 10, 2026
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
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

4 participants