Repository navigation
Fix accurate casts from an unsigned integer to IPv4 and IPv6 - #113040
antaljanosbenjamin merged 3 commits into
Conversation
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
Internal second-model review (0 blockers, 0 majors)Reviewed independently of the author: a cold read of the resulting code first (carriers enumerated Result: 0 blockers, 0 majors. The second-model pass returned no findings. Five nits from the
Independently verified during the cold read, rather than taken from the author's notes:
Session id: cron:clickhouse-review-slot-48:20260802-220600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260802-182400 |
|
cc @Ergus @KochetovNicolai, could you review this? |
|
Workflow [PR], commit [ef6d259] Summary: ✅
AI ReviewSummaryThis PR fixes the accurate-cast dispatch gap for unsigned-integer to Final Verdict
LLVM Coverage ReportMeasured on commit ef6d259.
Changed lines: Changed C/C++ lines covered: 37/37 (100.00%) · Uncovered code |
Build (arm_tidy) failed with cppcoreguidelines-init-variables, which is enabled with -warnings-as-errors: the loop-local out-parameter passed to accurate::convertNumeric was declared without an initializer. The header is included by 35 translation units, so the single declaration produced 38 diagnostics and dropped the other 151 jobs of the workflow. No behavior change: convertNumeric assigns the variable on every success path, and the failure path never reads it. Co-Authored-By: Claude Fable 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+60.31 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units40 translation units recompiled, 292 s compile time in total, 40 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.13 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger - 3c46800Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 175 check-runs, 0 queued or in progress,
Session id: cron:our-pr-ci-monitor:20260803-053000 |
…ey-in-nullable-uint32-set-index
|
The
CREATE TABLE t (k IPv4) ENGINE = MergeTree ORDER BY k;
INSERT INTO t SELECT number FROM numbers(1000);
SELECT count() FROM t WHERE k IN (SELECT number FROM numbers(100)); -- 0, expected 100
SELECT count() FROM t WHERE k NOT IN (SELECT number FROM numbers(100)); -- 1000, expected 900Both give the expected counts with |
… type Master's 04708_accurate_cast_integer_to_ip (from ClickHouse#113040) asserts that an IPv4 key compared with IN against a UInt32 subquery set still prunes (`Parts: 1/3`). keyToSetConversionMayCollapse sent that pair to its conversionPreservesOrder fallthrough, which knows no IP rule, so the set was declined and the Fast test failed. Set::execute casts the key into the set type with an accurate cast. Measured on this build: IPv4 into UInt32/UInt64/UInt128/UInt256 is the identity, into IPv6 it maps to ::ffff:a.b.c.d; IPv6 into UInt128 is the identity, into IPv4 it is exact for mapped addresses and NULL otherwise; UInt8..UInt64 into IPv4 are range-checked, UInt128 into IPv6 exact; every other pair throws or yields NULL. So no distinct keys merge. UInt128/UInt256 sets over an IPv4 key stay declined: the index casts such a set into IPv4 and gets NULL, so it prunes every part while the scan matches (master: count 0 vs 1). The new 05403 line checks that; it fails if the arm admits any unsigned set type. UInt8/UInt16 keys stay declined against an IPv4 set, since the index cannot cast IPv4 into them (master throws NOT_IMPLEMENTED there). Validation: 04708 FAIL -> OK; 936-test deterministic A/B against the previous head changes nothing else; 9 related tests x10 randomized OK. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #111418
Requested in #88234 (comment)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
accurateCast,accurateCastOrNullandaccurateCastOrDefaultfrom an unsigned integer toIPv4, and fromUInt128toIPv6: they never converted the value even though the plainCASTof it succeeds. Because the MergeTree set index builds its pruning set withaccurateCastOrNull, anIPv4primary key withINover aUInt32subquery returned no rows.Description
accurateCastOrNull(x, 'IPv4')returnedNULLfor every unsigned integer,accurateCastthrew, andaccurateCastOrDefaultreturned0.0.0.0, whileCAST(x, 'IPv4')converts it. Same forUInt128toIPv6:No unusual setting is needed: the AST fuzzer's TLP oracle hit this on master, where an
IPv4key with a plainUInt32GLOBAL INreturned 0 of 15 rows.FunctionCast::createWrapperenters its accurate branch for any integer source, then dispatches into a lambda whose value-producing arms are guarded byIsDataTypeNumber<RightDataType>. That trait is specialized only forDataTypeNumber<T>, whichDataTypeIPv4/DataTypeIPv6are not: their field type is aStrongTypedef. No arm matched, so the wrapper fell through to an all-NULLcolumn or a throw, never examining the value. PlainCASTreachesConvertImpl, which already supports integer toIPv4.This adds the missing dispatcher arm plus an accurate integer-to-
IPv4conversion that range-checks againstIPv4::UnderlyingType, mirroringconvertFieldToType. That check is load-bearing: the existing helper truncates, so reusing it would replaceNULLwith a wrong value.UInt128toIPv6needs only the dispatcher arm. Fixing the conversion layer corrects every consumer; aKeyCondition-only fix would leave symptoms 2 and 3.Plain
CASTkeeps its behaviour, including truncation above 2^32. Out-of-range values are now rejected rather than truncated, and the set index still prunes (Parts: 1/3, asserted).03212_variant_dynamic_cast_or_defaultis updated:toIPv4OrDefault/toIPv6OrDefaultbuild on the accurate cast, as in #110459.How the scope was established (702-pair cast sweep)
Consumers corrected by the single change:
Set(runtimeIN),KeyCondition(the set index),castOrDefault,KVStorageUtils,FunctionsJSON,evaluateConstantExpression.All 702 ordered pairs over 27 types were swept against the invariant "plain
CASTsucceeds, so theaccurate cast must not return
NULL". Exactly 6 pairs violated it, and all 6 are fixed here with noresidue:
CASTaccurateCastOrNullbeforeUInt8IPv40.0.0.1NULLUInt16IPv40.0.0.1NULLUInt32IPv40.0.0.1NULLUInt64IPv40.0.0.1NULLBoolIPv40.0.0.1NULLUInt128IPv6::1NULLBoolneeds no special handling, beingDataTypeUInt8.UUIDand theInt*/Float*/UInt256sources stay out of scope: plain
CASTthrows for those too, soNULLis already consistent, andmaking them convertible would be a new capability rather than a bug fix. The new test pins them as
negative controls, together with the
4294967295/4294967296boundary pair and theNullable/LowCardinality/Constwrapper matrix.Workflow [PR]
Sync PR [sync-upstream/pr/113040]
Version info
26.11.1.84-master(included in26.11and later)