Skip to content

Fix wrong results for hash joins on a single LowCardinality wide-integer key - #113230

Merged
harikrishnan94 merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-lowcardinality-wide-int-join-key
Aug 4, 2026
Merged

harikrishnan94 merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-lowcardinality-wide-int-join-key

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112957

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 wrong results when a hash join has a single LowCardinality key of a type wider than 8 bytes (UInt128, Int128, UInt256, Int256, and their Nullable variants). Such a join silently returned rows whose key values are not equal.

Description

HashJoin::chooseMethod selects the packed keys128 / keys256 map for a single numeric key of 16 or 32 bytes. That map's key getter reads key_sizes to copy the key bytes, but the selecting branch never assigned it.

For a non-LowCardinality column this went unnoticed, because the all_fixed loop above had already stored the same value. ColumnLowCardinality::isFixedAndContiguous is false, so that loop breaks before assigning, while isNumeric and sizeOfValueIfFixed forward to the dictionary and still report a 16 or 32 byte numeric key. The branch is thus entered with key_sizes[0] left at 0, usePreparedKeys rejects it, and packFixed copies zero bytes. Every key becomes all-zero, so keys that differ compare equal and the join reports non-matching rows as matches.

SET allow_suspicious_low_cardinality_types = 1;
SELECT count() FROM (SELECT toLowCardinality(toUInt128(1)) AS id) AS a
JOIN (SELECT toLowCardinality(toUInt128(materialize(0))) AS id) AS b USING (id);
-- returned 1, must be 0

The setting above is only needed to declare the column. Ordinary queries reach this at default settings too, because the analyzer produces the type on its own: toTypeName(toLowCardinality(toUInt128(materialize(0)))) is LowCardinality(UInt128).

The fix assigns key_sizes[0] = size_of_field in that branch. For every non-LowCardinality key the value written is the one already present, and map selection is unchanged, so no query plan or performance characteristic changes. It also repairs ConcurrentHashJoin::selectDispatchBlock, which reads the same key_sizes and until now sent every row to a single shard.

Wrong results reproduce under hash, parallel_hash and grace_hash. Keys of 8 bytes or less were never affected, because HashMethodOneNumber ignores key_sizes.

04745_join_low_cardinality_wide_int_key fails before the change and passes after it. It covers the four affected types plus Nullable, and asserts that unaffected shapes stay correct: LowCardinality over UInt8, UInt64, String, UUID, plain UInt128, multi-column keys, ASOF and full_sorting_merge.

Version info

  • Backported to: 26.7.4.46, 26.6.3.46, 26.3.31.5, 25.8.34.11

groeneai and others added 2 commits August 4, 2026 00:42
…ger key

HashJoin::chooseMethod selects the packed keys128/keys256 map for a single
numeric key of 16 or 32 bytes. That map's key getter reads key_sizes to copy
the key bytes, but the branch that selects it never assigned key_sizes.

For a non-LowCardinality column this went unnoticed, because the all_fixed
loop above the branch had already stored the same value. ColumnLowCardinality
reports isFixedAndContiguous() as false, so the loop breaks before assigning,
while isNumeric() and sizeOfValueIfFixed() are forwarded to the dictionary and
still report a 16 or 32 byte numeric key. The branch is thus entered with
key_sizes[0] left at 0, usePreparedKeys rejects it, and packFixed copies zero
bytes. Every build and probe key becomes the all-zero value, so all rows land
in one bucket and the join degenerates into a cross product.

Affected types are LowCardinality over UInt128, Int128, UInt256 and Int256,
including their Nullable variants. Keys of 8 bytes or less were never affected
because HashMethodOneNumber ignores key_sizes. Wrong results reproduced under
the hash, parallel_hash and grace_hash algorithms.

Assigning key_sizes[0] in that branch is a no-op for every non-LowCardinality
key, where the value written is the one already present, and it changes no map
selection, so no query plan or performance characteristic changes. It also
repairs ConcurrentHashJoin::selectDispatchBlock, which reads the same key_sizes
and until now dispatched every row of such a join to a single shard.

Verified by printing key_sizes after chooseMethod: it was 0 for LowCardinality
numeric keys and 16 for plain UInt128, and the non-LowCardinality values are
identical before and after the change.
The fix in this branch is a byte count (key_sizes[0] = size_of_field), but
every affected assertion used values 0/1/5/7, which differ only in byte 0.
A wrong-but-nonzero byte count, or a later truncation in the packing path,
would have satisfied the reference exactly.

