Repository navigation
Fix split-dependent hash of JSON/Object columns - #109450
alexey-milovidov merged 21 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260705-174300 |
|
cc @Avogar @harikrishnan94 — could you review this? It makes |
|
Workflow [PR], commit [b18a0d6] Summary: ✅
AI ReviewSummaryThis PR fixes Findings
Final VerdictNot ready to merge without a decision on the mixed-version LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 172/206 (83.50%) · Uncovered code |
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]>
|
Done in 560ff9e. The spill sub-case now asserts the exact self-join cardinality instead of 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):
|
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]>
|
The exact-cardinality strengthening pushed the spill fixture to Spilling is forced by |
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]>
|
Pre-PR validation gate for the ColumnDynamic split-invariant hashing follow-up (commit dda4d1f). Pre-PR validation gate (click to expand)
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]>
|
Pushed 6337b75 to fix the recurring flaky-check timeout on The Dynamic hashing extension added a second 20000-matched-pair grace-hash spill next to the JSON one, and both self-joins pinned Fix (test-only): drop Session id: cron:clickhouse-worker-slot-2:20260706-014000 |
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]>
|
Pre-PR validation gate for the per-row Arena follow-up (commit cde81de): Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260706-033900 |
CI finish ledger — cde81deCI is fully finished (Finish Workflow pass, no pending checks). Every failure below has an owner.
All other 151 checks green. The recurring flaky-check timeout on 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 |
There was a problem hiding this comment.
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?
|
@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 These methods are already required to be representation-independent. The current Why not a different hash in the join. The in-bucket key for these types is already It stays weak/fast. We hash with If you would still prefer to scope this differently (e.g. gate the canonical scatter behind |
|
@groeneai Why are check not successful? |
|
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
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 ( 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. 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 |
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.
|
@groeneai I made a commit with a simpler more readable implementation. Please check it, verify it's correctness and performance. |
|
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 Correctness: pass
Performance: one regression
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 What I established about itIt is purely a thread-scaling effect. On a 4-shared-path all-
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 I tried two fixes and both failed, so I do not want to guess at the mechanism:
That leaves the The only other note is that |
CI finish ledger - d9cb4aaEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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 On row 1: the failure is specific to the ParallelReplicas flavour, and #112385 disables parallel On row 2: Session id: cron:our-pr-ci-monitor:20260729-223000 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 137/139 (98.56%) · Uncovered code |
CI finish ledger - c1a1188Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: 175/175 check-runs completed, 0 incomplete,
Not caused by this PR. The diff is confined to The owner was resolved from the stack, not the STID: the abort is 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]>
…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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes11 object files changed (+20.10 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units133 translation units recompiled, 1089 s compile time in total, 133 of them have a recent master baseline. |
…h-split-invariance
|
🕵 Status of head Merged |
ReproducerSET 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:
Backport the fix to CC component owner: @Avogar @alexey-milovidov Analysis metadata
Introducing change: not identified
|
|
I checked the branch set before asking for a label, and the requested one needs two corrections. Ran the reproducer above against
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 That leaves 26.6, 26.7 and 26.8 as the portable set, which is exactly what @alexey-milovidov could you apply |
Closes: #112867
Related: #109428
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
JSON/Object/Dynamiccolumns hashing logically equal values differently depending on their physical layout: howJSON/Objectpaths were split between dynamic subcolumns and shared data, or whether aDynamicvalue sat in a typed or the shared variant. Hash-based joins on such a key silently missed matches, and agrace_hashspill could raise aLOGICAL_ERROR("Invalid state transition"). AJSONkey needed no non-default setting;Dynamicalso requiredallow_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
serializeValueIntoArenabytes and cost up to +568% CPU; this one produces none. Both measured below.computeHashIntois the per-row weak hash behind the in-memory scatter paths (sharded aggregation,grace_hashbucketing, windowPARTITION BY, join scatter). ForJSON/ObjectandDynamicit hashed the physical layout:ColumnDynamicforwarded toColumnVariant, which hashes a shared-variant value by its serialized blob but a typed one by the column's representation;ColumnObjectchained 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, whilecompareAtalready treats the representations as equal.JSONhits this at default settings, sincehasDynamicTypemisses its innerDynamic.ColumnDynamic::computeHashIntoforwards toColumnVariantas master does, then overwrites only shared-discriminator rows with the leaf hash the value would have when typed.ColumnObject::computeHashIntofolds(path, value)over the sorted union of the dynamic paths andshared_data, one cursor per row.updateHashFastandupdateHashWithValueRangestay 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::createColumnon every row of every shared path.IColumn::computeHashIntois per-row independent, so batching does not change any hash.04505_json_object_hash_split_invariancechecks that equal values with different layouts match under the three hash joins, collapse underGROUP BY/DISTINCT/uniqExact, and that a spill flushes real payload rather than only constructing buckets: six assertions fail on master, all pass here. ThreeComputeHashIntogtests cover the per-row hash and scratch state SQL cannot see.ShuffleSendStepshuffles 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_BLOCKSinGraceHashJoin::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
aarch64RelWithDebInfo,min(user CPU)over 5 reps, 1M rows ofJSON(max_dynamic_paths=1)carrying 19shared_datavalues per row throughScatterByPartitionTransform(a windowPARTITION BYon theJSONkey):max_threadsmasterThe 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 ofmaster(8.74s / 8.73s / 8.29s formaster/ one-at-a-time / batched atmax_threads = 8).Release-shaped build, three arms from one revision (master with these files reverted; the approved implementation; this one),
UserTimeMicrosecondsmin over 11 alternating reps; all arms agreed on all 12 workloads first.grace_hash, no sharedgrace_hash, mixedgrace_hash, all sharedDynamicgrace_hashDynamic, 100% sharedNon-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 thanpopBackbecausepopBackis a row operation:ColumnLowCardinality::popBackdrops indexes but not the dictionary, whichcomputeHashIntore-hashes in full per row, andColumnVariantnests the shape. Conditioning it on a measured property of the scratch column did not survive review, so it stays unconditional. The cliff is bounded percomputeHashIntocall, not by the table; a 5k-40k ladder is linear.Workflow [PR]
Sync PR [sync-upstream/pr/109450]