Skip to content

Fix CAST of nested UInt8 to Bool keeping values other than 0 and 1 - #129664

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:cast-nested-uint8-to-bool
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:cast-nested-uint8-to-bool

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129642

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 CAST of a container of UInt8 to the same container of Bool, for example CAST([toUInt8(2)] AS Array(Bool)), Tuple(Bool), Map(K, Bool), a JSON typed path, or a Dynamic/Variant value cast to Array(Bool): a value other than 0 and 1 was kept as is, so it was printed as true but did not compare equal to true, and toUInt8 returned the original value.

Description

On 26.8.18.2, 26.3.42.3 and master, SELECT CAST([toUInt8(2)] AS Array(Bool)) AS a, a[1] = true, toUInt8(a[1]) returns [true] 0 2, so WHERE a[1] = true drops the row and has(a, true) is 0. The scalar CAST(toUInt8(2) AS Bool) returns 1.

IDataType::equals does not compare the custom names of nested types (Array(UInt8) equals Array(Bool)), and FunctionCast::prepareImpl compared only the outermost custom names before reusing the column, so the nested UInt8 -> Bool conversion never ran. Bool is the only custom name that restricts the values of its base type, so the identity is now refused only when convertsUInt8ToBool finds a nested position that turns UInt8 into Bool. The existing Array/Tuple/Map wrappers then reach the scalar conversion; pairs that differ only in other custom names (geometry aliases, SimpleAggregateFunction) keep the identity. Dynamic and Variant sources reach prepareImpl the same way. For JSON with the same typed paths and parameters, createObjectWrapper converts only those typed path columns, with a plain CAST so that accurateCastOrNull keeps their declared layout, and reuses the dynamic paths and shared data, so unrelated values keep their types. A container of Variant whose alternative turns UInt8 into Bool now throws CANNOT_CONVERT_TYPE, as the same Variant cast already does at the top level.

Not changed: conversions that do not go through CAST (castColumn in format readers, the INSERT SELECT conversion handled in #129642, ALTER MODIFY COLUMN from UInt8 to Bool), and a CAST to SimpleAggregateFunction(any, Bool), which keeps the value even at the top level.

Validation: new test 05556_cast_nested_uint8_to_bool fails on master (18 rows) and passes with the fix; 50/50 randomized runs; the 1843 _cast_/bool/variant/dynamic/json/geo/tuple/map stateless tests have the same results on both binaries.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 6, 2026 01:43
`IDataType::equals` ignores custom names at every level, so `Array(UInt8)`
equals `Array(Bool)`. `FunctionCast::prepareImpl` only compared the custom
names of the outermost types before taking the identity shortcut, so
`CAST([toUInt8(2)] AS Array(Bool))` reused the column and the `Bool` element
kept the raw byte 2: it printed `true`, but `= true` was false, `has(.., true)`
returned 0 and `toUInt8` returned 2. The scalar `CAST(toUInt8(2) AS Bool)` was
already correct through `createUInt8ToBoolWrapper`.

`haveSameCustomNames` walks both type trees positionally through
`getNumberOfChildren` / `getChild` and requires equal custom names at every
level. At the root it is the old predicate, so every top-level decision is
unchanged. A pair that differs only in a nested custom name now takes the
container wrappers (Array, Tuple, Map), which recurse to the `UInt8 -> Bool`
wrapper for the differing leaf and to identity wrappers for the equal ones.
This also covers `Dynamic -> Array(Bool)` and `Variant(Array(UInt8), ..) ->
Array(Bool)`, which reach `prepareImpl` through `prepareUnpackDictionaries`.

`createObjectWrapper` had its own identity for `JSON` types equal up to
`SHARED` marks, which compares typed-path types with `equals`; it gets the
same guard, so `JSON(a UInt8) -> JSON(a Bool)` takes the text round trip and
parses 2 as `true`. Both changes are needed for the `JSON` case, because
`prepareImpl` tries its own identity first.

The removed `safe_convert_custom_types` comment was about IPv4/IPv6, which are
separate types now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the haveSameCustomNames comment accurate: Variant::equals does compare direct alternatives' custom names.

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

groeneai commented Nov 6, 2026

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) plus my own cold review (4 nits).

# Sev Finding Verdict Evidence / action
1 ❌ CAST(anyState(toUInt8(2)) AS AggregateFunction(any, Bool)) keeps the raw state (AggregateFunction exposes no children) DISAGREE Without the identity the pair goes to createAggregateFunctionWrapper, whose haveSameStateRepresentation branch (getStateType()->equals) shares the states as they are, so this guard cannot change it. Aggregate states are relabelled by design; a separate question, out of scope.
2 💡 A CAST between containers of Variant whose alternatives differ only in a nested custom name now throws CANNOT_CONVERT_TYPE AGREE, noted Same result as that Variant cast at the top level already gives; ALTER treats equals types as metadata-only and is unaffected.
3 💡 equals does compare custom names of direct Variant alternatives AGREE, noted The helper is stricter, so it is still correct; only the wording overstates.
4 💡 No row for JSON(a Bool) -> JSON(a UInt8) or Array(LowCardinality(Nullable(..))) AGREE, noted Both covered by reading: UInt8 JSON parsing accepts true/false; the LowCardinality(Nullable) path is the existing top-level one.

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

Session id: cron:clickhouse-review-self-slot-58:20261106-015000

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT CAST([toUInt8(2)] AS Array(Bool)) AS a, a[1] = true, toUInt8(a[1]) returns [true] 0 2 on every run on master, 26.8.18.2 and 26.3.42.3 (expected [true] 1 1).
b Root cause explained? IDataType::equals ignores nested custom names, so Array(UInt8) equals Array(Bool). FunctionCast::prepareImpl compared only the outermost custom names before taking the identity shortcut, so the column was reused and the nested UInt8 -> Bool conversion never ran. createObjectWrapper has the same shortcut for JSON typed paths.
c Fix matches root cause? Yes. The identity decision now requires equal custom names at every level (haveSameCustomNames); the existing container wrappers then do the normalization. No per-container special case.
d Test intent preserved / new tests added? New 05556_cast_nested_uint8_to_bool: 14 rows that read toUInt8 or compare with true (never the printed true), plus 6 control casts whose result must not change. No existing test changed.
e Both directions demonstrated? Yes. The new test passes on the fix build and fails on a pristine-HEAD build with exactly the 14 rows inverted; the controls are identical. Removing either of the two changes alone makes rows fail again.
f Fix is general across code paths? Covers every caller of prepareImpl's identity: Array, Tuple, Map key and value, nested arrays, Nullable/LowCardinality inside a container, and Dynamic/Variant sources (through prepareUnpackDictionaries), plus the JSON identity. The other equals checks in FunctionsConversion.cpp match Variant alternatives by type name, which already includes nested custom names, so Variant(UInt8, UUID) -> Variant(Bool, UUID) still throws CANNOT_CONVERT_TYPE.
g Fix generalizes across inputs (params/datatypes/wrappers)? Tested: const and materialize, a Memory table column, Array(Array(Bool)), Tuple(Bool, String), Map(UInt8, Bool), Map(Bool, UInt8), Array(Nullable(Bool)) with NULL, Array(LowCardinality(Bool)), Dynamic and Variant to Array(Bool), JSON(a Bool), accurateCast. 50/50 randomized runs pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change. The only visible change is that a Bool produced by CAST is 0 or 1. Casts between types that differ only in a nested geometry or SimpleAggregateFunction name keep their values (control rows).
i Invariants and contracts preserved? prepareImpl still returns a wrapper producing to_type columns; at the top level the new check is the old one, so no top-level decision changes, and the AggregateFunction strictEquals branch is untouched. The walk runs once per CAST preparation, not per row.

Session id: cron:clickhouse-impl-self-slot-57:20261106-005400

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e519be]

Summary: ✅


AI Review

Summary

This PR normalizes nested UInt8 values when CAST targets Bool, including typed JSON paths while preserving unrelated dynamic data. No unresolved findings remain at 7e519be530dc527876512fd357a31c82a1d718fd; both earlier JSON findings are fixed. The added stateless test matches all 26 reference rows on the PR binary. Stable 26.8.18.2 differs on the 18 regression rows and matches all eight controls.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @Algunenano, could you review this and add the can be tested label so CI runs? CAST([toUInt8(2)] AS Array(Bool)) kept the byte 2 because the identity shortcut in prepareImpl compared only the outer custom names (Array(UInt8) equals Array(Bool)); haveSameCustomNames now compares them at every level, so the container wrappers run the UInt8 -> Bool conversion, and the JSON identity in createObjectWrapper gets the same check.

@clickhouse-gh clickhouse-gh Bot added 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 6, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e519be53 with master c9e18d017 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 831894676; 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 (+119.73 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 24.64 MiB 24.76 MiB +119.73 KiB (+0.47%)

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

Compile time of recompiled translation units

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

Job report

Refusing the identity for every nested custom-name difference had two
side effects:

- A container of Variant whose alternatives differ only in a geometry
  alias, e.g. Array(Variant(Array(Point), String)) to
  Array(Variant(Array(Tuple(Float64, Float64)), String)), went to the
  Variant wrapper, which matches alternatives by name and threw
  CANNOT_CONVERT_TYPE. Such aliases share the representation, so the
  identity is correct for them, as before.
- A JSON cast that changes a typed path between UInt8 and Bool took the
  text round trip, which re-infers the types of unrelated dynamic paths
  (1.0 came back as Int64).

Bool is the only custom name that constrains the values of its base
type, so the identity is now refused only when some nested position
turns UInt8 into Bool. For JSON with the same typed paths and
parameters, only those typed path columns are converted; dynamic paths
and shared data are reused as they are. The top-level
safe_convert_custom_types check is restored unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Under accurateCastOrNull and accurateCastOrDefault, the Tuple wrapper
returns Nullable(Tuple) even for a non-Nullable target, to report
per-row conversion failures to its caller. The typed path conversion
installed that column directly into a path declared as Tuple(Bool) or
Array(Tuple(Bool)), so serialization downcast a ColumnNullable to
ColumnTuple (SIGSEGV in release, a failed assert_cast in debug):

    SELECT accurateCastOrNull(materialize('{"a":[2]}'::JSON(a Tuple(UInt8))),
                              'JSON(a Tuple(Bool))');

The typed path types differ only in Bool custom names here, so the
conversion cannot fail. Prepare the path wrappers with a plain CAST,
which keeps the declared layout at every nesting level.

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.

1 participant