Skip to content

Fix split-dependent hash of JSON/Object columns - #109450

Merged
alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-json-object-hash-split-invariance
Aug 26, 2026
Merged

alexey-milovidov merged 21 commits into
ClickHouse:masterfrom
groeneai:fix-json-object-hash-split-invariance

Conversation

@groeneai

@groeneai groeneai commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112867
Related: #109428

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 JSON/Object/Dynamic columns hashing logically equal values differently depending on their physical layout: how JSON/Object paths were split between dynamic subcolumns and shared data, or whether a Dynamic value sat in a typed or the shared variant. Hash-based joins on such a key silently missed matches, and a grace_hash spill could raise a LOGICAL_ERROR ("Invalid state transition"). A JSON key needed no non-default setting; Dynamic also required allow_dynamic_type_in_join_keys.

Description

The implementation changed since the earlier approval here, so please treat it as needing a fresh look. The approved version hashed canonical serializeValueIntoArena bytes and cost up to +568% CPU; this one produces none. Both measured below.

computeHashInto is the per-row weak hash behind the in-memory scatter paths (sharded aggregation, grace_hash bucketing, window PARTITION BY, join scatter). For JSON/Object and Dynamic it hashed the physical layout: ColumnDynamic forwarded to ColumnVariant, which hashes a shared-variant value by its serialized blob but a typed one by the column's representation; ColumnObject chained sub-columns in section order, so a path's contribution moved with it. Both splits follow insertion history and can change across a temp-file round-trip, while compareAt already treats the representations as equal. JSON hits this at default settings, since hasDynamicType misses its inner Dynamic.

ColumnDynamic::computeHashInto forwards to ColumnVariant as master does, then overwrites only shared-discriminator rows with the leaf hash the value would have when typed. ColumnObject::computeHashInto folds (path, value) over the sorted union of the dynamic paths and shared_data, one cursor per row. updateHashFast and updateHashWithValueRange stay layout-dependent.

The shared values of a whole range are decoded in one batch, grouped by the value's binary encoded type prefix, so each distinct type is deserialized into a single temporary column and hashed in one pass; a single-typed batch (the common case) deserializes in place with no grouping arrays. Decoding one value at a time was the hot-path regression raised in review: it put an IDataType::createColumn on every row of every shared path. IColumn::computeHashInto is per-row independent, so batching does not change any hash.

04505_json_object_hash_split_invariance checks that equal values with different layouts match under the three hash joins, collapse under GROUP BY/DISTINCT/uniqExact, and that a spill flushes real payload rather than only constructing buckets: six assertions fail on master, all pass here. Three ComputeHashInto gtests cover the per-row hash and scratch state SQL cannot see.

ShuffleSendStep shuffles rows to remote workers with this hash and marks no basis in its serialized step, so mixed versions could disagree on a shuffle key. Capability gate, or unsupported anyway?

Provenance and performance

Found by the AST fuzzer on #109428 as Invalid state transition, expected WRITING_BLOCKS, got JOINING_BLOCKS in GraceHashJoin::FileBucket, STID 3913-4579 (report): a key re-hashing into an earlier bucket mid-spill violates that state machine.

The table below predates the batching and measures the one-value-at-a-time decode. After batching, on aarch64 RelWithDebInfo, min(user CPU) over 5 reps, 1M rows of JSON(max_dynamic_paths=1) carrying 19 shared_data values per row through ScatterByPartitionTransform (a window PARTITION BY on the JSON key):

max_threads master one value at a time batched
2 0.99s 2.39s (+141%) 1.08s (+9%)
8 1.03s 2.42s (+135%) 1.12s (+9%)
16 1.08s 2.49s (+131%) 1.17s (+8%)

The superlinear term at higher parallelism is gone; the arm tracks master's scaling. On a 4-shared-path key the whole query is within noise of master (8.74s / 8.73s / 8.29s for master / one-at-a-time / batched at max_threads = 8).

Release-shaped build, three arms from one revision (master with these files reverted; the approved implementation; this one), UserTimeMicroseconds min over 11 alternating reps; all arms agreed on all 12 workloads first.

workload vs master vs appr.
JSON grace_hash, no shared +2.8% -61.2%
JSON grace_hash, mixed +8.2% -33.8%
JSON grace_hash, all shared +11.7% +6.5%
window JSON, no shared +12.8% -88.3%
window JSON, mixed -10.6% -1.7%
window JSON, 4 shared +51.5% -46.8%
Dynamic grace_hash +44.3% -34.3%
Dynamic, 100% shared +70.3% -1.2%

Non-JSON controls are flat and ArenaAlloc* matches master. Making a byte-producing basis cheap failed three times: even hoisting the buffer so the block allocated almost nothing still cost +1253%.

The residual tracks the shared representation only: each shared value pays one decode, one leaf hash, one fresh scratch column. Of the worst arm's +70.3%, about +30.4% is that scratch reset (+24.9%, +18.5% on the next two). It uses cloneEmpty() rather than popBack because popBack is a row operation: ColumnLowCardinality::popBack drops indexes but not the dictionary, which computeHashInto re-hashes in full per row, and ColumnVariant nests the shape. Conditioning it on a measured property of the scratch column did not survive review, so it stays unconditional. The cliff is bounded per computeHashInto call, not by the table; a 5k-40k ladder is linear.


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

ColumnObject::computeHashInto and updateHashFast hashed the physical path
layout: they chained the sub-columns in typed -> dynamic -> shared_data order,
hashing a dynamic path's value via its typed representation but the same value
in shared_data via its serialized string bytes. A logically equal object then
hashed differently depending on how its paths were split between dynamic
columns and shared_data. That split is not stable: it depends on insertion
history, varies across blocks, and can change when a value is round-tripped
through a temporary file.

Consequences for JSON/Object join keys (allow_dynamic_type_in_join_keys):
- grace_hash scatters keys into buckets by this hash, so equal keys with
  different splits landed in different buckets and silently failed to match.
