Skip to content

Fix LOGICAL_ERROR in accurateCastOrNull to a Nullable(Tuple) with an Array or Map element - #132543

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-array-map-element-type
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-array-map-element-type

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132281
Related: #119183

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 Nullable(Tuple) with an Array or Map element: its elements now convert to their declared type, so the cast no longer throws LOGICAL_ERROR and accurateCastOrDefault no longer returns wrong values. When a value does not fit, the numeric, date, IP, Decimal, FixedString, Variant, Dynamic and text-to-integer conversions of such an element now fail as with accurateCast. Closes #132281.

Description

On 26.10.3.7, accurateCastOrNull(tuple(materialize([toUInt16(1)])), 'Nullable(Tuple(Array(UInt8)))') throws LOGICAL_ERROR, and accurateCastOrDefault with that target returns ([144,230,155]) for [1,2,300]. The AST fuzzer hit it in master stress tests (amd_tsan, amd_msan). It predates #119183 (26.10.3.7 fails too), so no revert.

Since #119183 a tuple asks its elements to report a failed conversion as NULL; array and map elements are not asked, so they convert strictly. Only the text conversions honored that. The other conversions and the "not supported" fallbacks returned Nullable for every accurateCastOrNull, and an array element kept it. A Variant or Dynamic element instead dropped a member it could not convert and returned the default.

These conversions now report a failure only when asked (requested_result_is_nullable), else they act as accurateCast. Array/QBit to QBit relied on the unasked Nullable to make a failed element a NULL row, so it now asks, restoring the 26.10 result \N for accurateCastOrNull([1, NULL]::Array(Nullable(Float32)), 'QBit(Float32, 2)'), which throws on master.

Behavior change: in an array or map element, these conversions and text-to-integer parsing ('300' to UInt8 gave 44) now fail as with accurateCast when a value does not fit, as a malformed String element and a NULL element already do on master. Top-level casts, direct tuple elements and Nullable or Variant element targets still return NULL.

The new test aborts a master server at the CI query and passes with the fix; existing accurateCast*, Nullable(Tuple) and QBit tests pass unchanged.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits November 17, 2026 21:05
…llable(Tuple)

`accurateCastOrNull(tuple(materialize([CAST('1', 'Int128')])), 'Nullable(Tuple(Array(UInt64)))')`
threw `LOGICAL_ERROR: Unexpected return type ... Got Nullable(Tuple(Array(Nullable(UInt64))))`
(STID 3262-3c86, Stress test (azure, amd_tsan) on master 95bfedb), and
`accurateCastOrDefault` with such a target read the wrongly typed column (`[1,2,300]` ->
`[144,230,155]` on 26.10.3.7).