Each affected type now also joins two values that share their low 8 bytes
(128-bit) or low 16 bytes (256-bit) and differ only above, so a copy that
reads fewer bytes than the key type makes them collide. For Int128 and
Int256 the pair is -1 against 2^64-1 / 2^128-1, which covers the sign and
high half. Verified by mutation: with key_sizes[0] hard-coded to 8 the
128-bit rows fail, with 16 the 256-bit rows fail, and the unmutated fix
passes all of them.

The LowCardinality(Nullable(UInt128)) tables now also contain NULL on both
sides, with a row-level assertion, so NULL-key semantics on an affected
wide type are observable rather than implied by a count.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 6 findings adjudicated)

This PR was reviewed cold by a second model before publication, in two rounds. Round 1 bounced the
branch for insufficient test power; round 2 is clean. Nothing below is outstanding.

❌ Blockers

None.

⚠️ Major

wide-key-upper-bits-not-tested (round 1) - AGREED, fixed.
The fix is a byte count, but every affected assertion used values 0/1/5/7, which differ only in
byte 0. A wrong-but-nonzero byte count would have satisfied the reference exactly. The test now
joins, per affected type, two values sharing their low 8 bytes (128-bit) or low 16 bytes (256-bit)
and differing only above. Non-vacuity was proven with two mutation builds rather than asserted:
hard-coding key_sizes[0] = 8 reddens the UInt128/Int128/Int256 high-bit rows, hard-coding
16 reddens only the UInt256/Int256 rows, and the real fix reddens none. The two arms disagree
with each other, which is what makes the new assertions load-bearing.

nullable-wide-case-is-inert (round 1) - DISAGREED, with evidence.
The claim was that LowCardinality(Nullable(UInt128)) selects hashed because ColumnNullable is
not numeric, making that arm inert. At chooseMethod the column is ColumnLowCardinality, not
ColumnNullable: ColumnLowCardinality::isNumeric forwards to ColumnUnique::isNumeric and then to
column_holder, which has Nullable stripped by construction (ColumnUnique.h:269, enforced at
:285). So the column is ColumnVector<UInt128> - numeric, 16 bytes, branch entered. Decisive
measurement: the arm returns 6 rows on unfixed master and 1 after the fix, which is impossible if it
used hashed. The finding's secondary observation, that no NULL rows were inserted, was correct and
was fixed: both tables now carry NULL plus a row-level assertion.

test-does-not-pin-packed-dispatch-path (round 2) - DISAGREED, with evidence.
The claim was that the test still passes in two other worlds: one where wide LowCardinality keys
fall back to hashed, and one where ConcurrentHashJoin::selectDispatchBlock keeps sending every row
to a single shard after local packing is fixed.

Neither world is a reachable state. The map type comes from the same size_of_field the fix assigns:
for a single numeric key of 16 or 32 bytes chooseMethod returns keys128/keys256
unconditionally, and hashed is only reachable when that branch was not entered, so a hashed
fallback would need a source change this PR does not make.

The second world is refuted by the finding's own citations. key_sizes is one member written once per
clause, and both consumers read it: the local getter via join.key_sizes[i] and dispatch via
join.getKeySizes().at(0) - the only getKeySizes() caller in the tree. Both then build the same
HashMethodKeysFixed. There is no separate dispatch width, so "local packing fixed, dispatch still
degenerate" is not constructible. It was measured anyway: a 20k-row LowCardinality(UInt128)
parallel_hash join at max_threads = 8 on a debug build returns the correct 10000, and 04745
line 17 runs parallel_hash on every CI run, red before the fix.

The requested internal oracle is also unavailable: HashJoin::Type and key_sizes have no
SQL-observable surface (no EXPLAIN output, no system table, and no test in the tree asserts a join
datatype: line). The nearest precedent, 04327_packed_composite_key_join, states in its own header
that its assertions are independent of the internal hash-map type and pins packing by constructing
keys a truncating implementation must get wrong, which is the technique used here.

💡 Noted, not blocking

  • The fix flips HashMethodKeysFixed::usePreparedKeys from false to true for keys128: {0} fails
    its size-membership test while {16} passes, so the getter moves from the SSSE3 shuffle branch
    (whose masks were left all-0xFF, hence the zero key) to batched prepared_keys. That is the path
    a plain UInt128 key has always taken, and it was exercised at 20k rows on a debug build.
    keys256 is unaffected, since sizeof(Key) > 16 keeps usePreparedKeys false.
  • The LowCardinality(Nullable(UInt128)) arm covers NULL semantics but has no high-bits pair; the
    byte count it depends on is pinned by the four other high-bits assertions.
  • The multi-column case is a guard for an unaffected shape rather than added coverage: with two key
    columns the single-numeric branch is skipped, all_fixed is false, and the type is hashed, whose
    getter ignores key_sizes.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (SELECT toLowCardinality(toUInt128(1)) AS id) AS a JOIN (SELECT toLowCardinality(toUInt128(materialize(0))) AS id) AS b USING (id) returns 1 and must return 0, on 100% of runs. Confirmed on a pristine master snapshot as well as a locally reverted build.