- during a grace_hash spill, a key re-hashing to an earlier bucket violates the
  "rows move only forward" invariant and raised a FileBucket state-machine
  logical error (Invalid state transition, expected WRITING_BLOCKS, got
  JOINING_BLOCKS).

Hash the canonical, split-invariant per-row serialization instead (the same
bytes serializeValueIntoArena produces, which DISTINCT and uniqExact already
use): typed paths in sorted order, then dynamic paths and shared data merged in
sorted path order. A dynamic path and a shared-data path emit identical
(path, binary value) bytes for the same value, so the hash no longer depends on
the split and stays consistent with equality.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Build two logically equal {"x":1} JSON(max_dynamic_paths=1) values where x is a dynamic path in one and in shared data in the other, then grace_hash self-join: master returns 2 matches instead of 4, on demand. Captured as test 04505_json_object_hash_split_invariance.
b Root cause explained? ColumnObject::computeHashInto/updateHashFast hash the physical path layout (typed -> dynamic -> shared_data), hashing a dynamic path's value via its typed column but the same value in shared_data via its serialized string bytes. Equal objects with different physical splits get different hashes; grace_hash scatters by this hash, so equal keys land in different buckets (missed matches), and a key re-hashing backward across a spill trips the FileBucket WRITING_BLOCKS/JOINING_BLOCKS assertion.
c Fix matches root cause? Yes. The hash is now computed from the canonical, split-invariant per-row serialization (serializeValueIntoArena's bytes: typed paths sorted, then dynamic + shared_data merged in sorted path order), so it is identical for equal values regardless of split, consistent with equality and with DISTINCT/uniqExact.
d Test intent preserved / new tests added? New regression test 04505_json_object_hash_split_invariance added. Existing JSON/dynamic-join tests unchanged and still pass.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID cf6e8a0d): test's grace_hash line = 2 -> FAILS. Post-fix binary (Build ID 9524b6ee): = 4 -> PASSES.
f Fix is general across code paths? Yes. Both hash surfaces on ColumnObject are fixed (computeHashInto used by scatter/grace-hash and updateHashFast used by SipHash/bloom-filter), so the two do not disagree. It fixes the root cause (the hash), not the crash site in GraceHashJoin.
g Fix generalizes across inputs (params/datatypes/wrappers)? Verified across a value matrix (nested object, Array, String, multi-path, multiple max_dynamic_paths): all match across a dynamic/shared split under grace_hash; GROUP BY == uniqExact; and two genuinely different values are NOT over-merged (stay 2 groups / 2 self-join).
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or metadata change. Only the in-memory hash of JSON/Object values changes; it now agrees with equality. No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. Restores the IColumn::computeHashInto contract that equal values hash equally, which GraceHashJoin's "rows move only forward" invariant and every hash-based container rely on. serializeValueIntoArena is reused unchanged; the scratch Arena is rolled back per row so memory stays bounded.

Session id: cron:clickhouse-worker-slot-1:20260705-174300

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @harikrishnan94 — could you review this? It makes ColumnObject::computeHashInto/updateHashFast hash the canonical split-invariant serialization (the bytes serializeValueIntoArena already produces) instead of the physical typed/dynamic/shared_data layout, so a JSON value hashes the same regardless of its dynamic-vs-shared_data split. Fixes silent missed matches for JSON grace_hash join keys and the FileBucket "Invalid state transition" logical error. @harikrishnan94 since it touches the computeHashInto path from #106538.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b18a0d6]

Summary: ✅


AI Review

Summary

This PR fixes computeHashInto for JSON / Object / Dynamic so logically equal values hash identically across dynamic/shared layouts, and the added functional/gtest coverage matches that contract well. On the current HEAD, the local hash/equality bug looks fixed, but one previously raised distributed-plan compatibility concern still stands.

Findings

⚠️ Majors

  • [src/Columns/ColumnObject.cpp:1294; src/Processors/QueryPlan/ShuffleSendStep.cpp:97-105; src/Processors/QueryPlan/Serialization.cpp:71-84; src/Core/ProtocolDefines.h:96-101] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109450#discussion_r3673204210] The PR changes the routing hash that ScatterByPartitionTransform and JoinUtils::scatterBlockByHash use for JSON / Object / Dynamic, but ShuffleSendStep still serializes only key names, bucket count, and cast types, and distributed-plan serialization still silently downgrades to the peer's older version. During a rolling upgrade with make_distributed_plan = 1, old and new workers can therefore send the same logical key to different shuffle buckets, so matching rows never meet on the same worker. The feature is experimental and default-off, but the mixed-version wrong-results surface is still real; this needs either a fail-closed compatibility guard or an explicit contract that mixed-version distributed shuffles with these key types are unsupported.
Final Verdict

