Skip to content

Compare a Bool JOIN key with an integer key by value - #129894

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-bool-key-compared-by-value
Nov 7, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/join-bool-key-compared-by-value

Conversation

@groeneai

@groeneai groeneai commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129731

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 JOIN of a Bool key with an integer key matching true with integers other than 1 (such as 2) depending on the order of the tables. The keys are now compared by value, as = does.

Description

On 26.10.3.7 (and 26.8, 26.3), SELECT count() FROM (SELECT CAST(true, 'Nullable(Bool)') AS v) a JOIN (SELECT toUInt8(2) AS v) b ON a.v = b.v returns 1, while CAST(true, 'Nullable(Bool)') = toUInt8(2) is 0 and the same join with the tables swapped returns 0. Found while reviewing #129731.

Root cause: IDataType::equals treats Bool and UInt8 as the same type, so getLeastSupertype returns whichever key type comes first. With the Bool key on the left the keys are compared in Nullable(Bool), and the CAST of the UInt8 key into Bool maps every nonzero value to true. The runtime filter type ({build, probe} order) and the subtype fallback have the same order dependence, and a USING key reused its output cast into Bool as the comparison key.

Change: JoinCommon::compareBoolKeysAsUInt8 replaces a Bool of the common key type by UInt8 where the other key has an integer in that place (through Nullable, LowCardinality, Array, named or unnamed Tuple, Nested and JSON typed paths, also when the other key has an empty array in a sibling element). It is applied to the comparison type in predicateOperandsToCommonType (supertype and subtype fallback) and to the runtime filter type, and the USING output cast is reused only when its type name matches. Output column types are unchanged, including the merged USING column, which still follows getLeastSupertype (Bool when the Bool table is on the left). getLeastSupertype itself is unchanged, because array, if, coalesce and UNION also take their result type from it. Two similar Bool/UInt8 defects outside JOIN (number IN (SELECT true), = between Array(Nullable(Bool)) and Array(UInt8)) are in different code and not changed here.

Validation: the new test fails on master and passes with the fix (local and server, 50/50 randomized runs each way). 1705 join/using/asof/bool/runtime-filter/nested/json tests show no new failures against master.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1606-master (included in 26.11 and later)

IDataType::equals treats Bool and UInt8 as the same type, so the least
supertype of a Nullable(Bool) key and a UInt8 key is whichever comes
first. With the Bool key on the left the keys were compared in
Nullable(Bool): the UInt8 key was CAST to Bool, which maps every nonzero
value to true, so 2 and 255 matched true. The runtime filter type
({build, probe} order) and the subtype fallback had the same order
dependence, and a USING key reused its output cast into Bool as the
comparison key because that check used equals.

JoinCommon::compareBoolKeysAsUInt8 replaces a Bool of the common key type
by UInt8 where the other key has an integer in that place. It is applied
to the comparison type in predicateOperandsToCommonType (supertype and
subtype fallback) and to the runtime filter type, and the USING output
cast is reused only when its type name matches.

The type of the merged USING column is deliberately unchanged: it still
follows getLeastSupertype. Retyping it to UInt8 makes one column carry
both Bool and UInt8 in a query, because the analyzer compares column
types with equals.

The type walk pairs the common type with each key the way the common
type was built: a named and an unnamed Tuple by position, through a
custom name such as Nested on the key, and JSON typed paths by path.

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 (3 rounds, final HEAD 9ac2e99): 0 open findings
Finding Verdict
❌ A named Tuple key facing an unnamed common type kept the Bool comparison (supertype, subtype, runtime filter) AGREE, fixed (positional pairing)
⚠️ A Nested key and a JSON typed path kept the Bool comparison AGREE, fixed (walk through the custom name and typed paths)
⚠️ Runtime-filter arms could pass without a built and applied filter AGREE, inert arms removed, EXPLAIN guards on build and __applyFilter
⚠️ using types was pruned by count() AGREE, unwrapped
💡 Unused fixture AGREE, removed

