Skip to content

Fix accurateCastOrNull and CAST to Nullable for a FixedString source - #121064

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-accurate-cast-or-null-fixedstring-source
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-accurate-cast-or-null-fixedstring-source

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120674

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 accurateCastOrNull, accurateCastOrDefault and CAST(... AS Nullable(T)) throwing, or silently returning a wrapped value, when a FixedString is converted to a number, Decimal, date/time or UUID: they now return NULL (or the default) as they already did for a String source. Also fixes IN with an unparseable FixedString set element failing primary-key analysis, and toDecimal*OrNull/...OrZero returning NULL/0 for a valid decimal held in a zero-padded FixedString.

Description

True-master SQLancer (arm_release) hit accurateCastOrNull(c1, 'Int32') throwing CANNOT_PARSE_NUMBER for a FixedString(12) column (report). The throw is pre-existing; the silent half is worse: a FixedString never reached the NULL-on-error parser, so accurateCastOrNull(toFixedString('300', 12), 'Int8') returned 44 where a String returns NULL.

createWrapper picked that parser by testing for DataTypeString, so a FixedString fell through to the ordinary converter, whose integer reader has no range check; createDecimalWrapper had the same shape. Both now key off the requested error policy, excluding CastType::accurate, which must keep rejecting (redundant once #120674 lands).

Routing alone is not enough for Decimal*: the non-throwing reader hard-codes digits_only = true, so it fails on the zero padding where the throwing one stops and isAllRead forgives it. ConvertThroughParsing now trims trailing NULs before that read; SerializationDecimal and readDecimalText are untouched.

KeyCondition::tryPrepareSetColumnsForIndex uses castColumnAccurateOrNull to mark set elements a key type cannot represent, so it threw there too; such an element is now dropped and index analysis completes. Hence 03991_set_variant_low_cardinality_in_global_in now expects CANNOT_CONVERT_TYPE: there, a String element on master already failed that way and only a FixedString gave CANNOT_PARSE_TEXT. A non-key column is unchanged.

Validated with a 135-probe A/B matrix, a per-hunk mutation matrix, and all 535 stateless tests naming a FixedString diffed against base: no new failure.

Four adjacent defects measured and left out; happy to take any as a follow-up
  • FixedString to IPv4 fails with ILLEGAL_COLUMN even for '1.2.3.4': convertToIPv4 accepts only ColumnString, unlike convertToIPv6 and toIPv4.
  • A Tuple element conversion ignores the OrNull policy, for String and FixedString elements alike.
  • CAST to a Tuple rejects a FixedString source outright (Code 53), where a String source is parsed.
  • An all-NUL FixedString converts to 0 for integer targets but NULL for Float64; toInt32OrNull agrees with the 0.

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

groeneai and others added 2 commits September 19, 2026 17:09
accurateCastOrNull(c1, 'Int32') threw CANNOT_PARSE_NUMBER for a
FixedString(12) column on true master (SQLancer arm_release at
112492e), and the silent half of the same defect is worse: a
FixedString source never reached the NULL-on-error parser, so
accurateCastOrNull(toFixedString('300', 12), 'Int8') returned 44 where a
String source returns NULL.

accurateCastOrNull resolves to Nullable(Int32), so prepareRemoveNullable
passes requested_result_is_nullable = true but invokes the wrapper with the
nested Int32. createWrapper's NULL-on-error branch tested
checkAndGetDataType<DataTypeString> only, and can_apply_accurate_cast admits
a text source only for CastType::accurate, so both guards failed and the
conversion fell back to FunctionTo<T>::Type. That converter's own rescue for
a text source with a Nullable target is dead here, because the adaptor
received the nested type, so it selected
ConvertThroughParsing<FixedString, T, ..., Throw>, whose parseImpl calls
readIntText, which has no overflow check. createDecimalWrapper had the
identical shape one level down.

Both sites now select the parser from the error policy the caller requested
rather than from which of the two text types the source is, excluding
CastType::accurate, which must keep rejecting. That conjunct becomes
redundant once ClickHouse#120674 lands; until then it is the only thing keeping
accurateCast(FixedString, 'Nullable(T)') throwing.

Routing alone is not enough for Decimal* targets. The two decimal readers
disagree on digits_only: readDecimalText defaults it to false and stops at
the first byte it cannot parse, so isAllRead can forgive a FixedString's
zero padding afterwards, while tryReadDecimalText hard-codes it to true and
fails on that byte before isAllRead ever runs. Sending a padded value down
the NULL-on-error path therefore turned a correct 3.14 into NULL.
ConvertThroughParsing now trims trailing NULs off string_size for the
non-throwing FixedString to Decimal* case, before the read buffer is built;
next_offset stays the physical stride, so the per-row iteration is
unchanged. The same asymmetry was a second pre-existing defect, so this also
fixes toDecimal*OrNull and toDecimal*OrZero on a zero-padded FixedString.
SerializationDecimal, readDecimalText and tryReadDecimalText are untouched.

The trim is scoped rather than applied to every target: FixedString(16) to
UUID and to IPv6 read all 16 bytes binary, and a UUID or address ending in a
zero byte would be truncated. DateTime64 and Time64 are excluded because
IsDataTypeDecimal is specialized true for both, while the decimal branch is
only reached after those two are handled above it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the two clauses narrating the new predicate's own design; keep the accurate-cast policy as a one-line invariant and the decimal reader's padding semantics in two.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 19, 2026
@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; 0 findings; bounded: 1 full pass +
1 fix round + 1 delta recheck). It read every changed function and test in full, traced the cast
dispatch and its callers, and checked the String/FixedString, Nullable, LowCardinality,
Const, Variant, Dynamic, decimal, temporal, UUID and IPv6 sibling paths.

Two things I noticed myself and am not changing, listed so you do not have to find them:

# Sev Finding Verdict Evidence / action
1 💡 No mutation can redden site 3's !to_datetime64 && !to_time64 conjuncts DISAGREE They are required rather than defensive: the non-throwing branch is ordered to_datetime64, to_time64, then IsDataTypeDecimal, so only the third reaches the reader with digits_only = true, and IsDataTypeDecimal is specialized true for both temporal types. Without them the guard would be wider than the branch it protects.
2 💡 The same two-line predicate is spelled at createWrapper and createDecimalWrapper instead of in a helper DISAGREE Two occurrences, two lines, each with its own local comment; a helper is net-neutral on line count, and both copies become removable together once #120674 lands. Happy to extract it if you prefer.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260919-171300

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@groeneai
groeneai requested review from Avogar and nihalzp September 19, 2026 17:54
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4fa89a8]

Summary: ✅


AI Review

Summary

This PR routes FixedString conversions through the requested null-on-error parser and handles trailing NUL padding for non-throwing decimal conversions. Reviewed head 4fa89a82e16a7dc18895419ffbf90e56f3bc0b1e, the full diff, and all prior discussion. No actionable findings remain.

The PR-head CI binary reproduced all 67 regression output lines exactly, validated all five expected exceptions, and passed the modified 03991 test. Additional probes covered multi-row decimal padding, nullable sources, default substitution, date parsing modes, and explicit time zones.

Consumers checked for the newly nullable intermediate columns:

  • prepareRemoveNullable merges conversion and source null maps.
  • LowCardinality wrappers reconstruct dictionaries with the requested nullability.
  • Array and tuple wrappers preserve nullable elements and propagate tuple conversion failures.
  • Variant and Dynamic assemblers unify converted-column nullability, including shared Dynamic values.
  • accurateCastOrDefault substitutes defaults using conversion failures.
  • KeyCondition filters unrepresentable set elements through the failure null map; the index regression matched its reference.
Final Verdict

✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Sep 19, 2026
Fast test reddened 03991_set_variant_low_cardinality_in_global_in on this
branch. That test's set element is toFixedString(toLowCardinality('not a
number'), 12) and it pinned serverError CANNOT_PARSE_TEXT, which is the exact
throw this branch removes.

KeyCondition::tryPrepareSetColumnsForIndex prepares an IN set with
castColumnAccurateOrNull, whose job there is to write NULL where a set element
cannot be represented in the key type, so that the null map marks the cast
failures. For a FixedString element that call threw instead, from inside index
analysis, and the query failed. It now returns NULL, the element is dropped
from the set, index analysis completes and prunes every granule, and the query
proceeds to the Variant conversion a String element already reached on master.

That parity decides the new expectation, and it is measured rather than
argued: on unmodified master the same query with a String or
LowCardinality(String) element already fails with CANNOT_CONVERT_TYPE, and
only the FixedString element gave CANNOT_PARSE_TEXT. So the expectation moves
to CANNOT_CONVERT_TYPE and nothing else in that test changes. Its own
invariant still holds: issue ClickHouse#97854 is about a LOGICAL_ERROR bad cast, while
CANNOT_CONVERT_TYPE is an ordinary exception raised after index analysis has
run to completion, which is further than the test reached before.

Group L pins that carrier, with the String element beside it as the control.
The count alone would pass even if the primary key were never consulted, so it
also asserts through EXPLAIN indexes = 1 that the primary-key condition holds
a 0-element set: the subquery yields exactly one row, so zero elements is that
element being dropped. A non-key column yields 0 there instead of 1. The table
pins add_minmax_index_for_numeric_columns = 0, as 146 other stateless tests
already do, because the implicit index prints the same condition a second time
and would make the count 2.

Only a key column reaches this path. For a non-key column the row-level in
still fails with NOT_IMPLEMENTED, because the comparison itself does not
accept a FixedString set element; that is unchanged by this branch.

Over every stateless test that mentions a FixedString (535 of them) this
branch adds no failure base does not already have, and the only two tests that
redden on base and pass here are this one and 03991.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 986fda9

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 6/6) / optimize_time_filter_with_preimage #1 the dashboard-verdict gate merged on 2026-09-19 (#120927) reds the shard on a dashboard confirmed_regression that the shard's own report does not corroborate: client_time 0.4186 -> 0.4837 (+15.5%) is confirmed_regression, while the same run reports 4 too long, 1 faster, 1 unstable and no slower. Not reachable from this diff, which fixes accurateCastOrNull and CAST to Nullable for a FixedString source; the benchmark casts nothing from FixedString. Measured over the last 24 hours: 178 rows carrying this signature across 130 distinct pull requests and 134 distinct heads, onset 2026-09-19 14:02:31Z #121090 (mine, open)
Build profile diff job-level RuntimeError: CI logs cluster query failed traceback out of ci/jobs/build_profile_diff_job.py, so a non-ok CI logs cluster response aborts the job instead of degrading to "no baseline". The job only reads build_time_trace on the logs cluster and neither builds nor runs the server, so it is not reachable from this diff. Measured over the last 24 hours: 389 rows across 348 distinct pull requests #118708 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent failure #121090 (mine, open) and #118708 (mine, open)

Session id: cron:our-pr-ci-monitor:20260920-110135

The comment claimed that unparsable text now returns NULL for every
target family. It does not. A FixedString source reaches convertToIPv4,
which accepts only ColumnString and throws ILLEGAL_COLUMN: on this head
accurateCastOrNull(toFixedString('1.2.3.4', 7), 'IPv4') is Code 44 while
the String source returns 1.2.3.4. A Tuple target rejects a FixedString
source with Code 53 where a String source parses. Both gaps are in the
description as adjacent defects left out of this change, so the comment
now claims only what the queries below it prove.
…r-null-fixedstring-source

# Conflicts:
#	src/Functions/FunctionsConversion.h
@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4fa89a82e with master 97f90315e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.65, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 14.2 s +10.5 s (+280%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.6 s +5.4 s (+243%)
Compile time of recompiled translation units

40 translation units recompiled, 294 s compile time in total, 40 of them have a recent master baseline.

Job report

This branch has not been deployed

No deployments
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 comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants