Repository navigation
Fix the JOIN key conversion to a common subtype for a Tuple key with Nullable elements - #117409
Conversation
…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]>
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
My own review contributed one fix (the commit messages left about sixteen literal ClickHouse names Also noticed and deliberately not chased: Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260831-200004 |
|
Workflow [PR], commit [79d30bc] Summary: ✅
AI ReviewSummaryThis PR fixes the tuple-key subtype fallback used by Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 79d30bc.
Changed lines: Changed C/C++ lines covered: 26/27 (96.30%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260831-185600 |
|
cc @rschu1ze @davenger, could you review this? The common-subtype conversion for |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units158 translation units recompiled, 1774 s compile time in total, 158 of them have a recent master baseline. |
CI finish ledger - 89488acEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
None of the rows above is caused by this pull request. On the Session id: |
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, forhash,partial_merge,full_sorting_mergeandgrace_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 underJoin conditions:.INSERT INTO dst (t Tuple(UInt64)) SELECT t FROM ... USING (t): master fails withCode: 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.
There was a problem hiding this comment.
@groeneai sounds like a problem. pls reproduce and fix.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
CI finish ledger - 79d30bcEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
CI ran on the master merge pushed to this branch at 2026-09-08T03:46:07Z, so the failing head is Session id: cron:our-pr-ci-monitor:20260908-103036 |
97f5e09
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
Closes: #117102
Related: #112951
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Description
An
INNER JOINonTuplekeys whose integer elements differ in signedness returned a row count dependingonly on
join_algorithm: 1 for the three hash algorithms, 2 forpartial_mergeandfull_sorting_merge. Reachable since #112951, on master only, henceNot for changelog; before it thequery was rejected.
Root cause:
getMostSubtypekeeps the element nullability, so theaccurateCastOrNulltarget isNullable(Tuple(Nullable(UInt64))), where a genuine source NULL lands inside the tuple, not at the toplevel. 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
Nullablewrappers of the target's elements, so both a genuine NULL and anout-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_supertypealready declares ("NULL and out-of-range elements do not match").Three narrowings and one residual. A
Jointable engine keyed onTuple(Nullable(T))is rejected asbefore #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 dataincluded: that cast has no
accurateOrNullexemption and throwsCANNOT_INSERT_NULL_IN_ORDINARY_COLUMNinstead. A key-value storagekeyed on
Tuple(Nullable(T))loses thedirectalgorithm, which needs the right key in thestorage's own type. The residual: with one type on both sides the fallback never fires, so
ON toNullable(a.t) = toNullable(b.t)still giveshash1 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,LowCardinalityelements and null-safecomparison; reverting one line reddens exactly the two merge arms.
Workflow [PR]
Sync PR [sync-upstream/pr/117409]