b Root cause explained? Yes. chooseMethod returns keys128/keys256 while leaving key_sizes[0] at 0: the all_fixed loop breaks on ColumnLowCardinality::isFixedAndContiguous() == false before assigning, and the single-numeric branch tests isNumeric (forwarded to the dictionary) and returns without assigning. usePreparedKeys then rejects {0} and packFixed copies 0 bytes, so every key is all-zero: one bucket, cross product. Verified by printing key_sizes after chooseMethod, not by inference.
c Fix matches root cause? Yes. It assigns the single variable the branch failed to set. No widened bound, no no-random-* tag, no reduced dataset, no guard at the symptom site, no type forbidden.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed. New 04745_join_low_cardinality_wide_int_key with 22 assertions. Its oracle is live: it asserts a genuinely matching pair, so it cannot pass by returning nothing.
e Both directions demonstrated? Yes. Same test, same reference, two Build-ID-verified binaries. On a pristine master snapshot (cd03879e) 15 of the 22 assertions differ from the reference, including all four high-bit rows and the nullable row assertion; the 7 unaffected-shape guards stay unchanged. The fixed build (9419195f) passes all 22. Non-vacuity of the high-bit assertions was additionally proven with two mutation builds: hard-coding key_sizes[0] = 8 reddens the 128-bit rows, hard-coding 16 reddens only the 256-bit rows.
f Fix is general across code paths? Yes. All key_sizes consumers were enumerated and checked. Fixed at the source in chooseMethod rather than guarded at the getters. ConcurrentHashJoin::selectDispatchBlock is a second victim of the same unassigned value and is repaired by the same line, verified at 20k rows. Two-level maps inherit the fix. SetVariants and AggregatedDataVariants are already correct by other mechanisms; arrayEnumerateExtended::execute128bit requires isFixedAndContiguous for all columns and has no isNumeric bypass.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Affected set derived from the is_arithmetic specializations and ColumnVector instantiations: UInt128, Int128, UInt256, Int256, all four tested. Wrappers: Nullable (measured affected, fixed, tested), String, FixedString, UUID (unaffected, asserted), Decimal128 (unreachable, rejected at type creation), widths 1/2/4/8, and multi-column keys. Algorithms: hash, parallel_hash, grace_hash, with full_sorting_merge as an independent control. Scales: 1 row and 20k rows.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default, no serialization format, no persisted state, so no SettingsChangesHistory.cpp entry is needed. Map selection is provably unchanged (datatype: keys128 logged before and after), so no query plan or performance characteristic shifts. Behavior differs only where results were wrong.
i Invariants and contracts preserved? Yes. The change restores the local invariant that a map whose key getter consumes key_sizes is only selected with key_sizes populated, and that postcondition now holds on every return path of the branch. The ASOF path appends asof_size to the same vector after chooseMethod returns; this writes index 0 only, and an ASOF join over such a key was verified. No lifetime, allocation, locking or error-path change: one assignment into an already-sized vector. Ran on a debug build so the chasserts in ConcurrentHashJoin and HashMethodKeysFixed::shuffleKeyColumns were live, with no assertion failures.

Session id: cron:clickhouse-impl-slot-47:20260803-211000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @rschu1ze, could you review this? HashJoin::chooseMethod selects the packed keys128/keys256 map for a single 16 or 32 byte numeric key but never assigns key_sizes, which that map's getter reads to copy the key bytes. A LowCardinality column breaks the all_fixed loop above before it assigns, so packFixed copies zero bytes and every key collapses to all-zero, making unequal keys compare equal.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@PedroTadim PedroTadim self-assigned this Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [121bcb7]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue

AI Review

Summary

This PR fixes a real wrong-results bug in HashJoin::chooseMethod for a single wide numeric LowCardinality key by restoring the missing key_sizes[0] assignment before selecting keys128 / keys256. I traced the current code through the unchanged build/probe paths and ConcurrentHashJoin; the affected paths all consume the same repaired width, and the new stateless test covers the affected 128/256-bit cases, nullable coverage, unaffected controls, and the relevant hash-join algorithms. I did not find a remaining correctness, safety, or coverage gap in the current patch.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@rschu1ze rschu1ze assigned harikrishnan94 and unassigned PedroTadim Aug 4, 2026
@rschu1ze

rschu1ze commented Aug 4, 2026

Copy link
Copy Markdown
Member

@harikrishnan94 Like to take this one for review?

Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved

@harikrishnan94 harikrishnan94 left a comment

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.

Also explain to me the code flow of how this can happen

@harikrishnan94 asked for a shorter comment at the `chooseMethod`
assignment. The comment now states only the local invariant: the
`all_fixed` loop above bails out before assigning `key_sizes` for a
`LowCardinality` column. Why that matters (the packed `keys128`/`keys256`
getters read `key_sizes` to copy the key bytes, so a zero width collapses
every key to one bucket) belongs in the commit message and the pull
request description, not at the call site.

Trimmed the test comments the same way while in there, and wrapped
literal names in inline code blocks per `.claude/CLAUDE.md`.

No executable change: the diff is comments only.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

The walkthrough, all line numbers at 121bcb74.

1. The key column is still LowCardinality when chooseMethod runs. materializeBlockInplace strips only Const and special representations (Block.cpp:1181-1189), not the dictionary, and tryGetLowCardinalityMethod claims only the String/FixedString variants, so a numeric LowCardinality key falls through to chooseMethod as a live ColumnLowCardinality.

2. The all_fixed prologue bails out before assigning. ColumnLowCardinality::isFixedAndContiguous is hardcoded false (ColumnLowCardinality.h:274), so the loop breaks at HashJoin.cpp:329-332 and never reaches the key_sizes[j] = ... at :334. key_sizes was only resized, so element 0 is 0.

3. The single-numeric branch is entered anyway, because both of its predicates forward to the dictionary: isNumeric (ColumnLowCardinality.h:276 -> ColumnUnique.h:110 -> column_holder) and sizeOfValueIfFixed (:275 -> ColumnUnique.h:109). A LowCardinality(UInt128) therefore reports numeric and 16, and HashJoin.cpp:353 returns keys128. Before this patch nothing in that branch wrote key_sizes, so it stayed {0}.

4. keys128/keys256 map to HashMethodKeysFixed (KeyGetter.h:212,216), whose getter reads key_sizes to copy the key bytes. With {0}, both of its paths produce a zero key:

  • usePreparedKeys rejects it, since 0 is not in {1,2,4,8,16} (HashMethod.h:423-433), so prepared_keys stays empty.
  • The SSSE3 mask loop runs key_sizes[i] times, that is zero times (HashMethod.h:499-503), leaving the mask at the 0xFF fill from :494, and 0xFF means "write zero". Where that path is off (keys256, or MSan), packFixed falls to its default: arm and copies key_sizes[j] == 0 bytes into a zero-initialized key (AggregationCommon.h:151-153).

So every build and probe row hashes to the same key and unequal values compare equal.

5. ConcurrentHashJoin reads the same member, join.getKeySizes().at(0) (ConcurrentHashJoin.cpp:607), so selectDispatchBlock sent every row to one shard as well. Both consumers are repaired by the single assignment.

Keys of 8 bytes or less were never affected: they select HashMethodOneNumber, which ignores key_sizes entirely (HashMethod.h:53).

One thing worth noting: allow_suspicious_low_cardinality_types is only needed to declare such a column, not to reach the bug. SELECT toTypeName(toLowCardinality(toUInt128(materialize(0)))) returns LowCardinality(UInt128) at default settings.

@harikrishnan94 harikrishnan94 left a comment

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.

LGTM

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 16, 2026
Backport #113230 to 26.7: Fix wrong results for hash joins on a single LowCardinality wide-integer key
alexey-milovidov added a commit that referenced this pull request Aug 16, 2026
Backport #113230 to 26.6: Fix wrong results for hash joins on a single LowCardinality wide-integer key
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #113230 to 25.8: Fix wrong results for hash joins on a single LowCardinality wide-integer key
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #113230 to 26.5: Fix wrong results for hash joins on a single LowCardinality wide-integer key
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…on a single LowCardinality wide-integer key
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…on a single LowCardinality wide-integer key
alexey-milovidov added a commit that referenced this pull request Sep 4, 2026
Backport #113230 to 26.3: Fix wrong results for hash joins on a single LowCardinality wide-integer key
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
…on a single LowCardinality wide-integer key
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…on a single LowCardinality wide-integer key
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

8 participants