Not ready to merge without a decision on the mixed-version make_distributed_plan compatibility gap above.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 172/206 (83.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 5, 2026
The spill sub-case checked count() > 0, which a partially-broken spill
that keeps one bucket alive but drops most matches would still pass.
Assert the exact self-join cardinality (8000000 = 50 distinct keys x
400 rows each) and add a non-spilling hash join on the same data as a
cross-check, so the test catches silent wrong-result regressions as
well as the FileBucket state-machine exception.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 560ff9e. The spill sub-case now asserts the exact self-join cardinality instead of count() > 0: the key is fully determined by number % 50 (the b index (number*7+1) % 50 also depends only on number % 50), so there are 50 distinct keys with 400 rows each => 50 * 400 * 400 = 8000000 matched pairs. I also added a non-spilling join_algorithm='hash' count on the same data as the equivalence cross-check you suggested; both must return 8000000.

Verified both directions with Build-ID-confirmed binaries (only test files changed, ColumnObject.cpp temporarily reverted to master then restored, same-source relink -> identical Build ID 9524b6ee):

  • Pre-fix (master, Build ID cf6e8a0d): the in-memory grace_hash line is 2 (should be 4) -> test FAILS. For this particular fixture both spill counts already come out 8000000 on master too, so the deterministic pre-fix wrong-result signal is the in-memory grace_hash 2 line; the strengthened spill assertion is the strictly-stronger guard against a future silent-drop / one-bucket-alive regression rather than a second failing line today.
  • Post-fix (Build ID 9524b6ee): all lines match, grace_hash 4, spill_join_grace 8000000, spill_join_hash 8000000.

The exact-cardinality strengthening pushed the self-join fixture to
numbers(20000) -> 8000000 matched pairs, which on debug/asan under the
flaky-check parallel pool exceeded the 180s per-run limit (04505 FAIL,
"Test runs too long"). Reduce to numbers(1000) -> 50 keys x 20 rows =
20000 matched pairs.

Spilling is forced by grace_hash_join_initial_buckets = 8 independent of
data volume, so the smaller fixture still spills every bucket to a temp
file and exercises the delayed-bucket re-scatter (verified: 8 buckets
initialized, buckets 1-7 loaded from spill). The exact-count assertion
(the bot's requirement to catch silent-drop regressions) is preserved,
and the non-spilling hash join on the same data still cross-checks it.

Runtime: >180s timeout -> ~0.8s on debug. Both directions still hold:
grace_hash = 2 on the pre-fix binary (wrong), 4 with the fix.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

The exact-cardinality strengthening pushed the spill fixture to numbers(20000) (8000000 matched pairs), which timed out the 180s per-run test limit on debug/asan (04505 "Test runs too long"). Shrunk to numbers(1000) -> 50 keys x 20 rows = 20000 pairs @ b12971b.

Spilling is forced by grace_hash_join_initial_buckets = 8 regardless of data volume, so the smaller fixture still spills every bucket to a temp file and exercises the delayed-bucket re-scatter (verified locally: 8 buckets initialized, buckets 1-7 loaded from spill). The exact-count assertion and the non-spilling hash cross-check are kept, so it still catches silent-drop regressions, not just the FileBucket exception. Runtime: >180s -> ~0.8s on debug. Both directions still hold (Build-ID confirmed): grace_hash = 2 on pre-fix cf6e8a0d (wrong), 4 with the fix 9524b6ee.

Comment thread src/Columns/ColumnObject.cpp Resolved
computeHashInto/updateHashFast on ColumnDynamic forwarded to the raw
ColumnVariant layout (discriminator + typed offset), while compareAt,
serializeValueIntoArena and updateHashWithValue already canonicalize a value
regardless of whether it lives in a typed variant or the shared variant. So two
logically equal Dynamic values placed in different storages by insertion history
hashed into different hash/parallel_hash/grace_hash buckets, dropping matches for
direct Dynamic join keys (allow_dynamic_type_in_join_keys=1) and risking the
grace-hash FileBucket state-machine assertion after a spill.

Hash the same canonical per-row serialization serializeValueIntoArena produces,
mirroring the ColumnObject fix. Adds a direct Dynamic regression to
04505_json_object_hash_split_invariance (both storages of one value; hash /
parallel_hash / grace_hash / GROUP BY / DISTINCT / uniqExact, plus a grace-hash
spill on a Dynamic key with a deterministic 20000-pair self-join).

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

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the ColumnDynamic split-invariant hashing follow-up (commit dda4d1f).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a local debug build, a Dynamic(max_types = 1) self-join over a table where the same 50 keys appear 10x in a typed variant and 10x in the shared variant returns grace_hash = 11181 pre-fix vs the correct 20000 (= non-spilling hash join). Reproduces every run.
b Root cause explained? computeHashInto/updateHashFast forwarded to the raw ColumnVariant layout (discriminator + typed offset). compareAt treats a value in a typed variant and the same value in the shared variant as equal, but the hash differed by placement, so the grace-hash scatter routed the two representations to different buckets and dropped matches (and a backward re-hash after a temp-file spill risks the FileBucket assertion).
c Fix matches root cause? Yes. Hash the canonical per-row serializeValueIntoArena bytes (typed variant and shared variant emit identical (null bit, type, binary value) for the same value), the same basis compareAt/updateHashWithValue already use. Mirrors the ColumnObject fix in this PR.
d Test intent preserved / new tests added? New direct Dynamic regression added to 04505_json_object_hash_split_invariance: both storages of one value, asserting hash/parallel_hash/grace_hash/GROUP BY/DISTINCT/uniqExact collapse them, plus a grace-hash spill with an exact 20000-pair self-join compared against the hash join. No existing assertions weakened.
e Both directions demonstrated? Yes. Pre-fix binary: spill grace_hash = 11181 (wrong). Post-fix binary: 20000 = hash join (correct). Build IDs verified distinct (pre 0846270638..., post 3934fab35bcd...).
f Fix is general across code paths? Yes. Both cross-representation scatter/join entry points (computeHashInto, updateHashFast) are fixed. updateHashWithValueRange is deliberately left on the raw layout — it is the same-INSERT-data dedup path, exactly as the ColumnObject fix scoped it. updateHashWithValue (SipHash single-row) already canonicalizes.
g Fix generalizes across inputs? Yes. The hash is derived from serializeValueIntoArena, which is type-agnostic, so it holds for any variant type. Verified locally with both Int64 and String values (split across typed/shared): grace_hash and uniqExact collapse the representations for both.
h Backward compatible? Yes. No setting default, on-disk/wire format, or metadata change. Only the in-memory weak hash used for query-time scatter/join partitioning changed, aligning it with existing equality/serialization semantics.
i Invariants and contracts preserved? Yes. Honors the IColumn::computeHashInto representation-independence contract (combine the finalized per-row h, seed on initial). The Arena scratch is rolled back per row. updateHashFast matches computeHashInto's canonical basis.

Session id: cron:clickhouse-worker-slot-1:20260705-233900

The Dynamic hashing extension added a second 20000-pair grace-hash spill
alongside the JSON one, and both queries forced one output row per block
(max_joined_block_size_rows = 1). Under the flaky check's randomized
joined_block_split_single_row = 1 plus sanitizer instrumentation, the whole
test ran 210-290s and tripped the 180s per-run limit.

The bug being tested is a build-side scatter/spill issue: the output block
size does not affect it. Drop max_joined_block_size_rows = 1, pin
joined_block_split_single_row = 0, and shrink both fixtures (JSON 1000 -> 250
rows, Dynamic 500 -> 100 rows / 50 -> 25 keys). Disk spilling is still forced
by grace_hash_join_initial_buckets = 8 regardless of volume, so both fixtures
still exercise the full 8-bucket temp-file round-trip, and the Dynamic spill
still catches the pre-fix dropped-match (grace 1600 vs hash 1600; pre-fix
grace 864). Per-run time drops to ~1s.

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

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 6337b75 to fix the recurring flaky-check timeout on 04505_json_object_hash_split_invariance (210-290s > 180s on amd_debug/amd_asan_ubsan, flaky check).

The Dynamic hashing extension added a second 20000-matched-pair grace-hash spill next to the JSON one, and both self-joins pinned max_joined_block_size_rows = 1. That is a build-side scatter/spill bug, so the output block size is irrelevant to what the test verifies; combined with the flaky check's randomized joined_block_split_single_row = 1 and sanitizer instrumentation, emitting one output row per matched pair is what blew past the limit.

Fix (test-only): drop max_joined_block_size_rows = 1, pin joined_block_split_single_row = 0, and shrink both fixtures (JSON 1000 -> 250 rows, Dynamic 500 -> 100 rows / 50 -> 25 keys). Disk spilling is still forced by grace_hash_join_initial_buckets = 8 independent of volume, so both fixtures still exercise the full 8-bucket temp-file round-trip. Verified locally on debug and ASan: per-run ~1s under the exact failing settings; the test still catches the bug pre-fix (grace_hash 4->2, dyn_grace_hash 4->2, dyn_spill_grace 1600->864) and passes post-fix.

Session id: cron:clickhouse-worker-slot-2:20260706-014000

Comment thread src/Columns/ColumnObject.cpp Resolved
computeHashInto and updateHashFast serialized each row's canonical bytes
into a single Arena reused across the whole block and rolled it back per
row. serializeValueIntoArena grows the row buffer with allocContinue,
which on mid-row growth copies into a new chunk and abandons the
pre-growth copy; Arena::rollback only rewinds head.pos in the current
chunk and cannot reclaim those stranded copies. A reused arena therefore
retains the largest row's growth chain for the entire block-hashing call
for wide JSON/Object/Dynamic rows.

Move the Arena inside the per-row loop so it is destroyed each iteration,
bounding the transient to a single row. The canonical bytes are
unchanged, so the split-invariant hashes are byte-identical; 04505 passes
with and without randomization and the JSON-key join result is identical.
This matches the per-row buffer pattern in FunctionsHashing.

Addresses the code-review comment on PR ClickHouse#109450.

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

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the per-row Arena follow-up (commit cde81de):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Wide-JSON block hashed via a parallel_hash join key (400 paths x 128B, 30k x 30k) drives scatterBlockByHashImpl -> computeHashInto; deterministic on demand.
b Root cause explained? serializeValueIntoArena grows the row buffer via Arena::allocContinue, which on mid-row growth copies to a new chunk and abandons the old one; Arena::rollback only rewinds head.pos in the current chunk, so a single arena reused across the block retains the widest row's growth chain for the whole hashing call.
c Fix matches root cause? Yes. The Arena is moved inside the per-row loop in all four methods, so its destructor frees the chunk chain each iteration; nothing survives across rows. No rollback needed.
d Test intent preserved / new tests added? Yes. Canonical bytes are unchanged so hashes are identical; 04505 (which already covers the split-invariant hash/join semantics for both Object and Dynamic) still passes. No new test: this is a memory-management change with no observable behavior change to assert in SQL.
e Both directions demonstrated? Behavior is invariant by construction (same bytes hashed). Verified equal results and equal peak memory on pre-change vs post-change binaries for the wide-JSON parallel_hash join; 04505 30/30 with randomization on both.
f Fix is general across code paths? Yes. Applied to both flagged methods on ColumnObject AND the mirrored ColumnDynamic::computeHashInto/updateHashFast (same reused-arena pattern), not just the one line the bot pointed at.
g Fix generalizes across inputs? Yes. Type-agnostic: the loop hashes the canonical serialization for any value width/type wrapper; the per-row scope bounds the transient regardless of path count, value size, or variant/shared-data split.
h Backward compatible? Yes. No setting, format, or on-disk/wire change; hash outputs are byte-identical, so no behavior or compatibility surface changes.
i Invariants and contracts preserved? Yes. serializeValueIntoArena's contract (fresh begin, single contiguous range per call) holds with a fresh arena per row; computeHashInto's combine-vs-initial contract is untouched; the canonical-bytes basis shared with compareAt/updateHashWithValue is unchanged.

Session id: cron:clickhouse-worker-slot-1:20260706-033900

@harikrishnan94 harikrishnan94 self-assigned this Jul 6, 2026
@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cde81de

CI is fully finished (Finish Workflow pass, no pending checks). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Block structure mismatch in JoinStep: [__table3.number, __table3.number] (STID 0993-386d) trunk fuzzer bug, unrelated to this PR (correlated-subquery decorrelation + runtime-filter dup-key planning; 20+ unrelated PRs + master in 30d) #109114 (ours, open, on review)
CH Inc sync private upstream sync CH Inc sync (private, not actionable)

All other 151 checks green. The recurring flaky-check timeout on 04505_json_object_hash_split_invariance is resolved on this head: Stateless tests (amd_debug/amd_asan_ubsan/amd_msan/amd_tsan, flaky check) all pass. The bot code-review memory-leak finding (reused hashing Arena) is fixed in cde81de.

Report for the stress failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109450&sha=cde81de9716585c7096098591ce768b44f9ee236&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Session id: cron:clickhouse-worker-slot-0:20260706-141900

@Avogar Avogar left a comment •

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.

But comment in IColumn::computeHashInto/updateHashFast says that these methods provide weak hash and they are mainly needed to scatter data between threads. It was intended to make them very fast but not consistent with the same value in different in-memory represenations. Why do we use them in such scenario when this is important? Maybe we need to use another hash functions in the JOIN?

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

@Avogar good question, let me lay out why the join relies on these and why aligning them (rather than swapping in a different hash) is the fix.

Where the join uses computeHashInto. It is the scatter hook. grace_hash routes both sides through JoinCommon::scatterBlockByHash (src/Interpreters/JoinUtils.cpp:584, key_col->computeHashInto(...)), and parallel_hash routes through ConcurrentHashJoin::selectDispatchBlock. Scatter partitions keys into buckets/shards that are then joined independently, so correctness requires two logically-equal keys to land in the same bucket. If they scatter apart, the match is never attempted (dropped rows); and on a grace_hash spill the re-scatter across the temp-file round-trip must be stable, or a row re-hashing to an earlier bucket trips the FileBucket "Invalid state transition" LOGICAL_ERROR. That is exactly the 04505 failure.

These methods are already required to be representation-independent. The current computeHashInto contract (IColumn.h, "REPRESENTATION-INDEPENDENCE CONTRACT") states the non-initial combine path must produce identical hashes for physically-different-but-logically-equal columns, and ColumnConst, ColumnLowCardinality, ColumnSparse, ColumnReplicated all implement it. ColumnObject/ColumnDynamic were the only key-eligible types not holding up their end for the dynamic/shared split. The weak "not consistent across representations" disclaimer you are recalling lives on updateHashWithValueRange (the INSERT-dedup path) which we did not touch. So this is not strengthening the contract beyond its intent, it is making two types satisfy the same contract everything else already does.

Why not a different hash in the join. The in-bucket key for these types is already Type::hashed ("cryptographic hashes of unambiguously serialized values", HashJoin.cpp:432), i.e. it matches on the canonical serializeValueIntoArena bytes, which are representation-independent. The mismatch was that bucket routing used the raw ColumnVariant layout while in-bucket equality used the serialized value. Our change hashes the same canonical serialized bytes in computeHashInto, so scatter now agrees with the key basis. "Use a different hash in the join" would come down to hashing that same canonical serialization at the scatter step, which is what we do, and scatterBlockByHash has no per-type hook other than computeHashInto.

It stays weak/fast. We hash with updateWeakHash32 (CRC32C) over the serialized bytes, not a crypto hash. The only added cost is the per-row canonical serialization, which is unavoidable for any representation-independent hash of these types and is already paid by the in-bucket crypto key.

If you would still prefer to scope this differently (e.g. gate the canonical scatter behind allow_dynamic_type_in_join_keys / object-as-join-key, or restrict it to the join path), happy to adjust.

@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

@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Why are check not successful?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Short answer: there is one real red, it is not from this PR, and the run predates its fix by 11 days.

State of head cde81de9716585c7096098591ce768b44f9ee236 (170 check runs, all completed: 151 success, 18 skipped, 1 failure):

  • Stress test (amd_debug): Logical error: 'Block structure mismatch in JoinStep: [__table3.number, __table3.number] and [__table3.number]' (STID 0993-386d), thrown at src/Processors/QueryPlan/JoinStep.cpp:212 from JoinStep::updatePipeline. The captured context has zero JSON, Object, Dynamic, ColumnObject, ColumnDynamic or computeHashInto frames, so it is not reachable from anything this PR touches.
  • Mergeable Check and PR are aggregators of that same job (Failed: Stress test (amd_debug)), not independent failures.
  • All four flaky check variants (amd_debug, amd_asan_ubsan, amd_msan, amd_tsan) are green on this head, so the earlier 04505 timeouts are resolved.

That is a trunk-wide fuzzer bug rather than something specific to this branch: 435 occurrences over 277 distinct pull requests plus 19 master runs in the 40 days before it was fixed. It is fixed by #109114, merged 2026-07-17T02:21:49Z. This PR's CI ran at 2026-07-06 05:35Z, so its build cannot contain the fix (git merge-base --is-ancestor <fix merge> cde81de is false). Since that merge there are only 3 occurrences left, every one of them on a build that also lacks the fix, and 0 on master.

So the red is stale, not real. The branch is 8686 commits behind master; I will merge master and re-run so the checks refresh. git merge-tree against current master reports 0 conflicts, but ColumnObject::computeHashInto has been rewritten upstream since I branched, so I will re-verify the fix and the regression test in both directions on the merged tree rather than assume the clean merge is enough.

One thing I did not want to slip past silently before this merges: the design question Avogar raised on 2026-07-07 (whether the JOIN should rely on computeHashInto/updateHashFast at all, or use a separate consistent hash for Dynamic/Object keys) is still formally open. My answer is at #109450 (comment) and there has been no reply since. It argues that this PR makes these two types satisfy the representation-independence contract at IColumn.h:405 that everything else already satisfies, rather than extending the weak-hash guarantee. You added that contract in #106538, so if you are satisfied that aligning these two column types with it is the right layer, that resolves the question from my side and this is ready once the checks are refreshed.

groeneai added 2 commits July 27, 2026 14:26
The previous implementation of this fix hashed the canonical per-row
serialization that serializeValueIntoArena produces. It was correct, but it
built a byte string per row: for ColumnDynamic one WriteBufferFromVector plus
one encodeDataType and one serialization-cache lookup per value, and for
ColumnObject the same per path. Measured on a release-shaped build that cost up
to +568% UserTimeMicroseconds on a window PARTITION BY over a JSON key at
default settings, against master.

Three attempts to make a byte-producing basis cheap all failed: hoisting the
Arena out of the loop, switching to updateHashWithValue bytes, and hoisting the
serialization buffer so the block allocates nothing at all. The last one reduced
ArenaAllocChunks from 1000018 to 18 and was still +1253%, which proves the cost
is producing a byte string per row at all, not where the bytes are put.

So do not produce bytes. The hash contract is one-directional (equal values must
hash equal; unequal values need not differ), and master's hashing of typed rows
is already correct, because compareAt decides Dynamic equality on (type name,
logical value) and two differently-typed Dynamic values never compare equal.
Only two things are actually wrong:

- ColumnDynamic: a value in the shared variant hashes its serialized blob while
  the same value in a typed variant hashes the column's representation. Forward
  to ColumnVariant as master does, then overwrite only the shared-discriminator
  rows with the leaf hash the value would have in a typed variant. When the
  shared variant is empty, forward exactly, so such a column keeps master's hash
  and master's cost byte for byte.

- ColumnObject: a path's contribution lands at a different position depending on
  whether it lives in a dynamic column or in shared_data, and that split varies
  per block. Fold (path name, value) per path over the sorted union of both
  sections, with one forward cursor per row into the row's shared entries. Typed
  paths are a fixed sorted set that cannot move between sections, so their bulk
  sub-column hashes chain first. Scratch stays O(rows); peak query memory on a
  JSON(max_dynamic_paths = 1024) column is identical to master's and independent
  of the row count.

Hashing the shared blob's bytes directly would be cheaper but is wrong for more
types than it appears: the typed hash zero-extends a value into a 64-bit word,
while a raw-bytes hash of a shorter value mixes the byte count into that word,
so it diverges for String (varint length prefix) and for every numeric narrower
than 8 bytes. The test now covers a String and a UInt8 shared value; the
previous fixtures were all Int64, the one width where the two agree.

updateHashFast is left exactly as master has it in both columns. It has a
separate pre-existing defect (it iterates unordered maps) which is out of scope
here.

Arena allocation counters are now identical to master's, and the change is
faster than master on both default-settings window arms measured (-3.4% and
-15.1%). The residual cost is proportional to the shared representation only:
+29.1% on a Dynamic column that is 100% shared-variant, +12.6% on a window
partition over 4 shared paths per row, +5.6% on a JSON grace_hash join.
@Avogar

Avogar commented Jul 29, 2026

Copy link
Copy Markdown
Member

@groeneai I made a commit with a simpler more readable implementation. Please check it, verify it's correctness and performance.

Comment thread src/Columns/ColumnDynamic.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified. Correctness is clean; one workload has a real multi-threaded regression I could not fully localise, so I am reporting it rather than changing your commit.

Measured at d9cb4aa6 against master with the same harness as before (release-shaped build-rel, one server per arm, each server's buildId() asserted equal to its binary's ELF Build ID, min(UserTimeMicroseconds) over 11 alternating reps, 1M-row fixtures, window arms at default settings with ScatterByPartitionTransform asserted present). All three arms returned byte-identical output for all 12 workloads before any timing was compared (md5 8db937cc60dc, same value the earlier round recorded).

Correctness: pass

  • gtest_compute_hash_into 38/38 pass.
  • 04505_json_object_hash_split_invariance reproduces the reference byte-for-byte, all 32 rows, both spill oracles included.
  • The spill oracle is still live under your fold: forcing grace_hash_join_initial_buckets = 1 turns both spill rows into fail: write_part=2 uncompressed=0.
  • Arena counters equal master exactly on all four probed workloads (WINJ_NOSHARED 18 chunks / 73728 B, the others 1 / 4096), so no per-row byte production came back.
  • {"a":1} and {"a":1,"b":null} still hash together in both branches of your split, including the max_dynamic_paths = 0 bulk path.

Performance: one regression

workload master your commit vs master
JSON grace_hash join, no shared data 1.37s 1.34s -2.1%
JSON grace_hash join, mixed 2.69s 2.74s +1.7%
JSON grace_hash join, 4 shared/row 13.36s 14.80s +10.8%
window PARTITION BY JSON, no shared 0.64s 0.58s -9.4%
window PARTITION BY JSON, mixed 29.81s 14.30s -52.0%
window PARTITION BY JSON, 4 shared/row 1.14s 4.56s +299.5%
Dynamic grace_hash join 0.47s 0.66s +39.5%
Dynamic join, 100% shared variant 0.60s 0.99s +65.1%

Controls flat (+0.9%, -1.4%, -1.0%, -2.5%), so the harness is sound. Six of the eight arms are within a few percent of my version or better, and the mixed window arm is materially faster (-52.0% vs master, where mine was -16.1%).

The +299.5% is real, not host noise: an independent 8-rep run of the shared arms alone gives +302.3%, and q25 agrees (+310.5%). My version is +43.0% on the same arm.

What I established about it

It is purely a thread-scaling effect. On a 4-shared-path all-Int64 JSON fixture, same query shape:

max_threads master your commit mine
1 0.56s 0.56s 0.57s
2 0.66s 1.21s 1.15s
4 0.70s 3.04s 1.21s
8 0.84s 3.54s 1.28s
16 0.93s 8.05s 1.59s

At one thread the two implementations are indistinguishable (+0.6%), so the per-row work itself is not more expensive; the cost appears only as threads are added, and it grows superlinearly. At 16 threads your arm spends 7.25s user against master's 0.96s with no page-fault, allocator-purge or ContextLock difference to explain it.

I tried two fixes and both failed, so I do not want to guess at the mechanism:

  • reusing one scratch column per type instead of type->createColumn() per shared row: +748.7% at 16 threads, i.e. unchanged, so the per-row column allocation is not the cause;
  • replacing getDataTypesCache().getSerialization(...) with type->getDefaultSerialization(): +1657.6%, i.e. materially worse, so the thread-local cache is helping rather than hurting.

That leaves the ColumnObject::computeHashInto side rather than hashSharedValue as the remaining candidate, which is where the two implementations still differ structurally. Happy to keep digging, or to leave it to you if the mechanism is obvious from your side.

The only other note is that sorted_dynamic_paths is no longer read by computeHashInto (the dynamic-path loop now iterates dynamic_paths_ptrs directly). It is still used elsewhere in the file, so nothing is dead, but the fold order over dynamic paths is now hash-map order rather than sorted order. That is fine for correctness because the fold is commutative, which I confirmed by the byte-identical results above.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d9cb4aa

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit Code: 202 TOO_MANY_SIMULTANEOUS_QUERIES; under parallel replicas one statement becomes several same-table reads with different query ids, so the long-running query competes against itself for the single max_concurrent_queries slot #112385 (ours, merged 2026-07-29 15:37Z)
Bugfix validation (unit tests) harness abort, not a test failure: Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout (contrib/orc); the before-worktree cannot be populated at the merge-base submodule revisions a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)

All 174 check-runs on this commit are completed; those are the only two failing checks.

Neither is caused by this PR. The diff is src/Columns/ColumnDynamic.{cpp,h}, src/Columns/ColumnObject.cpp,
src/Columns/tests/gtest_compute_hash_into.cpp and its own 04505_json_object_hash_split_invariance
test pair, with zero contrib/ paths.

On row 1: the failure is specific to the ParallelReplicas flavour, and #112385 disables parallel
replicas for exactly that test for exactly this reason. This branch is 1170 commits behind that merge
commit, so the run predates the fix rather than failing with it present. Since the current head is your
own commit I am not merging master on top of it; the next run from any base that includes #112385 will
clear this row.

On row 2: contrib/orc is byte-identical at the merge-base and at this head while master has moved it
since the branch split, so the guard is firing purely on base-branch motion. The real unit-test jobs
are green on this head, and both functional Bugfix validators reported Failed: 1, Passed: 0, i.e. the
regression test does fail on the before-binary as intended. This is the eighth PR of ours hit by the
same harness condition.

Session id: cron:our-pr-ci-monitor:20260729-223000

Comment thread src/Columns/ColumnObject.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 137/139 (98.56%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c1a1188

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 175/175 check-runs completed, 0 incomplete, Config Workflow
and Finish Workflow both success, two failing jobs which are one defect.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Logical error: 'Query context must be created after authentication' (STID 3197-391f) the PostgreSQL wire handler builds a query context in the cancel-request path, before authentication #112940 (external, open)
Stress test (amd_asan_ubsan) / same signature (STID 3197-391f) same defect, second sanitizer flavour #112940 (external, open)

Not caused by this PR. The diff is confined to ColumnDynamic/ColumnObject hashing plus its own
gtest and one stateless test; it touches no server handler and no session code.

The owner was resolved from the stack, not the STID: the abort is
Session::makeQueryContextImpl (Session.cpp:690) <- Session::makeQueryContext <-
PostgreSQLHandler::cancelRequest (PostgreSQLHandler.cpp:867) <- startup <- run. #112940
reapplies the postgresql engine change with exactly that fix: it removes the only pre-auth
makeQueryContext in cancelRequest and replaces it with the session-free
ProcessList::sendCancelToQueryOfAnyUser. Tracking issue #84085.

Session id: cron:our-pr-ci-monitor:20260809-040000

…:ClickHouse/ClickHouse into fix-json-object-hash-split-invariance
`ColumnDynamic::hashSharedValue` resolved the serialization by type name for
every shared value: `decodeDataType` already returns the `DataTypePtr`, but the
name was then rebuilt with `getName` and looked up in `getDataTypesCache`. A
`perf` profile of a window `PARTITION BY` over a `JSON` column attributed 33% of
all CPU to `DataTypesCache::getSerialization`, on top of 36% in `hashSharedValue`
itself.

Add a per-call `SharedValueTypeCache` keyed by the value's encoded type prefix
bytes. Decoding is deterministic in those bytes, so an equal prefix means the
same type and the same prefix length; a hit therefore skips both the decode and
the serialization lookup. Entries live in a small bounded vector because types
repeat across the rows of one call, so a linear scan beats hashing.

Measured on a 16-core box over `JSON(max_dynamic_paths = 1)`, window
`PARTITION BY`, min of 2 runs at `max_threads = 16`:

  workload                before   after
  4 shared paths, 3M rows  0.79s   0.32s
  19 shared paths, 1M rows 1.17s   0.35s

CPU time for the 19-path case drops from 11.27s to 2.96s, and the previous
anti-scaling at 8 threads (1.21s at 1 thread vs 1.77s at 8) is gone. The
`parallel_hash` probe workload is unchanged. Hashes are bit-identical, including
for `LowCardinality`, `Array`, `Tuple` and `Map` values in the shared variant.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 22, 2026
…h-split-invariance

# Conflicts:
#	src/Columns/ColumnDynamic.cpp
… type

`ColumnObject::computeHashInto` and `ColumnDynamic::computeHashInto` decoded every
`shared_data` / shared-variant value on its own: one `IDataType::createColumn` plus a
one-row `IColumn::computeHashInto` per value. On the scatter path that is one allocation
per row per shared path, which is the hot-path regression reported in review
(ClickHouse#109450 (comment)).

`ColumnDynamic::hashSharedValue` is replaced by a batched `ColumnDynamic::hashSharedValues`
that takes the whole range at once, groups it by the value's binary encoded type prefix, and
deserializes one temporary column per distinct type, hashed in a single vectorised pass. When
the batch is single-typed - the common case - the values deserialize in place and hash straight
into the output, with no grouping arrays at all. The read buffer is hoisted out of the loop and
re-pointed at each value, which is measurable once the temporary column is gone.

The hashes are unchanged: `IColumn::computeHashInto` is per-row independent, so hashing k values
in one column gives each value exactly the hash it had from its own one-row column.

Measured on `aarch64` `RelWithDebInfo`, `min(user CPU)` over 5 reps, 1M rows of
`JSON(max_dynamic_paths=1)` with 19 `shared_data` values per row, driven through
`ScatterByPartitionTransform` by a window `PARTITION BY` on the `JSON` key:

| `max_threads` | `master` | before | after |
|---|---|---|---|
| 2  | 0.99s | 2.39s (+141%) | 1.08s (+9%) |
| 8  | 1.03s | 2.42s (+135%) | 1.12s (+9%) |
| 16 | 1.08s | 2.49s (+131%) | 1.17s (+8%) |

The superlinear term the review saw at higher parallelism is gone: the arm now tracks `master`'s
scaling across thread counts. On a 4-shared-path key the whole query is within noise of `master`
(8.74s / 8.73s / 8.29s for `master` / before / after at `max_threads = 8`).

`gtest_compute_hash_into` (38 tests) and the split-invariance assertions of
`04505_json_object_hash_split_invariance` reproduce their references unchanged.
`check_cpp.sh` rejects a bare `std::vector` in server code; the rest of this file already uses
`VectorWithMemoryTracking`, so the batch's type-group vector uses it too.
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b18a0d605 with master 26bd12dc6 (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
Binary Master PR Δ
programs/clickhouse-stripped 709.89 MiB 706.86 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

11 object files changed (+20.10 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Columns/ColumnDynamic.cpp.o 809.29 KiB 831.60 KiB +22.31 KiB (+2.76%)

737 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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status of head 9b0a574a: the only public CI red was Stress test (amd_asan_ubsan) failing with Logical error: 'Files metadata is empty' in StorageObjectStorageQueue::getTableMetadata — unrelated to this PR (it touches only JSON/Object/Dynamic hashing). It is the known issue #93009, with the fix already in progress in #113695. CH Inc sync is failing fleet-wide on 2026-08-24 for private-side reasons unrelated to this PR.

Merged master (b18a0d60) to re-arm a fresh CI run; the affected translation units (ColumnObject.cpp, ColumnDynamic.cpp, gtest_compute_hash_into.cpp) compile cleanly after the merge. The concurrent master change 9b38bbdf37ae (paths added to updateHashWithValueRange deduplication hashing) does not overlap with computeHashInto.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 26, 2026
Merged via the queue into ClickHouse:master with commit ab914fa Aug 26, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SET allow_experimental_json_type = 1;

CREATE TABLE t_dyn (k JSON(max_dynamic_paths = 1)) ENGINE = Memory;
INSERT INTO t_dyn VALUES ('{"x":1}');

-- same value, but `y` takes the single dynamic slot so `x` lands in shared_data
CREATE TABLE t_shared (k JSON(max_dynamic_paths = 1)) ENGINE = Memory;
INSERT INTO t_shared VALUES ('{"y":9}'), ('{"x":1}');

CREATE TABLE t_both (k JSON(max_dynamic_paths = 1)) ENGINE = Memory;
INSERT INTO t_both SELECT k FROM t_dyn;
INSERT INTO t_both SELECT k FROM t_shared WHERE k = '{"x":1}'::JSON(max_dynamic_paths = 1);

SELECT count() FROM t_both AS a INNER JOIN t_both AS b ON a.k = b.k
SETTINGS join_algorithm = 'hash';                       -- 4

SELECT count() FROM t_both AS a INNER JOIN t_both AS b ON a.k = b.k
SETTINGS join_algorithm = 'grace_hash', grace_hash_join_initial_buckets = 4, max_block_size = 1;
-- expected 4, observed 2 on 26.6/26.7

-- Dynamic key, same shape (also needs allow_dynamic_type_in_join_keys = 1):
-- Dynamic(max_types = 1) holding 1::Int64 typed in one row and in the shared
-- variant in another gives 2 instead of 4 under grace_hash on 25.12..26.7.

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3
  • Does not reproduce on: master, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3.

CC component owner: @Avogar @alexey-milovidov

Analysis metadata

comp-json-datatype · Severity P2 · Finding phase_d_pr109450

  • Verified against master build 573230bfe668 (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked the branch set before asking for a label, and the requested one needs two corrections.

Ran the reproducer above against builds.clickhouse.com/<branch>/amd64/clickhouse:

branch hash grace_hash cherry-pick of ab914fa
master 26.9.1.232 4 4 fix is here
26.8 26.8.1.2021 4 2 clean, all 6 files identical
26.7 26.7.6.19 4 2 1 conflict in ColumnDynamic.cpp
26.6 26.6.4.30 4 2 1 conflict in ColumnDynamic.cpp
26.3 26.3.25.2 0 0 does not apply

26.8 is affected and is not in the list above. 26.5 and 25.8 have had no open PRs since 2026-08-27, so a label cannot reach them.

26.3 is a different defect: plain hash returns 0 there, where every other branch returns 4. It also cannot take this patch, because IColumn::computeHashInto, the method this fix overrides, arrived in #106538 and is absent from 26.3 and 26.5 (both still declare the older WeakHash32 path in ColumnDynamic.h).

That leaves 26.6, 26.7 and 26.8 as the portable set, which is exactly what v26.6-must-backport expands to. v26.3-must-backport and pr-must-backport would also target 26.3.

@alexey-milovidov could you apply v26.6-must-backport? 26.6 and 26.7 will need the manual cherry-pick PR.

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-ci-master PR origin: master/nightly CI monitoring finding 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.

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

6 participants