Skip to content

Fix accurateCastOrNull to QBit returning NULL for a JSON, Dynamic or Variant vector - #132579

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-qbit-wrong-dimension
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/accurate-cast-or-null-qbit-wrong-dimension

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #100936
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, accurateCastOrDefault and JSONExtract to QBit returning NULL or zeros for a JSON, Dynamic or Variant value holding a valid vector. A value that does not fit the QBit (an array of another size, unparsable text, a QBit of another dimension) now gives NULL or the default instead of an exception. Closes #100936.

Description

On 26.10.3.7, accurateCastOrNull(j.e, 'QBit(Float32, 2)') returns \N for a JSON path holding [1, 2], while CAST(j.e, 'Nullable(QBit(Float32, 2))') returns [1,2]. The same holds for a Dynamic or Variant value, JSONExtract returns [0,0], and accurateCastOrNull([1., 2., 3.], 'QBit(Float32, 2)') throws. Found by the review bot on #132543 (thread).

A Variant/Dynamic member is kept only if converting its default value succeeds. The QBit conversion ignored the request to report failures as NULL: an array of the wrong size threw SIZES_OF_ARRAYS_DONT_MATCH, text was parsed strictly, and a QBit of another dimension threw TYPE_MISMATCH. So the default [] / '' failed, the member was dropped, and its rows became NULL or zeros.

When asked to report, a wrong-size array now marks its row in the row null map the Array to QBit wrapper already returns, text goes through createStringParsingWrapper as for Tuple, and a dimension mismatch returns NULL rows. accurateCast, CAST and Array/Map elements still throw. The second repro of #100936 already works since #109387.

Behavior change: accurateCastOrNull / accurateCastOrDefault to QBit return NULL / the default instead of throwing for such values; 03380 now expects \N on one line.

Based on #132543 (its commits show until it merges): without its nested element report, a JSON [1,null] would throw Code 349 once the member is accepted.

The new test fails on #132543's head and passes with the fix; the QBit, accurateCast* and Variant/Dynamic cast tests pass.


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

groeneai and others added 5 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]>
…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]>
…dimension

A Variant or Dynamic member is kept by accurateCastOrNull only if converting
its default value succeeds (createWrapperIfCanConvert). The QBit conversion
ignored the request to report failures as NULL (reports_failures): an array
of the wrong size threw SIZES_OF_ARRAYS_DONT_MATCH in convertArrayToQBit, a
String was parsed with ConvertImplGenericFromString<true>, and a QBit of
another dimension threw TYPE_MISMATCH when the wrapper was built. The default
of an Array member is [] and of a String member '', so the probe failed for
every Array and String member, the member was dropped, and a JSON, Dynamic or
Variant value holding a valid vector became NULL (top level), zeros (a tuple
element, accurateCastOrDefault, JSONExtract over a JSON column). The same
throws were the top-level exceptions of ClickHouse#100936.

Under reports_failures, convertArrayToQBit now marks a row of the wrong size
in the row null map createArrayToQBitWrapper already returns for element
failures (and zero-fills it instead of reading past a short row), the String
branch reuses createStringParsingWrapper as createTupleWrapper does, and a
dimension mismatch returns createToNullableColumnWrapper like the unsupported
source fallback. accurateCast, CAST and Array/Map elements, which are not
asked to report, still throw.

This builds on ClickHouse#132543, which asks the nested element conversion of
Array -> QBit to report; without it a JSON [1,null] would now throw Code 349
once the probe accepts the member.

03380 line 12 asserted the old exception; it now returns NULL.

Closes ClickHouse#100936

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

