Skip to content

Defer dedup data hash computation to eliminate squashing overhead - #101494

Merged
CheSema merged 21 commits into
masterfrom
fix-dedup-insert-hash-overhead
Apr 3, 2026
Merged

CheSema merged 21 commits into
masterfrom
fix-dedup-insert-hash-overhead

Conversation

@CheSema

@CheSema CheSema commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

During INSERT with deduplicate_insert=enable, calculateDataHash was called eagerly in updateOriginalBlock on every squashing step. For 10M rows this meant ~17 intermediate hash computations (each O(rows x columns) with SipHash), all discarded except the last.

Fix 1: Lazy hash evaluation

updateOriginalBlock now stores the block with COW-shared columns instead of computing the hash eagerly and discarding. The hash is computed lazily on first access in the sink via calculateDataHash, which caches the result and then releases the block columns (restoring the original memory optimization).

When insert_deduplication_token is set, the data hash is skipped entirely — only the user token is used.

Fix 2: Batch hashing via updateHashWithValueRange

Added IColumn::updateHashWithValueRange(begin, end, hash) virtual method that hashes a range of rows in one call. The default implementation loops row-by-row; overrides in ColumnVector, ColumnDecimal, ColumnFixedString, ColumnString, ColumnArray, ColumnNullable, ColumnTuple, and ColumnMap feed contiguous memory to SipHash, eliminating per-row virtual dispatch.

The new unified hash path (getBlockUnifiedHash) uses calculateDataHashBatch with batch hashing. The old hash path (getBlockHash) keeps row-by-row calculateDataHash for backward compatibility during the COMPATIBLE_DOUBLE_HASHES migration period.

Benchmark results

5M rows, 22 columns (all overridden types), 5 runs averaged:

Master (before) Fix (row-by-row) Fix + batch hash
Null disable 0.67s 0.67s 0.69s
Null enable 3.23s 0.68s 0.65s
MT disable 1.39s 1.39s 1.44s
MT enable 3.93s 2.62s 1.94s
MT token disable 1.39s 1.38s 1.38s
MT token enable 3.97s 1.38s 1.39s

Hash overhead isolated (enable - disable):

Engine Master Row-by-row fix Batch hash fix
Null 2.56s ~0s ~0s
MergeTree 2.54s 1.23s 0.50s
MT + token 2.58s ~0s ~0s
  • Null engine proves batch hash computation is effectively free — all overhead eliminated
  • MergeTree remaining 0.50s is dedup log writes, not hash computation
  • Token case: master still computed data hash even with token set; now properly skipped

Ref: #99241

Changelog category (leave one):

  • Performance Improvement

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

Fix significant INSERT performance regression when deduplicate_insert=enable (default since 26.2) by deferring data hash computation from squashing to the sink and using batch column hashing via updateHashWithValueRange, reducing overhead from ~2.5s to ~0.5s for 5M rows with 22 columns.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.561
  • Backported to: 26.3.5.2, 26.2.9.4

CheSema and others added 2 commits April 1, 2026 14:03
…ng squashing

During INSERT with `deduplicate_insert=enable`, `calculateDataHash` was called
eagerly in `updateOriginalBlock` on every squashing step. For 10M rows this
meant ~17 intermediate hash computations (each O(rows * columns) with SipHash),
all discarded except the last. This caused ~1.7s overhead (2.06s vs 0.35s for
Engine=Null, 2.27s vs 0.67s for MergeTree).

The fix defers hash computation: `updateOriginalBlock` stores the block with
COW-shared columns instead of computing the hash eagerly and discarding.
The hash is computed lazily on first access in the sink via `calculateDataHash`,
which caches the result and then releases the block columns.

After the fix, dedup ON/OFF performance is identical (0.19s/0.36s Null,
0.66s/0.66s MergeTree for 10M rows, 13 columns).

