Skip to content

Fix accurateCastOrNull of a Variant or Dynamic tuple element that cannot be converted - #132576

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-accurate-cast-or-null-variant-member-tuple-element
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-accurate-cast-or-null-variant-member-tuple-element

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #132543

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 accurateCastOrNull and accurateCastOrDefault to a Tuple whose element is a Variant or Dynamic value that cannot be converted to the element type: the result is now NULL (or the given default) instead of a tuple holding the default of the element type. For an Array, Map or LowCardinality element such a value now converts as with accurateCast.

Description

On 26.10.3.7, accurateCastOrNull(tuple(materialize(toUInt16(3)::Variant(UInt16))), 'Nullable(Tuple(FixedString(2)))') returns ('\0\0') instead of NULL, and accurateCastOrDefault returns it instead of its default. The same happens with Dynamic and for nested or numeric tuple elements. Raised in the review of #132543 (thread); it predates #119183, so there is nothing to revert.

A Variant or Dynamic source converts member by member. createWrapperIfCanConvert returned no conversion for a member it cannot convert, and the caller inserted the default of the target for its rows. That is a failure only when the default is NULL, but a tuple asks its elements for the non-nullable element type and reads failures from a Nullable result, so the default ended up in a non-NULL tuple. The result depended on the other members: Variant(UInt16, String) already gave NULL.

When asked to report failures to a type without NULL, such a member now fails its values: through the existing all-NULL "not supported" conversion when the type can be inside Nullable, otherwise (Array, Map, LowCardinality) by converting its values as an array element does.

Behavior change: for an Array, Map or LowCardinality element such a member now acts as accurateCast (toUInt16(3) throws TYPE_MISMATCH, '[1]'::Variant(String) gives ([1]) instead of ([]), and the values under a NULL tuple are not converted). A member rejected although its values convert (a number to an Enum without 0, an array to QBit) now gives NULL here, as the top-level cast already does; #132256 fixes the Enum part.

The new test fails on master and passes with the fix; existing accurateCast*, Variant/Dynamic cast, Nullable(Tuple) and QBit tests pass unchanged.


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

groeneai and others added 2 commits November 18, 2026 03:43
…not be converted

Under accurateCastOrNull a Variant or Dynamic source converts member by
member. createWrapperIfCanConvert probes each member and returns no wrapper
for one it cannot convert, and the assemblers then insert the default of the
target for its rows. That default is a failure only when it is NULL. Since
a tuple asks its elements for a non-nullable element type and reads failures
from a nullable result, a rejected member fed a plain default into a non-NULL
tuple: accurateCastOrNull(tuple(materialize(toUInt16(3)::Variant(UInt16))),
'Nullable(Tuple(FixedString(2)))') returned ('\0\0') instead of NULL, and
accurateCastOrDefault ignored its default. The answer depended on the other
members: one converting into a Nullable column made the result Nullable and
the default NULL.

When asked to report failures to a type that cannot contain NULL, a rejected
member now fails its values instead: createToNullableColumnWrapper (the
existing "not supported under accurateCastOrNull" fallback) when the type can
be inside Nullable, so the tuple takes the NULLs; otherwise (Array, Map,
LowCardinality, AggregateFunction) the member converts its actual values
without reporting failures, as an array element does, so '[1]'::Variant(String)
gives [1] instead of [] and UInt16 to Array(UInt8) throws TYPE_MISMATCH as
accurateCast does. An empty member is not converted. Top-level casts, Nullable
element targets and non-accurateOrNull casts are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop two in-body comments that narrated the new branches; state the never-empty case of createWrapperIfCanConvert precisely in its header (fails every value, or converts strictly when the target cannot be inside Nullable).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ A member the probe accepts ([1]::Variant(Array(UInt16)) to an Array(UInt8) element, Map alike, 300 to LowCardinality(UInt8)) aborts with LOGICAL_ERROR instead of acting as accurateCast DISAGREE Not changed by this PR: the probe-accepted path (createWrapperIfCanConvert try body) is untouched, and the same queries abort on master (A/B: signal 6 on both builds). The Array/Map part is fixed by #132543; the LowCardinality part is a separate fix in progress.

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

