Repository navigation
Fix CAST into SimpleAggregateFunction(f, Bool) keeping values other than 0 and 1 - #129731
Conversation
…han 0 and 1 SimpleAggregateFunction(f, Bool) is the Bool storage type under its own custom name, while the Bool branches of CAST and convertFieldToType recognize Bool by name (isBool). So a CAST into it took the plain UInt8 path: a UInt8 source was reused as is, wider integers were truncated (300 -> 44, -1 -> 255), 0.5 became 0, accurate casts failed on values that Bool accepts, and the JIT emitted an integer truncation. The value is printed as `true` but `= true` is false. isSimpleAggregateFunctionOfBool() recognizes the type when both the argument and the aggregate result are Bool (any, anyLast, min, max). sumWithOverflow and groupBitOr/And/Xor over Bool are accepted by the type because their UInt8 result equals the Bool storage, but their state legitimately exceeds 1, so they keep the UInt8 semantics. It is checked next to isBool in prepareImpl, ConvertImpl, FunctionCast::compile and convertFieldToType, and in the places that must agree with the new conversion: - createFunctionBaseCast: the cast is not injective, so it must not get the strict UInt8 monotonicity (read-in-order / DISTINCT-in-order would trust it); - tryConvertNumericColumnNative and nativeBatchApplicable: castColumnAccurateOrNull now maps an IN member 2 to 1, so these sets use the strict per-element conversion, as for Bool; - classifySubstitutionConversion: a non-Bool member must not reconstruct the correlated column, as for Bool (an outer value stored as 2 otherwise matched only with correlated_subqueries_substitute_equivalent_expressions = 0). tryConvertNativeNumberMembersBatch needs no change: it calls nativeBatchApplicable before converting. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The correlated subquery substitution guard accepted any Bool-valued member for a Bool or SimpleAggregateFunction(f, Bool) correlated column. A member with a different type name (SimpleAggregateFunction(max, Bool) for a SimpleAggregateFunction(any, Bool) column, Bool for such a column, or the reverse) then took the cross-base branch and was reconstructed through a CAST that now normalizes the value, so with a raw 2 stored on both sides (an INSERT ... SELECT of a UInt8 adds no CAST) EXISTS returned 0 with the substitution and 1 with correlated_subqueries_substitute_equivalent_expressions = 0. Only a member of the same type name may reconstruct such a column now; for plain Bool this is the same check as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review (click to expand)Gate B (cold, independent model, codex): 2 findings on
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261106-124200 |
|
Workflow [PR], commit [b667e67] Summary: ✅
AI ReviewSummaryThe PR makes conversions into Findings❌ Blockers
Previously dismissed findings, retained as deferred concerns:
Missing context / blind spots
Final Verdict❌ Block — preserve normalizing same-type casts during index analysis and add the regression above. The previously dismissed concerns remain deferred to their existing follow-ups. |
|
cc @nihalzp @Manerone, could you review this and add the |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes12 object files changed (+117.56 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units58 translation units recompiled, 524 s compile time in total, 58 of them have a recent master baseline. |
Manerone
left a comment
There was a problem hiding this comment.
Thanks, the root cause is clear, and making SimpleAggregateFunction(f, Bool) behave exactly like Bool looks like the right contract to me. The CAST / convertFieldToType part is correct, and the test covers each changed site well.
One thing before merge: the monotonicity override misses SimpleAggregateFunction(any, Nullable(Bool)) (inline comment below). It is a one-condition fix, and it also covers plain Bool, which keeps the "same as Bool" contract consistent there too.
About the two P1 comments from the AI review (subquery IN and JOIN keys): I checked them against plain Bool on 26.6.1, and Bool behaves the same way:
SELECT true IN (2); -- 0
SELECT 2 IN (SELECT true); -- 1 (Set::execute casts the probe into Bool, so 2 becomes 1)
SELECT groupArray(number) FROM numbers(4) WHERE number IN (SELECT true); -- [1,2,3]For JOINs, Nullable(Bool) vs a UInt8 key also gives 1 or 0 depending on table order (with join_algorithm = 'partial_merge' or enable_join_runtime_filters = 0), because getLeastSupertype keeps whichever custom-named UInt8 type comes first. So with this PR the SAF type simply matches Bool here, and I don't think it should be fixed in this PR. Two small asks:
- Mention in the description that subquery
INand JOIN keys into this type now followBool. For example,number IN (SELECT anySimpleState(true))changes from[1]to[1,2,3]. - Optionally, add a couple of queries to the test that show the SAF type and
Boolgive the same results there, so the two don't drift apart later.
The underlying problem is in Bool itself: implicit conversions and = disagree. = compares numerically (2 ≠ true), but the subquery IN probe and a JOIN key whose common type is Bool go through the cast into Bool, which turns any nonzero value into 1, so 2 matches true. For JOINs, the result also depends on table order. Could you open a separate issue for this, with the queries above, and link it here with Related:?
Minor follow-up, not blocking: JSONExtract('{"a":2}', 'a', 'SimpleAggregateFunction(any, Bool)') still returns 2 (JSONExtractTree.cpp also checks for Bool by name), while 'Bool' returns 1. This is another spot where the SAF type doesn't yet behave like Bool.
…IN keys and JSONExtract like Bool Review feedback on ClickHouse#129731: - The monotonicity override is checked after `removeNullable`, so for `SimpleAggregateFunction(any, Nullable(Bool))` (custom name on the Nullable wrapper) it saw plain `Bool`, which, like `Bool` and `Nullable(Bool)` themselves, fell into the `UInt8` branch that reports the cast as strict. Match plain `Bool` as well, so `optimize_read_in_order` / `optimize_distinct_in_order` over such a CAST no longer return wrong rows (the DISTINCT case aborted a debug build). - ClickHouse#129894 (merged into master) compares a `Bool` JOIN key with an integer key in `UInt8`, but checks for `Bool` by name. With the CAST into `SimpleAggregateFunction(any, Bool)` now mapping 2 to 1, a `Nullable(SimpleAggregateFunction(any, Bool))` key joined with an `UInt8` key 2 matched `true` in one table order only. `compareBoolKeysAsUInt8` now treats the SAF type as `Bool`. - `JSONExtract(..., 'SimpleAggregateFunction(any, Bool)')` kept 2 instead of 1, and so did `LowCardinality(Bool)`, whose branch checked the `LowCardinality` type instead of its dictionary type. The test gains `Bool` and `SimpleAggregateFunction(any, Nullable(Bool))` in the in-order section, and queries that show subquery `IN`, JOIN keys and `JSONExtract` give the same results for the SAF type and `Bool`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. Changes in 435e3ad, plus a master merge (see the JOIN point):
|
CI finish ledger - 435e3adEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261110-220011 |
CI finish ledger - 213163bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261116-213021 |
|
@groeneai check the failing tests in the CI, if they are caused by this PR fix them |
`functionIsCastPreservingFieldRepresentation` lets `KeyCondition` skip applying a cast to the analyzed range when both types share a Field representation. `Bool` and `SimpleAggregateFunction(f, Bool)` are `UInt8` with a custom name, so a cast from `UInt8` into them passed the width test, yet it maps every nonzero value to 1. A minmax skip index then kept the granule [2, 2] as 2 and pruned it against `CAST(u, 'Bool') = true`. With `use_skip_indexes_on_data_read = 0` that is a wrong count in release (1 instead of 3 over 0..3), and in debug the aggregate-projection count path aborts on `exact_ranges[i].end <= range.end` (AST fuzzer, STID 2508-46d3, `compatibility = '24.3'`). Plain `Bool` has this on master; this PR made `SimpleAggregateFunction(any, Bool)` reach it because its cast now normalizes like a cast into `Bool`. Never skip a cast into either type. Rows added to 05556 for both types. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The only failing check was Fixed in b667e67: |
AI review of a later commit does not approve the PR, see the AI Review comment.
9c1dc0f
ClickHouse#129731 made a CAST into `SimpleAggregateFunction(f, Bool)` (with `f` returning `Bool`) map every nonzero value to 1, as a CAST into `Bool` does, and added `isSimpleAggregateFunctionOfBool`. `convertsToBool` matched only the `Bool` custom name, so `UInt8` into such a column still counted as an identity conversion: INSERT SELECT, MODIFY COLUMN and the other gates kept the raw byte (2 stayed 2), and `WHERE CAST(v, 'Bool') = true` over a key on `toUInt8(v)` then disagreed with a full scan. `05556_cast_to_simple_aggregate_function_bool` inserted `toUInt8(2)` into `Bool` and `SimpleAggregateFunction(any, Bool)` columns and expected it to be stored as is. Both now store 1, so its correlated comparisons with the `UInt8` value 2 count 0, with and without the substitution. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…RT SELECT` Since ClickHouse#129731, `VALUES` into a `SimpleAggregateFunction(f, Bool)` column stores 0 and 1, so `t_saf` and `t_array_saf` no longer held the byte 2 the test is about. `INSERT SELECT` of a `UInt8` still stores it, for this type and for a plain `Bool`, so fill both tables that way. The reference is unchanged: 17 of the 25 lines fail on the merge base and on 26.8.37.168, 26.9.25.15 and 26.10.5.57, and all pass with the fix. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t-numbers-by-value ClickHouse#119183 moved the conversion of `IN` keys into `Set::castToKeyType`, so the exact-value conversion of a number for a `Bool` key moves there: such a probe converts into `UInt8` instead of `Bool`, and the number alternatives of a `Variant` probe are converted again after the cast of the whole column. ClickHouse#129731 made `SimpleAggregateFunction(f, Bool)` keep `Bool` values, so a key of that type gets the same exact-value conversion, and a probe of that type keeps the `Bool` one. Expectations that encoded the collapse of a number into `true` change: 05168 (`materialize(toUInt8(2)) IN (SELECT true)` with `transform_null_in = 0` is now 0, as it already was with `transform_null_in = 1`), 05556 `same as bool` (`[1]` for both sets) and the `u` lines of 05406. 04871 keeps its expectations: its `Bool` byte 2 is now a `Bool` from `reinterpret` instead of a `UInt8`, which the set compares by value.
…Bool) Since ClickHouse#129731, a CAST into `SimpleAggregateFunction(f, Bool)` normalizes the value like a CAST into `Bool`. `needsConvertingCast` kept only a node named `Bool` out of the relabelling casts, so `UInt8 -> SimpleAggregateFunction(any, Bool)` counted as a relabel and got a `_CAST`: an INSERT ... SELECT toUInt8(2) and a view over a `UInt8` column now stored/returned 1 for that type while `Bool` kept 2. That is what made `05556_cast_to_simple_aggregate_function_bool` fail after the master merge (its correlated block relies on the raw value). Keep the full name of such a node, so it is relabelled neither from `UInt8` nor from `Bool`, exactly as on master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #124074
Related: #129664
Related: #129683
Related: #129894
Related: #129892
Related: #116656
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
CASTintoSimpleAggregateFunction(f, Bool)forfreturningBool(any,anyLast,min,max) keeping the source value:CAST(300 AS SimpleAggregateFunction(any, Bool))was printed astruebut did not compare equal totrue, and0.5becamefalse. Such a column filled from aDEFAULT, anINSERT ... SELECTof another numeric type orVALUESnow gets 0 and 1, asBooldoes, and so doesJSONExtractinto it or intoLowCardinality(Bool). Also fixed wrong rows fromoptimize_read_in_order,optimize_distinct_in_orderand a minmax skip index over aCASTintoBool.Description
On 26.3.60.2, 26.8.18.2 and 26.10.2.103,
SELECT CAST(300 AS SimpleAggregateFunction(any, Bool)) AS x, toUInt8(x), x = truereturnstrue 44 0(CAST(300 AS Bool)givestrue 1 1), and anAggregatingMergeTreecolumnv SimpleAggregateFunction(any, Bool) DEFAULT 2filled byDEFAULT,INSERT ... SELECT toInt32(2)orVALUES (3, 300)makesWHERE v = truereturn no rows.SimpleAggregateFunction(f, Bool)is theBoolstorage type under its own name, and theBoolconversions recognizeBoolby name.isSimpleAggregateFunctionOfBool(argument and result areBool, so notsumWithOverfloworgroupBit*) is now checked next toisBoolinCAST(interpreted and JIT),convertFieldToTypeandJSONExtract, and where results must agree: the nativeINset fast paths, the correlated subquery substitution guard, theBoolJOIN key comparison of #129894, theCASTmonotonicity and index analysis. The last two also coverBoolitself (as #129683 and #116656 do): the cast was reported as strict, so in-order reading returned wrong rows, and index analysis kept the raw value for a granule range, so a minmax index pruned[2, 2]againstCAST(u, 'Bool') = true(the AST fuzzer's debug abort here).Behaviour change: subquery
INinto this type now followsBool, sonumber IN (SELECT anySimpleState(true))changes from[1]to[1,2,3], asnumber IN (SELECT true)gives (#129892 fixes that forBool).Not changed, as for
Bool: nested casts of aUInt8(#129664) andINSERT ... SELECTof aUInt8, which adds noCAST.Validation: the test fails on master and passes with the fix; reverting any changed site fails its part; 50/50 randomized runs.
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/129731]
Version info
26.11.1.2600-master(included in26.11and later)