# Sev Finding Verdict Evidence / action
1 ❌ accurateCastOrNull of an Array(IPv4), Array(UUID) or Array(Tuple(...)) to QBit still throws DISAGREE The throw is the element conversion to a number, not the QBit code: on 26.10.3.7 accurateCastOrNull(materialize(toIPv4('1.2.3.4')), 'Float32') and accurateCastOrNull(materialize(tuple(toIPv4('1.2.3.4'))), 'Nullable(Tuple(Float32))') throw Code 48 the same way. Unchanged by this PR; out of scope.

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

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: clickhouse local --queries-file 05832_accurate_cast_or_null_qbit_wrong_dimension.sql on the base build (#132543 head 9c97270) fails at the first query with Code 190, every run.
b Root cause explained? createWrapperIfCanConvert keeps a Variant/Dynamic member only if its default value converts. createQBitWrapper ignored reports_failures: wrong-size array threw 190, text parsed strictly (27), other dimension threw 53. The defaults [] / '' failed, so every Array/String member was dropped and its rows became NULL or zeros.
c Fix matches root cause? Yes: the QBit conversion now honours the same request its siblings honour (createStringParsingWrapper, the unsupported-source fallback, the existing row null map). The probe is untouched; no setting, tag or guard.
d Test intent preserved / new tests added? New test 05832 (wrong size, text, dimension, tuple element, Variant/Dynamic/JSON, JSONExtract, accurateCastOrDefault, plus 3 not-asked controls). 03380 line 12 now expects \N; its query is unchanged.
e Both directions demonstrated? Base: Code 190 / 27 / 53 and \N / [0,0] / ([0,0]) on the vector lines. Fix: matches the reference. Five mutations (always throw, drop the row map, strict text parse, drop the dimension branch, unasked nested conversion) each turn the test red.
f Fix is general across code paths? All three QBit failure points, the QBit to QBit reconstruct path, tuple elements, Variant/Dynamic/JSON, JSONExtract and accurateCastOrDefault. Array/Map elements stay strict (#132543's contract).
g Fix generalizes across inputs (params/datatypes/wrappers)? Float32/BFloat16/Int8/Float64 elements, stride layouts, String/Nullable(String)/LowCardinality(String), Array(Nullable)/Array(String)/Array(Dynamic), const and materialized, empty input, [], multi-row blocks with max_block_size = 1.
h Backward compatible? (maintainer-approved exception only) No setting or format change. Only results that were an exception or a wrong NULL/zero change; accurateCast and CAST are unchanged.
i Invariants and contracts preserved? The column shape is fixed per wrapper (Nullable(QBit) under the request, accepted by every caller that sets it); the row null map has one entry per array row; a wrong-size row is zero-filled and its data never read; the non-reporting path is unchanged.

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

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7721e4b]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR makes QBit conversions honor requests to report failures as NULL, restores valid vector conversions from JSON, Dynamic, and Variant, and fixes failed array rows exposing partial vectors. The PR binary at 7721e4b6bbf8 passes 03380, 05828, and 05832, including their expected exceptions. One previously reported correctness issue remains; it is retained below without another inline comment.

Nullable-result consumers checked: prepareRemoveNullable merges masks; createTupleWrapper extracts element failures; Variant/Dynamic assembly reconciles nullability; createQBitToQBitWrapper forwards the result; accurateCastOrDefault replaces failed rows; JSONExtract strips the mask and now receives zero-filled failed array vectors. Array/Map element conversions retain strict results.

Findings

❌ Blockers

  • src/Functions/FunctionsConversion.cpp:1314 — Textual integer vectors can silently overflow during accurate conversion. [dismissed by author -- https://github.com/Fix accurateCastOrNull to QBit returning NULL for a JSON, Dynamic or Variant vector #132579#discussion_r4610008286] The author deliberately retains existing composite text-parser behavior, also present for direct String casts and Tuple; the concern remains because the newly admitted member conversions accept an out-of-range vector as a different non-NULL vector.

    Reproduced on the current PR binary:

    SELECT accurateCastOrNull(materialize('[300]'::Dynamic), 'QBit(Int8, 1)');
    -- [44], rather than NULL
    SELECT accurateCastOrDefault(materialize('[300]'::Dynamic),
                                'QBit(Int8, 1)', [7]::QBit(Int8, 1));
    -- [44], rather than [7]

    Actual numeric arrays containing 300 correctly return NULL. SerializationQBit::deserializeText uses wrapping readText for integer elements, so the accurate conversion never records this failure. Range-check textual elements in the accurate conversion path while preserving ordinary CAST behavior.

Tests
  • ⚠️ Add focused textual integer-overflow coverage for accurateCastOrNull and accurateCastOrDefault through the newly accepted members. Existing regression tests pass but do not exercise this remaining failure.
Final Verdict

❌ Block — Address the retained textual-overflow issue before approval. The fixed partial-vector thread has been resolved; there are no new inline findings to submit.

@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
return ConvertImplGenericFromString<true>::execute(arguments, result_type, column_nullable, input_rows_count, settings);
};
}
return createStringParsingWrapper(reports_failures);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Check integer overflow when accepting textual vectors

The new non-throwing parser lets the default-value probe accept String members, but their actual values still go through SerializationQBit::deserializeText, which reads Int8 with the ordinary wrapping readText parser. Consequently an out-of-range vector is accepted as a different vector instead of reporting a failed accurate conversion.

Reproduced with this head's Fast test binary:

SELECT accurateCastOrNull(materialize('[300]'::Dynamic), 'QBit(Int8, 1)');
-- [44], expected NULL
SELECT accurateCastOrNull(materialize([300]), 'QBit(Int8, 1)');
-- NULL
SELECT accurateCastOrDefault(materialize('[300]'::Dynamic),
                            'QBit(Int8, 1)', [7]::QBit(Int8, 1));
-- [44], expected [7]

Variant(String) and a JSON path holding this string also return [44]. The unchecked direct-String path predates this patch, but the patch now admits it through these member conversions. Please range-check textual elements in the accurate conversion path while preserving ordinary CAST behavior, and cover overflow through the newly accepted members.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this here: the wrap is in the text parser of the composite type, not in the QBit code, and current master (26.11.1.2675) does the same for Tuple: accurateCastOrNull(materialize('(300)'::Dynamic), 'Tuple(Int8)') returns (44) (also through Variant(String), JSON and accurateCastOrDefault), and the direct accurateCastOrNull('[300]', 'QBit(Int8, 1)') returned [44] before this PR. Range-checking integers parsed from text under accurateCastOrNull is a separate change for every composite type, so this PR keeps the QBit String member consistent with Tuple.

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9b9782c39 with master c3ec2bd66 (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

4 object files changed (+22.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 25.07 MiB 25.09 MiB +22.90 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.80 (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.0 s 14.8 s +9.2 s (+163%)
Compile time of recompiled translation units

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

Job report

…eCastOrNull

createArrayToQBitWrapper marks a row whose element conversion failed (a NULL
element, an inexact Float32, unparsable text) in the row null map it passes to
convertArrayToQBit, but only a row of the wrong size was zero-filled. The other
elements of such a row were still transposed into the QBit, so a consumer that
strips the null mask saw a partial vector: JSONExtract on a JSON column
(castColumnAccurateOrNull, then removeNullable) returned [1,0] for [1,null]
instead of the default [0,0]. Zero-fill every row marked in failed_rows.

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

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

Copy link
Copy Markdown
Member

cc @rienath

@rienath rienath self-assigned this Nov 24, 2026

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hacky

@groeneai

Copy link
Copy Markdown
Collaborator Author

Which part should change: (a) the failed_rows map in convertArrayToQBit (a wrong-size row becomes NULL, so the Variant/Dynamic default-value probe keeps Array members), (b) the #132543 commits this stacked diff also contains, or (c) the member fix as a whole? For (c) I would cut this PR down to #100936 alone (a dimension mismatch returns NULL).

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.

accurateCastOrNull QBit->QBit with mismatched dimensions or element types throws instead of returning NULL

3 participants