Session id: cron:clickhouse-review-slot-8:20261118-034700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT accurateCastOrNull(tuple(materialize(toUInt16(3)::Variant(UInt16))), 'Nullable(Tuple(FixedString(2)))') prints ('\0\0') on every run on master (debug 361455a) and on 26.10.3.7.
b Root cause explained? createWrapperIfCanConvert returned no conversion for a Variant/Dynamic member it cannot convert, and the caller inserted the default of the target. A tuple asks its elements for the non-nullable element type and reads failures from a Nullable result, so the default went into a non-NULL tuple.
c Fix matches root cause? Yes. Such a member now reports its failure through the existing all-NULL "not supported" conversion (or converts strictly when the type cannot be inside Nullable), at the one place that decides a member has no conversion. No assembler or tuple change.
d Test intent preserved / new tests added? New test 05831_accurate_cast_or_null_variant_member_to_tuple_element: 11 bug rows, 7 controls, Array/Map values and errors. Mutating either new branch, the canContainNull condition or the empty-member guard makes it fail.
e Both directions demonstrated? Fails on the master build (defaults, ([]), unmet TYPE_MISMATCH), passes with the fix; 50/50 randomized runs and one non-randomized run pass.
f Fix is general across code paths? Both callers (Variant, and Dynamic incl. its shared variant) use the one helper, which has no other caller. Top-level casts, CAST, accurateCast and toX never reach the changed branches.
g Fix generalizes across inputs (params/datatypes/wrappers)? Variant, Dynamic, Dynamic(max_types = 0); OrNull and OrDefault; FixedString, numeric, nested and multi-element tuples; NULL rows; mixed members; Nullable element control; Array/Map values, errors and an empty member.
h Backward compatible? (maintainer-approved exception only) No setting, format or storage change. Rows that returned a wrong default now return NULL, the default, or the accurateCast result (stated in the description).
i Invariants and contracts preserved? Each member still yields one column of its own size (empty for an empty member), so discriminator and offset indexing holds; nullability unification is unchanged; the strict conversion's exception propagates.

Session id: cron:clickhouse-impl-slot-4:20261118-031300

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8b59f2]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

Reviewed #132576 at a8b59f29f425d2779a85ddbb1d23a1e77283df79. The change makes rejected Variant and Dynamic tuple elements report conversion failures correctly and excludes values hidden beneath source NULL tuples before strict conversion. The previous blocker is fixed; no outstanding findings remain. All 25 regression statements passed locally using the PR's fast-test binary, including expected exceptions, and the combined output matched the reference exactly.

Consumers of the intermediate nullable results were traced through createVariantToColumnWrapper and ConvertImplFromDynamicToColumn::execute (including shared storage), which unify column nullability; createTupleWrapper, which extracts failures into the tuple null map; prepareRemoveNullable, which restores row positions and merges source nulls; and FunctionCastOrDefault, which substitutes defaults for conversion failures.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 18, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit a8b59f29f425d2779a85ddbb1d23a1e77283df79 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

… member

A Variant or Dynamic member that the probe rejects now converts its values
strictly when the tuple element type cannot be inside Nullable. Those values
include the ones hidden under a NULL tuple, so
accurateCastOrNull(if(number = 0, NULL, tuple(materialize(toUInt16(3)::Variant(UInt16)))),
'Nullable(Tuple(Array(UInt8)))') threw TYPE_MISMATCH instead of returning NULL,
and a block mixing such a row with a convertible one failed as a whole.

prepareRemoveNullable already converts only the rows that are not NULL under
accurateCast. Do the same under accurateCastOrNull when the source type holds a
Variant or Dynamic, both for a Nullable result and for a tuple element asked to
report failures (a NULL tuple nested in a tuple), through one helper. Ordinary
tuples still convert every row, so they pay no filtering cost.

Reported in ClickHouse#132576 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a8b59f2

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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same job errored this way on 29 other PRs in the last 24 hours #129675 (mine, open)
PR praktika rollup of the row above #129675 (mine, open)

The other CIDB FAIL row on this head is Finish Workflow / Post Hooks of the earlier run that the review-threads gate limited; the re-run after the thread was resolved finished. All five Stateless tests (*, flaky check) jobs passed. Mergeable Check and CH Inc sync are green.

Session id: cron:our-pr-ci-monitor:20261118-110017

@PedroTadim PedroTadim self-assigned this Nov 23, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 24, 2026
Take the NULL-row filter helper `convertNotNullRows`, the position of the
`exclude_source_nulls` predicate and both call sites unchanged from ClickHouse#132576, so
the two PRs share one helper and differ only in the predicate. The helper now
returns the expanded column; the nullable-result branch wraps it with the
source null map, and the report-failures-as-NULL branch hands it to the
existing `wrapInNullable` tail, which merges the same map. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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... 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