Since 8f89508 (ClickHouse#119183) a tuple asks its elements to report a failed conversion as NULL
(`report_failures_as_null` -> `requested_result_is_nullable`), while the elements of an array
or a map are not asked and must convert strictly. Only the text conversions honored the flag.
The other producers of failure-NULLs keyed on `cast_type == CastType::accurateOrNull` alone:
the numeric, date/time and IPv4/IPv6 branches of `createWrapper`, `createDecimalWrapper`, the
NULL mode of `createFixedStringWrapper`, and the `createToNullableColumnWrapper` fallbacks of
`createWrapper`, `createDecimalWrapper`, `createEnumWrapper`, `createQBitWrapper`,
`prepareUnpackDictionaries` (NULL source) and `prepareImpl`. An unasked array element thus
came back as `Nullable(T)`, `ColumnArray` kept it, and the column type differed from the
declared one.

Each of these producers now reports a failure as NULL only when asked, and otherwise takes the
`accurateCast` branch it already had. Top-level `accurateCastOrNull` is unchanged (its result
is always Nullable, so it is asked), as are direct tuple elements and `Nullable` array
elements. `createArrayToQBitWrapper` (Array -> QBit and QBit -> QBit) relied on the unasked
Nullable to turn an element failure into a NULL row, so it now passes the request explicitly,
like `createTupleWrapper`; this also brings back the 26.10 result `\N` for
`accurateCastOrNull([1, NULL]::Array(Nullable(Float32)), 'QBit(Float32, 2)')`.

An array or map element that does not fit now fails as with `accurateCast`, as a malformed
String element and a NULL element already did.

Closes ClickHouse#132281

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

An Array or Map element of a Nullable(Tuple) is not asked to report a failed
conversion as NULL, so it must convert as accurateCast does. Two producers
still keyed on cast_type == accurateOrNull alone:

- createVariantToColumnWrapper / createDynamicToColumnWrapper pre-probed every
  member with createWrapperIfCanConvert and inserted the target default for a
  member without a wrapper. In an unasked element a String '1' member failed
  the probe on '' and became 0, and an IPv4 member to Decimal32(2) became 0
  (26.10.3.7 returns ([0]) for the String case). They now probe and drop only
  when asked: report_failures_as_null, or a NULL-capable target, which keeps
  the top level and direct tuple elements as before. Otherwise every member
  with values is converted strictly.
- The AggregateFunction "not supported" tail returned a Nullable wrapper for
  any accurateOrNull, so an unasked element failed with ILLEGAL_COLUMN; it now
  honors requested_result_is_nullable and otherwise throws the accurateCast
  CANNOT_CONVERT_TYPE.

A Variant or Dynamic target is NULL-capable, so it stays asked and is not
changed. The test gains the second master CI query (STID 3262-3a0d, Stress
test (azure, amd_msan)), the Variant/Dynamic and AggregateFunction element
lines, and controls for the asked paths.

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

createVariantToColumnWrapper and createDynamicToColumnWrapper decide whether
an accurateCastOrNull conversion is asked to report a failure as NULL. The
previous commit tested isNullableOrLowCardinalityNullable(to_type), which is
false for a Variant target. A Dynamic source can be cast to a Variant, and a
Variant target is never wrapped in Nullable (getReturnTypeImpl and
createInternalCast leave a canContainNull type as is), so the top-level call
passed report_failures_as_null = false and the strict branch threw Code 70 for
a stored type the Variant cannot hold:

  accurateCastOrNull(materialize(toUInt16(3)::Dynamic), 'Variant(UInt8, String)')
  accurateCastOrNull(tuple(materialize([toUInt16(3)::Dynamic])),
                     'Nullable(Tuple(Array(Variant(UInt8))))')

Base and 26.10.3.7 return \N and ([NULL]) there. Both wrappers now use
canContainNull(*to_type), so a Dynamic source still probes and drops at the top
level, in accurateCastOrDefault and in an Array(Variant) element. For a Variant
source nothing changes: its to_type is never a Variant or Dynamic, those are
routed earlier in prepareUnpackDictionaries.

The test gains the four lines above (plus accurateCastOrDefault and an IPv4
value) and two Dynamic -> Decimal32(2) controls.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3): 6 findings, 3 fixed, 2 DISAGREE, 1 nit noted
Finding Verdict
❌ Variant/Dynamic element of an array or map dropped a member it could not convert and inserted the default (e.g. IPv4 member to Decimal32(2)), unlike accurateCast AGREE, fixed @ 77cbfb0: such an element now converts strictly. String to a Variant/Dynamic target is not changed: that target can hold NULL, like an Array(Nullable(T)) element
⚠️ AggregateFunction fallback ignored whether a NULL result was requested (ILLEGAL_COLUMN instead of CANNOT_CONVERT_TYPE) AGREE, fixed @ 77cbfb0: it now follows the same rule
❌ The strict Dynamic path treated a Variant target as unable to hold NULL, so accurateCastOrNull(<Dynamic>, 'Variant(...)') threw instead of returning NULL AGREE, fixed @ 38f39b2: a Variant target counts as NULL-capable (canContainNull), as on 26.10
⚠️ Variant(String, UInt16) to Variant(String, UInt8) still throws DISAGREE: not touched here. A Variant target that is not an extension of the source is rejected by the type rule for CAST, accurateCast and accurateCastOrNull alike, the same on 26.10.3.7
⚠️ The accurateCastOrDefault(<Dynamic>, 'Variant(UInt64)') line cannot tell default substitution from a plain NULL DISAGREE: the line guards the throw it was added for and fails without 38f39b2. Default substitution is unchanged code; with an explicit default 26.10.3.7 returns it
💡 No query with a constant argument, as in the third master hit (Got Const(...), arm_tsan) Noted: constant folding runs the same conversion wrapper, so the fix covers it

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s, could you review this? Under accurateCastOrNull, the numeric, date, IP, Decimal, FixedString, Variant and Dynamic conversions returned Nullable even for an Array or Map element that did not ask for it, so Nullable(Tuple(Array(T))) got a column of the wrong type (LOGICAL_ERROR) and accurateCastOrDefault misread it; each conversion now honors requested_result_is_nullable.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT accurateCastOrNull(tuple(materialize([CAST('1', 'Int128')])), 'Nullable(Tuple(Array(UInt64)))')" aborts a master debug build with the CI's exact LOGICAL_ERROR every time.
b Root cause explained? The numeric/date/IP/Decimal/FixedString conversions and the "not supported" fallbacks returned Nullable for every accurateCastOrNull, ignoring that array and map elements are not asked to report failures, so the column type differed from the declared one; Variant/Dynamic sources dropped an unconvertible member to the default under the same blind check.
c Fix matches root cause? Yes. Each producer honors the existing requested_result_is_nullable flag; no consumer-side strip, no new validation.
d Test intent preserved / new tests added? New test 05828_...; no existing test changed. Reverting any one of six of the edits (three numeric/NULL/QBit producers, the Variant/Dynamic probe, its Variant-target predicate, the AggregateFunction tail) makes it fail.
e Both directions demonstrated? Yes. The test aborts a base server at the CI query and passes on the fix; every shape was also checked base vs fix one query per process.
f Fix is general across code paths? Yes. Every producer that keyed on accurateOrNull alone was changed, including the Variant/Dynamic member probe and the AggregateFunction tail; the one consumer relying on the leak (QBit) now asks explicitly.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Array, Map key and value, nested arrays and tuples, Variant, Dynamic, Nullable and LowCardinality sources, Variant targets, const and empty inputs, numeric/temporal/IP/Decimal/FixedString/Enum/UUID/Nothing targets, overflow values.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only inputs that threw LOGICAL_ERROR or returned misread values change, to a correct value or the accurateCast error.
i Invariants and contracts preserved? Yes. A wrapper returns the type it is asked for, plus an outer Nullable only when asked; a Nullable, LowCardinality(Nullable) or Variant target and a direct tuple element are asked, as before; CAST and accurateCast take the same branches as before.

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9c97270]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05257_autopr_rejected_by_cost_model FAIL cidb
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
codecs_float_insert #15 unstable query history
system_clusters_replicated_databases #0 unstable query history
system_clusters_replicated_databases #1 unstable query history

