Skip to content

Fix IN with a Bool subquery matching every nonzero number - #129892

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:in-subquery-bool-set-numbers-by-value
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:in-subquery-bool-set-numbers-by-value

Conversation

@groeneai

@groeneai groeneai commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #93115

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 IN with a subquery, a Set table or GLOBAL IN whose column is Bool matching every nonzero number on the left side. number IN (SELECT true) now matches only 1, like number IN (true) and number = true.

Description

On 26.3.42.3, 26.8.18.2 and 26.10.3.7, SELECT groupArray(number) FROM numbers(4) WHERE number IN (SELECT true) returns [1,2,3] and the NOT IN form returns [0], while IN (true), = true and the documented IN semantics give [1]. Also matched: -1, 0.5, 256, nan, inf. Master gives the same after #119183. No related open issue found.

Set::castToKeyType converts the left side into the set's key type before the lookup, and a conversion into Bool turns every nonzero number into true. Now, when the set key is Bool, Nullable(Bool) or SimpleAggregateFunction(f, Bool) (#129731) and the left side is a non-Bool integer or floating-point number, it is converted into UInt8, which stores Bool: the value is kept, or it does not fit and is not a member. This is the exact-value semantics #93115 introduced for the opposite direction. It covers in, notIn, nullIn, GLOBAL IN, multi-column keys, Set tables, transform_null_in, spilled sets and the number alternatives of a Variant left side. A Bool left side still converts, so a Bool byte 2 is true.

Not changed: a Bool inside a composite key (Tuple/Array/Map) and Decimal left sides.

Existing expectations of the old matching change: toUInt8(2) IN (SELECT true) in 05168_nullable_in_key_cast_null_rows (now 0 in both transform_null_in modes), same as bool in 05556_cast_to_simple_aggregate_function_bool ([1]) and the u lines of 05406_vortex_pushdown_probe_conversion. 04871_in_tuple_single_key_rewrite_in_to_join now takes its byte 2 from a Bool, so its results stay.

Validation: new test 05567_in_subquery_bool_set_compares_numbers_by_value (25 results, each wrong on master), 30 randomized runs of every touched test, and 543 related stateless tests (IN, sets, Bool, Variant) with the same verdicts as on master apart from the four above.


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

groeneai and others added 2 commits November 7, 2026 05:38
`Set::execute` converts each probe key column into the set's key type before the
hash lookup. For a `Bool` key that is `castColumnAccurateOrNull(probe, Bool)`, and a
conversion into `Bool` turns every nonzero number into `true`, so 2, 300, -1, 0.5
and NaN all hit the element `true`:

    SELECT groupArray(number) FROM numbers(4) WHERE number IN (SELECT true);      -- was [1,2,3]
    SELECT groupArray(number) FROM numbers(4) WHERE number NOT IN (SELECT true);  -- was [0]