Ref: #99241

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds a performance test comparing INSERT with `deduplicate_insert=enable`
vs `disable` on both Engine=Null (isolates hash overhead) and MergeTree
(combined overhead with part writes). Uses 5M rows, 13 columns, INSERT
SELECT with ORDER BY ALL to make the query deduplication-eligible.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f027755]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) failure
Server died FAIL cidb
Logical error: Can't extract iceberg table state from storage snapshot for table location A (STID: 2606-4a47) FAIL cidb
Stress test (arm_msan) failure
Server died FAIL cidb
MemorySanitizer: use-of-uninitialized-value (STID: 4179-5154) FAIL cidb

AI Review

Summary

This PR defers deduplication data-hash computation and introduces updateHashWithValueRange fast paths across many IColumn implementations to speed up INSERT deduplication. The optimization direction is good, but there are still correctness/safety blockers in the new range-hash path: out-of-bounds access on empty subranges and hash-stream incompatibilities that can change deduplication ids. The PR should not be merged until these are fixed.

Missing context
  • ⚠️ No CI results/logs were provided in this review context, so runtime behavior (including sanitizer coverage) could not be validated from CI artifacts.
Findings

❌ Blockers

  • [src/Columns/ColumnVariant.cpp:903] ColumnVariant::updateHashWithValueRange hashes every variant in the fast path, including variants with size == 0, and forwards (0, 0) to nested range hash methods. New implementations such as ColumnString/ColumnArray use &data[begin] / offsetAt(begin) and are not safe for empty ranges, which can trigger UB. Skip empty variants before calling nested range hashing.
  • [src/Columns/ColumnString.cpp:794] offsetAt(begin) is unsafe for begin == 0 and can read before offsets storage, causing undefined behavior in dedup hash computation.
  • [src/Columns/ColumnArray.cpp:308] same boundary bug as ColumnString: offsetAt(0) is invalid and may read out of bounds on first token.
  • [src/Interpreters/InsertDeduplication.cpp:375] unified hash now uses column-major order (all rows of col0, then col1...), while old path is row-major (row0 col0,col1...). This changes hash streams for multi-column blocks and breaks compatibility assumptions during migration.
  • [src/Columns/ColumnString.cpp:796] range hashing for String is not equivalent to repeated updateHashWithValue (size+payload+terminator format), changing dedup hash semantics.
  • [src/Columns/ColumnArray.cpp:311] range hashing for Array is not equivalent to per-row hashing (size + nested values per row), changing dedup hash semantics.
  • [src/Columns/ColumnTuple.cpp:415] tuple range hashing is column-major per element, not per-row, changing hash order and dedup ids.
  • [src/Columns/ColumnNullable.cpp:63] nullable range hash unconditionally hashes nested values and appends null map bytes, not matching per-row nullable semantics (null-flag-first and conditional nested hash).
  • [src/Columns/ColumnObject.cpp:1149] ColumnObject range hash does not preserve per-row merged-by-path semantics and can make hash depend on internal representation (dynamic_paths vs shared data).

💡 Nits

  • [src/Columns/ColumnVariant.cpp] comment typo: thupe → the.
  • [tests/queries/0_stateless/03711_deduplication_blocks_part_log.sql] typo: hame → name.
  • [tests/queries/0_stateless/03711_deduplication_blocks_part_log.sql] typo: as a has of data in the block → as a hash of data in the block.
  • [src/Interpreters/InsertDeduplication.h] stale comment about where original_block columns are released.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Dedup hashing logic in core insert path still has correctness/UB blockers.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ❌ Multiple range-hash implementations alter hash byte stream/order vs legacy behavior.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Not safe to roll out while dedup hash compatibility and UB issues remain.
Compilation time ✅
Performance & Safety

The new batching path can improve performance, but current implementation introduces safety and correctness risks:

  • UB risk from empty-range hashing in nested columns.
  • Dedup hash semantic drift (ordering/format changes) that can break dedup stability during mixed-version operation and migration.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Fix empty-range safety in range hash implementations/callers (including ColumnVariant fast path).
    2. Restore hash compatibility with previous semantics (or explicitly version/gate behavior and migration).
    3. Keep row-wise equivalence where compatibility is required during COMPATIBLE_DOUBLE_HASHES transition.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 1, 2026
