Repository navigation
Add non-allocating IColumn::computeHashInto column hash kernel - #106538
Conversation
Split out the hash-production half of ClickHouse#106120 into its own change, as requested in review: keep the per-column hash calculation separate from the batched scatter interface so each can be reviewed and benchmarked in isolation. `IColumn::computeHashInto(row_begin, row_end, hash_out, initial)` is a non-allocating per-row hash kernel that writes 32-bit `fmix32`-based hashes into a caller-provided buffer, with SIMD overrides (`MULTITARGET_FUNCTION_X86_V4_V3`) for the common column types. Multi-column keys compose in place via `fmix32Combined` with no intermediate arrays, and the contract is representation-independent: a materialized column and a transparent wrapper (`ColumnConst`, `ColumnLowCardinality`, `ColumnSparse`, `ColumnReplicated`) of the same values hash identically. `IColumn::getWeakHash32`, `WeakHash32` and `WeakHash.h`/`WeakHash.cpp` are removed; the remaining consumers (`JoinUtils::scatterBlockByHash`, `ScatterByPartitionTransform`, `BufferedShardByHashTransform`) fill a `PaddedPODArray<UInt32>` via chained `computeHashInto`. The CRC32C `updateWeakHash32` primitive stays, with its default initial value relocated to `WEAK_HASH32_INITIAL_VALUE` in `Hash.h`. `mapToRange` maps a 32-bit hash uniformly to a shard index via Lemire fastrange. Routing hash values change from CRC32C to the `fmix32` finalizer, which is safe because both consumers route in-memory per query; per-key stable shard identity was never guaranteed. Verified that `grace_hash` joins match the default `hash` join across the changed key families (`04312_grace_hash_vs_hash_join_key_types`). This intentionally excludes the `DB::ColumnsScatter::scatter` primitive, the `shard_by_hash_input_batch_bytes` input-batching mode, and their tests from ClickHouse#106120; the consumers retain the legacy per-chunk `IColumn::scatter`. Related: ClickHouse#105936 Related: ClickHouse#106120 Related: ClickHouse#106120 (review) Co-authored-by: Cursor <[email protected]>
|
Workflow [PR], commit [f22f3f8] Summary: ✅
AI ReviewSummaryThis PR replaces the allocating Missing context / blind spots
Findings
|
Fix two test issues flagged in review of the `computeHashInto` kernel: - `InitialFlagSemantics` computed `combined_manual` but never asserted it, so the test passed for any `initial=false` implementation that merely mutated the buffer. Assert the documented contract `EXPECT_EQ(combined_api, combined_manual)`. - The distributional chi-square tests seeded `rng` from `randomSeed`, so a correct hash could exceed the `p=0.001` cutoff and flake in CI. Use a fixed seed for reproducibility. Document the intentional layout-dependence of `ColumnDynamic::computeHashInto` and `ColumnObject::computeHashInto`: like the former `getWeakHash32` and `updateHashWithValueRange`, the weak routing hash is not guaranteed to be equal for logically equal values stored with different variant/path layouts. This matches prior behavior; the in-memory scatter consumers only need a fast per-query partitioning, not a layout-stable hash. Co-authored-by: Cursor <[email protected]>
`ColumnFunction::computeHashInto` streamed each captured column directly into the caller's buffer on the `initial == false` path, producing `combine(h_b, combine(h_a, prior))` instead of the contract's `combine(combine(h_b, h_a), prior)`. Since `ColumnConst` feeds back the finalized per-row value, a materialized `ColumnFunction` and a `ColumnConst(ColumnFunction)` of the same value composed differently when the function was not the first key, which could route equal keys to different shards or `grace_hash` partitions. Mirror `ColumnTuple`: build the finalized function hash in a scratch buffer, then combine it once via `fmix32Combined`. The empty-capture non-initial case now combines `0` instead of leaving the prior hash unchanged. Add deterministic `gtest_compute_hash_into` coverage for the >8-byte folding path in `hashValueRaw32`/`hashDecimalRaw32`, which the existing cases never reached: `UInt128`, `UInt256`, `Decimal128`, and `Decimal256`, each checked for distinct hashes, row-range split independence, and `initial == false` (`ColumnConst`) composition. Co-authored-by: Cursor <[email protected]>
…nd Replicated The representation-independence block (test 16) advertised `ColumnLowCardinality` and `ColumnReplicated` in its comment, but only built `ColumnConst` and `ColumnSparse`. The stateless `04312_grace_hash` test does not cover `ColumnLowCardinality::computeHashInto` either, because `JoinUtils::materializeColumn` strips LowCardinality keys before hashing. Add direct gtests for both wrappers: build a materialized column and a logically equal `ColumnLowCardinality` / `ColumnReplicated` with per-row varying values (a small pool with repeats so the dictionary/index mapping is non-trivial), then assert `composeKey(prefix, materialized) == composeKey(prefix, wrapper)` (the `initial == false` composition path) plus row-range split consistency via `expectRangeSplitConsistent`. Co-authored-by: Cursor <[email protected]>
|
📊 Cloud Performance Report 🔴 AI verdict: This PR rewrites per-column weak-hash computation from getWeakHash32 (allocating a full hash vector per column) to a range-based computeHashInto that writes directly into a caller-provided buffer. That code is on the hot path for both aggregation key hashing and hash-join row partitioning, which explains the flagged deltas: ClickBench Q22/Q23 (string GROUP BY) and TPC-H Q7/Q20 (joins) improve as intermediate allocations are eliminated, while TPC-H Q8 regresses ~15% — consistent with composite/Nullable keys now routing through an extra scratch buffer and combine step, on a query that was already trending slower. All flagged queries exercise the changed path, so none were downgraded; treat the very large Q20 number loosely since that query is intrinsically noisy. clickbench🟢 2 improved Flagged queries (2 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🔴 1 regressed · 🟢 2 improved Flagged queries (3 of 22)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
The non-allocating `IColumn::computeHashInto` kernel (PR ClickHouse#106538) bundled a CRC32C -> `fmix32` routing-hash switch that regressed join-heavy workloads: the Cloud Performance Report on the PR flagged TPC-H Q4 +33% slower because `fmix32` is far costlier than hardware CRC32C on the in-memory, per-query scatter paths (sharded aggregation, `grace_hash` bucketing, parallel-window partitioning, hash-join scatter) -- paths that never need a stable shard identity. Keep the non-allocating per-row buffer and the representation-independence contract, but restore CRC32C as both the per-row hash and the cross-column combiner: - Per-row `h(row)` is a finalized 32-bit CRC32C hash seeded with `WEAK_HASH32_INITIAL_VALUE`: `hashCRC32(value, ...)` for `ColumnVector` (one `_mm_crc32_u64` / `__crc32cd`, no hi/lo split), `intHashCRC32(v.value, ...)` for `ColumnDecimal`, and `updateWeakHash32` for the string/fixed-string/ aggregate families. Float `-0.0` -> `+0.0` normalization is preserved. - Composite keys combine each column's FINALIZED per-row hash via one shared, order-sensitive `combineWeakHash32` that packs `prior` and `value` into the two halves of a single 64-bit CRC input (a plain `intHashCRC32(value, prior)` is order-insensitive for 32-bit operands and would collide `(a, b)` with `(b, a)`). Wrappers (`Const` / `LowCardinality` / `Sparse` / `Replicated` / `Tuple` / `Array` / `Nullable` / `Object` / `Function` / `Variant`) combine the finalized nested hash, so SQL-equal keys hash identically across representations. - Remove `Common/HashCombine32.h` (`fmix32` / `fmix32Combined`) and every reference, comment, and doc. Validated by `gtest_compute_hash_into` (32/32) and `04312_grace_hash_vs_hash_join_key_types`. On the per-row hash benchmark the UInt64 (bigint) join-key path drops from ~1.36 to ~0.27 ns/row (~5.1x faster), restoring the fast scalar CRC32C path TPC-H Q4 joins use. Co-authored-by: Cursor <[email protected]>
`IColumnDummy::computeHashInto` only wrote `hash_out` on the `initial == true` path and left it unchanged when `initial == false`. A dummy column's finalized per-row hash is `0`, so a key `(prefix, materialized ColumnNothing)` hashed as just `prefix`, while `(prefix, ColumnConst(ColumnNothing))` combined `0` into `prefix` through `ColumnConst`. That breaks the representation-independence contract and can split equal multi-column keys if `Nothing`/dummy columns reach the scatter paths. Mirror the empty `ColumnTuple`/`ColumnFunction` handling: combine `0` via `combineWeakHash32` on the non-initial path. Add a `gtest_compute_hash_into` case asserting a materialized `ColumnNothing` and `ColumnConst(ColumnNothing)` compose identically. Addresses review comment: ClickHouse#106538 (comment) Co-authored-by: Cursor <[email protected]>
Stacked on top of ClickHouse#106538 (`IColumn::computeHashInto` hash kernel PR). This commit adds the scatter half and the `shard_by_hash_input_batch_bytes` input-batching mode. `DB::ColumnsScatter::scatter(source_columns, pids_per_source, num_shards, rows_per_shard)` is a batched, O(1)-dispatch physical split. The caller supplies one `IColumn` from each of B pending chunks at the same column-position, along with per-source `UInt32` partition-ids and precomputed per-shard row counts. A static function-pointer table keyed on `IColumn::getDataType()` selects the typed kernel with no virtual call on the hot path. Fast-path typed kernels for `ColumnVector`, `ColumnDecimal`, `ColumnFixedString`, `ColumnString`, `ColumnNullable`, and `ColumnTuple`; all other types delegate to the legacy `IColumn::scatter` fallback. Mixed-representation batches (`ColumnConst`/`ColumnSparse`/`ColumnReplicated` mixed with materialized columns) are normalized via `materializeTransparentWrappers` before dispatch, preserving `LowCardinality`; homogeneous `LowCardinality` batches use the fallback. `BufferedShardByHashTransform` input batching — new setting `shard_by_hash_input_batch_bytes` (default 2 MiB; 0 = legacy per-chunk path). The transform accumulates input chunks until the byte budget is reached, then flushes via `ColumnsScatter::scatter` once per column-position. Hash production uses `IColumn::computeHashInto` (CRC32C, from ClickHouse#106538) + `mapToRange`. `ScatterByPartitionTransform` is wired to `ColumnsScatter::scatter` for the same O(1)-dispatch benefit on the parallel-window partitioning path. Also adds: - `benchmark_columns_scatter.cpp` — RFC sweep over K and P - `gtest_columns_scatter.cpp` — equivalence vs legacy for all fast-path types, mixed-representation regressions, `LowCardinality` type preservation, and per-key count assertions - `04278_04101_sharded_aggregation_batched_input.sql` — batched vs legacy per-key-identical `GROUP BY` results across key types with small block size to exercise the threshold path, multi-chunk batches, and EOF flush Related: ClickHouse#105936 Related: ClickHouse#106120 Related: ClickHouse#106538 Co-authored-by: Cursor <[email protected]>
…pansion Two correctness/resource fixes in `ColumnsScatter::scatter`: 1. **`scatterFallback` nested-representation mismatch** — when `IColumn::scatter` is called across source chunks that share a logical type but differ in their nested concrete representation (e.g. `Array(UInt64)` with a full nested `ColumnUInt64` in one chunk vs `ColumnSparse(UInt64)` in another), the subsequent `insertRangeFrom` call on the destination's nested column would `assert_cast` on the wrong concrete type, causing undefined behaviour in release builds. Fix: add `deepNormalizeForFallback` which strips `ColumnConst`, `ColumnSparse`, and `ColumnReplicated` recursively at every nesting level (recursing into `ColumnArray` data and `ColumnTuple` elements) while preserving `ColumnLowCardinality`. `scatterFallback` normalizes all sources through this function before calling `IColumn::scatter`, and clones the destination from the normalized first source so all cross-chunk `insertRangeFrom` calls operate on matching concrete column types. 2. **Eager `ColumnConst` materialization before the UInt32 overflow guard** — the overflow guard previously ran after `materializeTransparentWrappers`, expanding O(1)-byte `ColumnConst` sources into full columns even when the only path taken was the size_t-safe `scatterFallback`. For const-heavy batches accumulated by `BufferedShardByHashTransform`, this could expand millions of logical rows into full allocations unnecessarily. Fix: move the UInt32 overflow guard before the wrapper materialization block. Additionally, add a fast compact path for a homogeneous batch of equal-valued `ColumnConst` sources: when all sources share the same constant value, produce `ColumnConst(value, rows_per_shard[s])` per shard via `cloneResized` — no materialization, O(1) memory, matching the behavior the legacy per-chunk `IColumn::scatter` had for constant-key workloads. Co-authored-by: Cursor <[email protected]>
…nConst` compaction Two new tests in `gtest_columns_scatter`: - `FallbackArrayMixedNestedRepresentation`: scatters two `Array(UInt64)` chunks where the first has a full nested `ColumnUInt64` and the second has a `ColumnSparse(UInt64)` nested column (identical logical values). Verifies that the scattered results match a reference built from two fully-materialized sources. Before the fix, the cross-chunk `insertRangeFrom` in `scatterFallback` would `assert_cast` a `ColumnSparse` as `ColumnVector` and produce wrong values or UB. - `ConstColumnStaysCompact`: scatters three `ColumnConst(UInt64=99)` sources through `ColumnsScatter::scatter` and asserts that every per-shard output column `isConst()`. Verifies that the new all-const compact path returns `ColumnConst(99, rows_per_shard[s])` without materializing the sources into full columns. Co-authored-by: Cursor <[email protected]>
…ce_hash buckets The power-of-two bucket selection in `scatterBlockByHashPow2` used `hash & mask`, which extracts only the low bits of the CRC32C hash. CRC32C has poor avalanche in the low bits for structured input (e.g. sequential integers), leaving the bucket distribution/performance contract unproven for the `grace_hash` path. Replace with Knuth's multiplicative (Fibonacci) hash: multiply by `floor(2^32/phi) = 0x9E3779B1` and take the top `log2(num_shards)` bits via `>> (32 - K)`. The high bits of the product depend on all 32 input bits, so even poor CRC32C low-bit distribution becomes uniform bucket assignment. This mirrors the approach already used by `scatterBlockByHashGeneric` and `mapToRange` (both use high-bit Lemire fastrange); the pow2 path now has consistent behaviour. Add two chi-squared distribution tests in `gtest_compute_hash_into` that exercise the Fibonacci sharder path directly: - `DistributionPow2FibRandom`: random UInt32 keys, 64 buckets. - `DistributionPow2FibSequential`: sequential UInt64 keys (0..65535), the pathological case for raw CRC32C low bits, verified uniform after the fix. Addresses reviewer comment on: ClickHouse#106538 Related: ClickHouse#106538 Related: ClickHouse#106120 Co-authored-by: Cursor <[email protected]>
Keep the `IColumn::computeHashInto` kernel work while removing the `ColumnsScatter` batching path, related setting, tests, and benchmark from this branch. Co-authored-by: Cursor <[email protected]>
Three correctness fixes for the `IColumn::computeHashInto` branch: 1. **BLOCKER — stale hash buffer in scatter transforms**: `ScatterByPartitionTransform` and `BufferedShardByHashTransform` reused a member `PaddedPODArray<UInt32>` across blocks via `resize_fill(n, WEAK_HASH32_INITIAL_VALUE)`. `resize_fill` only fills the grown tail `[old_size, n)`, so when a later block is `<=` the prior size (the common case with equal-size blocks) the buffer is NOT re-initialized. `computeHashInto` with `initial=false` then combines into stale data, routing equal keys to different shards across blocks — splitting window partitions and aggregation groups → wrong results. Fixed by `resize` + `std::fill(..., WEAK_HASH32_INITIAL_VALUE)`. 2. **Dropped grace_hash finalizer**: `JoinUtils::hashToSelector` was calling `sharder(hashes[i])` instead of `sharder(intHashCRC32(hashes[i]))`, losing the CRC32 avalanche step that the old `scatterBlockByHash` path depended on. Restored. 3. **Float `-0.0` normalization deviation**: `weakHashValue32` in `ColumnVector.cpp` was normalizing `-0.0` to `+0.0` before hashing, deviating from the old `getWeakHash32` byte-for-byte behavior. Reverted to raw-bit hashing. Updated the `ColumnBFloat16RawBitsAndSignedZero` test accordingly (`EXPECT_NE`). Also fixes a pre-existing `-Wimplicit-int-float-conversion` build error in `benchmark_column_insert_many_from.cpp`. Adds regression test `04316_fix_scatter_buffer_reuse_window` that catches the stale-buffer bug via a parallel window function cross-joined with a `GROUP BY` reference. Co-authored-by: Cursor <[email protected]>
Both ScatterByPartitionTransform and BufferedShardByHashTransform reused a member PaddedPODArray<UInt32> across blocks via resize_fill(n, value), which only fills the grown tail [old_size, n). When a later block is <= a prior block in size (the common case), no fill happens and the buffer retains stale hashes from the previous block. computeHashInto(initial=false) then combines into those stale values, routing equal keys to different shards across blocks and producing split window partitions / aggregation groups. Fix: replace resize_fill with resize + std::fill(…, WEAK_HASH32_INITIAL_VALUE) so the full buffer is always re-initialized each block. Also: - Restore the intHashCRC32 finalizer in JoinUtils::hashToSelector (grace_hash routing is now bit-identical to old WeakHash32-based code). - Revert float -0.0 normalization in weakHashValue32 (raw-bit hashing matches old getWeakHash32 byte-for-byte; SQL-equal -0.0/+0.0 routing to different shards is pre-existing old behavior). - Add regression test 04316_fix_scatter_buffer_reuse_window that cross-joins a parallel window function result against a GROUP BY reference and expects 0 mismatches. Co-authored-by: Cursor <[email protected]>
The `BM_HashAndFastrange_New` benchmark claimed to capture the `BufferedShardByHashTransform` hot path but diverged from the actual consumer loop in `generateOutputChunks`: it started the chain with `initial=true` for the first key column and omitted the per-iteration buffer seeding. The transform instead fills `hash_buffer` with `WEAK_HASH32_INITIAL_VALUE` every block and calls `computeHashInto` with `initial=false` for every key column. For `K=1` the benchmark therefore measured just `h(row) + mapToRange` instead of `combineWeakHash32(h(row), WEAK_HASH32_INITIAL_VALUE) + mapToRange`, overstating the improvement and missing regressions in the real loop. Seed `hash_buf` with `WEAK_HASH32_INITIAL_VALUE` each iteration (the re-seed is part of the consumer hot path) and call `computeHashInto` with `initial=false` for all columns, so the benchmark times the exact loop the PR's performance contract is about. Addresses review comment: ClickHouse#106538 (review) Co-authored-by: Cursor <[email protected]>
…at in computeHashInto Follow-up to review feedback (incl. @nickitat) on ClickHouse#106538, applied broadly in the same spirit rather than only at the tagged lines: - Drop `MULTITARGET_FUNCTION_X86_V4` from the CRC32C per-row kernels (`ColumnVector`, `ColumnDecimal`, `ColumnFixedString`, `ColumnNullable`). Hardware CRC32C is a dependency chain with no packed form, so the `x86_64_v4` clone was byte-identical to the scalar baseline. Multi-versioning is kept only in `mapToRange`, whose widening multiply genuinely vectorises. - Revert the wholesale `clang-format` churn that the hash change had dragged into `ColumnVector.cpp`, `ColumnNullable.cpp`, `ColumnString.cpp`, `ColumnFixedString.cpp`, and `ColumnDecimal.cpp` (include reordering, `ErrorCodes` re-indentation, unrelated signature/ctor rewraps). These files are restored from the merge base with only the `getWeakHash32` -> `computeHashInto` change re-applied. - `ScatterByPartitionTransform`: re-seed the hash buffer with `assign`, reuse `selector` as a member across blocks, and route through `mapToRange` instead of an inlined Lemire fastrange. `BufferedShardByHashTransform`: re-seed with `assign` and drop the duplicated finalizer comment. - `mapToRange`: remove the unused `UInt32`-output overload (only the `IColumn::Selector` UInt64 output is used) and move the implementation notes out of the header into the `.cpp`. - De-duplicate the per-kernel rationale comments down to a single `See IColumn::computeHashInto`, trim the contract block in `IColumn.h`, and drop the "former `getWeakHash32`/`WeakHash32`" history references that belong in the commit log, not the source. - Standardise the new `computeHashInto` API on `UInt32` (the surrounding column code's house type) instead of mixing `uint32_t` in signatures with `UInt32` buffers. - Benchmark: write a UInt64 selector via `mapToRange`, drop now-unused includes. Test: drop the unnecessary `no-random-settings` tag from `04312_grace_hash_vs_hash_join_key_types` (the explicit `SETTINGS` pin the relevant knobs). Verified by building `unit_tests_dbms` and running the 36 `ComputeHashInto` gtest cases (all pass). Related: ClickHouse#106538 Co-authored-by: Cursor <[email protected]>
Drop the inline code example and condense the rationale, per review preference to keep implementation detail out of the header. Related: ClickHouse#106538 Co-authored-by: Cursor <[email protected]>
Re-applies the batched, O(1)-dispatch `DB::ColumnsScatter::scatter` primitive and the `shard_by_hash_input_batch_bytes` input-batching mode on top of the `IColumn::computeHashInto` hash kernel branch, so PR ClickHouse#106120 is properly stacked on PR ClickHouse#106538 (its diff vs the hash branch contains only scatter). The scatter work had been temporarily reverted on the hash branch (commit 08b91f7) so that ClickHouse#106538 could be reviewed in isolation; this revert-the-revert brings it back and adapts it to the post-review APIs of the hash branch: - `BufferedShardByHashTransform` / `ScatterByPartitionTransform`: keep the batched `ColumnsScatter::scatter` path, but re-seed the per-flush/per-block hash buffer with `assign(WEAK_HASH32_INITIAL_VALUE)` and combine every key column with `initial=false` (matching the grace_hash routing and the stale-buffer fix), and drop the now-unused `Common/Exception.h` include. - `Common/MapToRange`: re-add the `UInt32`-output overload that the scatter consumers need for partition ids; the `UInt64` overload feeds `IColumn::Selector` as before. - `JoinUtils::scatterBlockByHashPow2`: keep the Fibonacci (Knuth multiplicative) bucket selection, retaining the `intHashCRC32` finalizer in `hashToSelector`. Also restores `gtest_columns_scatter`, `benchmark_columns_scatter`, the Fibonacci distribution gtests, the `04278_04101_sharded_aggregation_batched_input` stateless test, and the `shard_by_hash_input_batch_bytes` setting. Related: ClickHouse#105936 Related: ClickHouse#106538 Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]> # Conflicts: # src/Processors/Transforms/ScatterByPartitionTransform.cpp
`Chunk::getNumRows` returns `UInt64`, which on Darwin is `unsigned long
long` while `size_t` is `unsigned long`. In
`assign(num_rows, WEAK_HASH32_INITIAL_VALUE)` the non-template
`assign(size_t, const T &)` then needs an integral conversion, so the
iterator-pair `assign(It1, It2)` template wins deduction and fails to
compile dereferencing an integer:
src/Common/PODArray.h:709: error: indirection requires pointer
operand ('unsigned long long' invalid)
On Linux `UInt64` is `size_t`, so the non-template overload was an exact
match and the issue was invisible. Cast `num_rows` to `size_t` at both
hash-buffer reseed call sites.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106538&sha=4adb3be10dd855ce15c9b13d7b9c64046eb4a8c7&name_0=PR&name_1=Build%20%28amd_darwin%29
PR: ClickHouse#106538
Co-authored-by: Cursor <[email protected]>
nickitat
left a comment
There was a problem hiding this comment.
Looks fine to me, apart from a couple of suggestions.
…p NULL hash value Apply three review suggestions from @nickitat on ClickHouse#106538: - Drop `[[gnu::always_inline]]` from `weakHashValue32` (`ColumnVector.cpp`) and `weakHashDecimalValue32` (`ColumnDecimal.cpp`): it is unnecessary for these one-line static helpers wrapping a single CRC32C intrinsic, and the codebase convention is the `ALWAYS_INLINE` macro anyway. - `ColumnVariant::computeHashInto`: use `VectorWithMemoryTracking` instead of a plain `std::vector` for the per-variant scratch hash buffers, matching the former `getWeakHash32` implementation. - `ColumnVariant::computeHashInto`: hash NULL rows to `WEAK_HASH32_INITIAL_VALUE` instead of `0`, preserving the former `getWeakHash32` behaviour and making the NULL constant consistent with `ColumnNullable::computeHashInto`. Verified by building `unit_tests_dbms` and running the 36 `ComputeHashInto` gtest cases (all pass). Related: ClickHouse#106538 Co-authored-by: Cursor <[email protected]>
…h-into Co-authored-by: Cursor <[email protected]> # Conflicts: # src/Processors/Transforms/ScatterByPartitionTransform.cpp
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 716/804 (89.05%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 9 line(s) · Uncovered code |
Split out the hash-production half of #106120 into its own pull request, as requested in review: keep the per-column hash calculation separate from the batched scatter interface so each can be reviewed and benchmarked in isolation.
Motivation
Several in-memory routing paths — sharded aggregation (
BufferedShardByHashTransform),grace_hashjoin bucketing (JoinUtils::scatterBlockByHash), and parallel window partitioning (ScatterByPartitionTransform) — hashed their key columns by allocating aWeakHash32per chunk and chainingIColumn::getWeakHash32across the key columns. The per-chunk allocation dominates for narrow keys at high throughput.Changes
IColumn::computeHashInto(row_begin, row_end, hash_out, initial)is a per-row hash kernel that writes a finalized 32-bit hash for each row into a caller-provided buffer. The per-row hash is produced with hardware CRC32C —hashCRC32/intHashCRC32/updateWeakHash32, i.e._mm_crc32_u64on x86 (SSE4.2),__crc32cdon ARM, with a software fallback — seeded withWEAK_HASH32_INITIAL_VALUE, consuming a full 64-bit word in a single instruction. Multi-column keys compose in place — with no intermediate per-column arrays — viacombineWeakHash32, a single order-sensitive CRC32C step that packs the prior accumulator and the new per-row hash into the two halves of one 64-bit CRC input.The kernels are plain scalar loops: hardware CRC32C is a dependency chain with no packed form, so SIMD multi-versioning does not vectorise it. (
mapToRange, whose widening multiply genuinely vectorises, is the one place that keeps aMULTITARGET_FUNCTION_X86_V4clone.)For flat primitive keys (
UInt*/Decimal/FixedString/String) the kernel is allocation-free, writing directly into the caller's buffer. Wrapper and composite columns (ColumnNullable,ColumnTuple,ColumnArray,ColumnLowCardinality,ColumnObject,ColumnFunction,ColumnVariant) build their nested hashes into a transient per-call scratch buffer before combining, so they still allocate once per block — the same place the old per-chunkgetWeakHash32allocated.The kernel obeys a representation-independence contract: a materialized column and a transparent wrapper of the same values (
ColumnConst,ColumnLowCardinality,ColumnSparse,ColumnReplicated) compose to identical hashes, so equal multi-column keys are never split across shards or join buckets because of physical representation. Every column type combines its finalized per-row hash through the samecombineWeakHash32.IColumn::getWeakHash32,WeakHash32, andWeakHash.h/WeakHash.cppare removed; the three consumers now fill aPaddedPODArray<UInt32>via chainedcomputeHashInto. The CRC32CupdateWeakHash32primitive stays, with its default initial valueWEAK_HASH32_INITIAL_VALUEand the newcombineWeakHash32combiner co-located inHash.h.The routing hashes are then mapped to a shard/bucket index by the consumers:
grace_hashpower-of-two path (scatterBlockByHashPow2) selects buckets withhash & mask, which uses only the low bits, sohashToSelectorkeeps theintHashCRC32finalizer (sharder(intHashCRC32(hash))) to preserve avalanche there — bit-identical to the oldWeakHash32-based routing.BufferedShardByHashTransformandScatterByPartitionTransform, both viamapToRange's Lemire(h * P) >> 32, and the generic non-pow2grace_hashpath) read the top bits, which already depend on the whole 32-bit hash, so no extra finalizer is needed.The per-row hash values differ from the old per-chunk
getWeakHash32chain. Changing the exact hash values is safe because all three consumers route in-memory per query; per-key stable shard identity was never guaranteed.Testing
gtest_compute_hash_into(36 cases): row-range independence,initial/combine semantics, null-payload independence, array-length seeding,BFloat16raw-bit hashing, chi-squared distribution uniformity, order sensitivity, wide 128/256-bit folding (UInt128/UInt256/Decimal128/Decimal256), and representation independence acrossConst/Sparse/LowCardinality/Replicated/NothingforUInt64/String/Tuple/Array/Decimal/FixedStringkeys.04312_grace_hash_vs_hash_join_key_typesassertsgrace_hashjoins match the defaulthashjoin acrossUInt/String/Nullable/LowCardinality/Array/Tuplekeys.04316_fix_scatter_buffer_reuse_windowcross-joins a parallel window-function result against aGROUP BYreference to catch the cross-block hash-buffer reuse bug.03927,03928,04097–04100).Related: #105936
Related: #106120
Related: #106120 (review)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up sharded aggregation,
grace_hashjoin bucketing, and parallel window partitioning by replacing the per-chunk allocatinggetWeakHash32column hashing with anIColumn::computeHashIntokernel that writes finalized per-row hardware-CRC32C hashes and composes multi-column keys in place viacombineWeakHash32.Version info
26.6.1.753