Repository navigation
Make accurateCast reject text a Nullable target cannot represent - #120674
alexey-milovidov merged 4 commits into
Conversation
accurateCast is documented to throw when a value cannot be converted, and it does, except when the requested target is Nullable and the source is String or FixedString: there it silently returned NULL. FunctionCast::createWrapper picks the NULL-on-error text parser from requested_result_is_nullable alone, without consulting cast_type, which shadows the accurate strategy that 92dfaa7 added for String to integer. createDecimalWrapper, createFixedStringWrapper and the IPv4/IPv6 wrappers branch on the same flag. The reported consequence (ClickHouse#120524) is silent data corruption in the DeltaLake write path, which casts with castColumnAccurate: an unparsable or out-of-range string is committed as NULL and the INSERT is acked, for data columns and for partition keys (which land under p=__HIVE_DEFAULT_PARTITION__). The same hole exists at every nesting level, and for a String variant of Variant/Dynamic. prepareRemoveNullable now asks prepareImpl for the non-Nullable result for an accurate text conversion, so the conversion itself raises its own error: each Nullable arm reports what its non-Nullable twin already reported, and no error code is synthesized. Every accurate cast whose source is nullable now filters its NULL rows out before converting and expands them back, the shape IExecutableFunction::defaultImplementationForNulls already uses, so a row the user marked NULL is never parsed. Filtering per nullable level, rather than propagating a mask down to the leaf, is what makes a nested conversion structurally unable to see a masked payload. An identity conversion is left alone, since it can neither reject a value nor produce a NULL, so filtering and expanding it cannot change its result and would only cost it a per-block copy. That second half also fixes a pre-existing bug of the same family: accurateCast(nullIf(materialize(999999999999::Int64), 999999999999), 'Nullable(Int8)') threw CANNOT_CONVERT_TYPE on a row the user marked NULL, where CAST and accurateCastOrNull correctly returned NULL. CAST, accurateCastOrNull, accurateCastOrDefault, ordinary INSERT conversions, delta_lake_accurate_write_cast=0 and every non-text source are unchanged. With cast_ipv4_ipv6_default_on_conversion_error set, an unparsable address now yields the type's default, which is what the setting asks for, where the Nullable target used to override it with NULL. No DeltaLake source file changes: both Delta carriers are fixed through the shared cast. Closes: ClickHouse#120524 Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the narration of how the fix routes the cast and why the identity conjunct is cheaper; keep the three pre-existing properties (NULL-on-error text parsing under a Nullable request, an identity conversion cannot reject or NULL, a NULL row's nested payload is a default) as standalone invariants.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). Two rounds: 1 finding on the first head
Checked and found sound rather than assumed, since each is load-bearing: the Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20260917-181502 |
Pre-PR validation (a-i)
Also: 61 of 62 tests in the cast/nullable/deltalake families pass; the one failure |
|
Workflow [PR], commit [f45da44] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings on the current head. LLVM Coverage ReportMeasured on commit f45da44.
Changed lines: Changed C/C++ lines covered: 80/81 (98.77%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units13 translation units recompiled, 93 s compile time in total, 13 of them have a recent master baseline. |
The accurate cast now rejects a text value the attribute cannot represent, and two
kinds of row in a getOrDefault call never hold a value the user meant as a default:
* maskedExecute evaluates a lazily evaluated default argument only on the rows whose
key was missing and expands the result back to full size, filling the rest with the
argument type's own default value. An empty String is not a number, so a query whose
defaults are all valid started failing with CANNOT_PARSE_TEXT as soon as one key was
found.
* A row whose key is NULL takes NULL from the key's null map after the lookup, so the
default is irrelevant there, yet it was still computed and converted.
Convert the rows the mask selects, after clearing the NULL keys from it, and expand the
result back, which is the shape maskedExecute uses itself. An identity conversion is left
alone, so a default whose type already matches the attribute pays nothing for it.
Two failures that predate this PR go away with the same change, because
clearMaskedNullsBeforeCast can only clear a null map and not a payload the parser refuses:
the same lazy default fails on master for a non-Nullable attribute, and a key-derived
default fails on master with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN when one key is NULL.
05232 covers the two internal users of the accurate cast that the changelog entry names,
a dictionary attribute default and an IN set key under transform_null_in = 1, plus the
rows above.
CI finish ledger - 122246dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
None of this is reachable from this PR's diff ( Session id: cron:our-pr-ci-monitor:20260918-060050 |
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Could you review the test PR and add the |
…`05217` Master ClickHouse#120674 made `castColumnAccurate` reject a text value a `Nullable` target cannot represent instead of returning `NULL`, and `IDictionary::convertKeyColumns` converts key expressions with it. `dictGet('conversion_null_scalar', 'attr', s)` for `s = 'bad'` now throws `CANNOT_PARSE_TEXT` with `optimize_inverse_dictionary_lookup` off, and with it on too, since the pass leaves a `String` probe of a `Nullable(UInt8)` key alone. The `nullable conversion results` section asserted the old behaviour, that `'bad'` becomes `NULL` and finds the `NULL`-keyed row. Split the section: the unparsable string asserts the exception with the setting off and on, and the parsable rows keep the result comparison between the two settings. The `Fast test` on `e01a39b7` ran on the merge with that master and failed exactly there: https://github.com/ClickHouse/ClickHouse/actions/runs/35542885571/job/106163846437 Related: ClickHouse#120674
…old-analyzer assertions
Two statements of `04545_transform_null_in_non_nullable_key` stopped working against
current master. Neither is reached by this branch's `KeyCondition` change: both were
reproduced on the master snapshot binary, which does not carry it.
1. `SELECT hex(s) FROM t_f2 WHERE s IN (SELECT CAST('a', 'Nullable(FixedString(1))') ...)`
now fails with `TOO_LARGE_STRING_SIZE`. With `transform_null_in = 1` the runtime
membership check casts the key into the set's element type with the throwing accurate
cast, and `FixedString(2) -> Nullable(FixedString(1))` used to return NULL for every
value, so every row matched the NULL in the set: that is why the reference listed all
three rows. ClickHouse#120674 made an accurate cast raise instead of silently returning NULL for
a text source with a Nullable target, so the query is now rejected outright. The arm
pins the rejection, and the index-level decline it exists for is asserted as before.
The same query with `transform_null_in = 0` still returns an empty result.
2. The two `SETTINGS enable_analyzer = 0` assertions cannot run: the setting is refused
since v26.9 (`SETTING_CONSTRAINT_VIOLATION`). They asserted the trivial-count
optimization, which only the removed old query analysis reached for a `SELECT count()`
carrying a `WHERE`; the analyzer plans both an exact-empty and a relaxed set of that
shape as the same implicit-projection read, so the distinction is no longer observable
and the assertions are dropped rather than ported.
Verified with the real runner against a debug build of this branch merged with master:
04545 passes 30/30 with randomized settings and 1/1 without, and replacing the expected
error name makes it fail, so the new annotation is enforced.
Co-Authored-By: Claude Opus 5 <[email protected]>
A NULL row of a Nullable(Tuple) stores placeholders in its elements ('' for
a String, a NULL in a Nullable element, 0 for an Enum). prepareRemoveNullable
ran the Tuple conversion over the nested column of every row, and the
element conversions do not all read the null map they are handed: the
function adaptors parse the placeholder '' (Code 32/38), the not-NULL
precheck of a Nullable element and the LowCardinality containsNull() check
see the element NULL under a NULL tuple row (Code 349), and an Enum
placeholder 0 serialized to String throws 691. So CAST, INSERT SELECT and
ALTER TABLE ... MODIFY COLUMN from a Nullable(Tuple) with NULL rows threw
instead of returning NULL for those rows; the ALTER left a stuck mutation
and an unreadable column.
accurateCast already filters the NULL rows out, converts, and expands the
result (exclude_source_nulls, ClickHouse#120674). Enable it for every cast type when
the source is a Nullable(Tuple) whose nested type changes. The filter costs
+1.2 ns/row per Int element and +4-5 ns/row per String element on blocks
that contain a NULL row (release 26.10.5.57, measured through accurateCast);
blocks without NULLs are unchanged. The nested values of NULL rows in the
result are now the column default, as with accurateCast.
Related: ClickHouse#132577
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #120524
Related: #120518
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
accurateCastfromStringorFixedStringto aNullabletarget now throws the error its non-Nullabletarget already raised (CANNOT_PARSE_TEXT,TOO_LARGE_STRING_SIZE, ...) instead of returningNULL, and no longer throws for a row the source markedNULL. This covers every user of the accurate cast:DeltaLakewrites stop committing an unrepresentable value asNULL,dictGetOrDefaultrejects a default itsNullableattribute cannot hold and now converts only the defaults it uses,INno longer matches an unparsable key against aNULLin the set and raises the parse error instead wherever the set converts its keys strictly (undertransform_null_in = 1, and at any value of that setting when the key is aTuple,ArrayorMap; see #121232), andcast_ipv4_ipv6_default_on_conversion_erroryields the type's default for an unparsable address.CAST,accurateCastOrNull,accurateCastOrDefaultand ordinaryINSERTare unchanged, as is what a non-text source does with a value it cannot represent; useaccurateCastOrNullfor the previous behaviour. Closes #120524.Description
accurateCastis documented to throw when a value cannot be converted, and does, except for text into aNullabletarget:FunctionCast::createWrapperpicks the NULL-on-error text parser fromrequested_result_is_nullablealone, ignoringcast_type, which shadows the accurate strategy92dfaa7e49944added forStringto integer.createDecimalWrapper,createFixedStringWrapperand the IP wrappers branch on the same flag. TheDeltaLakesink casts withcastColumnAccurate, so an unparsable or out-of-range string was committed asNULLand theINSERTacked: data columns, partition keys (landing underp=__HIVE_DEFAULT_PARTITION__), every nesting level, andVariant/DynamicStringvariants.prepareRemoveNullablenow asksprepareImplfor the non-Nullableresult for an accurate text conversion, so the conversion itself raises its own error. Every accurate cast whose source is nullable filters itsNULLrows out before converting and expands them back, the shapeIExecutableFunction::defaultImplementationForNullsalready uses; per-level filtering is what keeps a nested conversion from seeing a masked payload. NoDeltaLakefile changes.Validated with a 93-arm A/B matrix (29 arms change, all intended; controls byte-identical), six mutation arms and 50 randomized runs. One residual, deliberately unchanged: a non-text
IPv6outside theIPv4mapping range still becomesNULL. A deeper placement insideConvertThroughParsingmeasures identical at a per-row cost; happy to move it there.Workflow [PR]
Sync PR [sync-upstream/pr/120674]