Prevents parts from piling up across iterations, keeping each run
independent.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@CheSema
CheSema force-pushed the fix-dedup-insert-hash-overhead branch from 17236a5 to 9045311 Compare April 1, 2026 12:12
Use rand() in one column so each run produces unique data hashes,
preventing the dedup log from suppressing writes on subsequent
iterations. Also truncate MergeTree table between runs to avoid
accumulating parts.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@CheSema
CheSema force-pushed the fix-dedup-insert-hash-overhead branch from 9045311 to 8705de5 Compare April 1, 2026 12:12
@Avogar

Avogar commented Apr 1, 2026

Copy link
Copy Markdown
Member

I also noticed that deduplicate_insert='backward_compatible_choice' doesn’t help to bring back old performance for regular MergeTree. This is because previously to enable deduplication for regular MergeTree we needed both non_replicated_deduplication_window > 0 (was 0 by default) and insert_deduplicate = true . Now non_replicated_deduplication_window is not checked. Should we fix that?

@den-crane

den-crane commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

0.19s/0.36s Null

It's still bad.

My guess If you do insert from prepared .native file and MergeTree with order by (), the regression still be visible.
It's hidden by select's order by all and MergeTree order by (id, category, value1, datetime)

25.8

CREATE TABLE dedup_mt (
    id UInt32,
    datetime DateTime,
    category LowCardinality(String),
    value1 UInt64,
    value2 UInt32,
    value3 UInt16,
    ts1 DateTime,
    counter1 UInt32,
    counter2 UInt32,
    counter3 UInt32,
    counter4 UInt32,
    counter5 UInt32,
    status UInt8
) ENGINE = MergeTree
ORDER BY ()
PARTITION BY toYYYYMMDD(datetime)
settings non_replicated_deduplication_window = 1000;

CREATE TABLE dedup_mt1 as dedup_mt ENGINE = MergeTree ORDER BY () PARTITION BY toYYYYMMDD(datetime);

SELECT number, toDateTime('2024-01-01') + toIntervalSecond(number % 86400), ['a','b','c','d','e'][number % 5 + 1], rand(), number % 1000000, number % 65535, toDateTime('2024-01-01') + toIntervalSecond(number % 43200), number % 100000, number % 200000, number % 300000, number % 400000, number % 500000, number % 256 FROM numbers(5000000)
into outfile 'test_dedup.native' format Native;

insert into dedup_mt from infile 'test_dedup.native' format Native;
Elapsed: 0.209 sec

insert into dedup_mt1 from infile 'test_dedup.native' format Native;
Elapsed: 0.208 sec

No difference with or without non_replicated_deduplication_window, no dedup overhead.

@CheSema

CheSema commented Apr 1, 2026

Copy link
Copy Markdown
Member Author

I also noticed that deduplicate_insert='backward_compatible_choice' doesn’t help to bring back old performance for regular MergeTree. This is because previously to enable deduplication for regular MergeTree we needed both non_replicated_deduplication_window > 0 (was 0 by default) and insert_deduplicate = true . Now non_replicated_deduplication_window is not checked. Should we fix that?

deduplicate_insert='backward_compatible_choice' is about how to resolve turn on or turn off the deduplication. backward_compatible_choice means look at old settings insert_deduplicate or async_insert_deduplicate.

I believe that with this fix the case when non_replicated_deduplication_window = 0 would also skip hash calculation.

@CheSema

CheSema commented Apr 1, 2026 •

Copy link
Copy Markdown
Member Author

0.19s/0.36s Null

It's still bad.

My guess If you do insert from prepared .native file and MergeTree with order by (), the regression still be visible. It's hidden by select's order by all and MergeTree order by (id, category, value1, datetime)

Actually this numbers I do not know from where claude took them. Lets look at perf tests in this PR when they are done.

I see the following result in my local run for the perf test from PR

  ┌───────────┬─────────┐
  │           │ Median  │
  ├───────────┼─────────┤
  │ dedup OFF │ ~0.185s │
  ├───────────┼─────────┤
  │ dedup ON  │ ~0.190s │
  └───────────┴─────────┘