while `number IN (true)`, `number = true`, the documented `IN` semantics
(`accurateCastOrNull` of the right side to the left side's type) and the
primary-key read all give [1] / [0,2,3].

`Bool` is stored as `UInt8`, so when the set key is `Bool` (or `Nullable(Bool)`) and
the probe is a non-`Bool` integer or floating-point number, convert the probe into
`UInt8` instead: an accurate conversion into `UInt8` keeps the value or yields NULL
(a non-member), so only 0 and 1 can match. This mirrors the exact-value semantics of
ClickHouse#93115, which covered the opposite direction (a `Bool` probe against numbers).

Covers every `IN` flavour that reaches `Set::execute` (`in`, `notIn`, `nullIn`,
`globalIn`), multi-column keys, `Nullable`/`LowCardinality` probes and set columns,
`transform_null_in`, `ENGINE = Set` tables, `GLOBAL IN`, and the spilled `DiskSet`.
Composite keys (`Tuple`/`Array`/`Map` holding a `Bool`) and `Decimal` probes are left
unchanged: the former are converted strictly, where an `UInt8` element would throw for
values above 255, and an accurate `Decimal` -> `UInt8` conversion truncates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the getTypeToConvertKeyTo comment to the cast invariant.

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

groeneai commented Nov 7, 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; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The spilled-set query (max_bytes_before_external_set = 1) asserts only its result, not that the set was spilled DISAGREE The query spilled when measured (SetsSpilledToDisk = 1), and its threshold is pinned in its own SETTINGS. Without the fix it returns [1,2,3]. The change is in the key conversion, which executeDiskSet consumes unchanged. Spill triggering is asserted by the external_set tests.

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

Session id: cron:clickhouse-review-self-slot-58:20261107-055200

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT groupArray(number) FROM numbers(4) WHERE number IN (SELECT true) returns [1,2,3] on every run of the unfixed build, no randomization involved (also on 26.3.42.3, 26.8.18.2, 26.10.3.7).
b Root cause explained? Set::execute converts the left side into the set's key type Bool; that conversion maps every nonzero number to true, so 2, 300, -1, 0.5 and NaN find the stored true.
c Fix matches root cause? Yes. The conversion target becomes UInt8 (Bool's storage) at the one place the left side meets the set's type; no guard, no setting.
d Test intent preserved / new tests added? New 05567_in_subquery_bool_set_compares_numbers_by_value, 18 results, each wrong before the fix.
e Both directions demonstrated? Yes. The test fails on the unfixed build with the exact inverse diff on all 18 lines and passes with the fix; 100 randomized runs pass.
f Fix is general across code paths? in, notIn, nullIn, GLOBAL IN, multi-column keys, Set tables and spilled sets share the changed loop; all three conversion calls use the new target. Constant sets and index analysis already compare by value. Composite keys and Decimal left sides are deliberately unchanged (stated in the description).
g Fix generalizes across inputs (params/datatypes/wrappers)? Test matrix: Nullable/LowCardinality on both sides, negative Int8, 254-257, float halves, NaN, Int128, UInt8, transform_null_in with NULLs on both sides; Bool/String left sides checked unchanged.
h Backward compatible? (maintainer-approved exception only) No setting; only wrong answers change (numbers other than 0 and 1 stop matching a Bool set), and the new answer equals IN (true), = and the indexed read. An un-upgraded shard keeps the old answer for its part.
i Invariants and contracts preserved? The converted key column keeps the set's byte representation and its nullability follows the set key type, so the null-map, transform_null_in and spilled-set paths see the same bytes for 0 and 1. No locking or set-building change.

Session id: cron:clickhouse-impl-self-slot-57:20261107-051500

@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52629125]

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

The PR makes integer and floating-point probes compare by value against Bool sets, including numeric Variant alternatives. Review of head 52629125509854c55ad4f15c4c9f5aba6eb16c3a found one new blocker: extending boolean normalization to aggregate boolean keys makes query results depend on primary-key pruning.

Findings

❌ Blockers

  • src/Interpreters/Set.cpp:742: Boolean normalization and index analysis disagree. The lookup now normalizes stored nonzero Bool bytes for a SimpleAggregateFunction(any, Bool) set, while KeyCondition::tryPrepareSetColumnsForIndex still prunes against the single byte 1. An ordinary insert can store the affected bytes:

    CREATE TABLE t (b Bool) ENGINE = MergeTree ORDER BY b
    SETTINGS index_granularity = 1;
    INSERT INTO t SELECT toUInt8(number) FROM numbers(4);
    
    SELECT arraySort(groupArray(toUInt8(b))) FROM t
    WHERE b IN (SELECT anySimpleState(true))
    SETTINGS use_primary_key = 0, optimize_use_implicit_projections = 0;
    
    SELECT arraySort(groupArray(toUInt8(b))) FROM t
    WHERE b IN (SELECT anySimpleState(true))
    SETTINGS use_primary_key = 1, optimize_use_implicit_projections = 0;

    Reproduced with the PR-head fast-test binary: the results are [1,2,3] and [1]. With the previous 95e7b2e5c872 binary, both return [1]. Matching rows are silently omitted by the indexed execution. Make index analysis honor boolean normalization, or decline unsafe pruning.

Tests
  • ⚠️ Add a focused stateless regression comparing indexed and full-scan membership for stored noncanonical Bool bytes against aggregate boolean keys. The added Memory test verifies normalization but cannot detect incorrect pruning.
Final Verdict

Status: ❌ Block

Make indexed and full-scan results agree for the reproduction above and add regression coverage.

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

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @yariks5s, could you review this and add the can be tested label so CI runs? Set::execute converted a number into a Bool set key with castColumnAccurateOrNull, which maps every nonzero value to true, so number IN (SELECT true) matched 2 and 3; such a number is now converted into UInt8 (the storage of Bool), the exact-value semantics of #93115.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 526291255 with master 2b9cabd09 (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.

Compile time of recompiled translation units

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

Job report

`05406_vortex_pushdown_probe_conversion` used `UInt8` `2 IN (SELECT k FROM bool_keys)` with the
key `true` as an example of a non-injective row conversion: `Set::execute` cast the row to `Bool`,
so `2` became `true` and matched. With this PR the row is compared with the `Bool` key by its value,
so `2` matches no key: the `u` lines become 0 / 1 with the pushdown both on and off, which still
agree. The Vortex converter keeps refusing to push a `Bool` key for a non-`Bool` column; only the
comments that cited this example are updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/Set.cpp Resolved
A `Variant` probe reaches `Set::execute` as a whole in a multi-column key
(`(v, 1) IN (SELECT true, 1)`) and in the null-aware membership (`nullIn`,
`IN` with `transform_null_in = 1`), which do not use the default `Variant`
adaptor. Its cast into the `Bool` key converts every alternative into `Bool`,
so a number alternative other than 0 or 1 still became `true` and matched.

After that cast, the number alternatives are converted again into `UInt8`,
the same conversion a probe of their own type gets, and only their rows are
replaced. `String`, `Bool`, NULL and unconvertible alternatives keep the
result of the `Bool` cast.

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.
Comment thread src/Interpreters/Set.cpp Resolved
A `Bool` key converts a probe of its own type with `transform_null_in = 0`,
so a `Bool` value holding a byte other than 0 and 1 is `true`. The check
used `isBool`, which is false for `SimpleAggregateFunction(any, Bool)`,
while `equals` holds between that type and `Bool`, so the conversion was
skipped as a no-op: `b IN (SELECT anySimpleState(true))` returned 0 for a
`Bool` byte 2 where `b IN (SELECT true)` returns 1, and a `Variant` probe
in a multi-column key, which is always converted, returned 1 again. Use
`holdsBool`, which the number-probe path already uses for such keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 21, 2026
Comment thread src/Interpreters/Set.cpp
/// can hold such a byte, e.g. from `reinterpret`. With `transform_null_in = 1` the probe keeps its bytes,
/// as primary-key analysis does, which matches a `Bool` member only against the byte 1 (see
/// `KeyCondition::tryPrepareSetColumnsForIndex`).
const bool converts_bool_key = !transform_null_in && holdsBool(target_type);

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] Keep primary-key pruning consistent with boolean normalization

