Repository navigation
Conversation
…ubquery canBeSafelyCast(Nullable(X), T) wrongly returned true when T is a non-Nullable String (and, via element recursion, Array/Map/Tuple). A Nullable source cannot be safely cast to a non-Nullable target: a NULL value has no representation there, so a strict cast throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN (error 349). This surfaced in MergeTree KeyCondition set-index analysis (tryPrepareSetColumnsForIndex): for a query like SELECT s FROM t WHERE s IN (SELECT s FROM t UNION ALL SELECT NULL) SETTINGS transform_null_in = 1 with t(s String) ORDER BY s, the subquery set element type is Nullable(String) and the key type is String. canBeSafelyCast returned true, so the code took the strict castColumn branch and threw 349 on the NULL element instead of the NULL-safe castColumnAccurateOrNull fallback. Int64 was unaffected because Nullable(Int64) -> Int64 already returned false and used the correct fallback. Fix in the predicate so all callers route a Nullable-source / non-Nullable-target cast through their NULL-safe path: the Nullable case returns false unless the target is also Nullable. The LowCardinality case recurses against removeLowCardinality(to_type) so it keeps the target's Nullable wrapper (LowCardinality(Nullable(X)) -> Nullable(X) stays exact and set-index pruning is preserved). The NULL-safe fallback keeps a NULL set element as the key's nested default. That set is a subset of the original, which weakens IN and, after negation, strengthens NOT IN, so single-point key ranges (partition pruning, minmax) could be pruned away incorrectly. Example: `s NOT IN (SELECT 'a' UNION ALL SELECT NULL)` on `t(s String) ORDER BY s PARTITION BY s` dropped the '' row. tryPrepareSetColumnsForIndex now reports set_is_relaxed only when it retains such an approximated NULL element (not when a cast-produced NULL is filtered out, which keeps the set exact), and both callers (IN and has) mark the atom relaxed so checkInRange() does not return an exact can_be_false for a single-point range. This also fixes the pre-existing same bug for Nullable(Int64) -> Int64 NOT IN pruning. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-7:20260722-134700 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 6 findings across a full pass + a delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-7:20260722-134700 |
|
cc @Avogar @hanfei1991 — could you review this? It fixes error 349 (CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN) for a non-Nullable key |
|
Workflow [PR], commit [1f74024] Summary: ❌
AI ReviewSummaryThis PR fixes the original Findings❌ Blockers
Tests
Final Verdict❌ Changes required before merge. |
The NOT IN / NOT has cases checked only query results, which still pass if tryPrepareSetColumnsForIndex declines and the engine full-scans. Add an EXPLAIN indexes = 1 assertion for each negated case proving KeyCondition builds a 'notIn ... set' atom (a declined path yields 'Condition: true', which the ILIKE misses), so the relaxed set-index path is exercised, not just correct results. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| /// Mark the atom relaxed so `checkInRange()` never reports an exact `can_be_false`. | ||
| /// Cast-produced NULLs, in contrast, are dropped by the filter below and keep the set | ||
| /// exact, so they must not relax it. | ||
| if (i < set_column_null_map->size() && (*set_column_null_map)[i]) |
There was a problem hiding this comment.
This relaxes every retained source NULL, but the set is still exact when that NULL collapses to a key default that is already present explicitly in the set. For a non-nullable String key, s NOT IN (SELECT '' UNION ALL SELECT NULL) is semantically just s NOT IN (''); after MergeTreeSetIndex deduplicates the two '' entries, the pruning set is exact again. With the unconditional set_is_relaxed = true here we still mark the atom relaxed and lose exact NOT IN / NOT has partition/minmax pruning for that case.
Please base set_is_relaxed on whether a retained source NULL introduces a new key value after cast/filter/dedup, not just on the presence of a source null.
CI finish ledger — 1f74024All checks passed. Finish Workflow and Mergeable Check are green; no failing tests on this commit.
Session id: cron:our-pr-ci-monitor:20260723-010000 |
|
Superseded by #112890, which carries the complete fix for issue #111340; please review there. This PR's head is an early revision holding only the first two commits. Six further revisions, driven by eight rounds of internal review, found and fixed additional wrong-results bugs in the same code path. They ended up on a separate branch and therefore in a second PR rather than as pushes here, which was my tooling's mistake. I am leaving this open rather than closing it myself. Happy to close it if you would prefer a single PR. |
0356aec to
1f74024
Compare
| /// Mark the atom relaxed so `checkInRange()` never reports an exact `can_be_false`. | ||
| /// Cast-produced NULLs, in contrast, are dropped by the filter below and keep the set | ||
| /// exact, so they must not relax it. | ||
| if (i < set_column_null_map->size() && (*set_column_null_map)[i]) |
There was a problem hiding this comment.
set_is_relaxed is still keyed only on retained source NULLs, but this fallback can be non-exact even when every RHS row is non-NULL.
Two concrete counterexamples stay wrong on this branch:
UInt64key:k NOT IN (SELECT CAST('01', 'Nullable(String)'))builds the pruning set{1}here, so partition1can be dropped, but runtimeSet::executecasts the key intoNullable(String)and compares'1'to'01', so the row1should survive.Stringkey:s IN (SELECT CAST(1, 'Nullable(UInt64)'))builds only'1', but runtime membership casts both'1'and'01'to1, so positiveINcan also lose matching rows.
The exact/relaxed decision needs to be based on whether the set/key conversion preserves IN equality in both directions, not just on whether a source NULL was retained.
There was a problem hiding this comment.
Both counterexamples reproduce, and both are already fixed by #112966.
Measured on three debug binaries against an ENGINE = Memory oracle running identical SQL:
| arm | k NOT IN (SELECT CAST('01','Nullable(String)')) |
s IN (SELECT CAST(1,'Nullable(UInt64)')) |
|---|---|---|
pristine master 70d41612297a |
[2], oracle [1,2] |
['1'], oracle ['01','1'] |
this branch 1f7402426f05 |
[2] |
['1'] |
#112966 0356aecfcab9 |
[1,2] |
['01','1'] |
So the fallback is non-exact as described, the two casts do run in opposite directions, and keying the decision on retained source NULLs alone is not sufficient. It is pre-existing rather than introduced here: master is wrong on both shapes with byte-identical output.
#112966 derives exactness from the strictness of the two casts instead of a list of type pairs, and the check sits in the shared tryPrepareSetColumnsForIndex, so it covers the Nullable source path as well. Both of your shapes are regression cases in it: A Nullable element is k NOT IN (SELECT CAST('01', 'Nullable(String)')) on a UInt64 key, and D Nullable element is the positive IN over a String key with CAST(1, 'Nullable(UInt8)'). Pruning stays live where the conversion does preserve equality: on that build k IN (SELECT toUInt64(1)) still reports in 1-element set and Parts: 1/3.
On scope: this PR is superseded by #112890, and the head you reviewed here is the early revision from 2026-07-22. I am keeping the exactness rework in its own PR rather than folding it into either one.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 27/32 (84.38%) · Uncovered code |
PR ClickHouse#111418 was closed on 2026-08-17 and superseded by ClickHouse#112890, so the comment pointed at a dead PR. Rewrote it as the local invariant instead of citing any PR, since a reader of the test does not need the fix history to understand which shapes the file deliberately omits.
accurateCast, accurateCastOrNull and accurateCastOrDefault never converted an unsigned integer to IPv4, nor UInt128 to IPv6, even though the plain CAST of the same value succeeds. accurateCastOrNull returned NULL, accurateCast threw CANNOT_CONVERT_TYPE, and accurateCastOrDefault returned 0.0.0.0. Because the MergeTree set index builds its pruning set with castColumnAccurateOrNull, this silently returned wrong results: an IPv4 primary key compared with IN against a UInt32 subquery pruned every part, since every set element became NULL. Set also uses the accurate casts, so a runtime IN over the same cross-type pair returned 0 while = returned 1, and under transform_null_in = 1 the same query threw instead. FunctionCast::createWrapper enters its accurate branch for any integer source, then dispatches into a lambda whose value-producing arms are guarded by IsDataTypeNumber<RightDataType>. That trait is specialized only for DataTypeNumber<T>, and DataTypeIPv4/DataTypeIPv6 are not, because their field type is a StrongTypedef. No arm matched, so the wrapper fell through to an all-NULL column or a throw without ever examining the value. The plain CAST was unaffected because it reaches ConvertImpl, which already whitelists UInt8/UInt16/UInt32/UInt64 as IPv4 sources. This adds the missing dispatcher arm plus an accurate integer-to-IPv4 conversion. The conversion range-checks against IPv4::UnderlyingType rather than the StrongTypedef itself, mirroring convertFieldToType, which converts a UInt64 field to IPv4 through UInt32; accurate::convertNumeric cannot be instantiated for a StrongTypedef target at all. The check is load-bearing: the existing convertFromUInt64ToIPv4 truncates, so reusing it would have replaced NULL with a silently wrong value. UInt128 to IPv6 needs only the dispatcher arm, since that conversion already handles accurate additions; it is left untouched because IPv6 is stored big-endian and its helper byte-swaps both limbs. Fixing the conversion layer corrects every consumer at once: Set, KeyCondition, castOrDefault, KVStorageUtils, FunctionsJSON and evaluateConstantExpression. Plain CAST keeps its behaviour, including truncating values above 2^32, because the new ConvertImpl arm is selected only for the accurate additions types. Scope was established by sweeping all 702 ordered pairs over 27 types against the invariant "plain CAST succeeds, so the accurate cast must not return NULL". Exactly 6 pairs violated it (UInt8/UInt16/UInt32/UInt64/Bool to IPv4, UInt128 to IPv6) and all 6 are fixed with no residue. UUID and the Int*, Float* and UInt256 sources are deliberately out of scope: plain CAST throws for those too, so returning NULL is consistent, and making them convertible would be a new capability rather than a bug fix. The new test pins them as negative controls. 03212_variant_dynamic_cast_or_default is updated because toIPv4OrDefault and toIPv6OrDefault over a Dynamic column build on the accurate cast, so values that previously fell to the type default now convert, matching what plain CAST returns for the same inputs. Its diagnostic allow-list is widened for the same reason rather than removed. This is the same update c9e6de1 made to that reference when the accurate cast to Date32 became strict. Related: ClickHouse#111418
Closes: #111340
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
Cannot convert NULL value to non-Nullable typeerror when a non-Nullable column is used inINwith a subquery whose result isNullable(for exampleUNION ALL SELECT NULL) andtransform_null_in = 1.Description
canBeSafelyCast(Nullable(X), T)returnedtruewhenTis a non-NullableString(and, via element recursion,Array/Map/Tuple). ANullablesource cannot be safely cast to a non-Nullable target: aNULLvalue has no representation there, so a strict cast throwsCANNOT_INSERT_NULL_IN_ORDINARY_COLUMN(error 349).This surfaced in MergeTree
KeyConditionset-index analysis (tryPrepareSetColumnsForIndex). Forthe subquery set element type is
Nullable(String)and the key type isString.canBeSafelyCastreturnedtrue, so the code took the strictcastColumnbranch and threw 349 on theNULLelement instead of the NULL-safecastColumnAccurateOrNullfallback.Int64was unaffected becauseNullable(Int64) -> Int64already returnedfalseand used the correct fallback.Fix is in the predicate so all five callers route
Nullable-source / non-Nullable-target casts through their NULL-safe path:Nullablecase: returnfalseunless the target is alsoNullable.LowCardinalitycase: recurse againstremoveLowCardinality(to_type)(keeping the target'sNullablewrapper) instead of the fully unwrapped type, soLowCardinality(Nullable(X)) -> Nullable(X)stays safe and set-index construction is preserved for aNullablekey.