Skip to content

Do not treat a cast to String from a type that can hold NULL as safe - #115647

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-nullable-to-string-not-safely-castable
Aug 21, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-nullable-to-string-not-safely-castable

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115294

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):

Fixed Code: 349. Cannot convert NULL value to non-Nullable type when a has or notHas predicate carries a NULL array element and the primary key is a String, Array(String) or Map(String, String), and fixed wrong results when that element is a Dynamic or Variant holding 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:

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 key analysis raises the error, so no rewrite avoids it.

canBeSafelyCast declared Nullable(X) -> String safe, but String cannot hold a NULL. tryPrepareSetColumnsForIndex trusts that and exits early through the non-accurate castColumn, which throws. Every other target answers "not safe" and routes to castColumnAccurateOrNull, which filters unrepresentable elements out; this pair never reached it. Array and Map inherit it by recursion.

The switch made the same claim for Dynamic and Variant, 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 ''. A Nullable target represents it, so those two stay safe against one.

That routes more targets into castColumnAccurateOrNull, which refuses a target it cannot wrap in Nullable. All four guards over such a cast tested only the outer type, so a Tuple(Array(String)) key passed and then raised Code: 43; the EmbeddedRocksDB/KeeperMap/Redis helper had no check at all. Each now asks the cast about the target, and that helper also strips the LowCardinality encoding, as the key-analysis guards did.

Scalar, Nullable, LowCardinality and plain Tuple keys 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 canBeSafelyCast changes without these guards, so alone it raises that Code: 43 for a container key.


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

Version info

  • Merged into: 26.8.1.1872 (included in 26.8 and later)

groeneai and others added 8 commits August 18, 2026 22:35
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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change against the repo review skill, and I adjudicated every
finding before opening the PR. Six fix rounds; this is the last one, so the entries below are what
was still open plus one finding from my own final read. Earlier rounds are folded in: each ended
with a fix, and the final round found nothing left in the fix logic.

# Finding Verdict Resolution
❌ 1 The branch did not merge cleanly into current master: both sides append a declaration after createInternalCast in src/Functions/CastOverloadResolver.h. AGREED Merged master, keeping both createCastOverloadResolver and canBeAccurateCastOrNullTarget. Verified after: git merge-tree exits 0, the merge touches only this branch's 9 files, no conflict markers. Rebuilt and re-ran the tests on the merged tree, plus master's two accurateCastOrNull validator tests.
❌ 2 #112890, also open and also mine, already makes two of these three canBeSafelyCast changes but carries none of the four target guards. AGREED Confirmed against its head tree, not just its patch: the Nullable-arm deletion and the identical LowCardinality recursion are there since 2026-07-22, while its KeyCondition.cpp still has the outer-only tests and it does not touch KVStorageUtils.cpp. Its own collapse check cannot cover this: that block sits behind isNullableOrLowCardinalityNullable, which is false for a Tuple element type. So alone it raises Code: 43 for a container key. Stated in the description; the guards belong to that PR or this one merges first.
⚠️ 3 The new canBeAccurateCastOrNullTarget comment claimed every nested type must be able to be inside Nullable. AGREED Wrong: a nested type is also accepted when it carries a NULL itself, as Dynamic and Variant do. Re-derived from canContainNull before rewriting; the comment now states the outer-versus-nested rule.
💡 4 canBeSafelyCast's header documented it only by examples, never by the invariant this change rests on. AGREED One sentence added: safety means every source value is representable in the target, NULL included.

Two findings from the previous round were re-checked and confirmed closed: a LowCardinality(String)
key-value primary key that had lost its point lookup (fixed by stripping the encoding from the cast
target, as the three sibling MergeTree guards already did), and four test assertions that could not
fail (the read-type controls now assert a Dynamic element, which actually reaches the guarded
branch, and the Nullable-key block asserts isNull() over a fixture holding a NULL row beside an
empty-string row in separate parts, so a NULL that decayed to the default value is observable).

Two things I noticed and deliberately did not change: canBeSafelyCast also calls
Array(X) -> String and Map -> String safe, and the Map arm surfaces Code: 70 rather than
Code: 349. Neither has a consequence beyond the one fixed here, and one concern per PR.

Bounce budget reached its cap at this round, so the tree is published as reviewed. Nothing was left
unresolved to reach it: the only open items were the merge and three comment fixes, all applied.

@clickhouse-gh clickhouse-gh Bot closed this Aug 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [84b1864]

Summary: ✅


AI Review

Summary

This PR tightens canBeSafelyCast for NULL-carrying sources and adds the missing accurateCastOrNull target checks on the affected MergeTree and key-value lookup paths, so unsupported container targets now decline the set index instead of throwing, while nullable-compatible scalar paths keep their pruning. I re-checked the two earlier bot findings against the current code and their reachable callers; neither still holds, and I did not find any new correctness, metadata, or coverage issues in the current diff.

Final Verdict

✅ No findings in current HEAD.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 49/55 (89.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization. Throw: the String-key has([CAST(NULL,'Nullable(String)')], k) in the description. Wrong results: the same key type holding '' and 'a' in two parts, where notHas(CAST([NULL],'Array(Dynamic)'), k) returns 1 and the answer is 2. A single-part table hides the second defect.
b Root cause explained? Yes, one mechanism in two type families. canBeSafelyCast called a String target safe for a NULL-carrying source, so tryPrepareSetColumnsForIndex took its fast exit through the non-accurate castColumn. For Nullable that throws. For Dynamic/Variant it cannot even throw (shouldThrowOnNull needs !canBeInsideNullable(), false for String), so the NULL became '' and entered the set index as a real element.
c Fix matches root cause? Yes, both false claims are deleted where they are made; the correct handling already existed downstream. The four guard edits follow from it: routing more targets into castColumnAccurateOrNull exposed that its callers asked a weaker question than the cast answers. A catch was rejected (it would hide a genuine unsupported-target signal). The predicate also had to model both of the cast's refusals, not just the validator's, since castColumn calls makeNullable unconditionally.
d Test intent preserved / new tests? Yes. Every pre-existing assertion kept; both references append-only across all six rounds (0 changed lines). New: the Dynamic/Variant block in both polarities via has/notHas and IN/NOT IN, untyped-NULL arms, container-key pruning pins, Tuple(Array) keys direct and via an expression key, and a new 04701 for key-value primary keys. Four assertions that could not fail were found and replaced (a Nullable element is unwrapped before the guard, so the read-type controls now assert Dynamic; the Nullable-key block asserts isNull(k) over a two-part ''/NULL fixture). One prescribed control was vacuous (count() resolves to _exact_count_projection, emitting no Granules: line) and was rewritten. Multi-part fixtures are pinned with SYSTEM STOP MERGES and the part count asserted.
e Both directions? Yes, on three binaries (pristine base, the intermediate head carrying only the earlier hunks, the final build). Base [ FAIL ] Code: 349 on one file; the pre-fix head [ FAIL ] Code: 43 on both; final [ OK ] on both. So each new block reddens on the binary whose defect it targets. The wrong-results block was run in isolation, since the throwing arm fires earlier and masks it. Every server was Build-ID-asserted against its binary before each verdict.
f General across code paths? Yes, and this question caught the round's blocker. grep -rn canBeSafelyCast src/ returns exactly 5 callers; 4 reach an accurate-or-null cast and all 4 now carry the predicate. KeyCondition.cpp:1694 is excluded on reading (bare return false, then only castColumnAccurate). Two were found only by enumerating rather than arguing: :1660, previously excluded on "no arm reached it", is reached by materialize/assumeNotNull/coalesce; and KVStorageUtils.cpp:207 had no check at all. A binary carrying only the first guard still errored through the second path. That key-value site also probed the raw declared type where its three siblings strip LowCardinality, which cost a LowCardinality(String) key its point lookup.
g Generalizes across inputs? Yes: Nullable, LowCardinality(Nullable), untyped NULL (a Nothing source, Code: 70), Array/Map/Tuple(Array) nestings, Tuple(Array(UInt64)) vs a UInt8 key (no Nullable at all, erroring before this PR too), Dynamic, Variant, mixed and all-NULL sets, has/notHas/IN/NOT IN, six ORDER BY wrapper shapes, Nullable keys, and MergeTree vs EmbeddedRocksDB vs Redis. Pruning is asserted across the same matrix, including a scalar expression key that must keep its granule count so a too-broad guard is caught.
h Backward compatible? Yes. No setting, default or format, so no SettingsChangesHistory.cpp entry. Errors become documented answers and wrong results become correct ones. One trade-off, disclosed: a container key gives up its set index when the element is Nullable-nested, even with no NULL (2/16 to 16/16). Results stay correct. A round also found the diff had cost a scalar Nullable key its pruning; that was repaired, so the trade is confined to container keys. A NULL-inspecting guard to recover the fast exit was rejected on measurement: a NULL-free element can still be lossy (CAST(CAST([256],'Array(Nullable(UInt64))'),'Array(UInt8)') gives [0] where accurateCastOrNull gives NULL).
i Invariants preserved? Three. canBeSafelyCast is false whenever the source can produce a NULL the target cannot represent, nested cases included, now consistent across all three carriers getSourceNullMap recognises. A guard before castColumnAccurateOrNull must test what the cast accepts, not just outer nullability; the non-throwing predicate and the throwing validator share one implementation so they cannot drift. Stripping LowCardinality from the key-value cast target changes the encoding asked of the cast, never the key bytes: rows cross as Fields, both consumers re-derive serialization from the declared key type, and SerializationLowCardinality::serializeBinary(const Field &, ...) delegates verbatim; the test asserts it by selecting the row's value on the point-lookup plan, which a wrong encoding would return empty.

Session id: cron:clickhouse-review-self-slot-58:20260820-152500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @shankar-iyer, could you review this? canBeSafelyCast declared a String target safe for a source that can hold a NULL, so set-index preparation took its non-accurate fast exit and raised Code: 349 for a String, Array(String) or Map primary key, and silently decayed a Dynamic/Variant NULL to '' inside the set. Routing those pairs to castColumnAccurateOrNull then needed the four guards over that cast to ask what it actually accepts rather than only testing the outer type's nullability.

Comment thread src/Functions/CastOverloadResolver.h Resolved
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both findings checked against the code and measured on a build of this branch (Build ID
cd39b309714bca7cad5270d616fbf72f7055eb5a) versus the pre-fix base
(c0ebcbf9653216d9a9b73a07d4e3042477631301).

Finding 1 (tryCastColumn in evaluateConstantExpression.cpp) - not taking it. The citation is
accurate: that guard does check only canBeInsideNullable(), and DataTypeTuple returns true
unconditionally. But the target is not user-chosen at either reachable call site. At
VirtualColumnUtils.cpp:783 it is the _path node, declared LowCardinality(String) at
VirtualColumnUtils.cpp:193. At StorageDistributed.cpp:1946 and :2010 it is the sharding key,
and checkShardingKeyExistsAndIsNumeric (StorageDistributed.cpp:284-300) rejects anything that
is not isValueRepresentedByInteger() at DDL time - measured, Tuple(a Array(String)) as a
sharding key gives Code: 53 ... but should be one of integer type, so the container target cannot
be installed. The element you supplied also does not survive on its own:
accurateCastOrNull(tuple([NULL]), 'Tuple(Array(Nullable(String)))') is
Code: 43 ... Type Array(Nullable(String)) is not supported for accurateCastOrNull, rejected by
the validator this PR refactored. I have no user-runnable input that reaches the branch, so I am
leaving it out rather than widening this PR into constant folding.

Finding 2, code half (source_is_nothing) - not taking it. [NULL] is
Array(Nullable(Nothing)), so set_element_type is Nullable(Nothing) and
WhichDataType(...).isNothing() is false; the isNullableOrLowCardinalityNullable branch above
runs instead and populates the real source null map. Bare Nothing carrying rows is not
constructible from SQL: CAST(NULL,'Nothing') and CAST([NULL],'Array(Nothing)') are Code: 70,
arrayJoin([]) is Code: 43, and [] types as Array(Nothing) with zero rows. Measured with the
row you asked for: has([NULL], k) is 0 with Condition: (k in 0-element set) and Granules: 0/3, and a 16-shape index-versus-no-index sweep agrees on all 16, including has(['', NULL], k)
returning 1. The literal poisoned form has([''], k) returns 1, so the oracle does discriminate.
KVStorageUtils.cpp:217-224 has no Nothing branch at all and already returns false on any cast
failure. That code is also not from this PR - it is 1418e54127b50e0, an ancestor of master.

Finding 2, test half - taken, pushed in 84b1864. Correct that with only 'a' and 'b' the
section could not fail: a NULL decaying into the default would match no row either, so the correct
and decayed answers coincided. Added an empty-string row plus an explicit has(['']) arm. Worth
noting the discriminating arms are the pre-existing pure-NULL ones, not new arms over ['', NULL]:
under a decay that set dedups to [''] and returns the same counts, so those would have asserted
nothing. 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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 84b186479 with master daae2ec89 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0b043a6c6; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.45 MiB 701.40 MiB -3.05 MiB (-0.43%)

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 units

740 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.
The matched translation units cost +572.6 s (+9%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov 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.

Ok.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 68d548f Aug 21, 2026
176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 12, 2026
… 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]>
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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants