Skip to content

Add non-allocating IColumn::computeHashInto column hash kernel - #106538

Merged
harikrishnan94 merged 20 commits into
ClickHouse:masterfrom
harikrishnan94:icolumn-compute-hash-into
Jun 13, 2026
Merged

harikrishnan94 merged 20 commits into
ClickHouse:masterfrom
harikrishnan94:icolumn-compute-hash-into

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

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_hash join bucketing (JoinUtils::scatterBlockByHash), and parallel window partitioning (ScatterByPartitionTransform) — hashed their key columns by allocating a WeakHash32 per chunk and chaining IColumn::getWeakHash32 across 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_u64 on x86 (SSE4.2), __crc32cd on ARM, with a software fallback — seeded with WEAK_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 — via combineWeakHash32, 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 a MULTITARGET_FUNCTION_X86_V4 clone.)

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-chunk getWeakHash32 allocated.

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 same combineWeakHash32.

IColumn::getWeakHash32, WeakHash32, and WeakHash.h/WeakHash.cpp are removed; the three consumers now fill a PaddedPODArray<UInt32> via chained computeHashInto. The CRC32C updateWeakHash32 primitive stays, with its default initial value WEAK_HASH32_INITIAL_VALUE and the new combineWeakHash32 combiner co-located in Hash.h.

The routing hashes are then mapped to a shard/bucket index by the consumers:

  • The grace_hash power-of-two path (scatterBlockByHashPow2) selects buckets with hash & mask, which uses only the low bits, so hashToSelector keeps the intHashCRC32 finalizer (sharder(intHashCRC32(hash))) to preserve avalanche there — bit-identical to the old WeakHash32-based routing.
  • The high-bit fastrange consumers (BufferedShardByHashTransform and ScatterByPartitionTransform, both via mapToRange's Lemire (h * P) >> 32, and the generic non-pow2 grace_hash path) 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 getWeakHash32 chain. 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

  • New unit test gtest_compute_hash_into (36 cases): row-range independence, initial/combine semantics, null-payload independence, array-length seeding, BFloat16 raw-bit hashing, chi-squared distribution uniformity, order sensitivity, wide 128/256-bit folding (UInt128/UInt256/Decimal128/Decimal256), and representation independence across Const/Sparse/LowCardinality/Replicated/Nothing for UInt64/String/Tuple/Array/Decimal/FixedString keys.
  • New stateless test 04312_grace_hash_vs_hash_join_key_types asserts grace_hash joins match the default hash join across UInt/String/Nullable/LowCardinality/Array/Tuple keys.
  • New stateless test 04316_fix_scatter_buffer_reuse_window cross-joins a parallel window-function result against a GROUP BY reference to catch the cross-block hash-buffer reuse bug.
  • Verified locally against the existing sharded-aggregation suite (03927, 03928, 04097–04100).

Related: #105936
Related: #106120
Related: #106120 (review)

Changelog category (leave one):

  • Not for changelog

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Speed up sharded aggregation, grace_hash join bucketing, and parallel window partitioning by replacing the per-chunk allocating getWeakHash32 column hashing with an IColumn::computeHashInto kernel that writes finalized per-row hardware-CRC32C hashes and composes multi-column keys in place via combineWeakHash32.

Version info

  • Merged into: 26.6.1.753

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f22f3f8]

Summary: ✅


AI Review

Summary

This PR replaces the allocating WeakHash32 column-hash path with IColumn::computeHashInto, wires it into sharded aggregation, grace_hash bucketing, and parallel window partitioning, and adds focused gtest_compute_hash_into plus stateless coverage. I do not see a new correctness issue in the current implementation; the earlier wrapper, wide-type, ColumnFunction, deterministic-test, and IColumnDummy concerns are addressed. The remaining unresolved point is evidence for the advertised Performance Improvement.

Missing context / blind spots
  • ⚠️ Fast test and Build (arm_tidy) were still in progress for f22f3f8d702ec84858a7d0ef3f236ce0d929ed40 when I checked the GitHub check runs; completed CI would close that validation gap.
  • ⚠️ I could not run gtest_compute_hash_into locally because this workspace does not contain a built clickhouse or gtest_compute_hash_into binary.
