Skip to content

Fix transform_null_in=1 for a non-Nullable key IN/NOT IN a Nullable subquery - #111418

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-transform-null-in-non-nullable-key-111340
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-transform-null-in-non-nullable-key-111340

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes: #111340

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix Cannot convert NULL value to non-Nullable type error when a non-Nullable column is used in IN with a subquery whose result is Nullable (for example UNION ALL SELECT NULL) and transform_null_in = 1.

Description

canBeSafelyCast(Nullable(X), T) 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

CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY s;
INSERT INTO t VALUES ('a'), ('b'), ('c');
SELECT s FROM t WHERE s IN (SELECT s FROM t UNION ALL SELECT NULL) SETTINGS transform_null_in = 1;

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 is in the predicate so all five callers route Nullable-source / non-Nullable-target casts through their NULL-safe path:

  • Nullable case: return false unless the target is also Nullable.
  • LowCardinality case: recurse against removeLowCardinality(to_type) (keeping the target's Nullable wrapper) instead of the fully unwrapped type, so LowCardinality(Nullable(X)) -> Nullable(X) stays safe and set-index construction is preserved for a Nullable key.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (s String) ENGINE=MergeTree ORDER BY s; INSERT INTO t VALUES ('a'),('b'),('c'); SELECT s FROM t WHERE s IN (SELECT s FROM t UNION ALL SELECT NULL) SETTINGS transform_null_in=1; throws error 349 every time on master.
b Root cause explained? canBeSafelyCast(Nullable(String), String) returned true (via the isString() shortcut in the Nullable case). MergeTree KeyCondition::tryPrepareSetColumnsForIndex then took the strict castColumn branch, which throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN on the NULL set element. Int64 was unaffected because Nullable(Int64) -> Int64 returned false and used the NULL-safe fallback.
c Fix matches root cause? Yes. The predicate now returns false for a Nullable source into a non-Nullable target, so all callers route through their existing NULL-safe castColumnAccurateOrNull path. Not a symptom guard.
d Test intent preserved / new tests added? New 04545_transform_null_in_non_nullable_key.sql (type matrix + NOT IN partition pruning + NOT has + Nullable key + column-count error). No existing test weakened.
e Both directions demonstrated? Fails on master (349), passes with fix (a,b,c). 50/50 with randomized settings.
f Fix is general across code paths? Yes. Fixed the shared predicate (5 callers), not the single KeyCondition site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified String, FixedString, Int64, LowCardinality(String), Date, non-PK; LowCardinality(Nullable(X)) -> Nullable(X) kept exact (LowCardinality recursion preserves target nullability), so set-index pruning is preserved.
h Backward compatible? Yes. No setting default / on-disk / wire format change; SettingsChangesHistory.cpp untouched. Behavior change is strictly: a cast that threw 349 now returns correct rows.
i Invariants and contracts preserved? Yes. canBeSafelyCast's "strict cast is safe" contract made correct; the NULL-safe fallback keeps a NULL element as the key default, so the pruning atom is marked relaxed only when it retains such an approximation — this also fixes pre-existing NOT IN/NOT has mis-pruning (Int64 too). Positive IN pruning and IN column-count validation preserved.

Session id: cron:clickhouse-author-slot-7:20260722-134700

@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; 6 findings across a full pass + a delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Routing Nullable(String) -> String through the NULL-safe fallback makes negated set pruning treat RHS NULL as the nested default, dropping valid NOT IN rows AGREE — fixed Reproduced: s NOT IN (SELECT 'a' UNION ALL SELECT NULL) on t(s String) PARTITION BY s returned only b vs the literal oracle's '',b. Added set_is_relaxed out-param to tryPrepareSetColumnsForIndex; both IN/has callers mark the atom relaxed. Verified correct; also fixes the pre-existing Nullable(Int64) -> Int64 case.
2 ⚠️ set_is_relaxed also fired for cast-produced NULLs that are filtered out, causing avoidable full scans (set stays exact) AGREE — fixed Verified: UInt8 key NOT IN (5, 256) read 3/3 parts though 256 is filtered and the set {5} is exact. Now relaxes ONLY for a retained source-NULL approximation; NOT IN (5,256) reads 2/3 again, NOT IN (5,NULL) still relaxes.
3 ⚠️ LowCardinality(Nullable(X)) -> Nullable(X) is exact but was rejected, relaxing has() pruning AGREE — fixed The has() caller reaches the LowCardinality from-type branch (arrays are not LC-stripped the way Set::setHeader strips IN sets). LowCardinality case now recurses against removeLowCardinality(to_type), keeping the target's Nullable wrapper.
4 ⚠️ The changed has caller had no NULL-relaxation regression coverage AGREE — fixed Added a NOT has([CAST('a','Nullable(String)'), NULL], s) partition-pruning case (with optimize_rewrite_has_to_in = 0) to the test.
5 ⚠️ (initial pass) The LowCardinality regression guard did not exercise the changed LowCardinality branch via IN AGREE Correct for the IN path (Set::setHeader strips LC). Superseded by #3: the branch IS reachable via has(), so the LowCardinality recursion fix is retained and covered by the new NOT has test.
6 💡 Test preamble restated PR-level detail AGREE — fixed Shortened to two lines.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-7:20260722-134700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @hanfei1991 — could you review this? It fixes error 349 (CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN) for a non-Nullable key IN/NOT IN a Nullable subquery under transform_null_in=1: canBeSafelyCast wrongly treated Nullable(X) -> non-Nullable as safe, and the MergeTree KeyCondition set-index path then either threw on the NULL element or (for NOT IN) pruned valid rows. Fix is in the cast predicate plus a relaxed-atom guard in tryPrepareSetColumnsForIndex.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f74024]