Extending this exception to SimpleAggregateFunction(f, Bool) makes the lookup accept stored boolean bytes 2 and 3, but KeyCondition::tryPrepareSetColumnsForIndex still treats the set as the single key point 1. Consequently, enabling the primary key silently removes matching rows:

CREATE TABLE t (b Bool) ENGINE = MergeTree ORDER BY b
SETTINGS index_granularity = 1;
INSERT INTO t SELECT toUInt8(number) FROM numbers(4);

SELECT arraySort(groupArray(toUInt8(b))) FROM t
WHERE b IN (SELECT anySimpleState(true))
SETTINGS use_primary_key = 0, optimize_use_implicit_projections = 0;

SELECT arraySort(groupArray(toUInt8(b))) FROM t
WHERE b IN (SELECT anySimpleState(true))
SETTINGS use_primary_key = 1, optimize_use_implicit_projections = 0;

Reproduced with the 526291255098 fast-test binary: the results are [1,2,3] and [1], respectively. Both queries return [1] with the previous 95e7b2e5c872 binary. The ordinary INSERT ... SELECT preserves these bytes, so this affects existing data as well as the newly added boolean-byte test case.

Please make index analysis account for the normalization, or decline unsafe pruning, and add a regression comparing indexed and full-scan execution. The new Memory test cannot exercise this boundary.

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.

A plain Bool key already splits this way: b IN (SELECT true) and b IN (true) give [1,2,3] without and [1] with the primary key on 26.8.37.168, 26.10.5.57 and master 573bbb2, and with this PR the anySimpleState(true) set gives the same results as true in both modes (also for NOT IN). The root cause is the stored bytes 2 and 3, which #131433 stops INSERT ... SELECT from writing, so I am leaving primary-key analysis unchanged here.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 21, 2026 18:54

AI review of a later commit does not approve the PR, see the AI Review comment.

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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