Findings
⚠️ Majors
  • [src/Processors/Transforms/BufferedShardByHashTransform.cpp:143] [dismissed by author -- https://github.com/Add non-allocating IColumn::computeHashInto column hash kernel #106538#discussion_r3371924944] The PR is categorized as Performance Improvement and promises faster sharded aggregation, grace_hash bucketing, and parallel window partitioning, but the visible evidence still only shows a Cloud report with no significant macro-query changes. There is no attached before/after output for benchmark_compute_hash_into or an affected high-cardinality routing workload at the current head, so the performance contract remains unproven even though the implementation is plausible. Suggested fix: attach current before/after benchmark numbers for the new benchmark or an affected query workload, including the baseline SHA and PR SHA.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: provide current before/after performance evidence for the affected computeHashInto consumer paths.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 5, 2026
@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Jun 5, 2026
Comment thread src/Columns/ColumnDynamic.h Resolved
Comment thread src/Columns/ColumnObject.cpp Resolved
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]>
Comment thread src/Columns/ColumnFunction.cpp Resolved
Comment thread src/Columns/ColumnVector.cpp Resolved
harikrishnan94 and others added 2 commits June 5, 2026 17:14
`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]>
Comment thread src/Columns/IColumnDummy.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 1 regressed, 4 improved out of 38 analysed

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)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 22 improvement 334 259 -22.5% <0.0001 aggregation: String GROUP BY hashing rewritten (computeHashInto) cuts per-block allocation; underlying runs were noisy but delta is c
🟢 23 improvement 297 199 -33.0% <0.0001 aggregation: String GROUP BY key hashing now writes into caller buffers, avoiding intermediate hash vectors; clean -33% on low-noise

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)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🔴 8 regression 156 179 +15.1% <0.0001 join_operator: Multi-key join hashing now allocates scratch for composite keys; +15% is real and confirmed, on a query already trending
🟢 7 improvement 113 73 -35.4% <0.0001 join_operator: Hash-join row partitioning uses the rewritten per-column weak hash; -35% improvement is consistent and on-path
🟢 20 improvement 248 129 -48.0% <0.0001 join_operator: Join/subquery hashing on-path for this PR; large -48% delta but query is intrinsically noisy, so read the magnitude loos

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
  • StressHouse run: d16954eb-f770-42b6-a905-40106c4df321
  • MIRAI run: 17ebfda4-46fd-4fe1-bd2b-075d990dbdb9
  • PR check IDs:
    • clickbench_9086_1781295812
    • clickbench_9196_1781295879
    • clickbench_9307_1781295949
    • tpch_adapted_1_official_9327_1781295949
    • tpch_adapted_1_official_9491_1781296011
    • tpch_adapted_1_official_9604_1781296082

harikrishnan94 and others added 2 commits June 5, 2026 19:41
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]>
Comment thread src/Interpreters/JoinUtils.h Resolved
@nickitat nickitat self-assigned this Jun 5, 2026
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]>
harikrishnan94 and others added 2 commits June 6, 2026 16:42
…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]>
Comment thread src/Columns/ColumnsScatter.cpp Resolved
Comment thread src/Columns/ColumnsScatter.cpp Resolved
harikrishnan94 and others added 2 commits June 7, 2026 14:40
…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]>
harikrishnan94 and others added 2 commits June 8, 2026 19:39
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]>

@nickitat nickitat 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.

That is indeed a much better-scoped and easier-to-review patch. Thanks.

Comment thread src/Common/MapToRange.h Resolved
Comment thread src/Columns/ColumnDecimal.cpp Resolved
Comment thread src/Columns/ColumnDecimal.cpp Resolved
harikrishnan94 and others added 2 commits June 9, 2026 10:59
…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]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 9, 2026
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
Comment thread src/Columns/ColumnVector.cpp Resolved
`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 nickitat 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.

Looks fine to me, apart from a couple of suggestions.

Comment thread src/Columns/ColumnDecimal.cpp Resolved
Comment thread src/Columns/ColumnVariant.cpp Resolved
Comment thread src/Columns/ColumnVariant.cpp Resolved
harikrishnan94 and others added 2 commits June 11, 2026 14:54
…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
@harikrishnan94 harikrishnan94 removed the pr-performance Pull request with some performance improvements label Jun 11, 2026
@harikrishnan94
harikrishnan94 removed the request for review from nihalzp June 11, 2026 13:05
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

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

Full report · Diff report

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Jun 13, 2026
Merged via the queue into ClickHouse:master with commit b899e50 Jun 13, 2026
166 checks passed
@harikrishnan94
harikrishnan94 deleted the icolumn-compute-hash-into branch June 13, 2026 16:49
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
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 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.

3 participants