Repository navigation
Do not treat a cast to String from a type that can hold NULL as safe - #115647
alexey-milovidov merged 9 commits into
Conversation
canBeSafelyCast declared Nullable(X) -> String safe, but String cannot
hold a NULL. tryPrepareSetColumnsForIndex trusts that claim to take a
fast exit through the non-accurate castColumn, which throws
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN on a source NULL. So an ordinary
query against a String primary key failed during key analysis:
CREATE TABLE a3 (k String) ENGINE = MergeTree ORDER BY k;
INSERT INTO a3 VALUES ('a');
SELECT count() FROM a3 WHERE has([CAST(NULL, 'Nullable(String)')], k);
-- Code: 349. Cannot convert NULL value to non-Nullable type.
ENGINE = Memory answers 0 for the same data and predicate, so the value
is well defined and only the MergeTree path errored. Every non-String
target already answered "not safe" and therefore routed to the
castColumnAccurateOrNull fallback, which records the source null map and
filters unrepresentable elements out. The correct handling already
existed; this type pair never reached it.
Array and Map inherit the defect through the predicate's own recursion on
nested types, not through the call site, so a call-site nullability guard
cannot see it: measured, such a guard fixes the six scalar cases and
leaves Array(Nullable(String)) and Map(..., Nullable(String)) throwing.
Hence the fix removes the false claim from the predicate itself.
Nullable -> Nullable still recurses, so a Nullable key keeps its fast
path and still matches a NULL set element. All five callers were measured
before and after: the four others are unchanged, since each already
handles a "not safe" answer with castColumnAccurateOrNull plus
reject-or-filter on null. Index effectiveness is unchanged as well, with
EXPLAIN indexes = 1 identical on seven arms, and the previously-throwing
mixed set now prunes to a single granule instead of scanning everything.
Found by an internal review of KeyCondition set-index preparation.
Reproduces on released 26.7.4.55.
Co-Authored-By: Claude Fable 5 <[email protected]>
Variant and Dynamic encode a NULL through NULL_DISCRIMINATOR rather than a separate null map, so a non-Nullable target cannot represent it. For a String target the conversion could not even report the problem: throw_on_null requires shouldThrowOnNull(), which needs !result_type->canBeInsideNullable(), and that is false for String. Execution therefore reached insertDefault() and the NULL became the empty string. In set index preparation the decayed '' entered the set as a genuine element, so notHas pruned away rows whose key really was ''. Measured against a Memory oracle on a String key holding '' and 'a', three of four Dynamic and Variant arms returned wrong counts, in both the has and notHas directions and through IN and NOT IN. Returning false routes these types to the castColumnAccurateOrNull path that already filters unrepresentable elements out, which is the same handling the Nullable case received in the previous commit. Object stays where it was: it is not one of the NULL carriers that getSourceNullMap() reconstructs a null map for, and its NULL arrives through an outer Nullable that the Nullable arm already rejects. An Array or Map key cannot be inside Nullable, so a Nullable-nested set element now gives up the set index even when it holds no NULL. Results stay correct and only the pruning is traded for the correctness fix; the test pins both the scan and the plain element that still prunes.
Making canBeSafelyCast answer false for a NULL-carrying source and a String target routes more type pairs into castColumnAccurateOrNull. That cast rejects a target whose nested type cannot be inside Nullable, and the two guards in front of it on the key-column path tested only the outer type. A Tuple(Array(String)) key therefore passed both and then raised Code: 43 ILLEGAL_TYPE_OF_ARGUMENT, which nothing catches, so a query that returned a row before started erroring. Both guards now ask the question the cast answers. The existing recursive validator is reimplemented on a non-throwing predicate exported from CastOverloadResolver.h, so the throwing and non-throwing forms cannot drift. A refused target declines the set index: correct results, no pruning. The second guard is in applyDeterministicDagToColumn and is reached BEFORE the first one whenever the key is an expression, for example ORDER BY tupleElement(t, 1). A binary carrying only the guard in tryPrepareSetColumnsForIndex was built and still raised Code: 43 on that path, so both sites are required. Four expression-key shapes funnel through it. The third guard of the same shape, in applyFunctionChainToColumn, is left alone: its target is a monotonic function's argument type and entry requires hasInformationAboutMonotonicity(), which no container-argument function has. Tuple(Array(UInt64)) against a Tuple(Array(UInt8)) key already raised Code: 43 before this change, with no Nullable involved, and now returns the same answer as ENGINE = Memory. Measured on three binaries against a Memory oracle: pristine master, the head carrying only the earlier hunks, and this one. The extended test fails on the first with Code: 349, on the second with Code: 43, and passes here, 50/50 under randomization. A focused 477-test selection ran on all three; every fix-only failure was Code: 701 CLUSTER_DOESNT_EXIST from the randomizer enabling parallel replicas against a single-node server, and all 29 pass when re-run deterministically. A scalar key reached through the same transform keeps Granules: 2/16, pinned in the test so a too-broad guard would be caught. An Array, Map or Tuple(Array) key gives up its set index when the set element is Nullable-nested, even with no NULL in it; results stay correct.
Making canBeSafelyCast answer "not safe" for a NULL-carrying source and a String target routes more targets into castColumnAccurateOrNull, which refuses a target whose nested type cannot be inside Nullable. Two earlier rounds guarded the two sites in KeyCondition.cpp that were found by inspection; the guard set is now established by enumerating the predicate's callers instead. grep -rn canBeSafelyCast src/ returns five call sites. Four reach an accurateOrNull cast and all four now consult canBeAccurateCastOrNullTarget: tryPrepareSetColumnsForIndex, applyDeterministicDagToColumn (both earlier), applyFunctionChainToColumn and traverseDAGFilterSingleColumn (both here). KeyCondition.cpp:1694 is excluded because its false branch returns immediately and the only cast after it is castColumnAccurate. Every other castColumnAccurateOrNull in the tree is gated by its own predicate rather than by canBeSafelyCast, so this change cannot alter which branch it takes. applyFunctionChainToColumn's guard tested the outer type only, and DataTypeTuple can be inside Nullable, so a Tuple(Array(String)) key walked through it and raised Code 43 from the cast's nested-type validator. A monotonic wrapper whose argument type is the key itself reaches it: materialize, assumeNotNull and coalesce over such a key each returned one row before this series and Code 43 after the earlier hunks. The throw escapes, since the file's only try/catch is in a different function. traverseDAGFilterSingleColumn had no target check at all. A container primary key on EmbeddedRocksDB, KeeperMap or Redis reaches its accurateOrNull call during filter pushdown and raised Code 43 the same way, with nothing catching it in the helper or in any of the three storages. Declining returns false, which the helper already treats as "no keys matched" and answers with a full scan, matching what its own comment documents for a set it cannot convert. Both are regressions of this series rather than latent defects: on pristine master every arm returns the same row count as a Memory oracle, and only the intermediate builds error. Coverage is a container-key arm in 04510_not_has_function_explain and a new 04701_kv_container_key_set_cast, each verified to fail on the pre-fix binary before its reference was generated.
…get's nullability canBeAccurateCastOrNullTarget modelled only one of castColumnAccurateOrNull's two refusals. createInternalCast validates nested types only when the target cannot contain a NULL, but castColumn then calls makeNullable unconditionally, and DataTypeNullable's constructor rejects a nested type that cannot be inside Nullable. So the predicate permitted LowCardinality(Nullable(X)), Dynamic and Variant, which satisfy canContainNull yet cannot be wrapped. A LowCardinality(Nullable(String)) EmbeddedRocksDB primary key reached the cast through KVStorageUtils and answered Code 43 instead of a row count. Test the target's own Nullable capability before walking its nested types. canBeSafelyCast also stopped reporting two casts as safe that a Nullable target can represent. The new Variant/Dynamic arm ignored to_type_was_nullable, and the LowCardinality arm recursed with the target stripped of both wrappers, so a Nullable dictionary type saw a non-Nullable target in the recursive call. Both sent a scalar Nullable key to the accurate-or-null route, where the pre-existing canBeInsideNullable disjunct declines the set index, costing pruning (2/16 granules became 16/16). Recursing with removeLowCardinality leaves the unwrapped target unchanged, so only the nullability the recursion needs is preserved; it also restores pruning for a LowCardinality(Nullable(numeric)) element against a wider Nullable numeric key. The 04701 scalar control asserted only counts, which a guard that declined for every target would satisfy, so it now asserts the rocksdb read type instead.
A LowCardinality(String) key-value primary key is only an encoding of String, but castColumnAccurateOrNull reports a conversion failure by wrapping its target in Nullable, which LowCardinality cannot be. Asking about the raw declared type therefore declined the whole set and gave up the point lookup for a full scan on any element the key type cannot be cast to safely, such as Dynamic or Variant. The three sibling MergeTree guards already strip the encoding before probing; this brings the key-value site in line with them. The strip is confined to the cast target. The rows pushed to the caller are Fields, and both consumers re-derive the serialization from the declared key type, whose LowCardinality serialization delegates a Field verbatim to the dictionary type, so the key bytes are unchanged. removeLowCardinality is not recursive, so a Tuple(LowCardinality(String)) target still declines rather than reaching a cast that cannot accept it. Measured on an EmbeddedRocksDB table with a LowCardinality(String) key: a non-NULL Dynamic or Variant element reads GetKeys again instead of FullScan, and every container-key and plain-String control is unchanged. Also makes four test assertions able to fail. The scalar and LowCardinality(Nullable(String)) read-type controls asserted plain or Nullable elements, which the set unwraps before the guard sees them, so they never reached the guarded branch; they now assert a Dynamic element as well, verified to flip to FullScan on a deliberately broadened build. The Nullable-key carrier block gained a fixture holding a NULL row beside an empty-string row across two parts and asserts which row matched, so a NULL that decayed to the default value is observable, and the mixed-set block gained the pruning assertion for the element that survives the dropped NULL. Co-Authored-By: Claude Opus 5 <[email protected]>
Master appended createCastOverloadResolver to CastOverloadResolver.h at the same trailing slot where this branch appended canBeAccurateCastOrNullTarget. Adjacent insert with no semantic overlap: both declarations are kept. Merging rather than rebasing because the base has moved 966 commits and a rebase of the six commits on this branch would re-resolve the same conflict repeatedly.
canBeSafelyCast's doc comment listed five examples but never stated the invariant, so a caller had no way to know that NULL representability is part of "safely". State it, since the two withdrawn Nullable-to-non-Nullable claims rest on exactly that. canBeAccurateCastOrNullTarget's comment claimed every nested type must be able to be inside Nullable. findUnsupportedTypeForAccurateCastOrNull refuses a nested type only when it can neither be inside Nullable nor contain a NULL itself, so nested Dynamic, Variant and LowCardinality(Nullable(X)) are all accepted. The outer and nested tests genuinely differ; the comment now says which is which.
Internal second-model reviewAn independent model reviewed this change against the repo review skill, and I adjudicated every
Two findings from the previous round were re-checked and confirmed closed: a Two things I noticed and deliberately did not change: Bounce budget reached its cap at this round, so the tree is published as reviewed. Nothing was left |
|
Workflow [PR], commit [84b1864] Summary: ✅
AI ReviewSummaryThis PR tightens Final Verdict✅ No findings in current HEAD. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 49/55 (89.09%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-self-slot-58:20260820-152500 |
|
cc @azat @shankar-iyer, could you review this? |
The String section of 04510 only inserted 'a' and 'b'. Neither equals the default value of the key type, so its pure-NULL assertions could not fail: a NULL set element that had decayed into the target's default would match no row, which is the same answer as correctly dropping it. Insert an empty-string row so the two outcomes differ, and add an explicit has(['']) arm showing that a real empty string does match that row. The Dynamic and Variant section of the same file already relied on such a row for the same reason, so this makes the String section consistent with it. Test only, no behavior change. Verified both directions with the clickhouse-test runner: the file passes on this branch and still fails on the pre-fix base, so the added row does not weaken the existing arms. The mixed-set granule assertion moves from 1/2 to 2/3 because the extra row adds a mark at index_granularity = 1; a full scan of the same table reads 3/3, so pruning is still asserted.
|
Both findings checked against the code and measured on a build of this branch (Build ID Finding 1 ( Finding 2, code half ( Finding 2, test half - taken, pushed in 84b1864. Correct that with only |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units740 translation units recompiled, 7228 s compile time in total, 740 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
… can run 26.3's KeyDescription::getKeyFromAST takes no `virtuals` argument (#102827 is not on 26.3), so drop the `{}` the cherry-pick carried. The test built its Delta tables with INSERT INTO FUNCTION deltaLakeLocal under allow_delta_lake_writes. On 26.3 that setting is still called allow_experimental_delta_lake_writes, and a partitioned INSERT of a NULL value fails with NOT_IMPLEMENTED (#111793 is not on 26.3). Write the same tables by hand instead, as 26.3's 05237 test does: Parquet data files through file() and one add action per file, a NULL partition value committed as a JSON null under __HIVE_DEFAULT_PARTITION__. Two cases fail on 26.3 with and without this change, so they are dropped: `ifNull(p, 0) IN (0)` prunes the NULL partition (a MergeTree table partitioned by the same Nullable column returns the same wrong rows on 26.3), and `has([NULL, 'a'], s)` throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN (#115647 is not on 26.3). On 26.3 the fix keeps the NULL partition's file for `has([5, 7], p)`, so that case prunes 1 file instead of 2 (rows unchanged): 26.3 builds no set index for a UInt8 array over a Nullable(Int64) key; 26.3's MergeTree partition pruning does not use that predicate on a Nullable key either. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #115294
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Code: 349. Cannot convert NULL value to non-Nullable typewhen ahasornotHaspredicate carries a NULL array element and the primary key is aString,Array(String)orMap(String, String), and fixed wrong results when that element is aDynamicorVariantholding NULL. The NULL is now dropped from the set during key analysis, as it already was for other key types.Description
No related open issue. Reproduces on 26.7.4.55:
ENGINE = Memoryanswers0for the same data, and key analysis raises the error, so no rewrite avoids it.canBeSafelyCastdeclaredNullable(X) -> Stringsafe, butStringcannot hold a NULL.tryPrepareSetColumnsForIndextrusts that and exits early through the non-accuratecastColumn, which throws. Every other target answers "not safe" and routes tocastColumnAccurateOrNull, which filters unrepresentable elements out; this pair never reached it.ArrayandMapinherit it by recursion.The switch made the same claim for
DynamicandVariant, which carry NULL in a discriminator. There it gave wrong results rather than an error: the NULL became'', entered the set index and pruned away rows keyed''. ANullabletarget represents it, so those two stay safe against one.That routes more targets into
castColumnAccurateOrNull, which refuses a target it cannot wrap inNullable. All four guards over such a cast tested only the outer type, so aTuple(Array(String))key passed and then raisedCode: 43; theEmbeddedRocksDB/KeeperMap/Redishelper had no check at all. Each now asks the cast about the target, and that helper also strips theLowCardinalityencoding, as the key-analysis guards did.Scalar,
Nullable,LowCardinalityand plainTuplekeys keep their pruning; a container key scans when its element is Nullable-nested. Both tests fail without this change and pass with it, 50/50 under randomization.Two of my open PRs touch this. #115294 is orthogonal but appends to the same test, so the second to merge rebases it. #112890 makes two of the same
canBeSafelyCastchanges without these guards, so alone it raises thatCode: 43for a container key.Workflow [PR]
Sync PR [sync-upstream/pr/115647]
Version info
26.8.1.1872(included in26.8and later)