AI Review

Summary

The change fixes mismatched nested column types in accurateCastOrNull and accurateCastOrDefault to Nullable(Tuple(...)). Array and map elements now convert strictly unless their target can represent failure as NULL; QBit explicitly requests failure reporting. No new findings. The previous text-overflow finding is fixed; the other previous reports have separate tracking fixes in #132576, #132577, and #132579.

Consumer coverage: tuple conversion extracts requested failure masks; array and map construction receive their declared element types; Variant and Dynamic assembly retain nullable-target behavior; QBit aggregates element failures into row masks; accurateCastOrDefault receives the declared nested column layout. All 57 added regression queries and 23 valid exploratory queries passed using the fast-test binary for PR head 9c97270d1a04983e75cf3f6daf6e2d2989c261b5.

Final Verdict

✅ 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
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
…astOrNull

An Array or Map element of an accurateCastOrNull / accurateCastOrDefault
target is not asked to report a failed conversion as NULL, so it converts
as with accurateCast. Its String and FixedString to native integer
conversion still used the ordinary parser, which wraps an out-of-range
value: '300' to UInt8 gave 44, also for a Variant(String) or Dynamic
member, where accurateCast throws CANNOT_PARSE_TEXT. Use the accurate
parser there too.

Found by the clickhouse-gh review of ClickHouse#132543.

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

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9c97270d1 with master 59e76b2ee (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.

Object file sizes

5 object files changed (+22.80 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 25.07 MiB 25.09 MiB +22.80 KiB (+0.09%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.89 (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&) 7.2 s 16.4 s +9.9 s (+154%)
Compile time of recompiled translation units

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@nihalzp this should be the last of the bunch related to nullable tuples

@PedroTadim PedroTadim assigned nihalzp and unassigned PedroTadim Nov 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9c97270

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
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) / 05257_autopr_rejected_by_cost_model not related to this diff: deterministic (it also failed 244 of 244 runs without randomized settings). It failed on master until its compression codec was pinned; this re-run tests the merge commit of 2026-11-18, which predates that fix, and master has 0 failures of it since #132570 (mine, merged)
Performance Comparison (arm_release, master_head, 3/6) infra, not related to this diff: the runner disk filled up (peak 100% of 193.63 GB) and codecs_float_insert failed with Code: 243 ... Cannot reserve 8.48 MiB, not enough space. The tested merge commit predates the fix. The job's other notes (2 too long, 3 unstable) also appear on green master runs of this shard #131429 (mine, merged)

Mergeable Check and PR are the praktika rollups of these rows. The other CIDB FAIL row is the Finish Workflow / Post Hooks of the 2026-11-18 run, while a review thread was unresolved; the threads are resolved now and the workflow re-ran.

Session id: cron:our-pr-ci-monitor:20261124-163029

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

3 participants