and for the bigger set

  ┌───────────┬──────────────────────────────┬────────┐
  │           │             Runs             │ Median │
  ├───────────┼──────────────────────────────┼────────┤
  │ dedup OFF │ 0.90, 0.82, 0.82, 0.81, 0.82 │ ~0.82s │
  ├───────────┼──────────────────────────────┼────────┤
  │ dedup ON  │ 0.81, 0.84, 0.83, 0.84, 0.82 │ ~0.83s │
  └───────────┴──────────────────────────────┴────────┘

PS: this is exactly for the case when non_replicated_deduplication_window = 0, it answers Pavel's question but it is WRONG RESULTS for the purpose of the PR

@CheSema

CheSema commented Apr 1, 2026

Copy link
Copy Markdown
Member Author

My guess If you do insert from prepared .native file and MergeTree with order by (), the regression still be visible.

Ok, let me try to add this case to the perf tests also.

@den-crane

Copy link
Copy Markdown
Contributor

Argh, my example is bad. It inserted zeros because of column's names in 'test_dedup.native'. There is some setting how to enable insertion using positions, something like column_names..inference

Without non_replicated_deduplication_window the dedup log is inactive,
so getDeduplicationHashes returns empty and the hash is never computed —
making the MergeTree benchmark meaningless. Also switch to ORDER BY ()
to isolate dedup overhead from sorting cost.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@CheSema

CheSema commented Apr 1, 2026 •

Copy link
Copy Markdown
Member Author

In general, the deduplication requires the hash calculation from inserted data. It is not for free.

We used to use the hash from PartWriter. That was almost for free. But this hash is not suited in generic logic for async inserts and does not allow to make switching sync <--> async transparent. I can't use it. I need separate hash for inserted data.

Here I removed a bug, when I call hash calculation from data several times when data squashed. But the final hash calculation still cost some time.

It turns out that using insert_deduplication_token makes insertions cheaper, clickhouse does not calculate the hash from the data.

@CheSema

CheSema commented Apr 1, 2026

Copy link
Copy Markdown
Member Author

I have one more idea.
Our hash function is not optimized. It calculate the hash by feeding row by row and field by field to the hasher.
It would be much more efficient to calc hash on the columns by ranges in a batch.
It still safe to change the new hash as long as it works in pair with old one.

@CheSema

CheSema commented Apr 1, 2026

Copy link
Copy Markdown
Member Author

22 columns, 5M rows:

  ┌──────────────────┬────────┬──────────────────┬──────────────────┐
  │       Test       │ Master │ Fix (row-by-row) │ Fix + batch hash │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ Null disable     │ 0.67s  │ 0.67s            │ 0.69s            │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ Null enable      │ 3.23s  │ 0.68s            │ 0.65s            │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ MT disable       │ 1.39s  │ 1.39s            │ 1.44s            │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ MT enable        │ 3.93s  │ 2.62s            │ 1.94s            │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ MT token disable │ 1.39s  │ 1.38s            │ 1.38s            │
  ├──────────────────┼────────┼──────────────────┼──────────────────┤
  │ MT token enable  │ 3.97s  │ 1.38s            │ 1.39s            │
  └──────────────────┴────────┴──────────────────┴──────────────────┘

Hash overhead isolated (enable - disable):

  ┌──────────┬────────┬────────────────┬────────────────┐
  │  Engine  │ Master │ Row-by-row fix │ Batch hash fix │
  ├──────────┼────────┼────────────────┼────────────────┤
  │ Null     │ 2.56s  │ 0.01s          │ ~0s            │
  ├──────────┼────────┼────────────────┼────────────────┤
  │ MT       │ 2.54s  │ 1.23s          │ 0.50s          │
  ├──────────┼────────┼────────────────┼────────────────┤
  │ MT token │ 2.58s  │ ~0s            │ ~0s            │
  └──────────┴────────┴────────────────┴────────────────┘

CheSema and others added 2 commits April 1, 2026 18:16
Add `IColumn::updateHashWithValueRange` virtual method that hashes a
range of rows in one call. The default implementation loops row-by-row;
overrides in `ColumnVector`, `ColumnDecimal`, `ColumnFixedString`,
`ColumnString`, `ColumnArray`, `ColumnNullable`, `ColumnTuple`, and
`ColumnMap` feed contiguous memory to SipHash, eliminating per-row
virtual dispatch.

`InsertDeduplication` now uses `calculateDataHashBatch` (calling the new
method) for the unified hash path. The old row-by-row path is kept for
backward-compatible hashes during the `COMPATIBLE_DOUBLE_HASHES` period.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add Decimal64, Float64, DateTime64, FixedString, String, Array,
Nullable, Tuple, and Map columns to exercise all `updateHashWithValueRange`
overrides. Add a query with `insert_deduplication_token` to show zero
hash overhead when a user token is set.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Columns/ColumnNullable.cpp Resolved
Comment thread src/Columns/ColumnTuple.cpp Resolved
Comment thread src/Columns/ColumnString.cpp Resolved
Add tables for Decimal64, Float64, FixedString, String, Array,
Nullable, Tuple, Map, and a mixed-types table to
`03711_deduplication_blocks_part_log`. This verifies that
`updateHashWithValueRange` batch hashing produces stable deduplication
hashes for every overridden column type.

Update reference hashes: the unified hash changed for tables containing
String and other variable-length columns because batch hashing feeds
data differently to SipHash. The old (row-by-row) hash is unchanged.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Columns/ColumnString.cpp Resolved
Comment thread src/Columns/ColumnArray.cpp Resolved
Add async insert tables for UInt32, String, Array, and mixed types to
`03711_deduplication_blocks_part_log`. Async inserts compute data hash
directly from the block via `calculateDataHashBatch`, exercising the
batch hashing path independently from the sync MergeTreePartWriter path.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Avogar Avogar self-assigned this Apr 1, 2026
Comment thread src/Columns/ColumnArray.cpp Resolved
++global_discr)
{
auto local_discr = global_to_local_discriminators[global_discr];
variants[local_discr]->updateHashWithValueRange(0, variants[local_discr]->size(), hash);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ ColumnVariant::updateHashWithValueRange calls updateHashWithValueRange(0, size) for all variants in the fast path, including variants with size == 0.

This reaches nested overrides with an empty range. Several new range implementations use &data[begin] / offsetAt(begin) and are not safe for begin == end == 0 on empty columns, so this can read out of bounds (UB) during dedup hash computation.

Concrete path: a Variant(UInt64, String, Array(UInt32)) block containing only UInt64 values executes this loop, then calls the String/Array variant hash with (0, 0).

Please skip empty variants in the fast path, e.g. guard with if (variants[local_discr]->size() == 0) continue; before calling updateHashWithValueRange.

@clickhouse-gh

clickhouse-gh Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 78.00% (685,718/879,053) 84.10% (739,436/879,135) +6.10% (+53,718)
Functions 90.40% (794,106/878,414) 90.90% (798,277/878,469) +0.50% (+4,171)
Branches 70.60% (220,742/312,660) 76.70% (239,688/312,682) +6.10% (+18,946)

Changed lines: 80.51% (157/195) | lost baseline coverage: 15 line(s) · Uncovered code

Full report · Diff report

@CheSema
CheSema added this pull request to the merge queue Apr 3, 2026
Merged via the queue into master with commit 86e3614 Apr 3, 2026
157 of 159 checks passed
@CheSema
CheSema deleted the fix-dedup-insert-hash-overhead branch April 3, 2026 20:48
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 3, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Apr 3, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Apr 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @CheSema @Avogar — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

robot-clickhouse added a commit that referenced this pull request Apr 3, 2026
robot-clickhouse added a commit that referenced this pull request Apr 7, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Apr 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Apr 7, 2026
Backport #101494 to 26.3: Defer dedup data hash computation to eliminate squashing overhead
CheSema added a commit that referenced this pull request Apr 8, 2026
Backport #101494 to 26.2: Defer dedup data hash computation to eliminate squashing overhead
@fm4v fm4v linked an issue Jun 6, 2026 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

INSERT queries are 3x slower after upgrading from 25.12 to 26.2

7 participants