@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. 05564_join_bool_key_compared_by_value.sql gives 25 wrong results on every run of the base binary and of the master snapshot c9e18d01727e (e.g. on 4, anti rf 0, asof [255], expected 2, 2, [1]).
b Root cause explained? IDataType::equals treats Bool and UInt8 as equal, so getLeastSupertype({Nullable(Bool), UInt8}) returns the first type. The UInt8 key is then CAST into Bool, which maps 2 and 255 to true. The runtime filter type and the subtype fallback pick their type the same way, and a USING key reused its output cast into Bool.
c Fix matches root cause? Yes. The comparison type is chosen value-preserving where the join chooses it (supertype, subtype fallback, runtime filter), and the USING cast is reused only when its type name matches. No output type changes.
d Test intent preserved / new tests added? New test: ON over every join algorithm, table swap, USING, NATURAL, null-safe, RIGHT ANTI, LEFT ANTI with and without the runtime filter (plus checks that the filter is built and applied), join_use_nulls, LowCardinality, Array, named and unnamed Tuple, Nested, JSON typed paths, the subtype fallback and ASOF.
e Both directions demonstrated? Yes. Fails on master and passes with the fix, in clickhouse local and against a server: 50/50 randomized runs OK on the fix, 50/50 FAIL on master. Reverting the USING-cast change, the runtime-filter change, the named-Tuple pairing, the Nested custom-name step or the JSON path pairing each reddens its own arms.
f Fix is general across code paths? Covers every place the join picks a comparison type for a key pair: equality, null-safe, ASOF and IE keys share predicateOperandsToCommonType, plus the runtime filter in both build orders. The equals short-circuits that skip a cast are safe because Bool and UInt8 share storage and a Bool column holds only 0/1.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality(Nullable), Array, named and unnamed Tuple (also against each other), Nested, JSON typed paths and a Tuple subtype fallback; values 0, 1, 2, 255 and NULL.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Only rows that were matched by a wrong comparison change.
i Invariants and contracts preserved? Column and output types are unchanged, including the merged USING column, and both keys are cast into the same comparison type. A 1705-test join/using/asof/bool/runtime-filter/nested/json selection has no new failures against master.

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

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @antaljanosbenjamin, could you review this and add the can be tested label so CI runs? getLeastSupertype returns the first of two equals-equal key types, so with the Nullable(Bool) key on the left the join cast the UInt8 key into Bool (2 -> true); the comparison type now keeps UInt8 where a key has an integer, in predicateOperandsToCommonType and the runtime filter.

@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b548d8f]

Summary: ✅


AI Review

Summary

The PR makes Bool and integer JOIN keys compare by value across comparison casts and runtime filters while preserving output column types. Reviewed head b548d8f3c83419ae60a97c51b9a7b74eb00dad7d, including the follow-up fix: the previous empty-array finding is addressed, and no actionable findings remain. The new stateless regression produces all 39 expected output lines using the current-head CI binary.

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 7, 2026
Comment thread src/Interpreters/JoinUtils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b548d8f3c with master 7a516a1ab (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

9 object files changed (+32.71 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/transformTypesRecursively.cpp.o 100.13 KiB 124.16 KiB +24.03 KiB (+24.00%)

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

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

Job report

getLeastSupertype skips Nothing, so the common type of the keys
Tuple(Array(Array(UInt8)), Nullable(Bool)) and Tuple(Array(Nothing), UInt8)
is Tuple(Array(Array(UInt8)), Nullable(Bool)): it has structure where the
second key has Nothing. The type walk in compareBoolKeysAsUInt8 refused the
pair at Array(UInt8) vs Nothing, so the Bool element was never replaced and
the UInt8 key was still CAST to Bool (2 matched true) when the Bool table
came first, in the JOIN comparison and in the runtime filter type.

With left_is_common_type, a Nothing on the key side now leaves that part
of the common type as is, and the walk continues with its siblings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
Merged via the queue into ClickHouse:master with commit 6d0ae09 Nov 7, 2026
187 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
…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]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 22, 2026
`Bool` equals `UInt8` (`DataTypeNumber::equals` compares `typeid`), so the
common-type loop of `tryAddJoinRuntimeFilter` took the equal-types branch and
kept the build key type, `Bool`, for the runtime filter. The JOIN compares
such keys by value (no cast for equal key types), but the `Set` behind
`ExactSetRuntimeFilter` converts a probe into a `Bool` key with a real cast
(`Set::castToKeyType`, the `IN` semantics), so the integer 2 became `true`.
For `LEFT ANTI JOIN` the filter is `NOT IN`, and every probe row whose key is
neither 0 nor 1 was dropped before the JOIN saw it: `t_int (k UInt8)
LEFT ANTI JOIN t_bool (k Bool)` returned 0 rows instead of 2. With default
settings the filter is built unless the probe side is estimated at no more
than `join_runtime_filter_min_probe_rows` (1000) rows.

Pass the equal-types branch through `JoinCommon::compareBoolKeysAsUInt8` too,
as the unequal-types branch already does since ClickHouse#129894. The filter key type
is then `UInt8` (also inside `Nullable` and `LowCardinality`), and the probe
bytes are compared as the JOIN compares them. All other equal pairs keep
their type.

Closes ClickHouse#129970

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants