Skip to content

Fix JSON grace hash join - #113398

Closed
asya-ch wants to merge 3 commits into
masterfrom
asya/fix_json_grace_hash_join
Closed

asya-ch wants to merge 3 commits into
masterfrom
asya/fix_json_grace_hash_join

Conversation

@asya-ch

@asya-ch asya-ch commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Resolves #112867

Summary

Grace hash joins have a bug when the join key is a json column and there is a nested join. The problem is that right now the hash computation for json keys is not deterministic because it iterates through the path keys in no particular order. If we instead use the sorted version, the hashed values will be consistent across the nested joins.

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):

Fix logical error Invalid state transition, expected WRITING_BLOCKS, got JOINING_BLOCKS in grace hash join with JSON keys.

@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c03c9ae]

Summary: ✅


AI Review

Summary

This PR makes ColumnObject::computeHashInto stable across typed/dynamic path iteration order and adds a regression for the spill/reload Invalid state transition exception from #112867. That fixes the specific map-order instability, but it does not make grace_hash correct for general JSON join keys: bucket routing is still based on a layout-dependent hash, so equal keys stored with different dynamic/shared layouts can still land in different buckets and miss matches.

Missing context / blind spots
  • ⚠️ The only Praktika artifact currently attached to the PR is Build profile diff; I could not verify a stateless test run for the new regression from CI.
Findings

❌ Blockers

  • [src/Columns/ColumnObject.cpp:1272-1296] [dismissed by author -- https://github.com/Fix JSON grace hash join #113398#discussion_r3717187694] grace_hash requires equal join keys to route to the same bucket, but ColumnObject::computeHashInto still hashes the physical JSON layout rather than the logical object. JoinUtils::scatterBlockByHash uses this method for both sides of grace_hash joins, so a key stored as a dynamic subcolumn on one side and in shared_data on the other still routes to different buckets and silently drops matches. This patch fixes the spill/reload order instability from #112867, but it still leaves grace_hash incorrect for layout-divergent equal JSON keys. Suggested fix: either switch grace_hash bucket routing for JSON / Object keys to a representation-independent logical hash (for example the serializeForHashCalculation / updateHashWithValue path) or reject JSON / Object keys in grace_hash until such a weak hash exists.
Tests
  • ⚠️ Add a focused grace_hash vs hash regression where the same logical JSON(max_dynamic_paths = 1) key is stored as a dynamic path on one side and in shared_data on the other, analogous to 04496_parallel_full_sorting_merge_join_json_keys.sql. That is the smallest proof that grace_hash either routes equal JSON keys together or rejects them explicitly.
Final Verdict

Changes requested. The patch fixes the specific spill-order exception, but grace_hash with JSON keys is still incorrect for layout-divergent equal values.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 7/9 (77.78%) · 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 5, 2026
///
/// Paths must be visited in sorted order, not in map order: map order differs between column
/// instances holding the same data, and `GraceHashJoin` requires the same row to hash
/// identically before and after a spill round-trip through disk (see issue #112867).

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.

GraceHashJoin needs a stronger invariant than "the same row hashes the same before and after spill": logically equal keys on the left and right also have to land in the same bucket. computeHashInto still explicitly does not provide that for JSON / Object when one side stores a path as a dynamic subcolumn and the other overflows the same path into shared_data, because those two carriers are still hashed differently here.

The existing 04496_parallel_full_sorting_merge_join_json_keys.sql regression already demonstrates that exact computeHashInto mismatch with JSON(max_dynamic_paths = 1). GraceHashJoin::addBlockToJoinImpl and GraceHashJoin::joinBlock both partition through scatterBlockByHash -> computeHashInto, so this patch fixes the typed-path spill repro from #112867 but still leaves grace_hash able to silently miss matches for layout-divergent JSON keys. Either bucket scattering has to switch to the logical JSON hash (serializeForHashCalculation / updateHashWithValue) or GraceHashJoin needs to reject JSON / Object keys until that exists.

@asya-ch asya-ch Aug 6, 2026 •

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.

I'm not sure whether it is better to switch to the slow logical hash or for grace hash joins to block JSON keys altogether. (Reviewers, let me know if you have insight here.)

I would proceed with this PR so that it is fixed for physically equivalent rows. We can improve it for physically divergent keys at a later point.

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.

If the logical hash is too expensive to use in the scatter path immediately, I would reject JSON / Object keys in grace_hash for now. JoinUtils::scatterBlockByHash still partitions exclusively via IColumn::computeHashInto (src/Interpreters/JoinUtils.cpp:639-642), and ColumnObject::computeHashInto still documents the dynamic-path vs shared_data layout split at src/Columns/ColumnObject.cpp:1272-1274. That means partial support still returns wrong join results for equal keys stored with different layouts, whereas an explicit rejection would fail closed until a representation-independent weak hash exists.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we cannot use a layout dependant hash to scatter rows for partitioning purposes. It makes the results wrong. I think the main comment of IColumn::computeHashInto is plain against the comment of this function:

/// Per-row weak hash kernel. Writes a 32-bit CRC32C-based hash for each row in
/// [row_begin, row_end) into the caller-provided buffer `hash_out` (which must hold at
/// least row_end - row_begin entries). It's a fast weak hash, mainly needed to scatter
/// data between threads (sharded aggregation, `grace_hash` joins, parallel-window
/// partitioning, hash-join scatter).

It explicitly mentions partitioning, but then this function:

/// Like `updateHashWithValueRange`, this hashes the physical path layout: it does NOT guarantee
/// equal hashes for a logically equal object whose paths are split differently between dynamic
/// columns and `shared_data` across blocks.

For partitioning we need a hash that is the same for logically equal objects. Let's also tag @harikrishnan94 as he added the comments.

@harikrishnan94 harikrishnan94 Aug 11, 2026 •

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.

I think we cannot use a layout-dependent hash to scatter rows for partitioning.
The only contract we need is: equal join keys from probe and build (with possibly different representations) must land in the same bucket. the same row hashes the same before and after spill is a non-requirement.

grace_hash scatters via computeHashInto, which uses a different HASH (CRC32C) than the in-memory JOIN. Sorting Object path iteration only stabilizes one layout; it does not make equal JSON keys with different physical layouts route together.

For context on the JOIN side: AFAIK, there are only 3 distinct key types supported by HashJoin and all types are mapped to one of the 3 cases.
a) 8, 16, 32, 64, 128 or 256 bit keys
b) String keys
c) LowCardinality keys.

There is an additional case called range keys, but they're a strict subset of (a).

Integer/numeric keys with bit-widths <= 256 map exactly to the corresponding case in (a).
String keys map exactly to (b).
LowCardinality keys map exactly to (c).

Multi-column fixed width keys with total bit-width <= 256 again map exactly to the corresponding case in (a).
Multi-column fixed width keys with total bit-width > 256 or String/Other keys like JSON map to 128 bit keys with a SipHash128 applied - i.e. the HT key itself is a hash (SipHash128) instead of the actual keys.
For SipHash128: the accidental-collision (birthday problem) bound is of the order ~2^64 rather than ~2^32 for regular hash kinds.

@asya-ch asya-ch Aug 11, 2026 •

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.

Thanks for taking a look. As discussed offline, I'll close this PR and let one of you pick it up.

@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit c03c9ae - the build was skipped, reused from cache, or predates profile upload.

@asya-ch

asya-ch commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator Author

Closes issue #112867.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

grace_hash + correlated EXISTS with RIGHT JOIN on a JSON key: logical error Invalid state transition, expected WRITING_BLOCKS, got JOINING_BLOCKS

3 participants