Summary: ❌

job_name test_name status info comment
Install packages (amd_release) FAIL
Install server rpm FAIL cidb
Install keeper rpm FAIL cidb
Install tgz over a dangling symlink in clickhouse/install-deb-test:ec2879744cacbe7f4957_amd FAIL cidb
Install tgz over a dangling symlink in clickhouse/install-rpm-test:6f408fc7fa9d466a1090_amd FAIL cidb
Install packages (arm_release) FAIL
Install server rpm FAIL cidb
Install keeper rpm FAIL cidb
Install tgz over a dangling symlink in clickhouse/install-deb-test:ec2879744cacbe7f4957_arm FAIL cidb
Install tgz over a dangling symlink in clickhouse/install-rpm-test:6f408fc7fa9d466a1090_arm FAIL cidb

AI Review

Summary

This PR fixes the original CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN exception for transform_null_in = 1, but the KeyCondition set-index path is still too optimistic about when a Nullable RHS can be treated as exact. One remaining blocker can still mis-prune IN / NOT IN / has conditions with nullable-typed but non-NULL values, and one older pruning-precision issue is still present. I would not merge this branch as-is.

Findings

❌ Blockers

  • [src/Storages/MergeTree/KeyCondition.cpp:2477-2490] The new set_is_relaxed logic only notices retained source NULLs, but castColumnAccurateOrNull also hides non-NULL equality changes. For example, UInt64 key k NOT IN (SELECT CAST('01', 'Nullable(String)')) builds {1} and can prune partition 1, even though runtime Set::execute compares the key as Nullable(String) and 1 should survive. The mirror case also breaks positive predicates: String key s IN (SELECT CAST(1, 'Nullable(UInt64)')) builds only '1', while runtime membership matches both '1' and '01'. The exact/relaxed decision has to account for whether the conversion preserves IN equality in both directions; source-NULL presence alone is not enough.

⚠️ Majors

  • [src/Storages/MergeTree/KeyCondition.cpp:2477-2489] The existing unresolved review point still holds: every retained source NULL sets set_is_relaxed = true, even when that NULL collapses to a key default that is already present explicitly in the set. In a case like s NOT IN (SELECT '' UNION ALL SELECT NULL), the prepared set is exact again after cast and dedup, but this code still forces the atom relaxed and gives up exact NOT IN / NOT has pruning for no correctness benefit.
Tests

⚠️ Add focused cases where the RHS type is Nullable(...) but the data contains no actual NULL rows, for both directions of the conversion. The current 04545 coverage only exercises real NULL elements, so it cannot catch the remaining CAST('01', 'Nullable(String)') / CAST(1, 'Nullable(UInt64)') exactness bugs above.

Final Verdict

❌ Changes required before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
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])

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.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1f74024

All checks passed. Finish Workflow and Mergeable Check are green; no failing tests on this commit.

Check / test Reason Owner
(all checks) pass none
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260723-010000

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@groeneai
groeneai force-pushed the groeneai/fix-transform-null-in-non-nullable-key-111340 branch 2 times, most recently from 0356aec to 1f74024 Compare August 2, 2026 06:37
/// 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])

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.

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:

  • UInt64 key: k NOT IN (SELECT CAST('01', 'Nullable(String)')) builds the pruning set {1} here, so partition 1 can be dropped, but runtime Set::execute casts the key into Nullable(String) and compares '1' to '01', so the row 1 should survive.
  • String key: s IN (SELECT CAST(1, 'Nullable(UInt64)')) builds only '1', but runtime membership casts both '1' and '01' to 1, so positive IN can 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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 27/32 (84.38%) · Uncovered code

Full report · Diff report

@hanfei1991 hanfei1991 self-assigned this Aug 4, 2026
@hanfei1991 hanfei1991 closed this Aug 17, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 18, 2026
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.
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Oct 16, 2026
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
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

transform_null_in=1 fails for non-nullable String IN nullable subquery result

3 participants