Skip to content

Do not consume a source block number for row-less chunks in insert deduplication - #111881

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-dedup-source-block-number-rowless-chunk
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-dedup-source-block-number-rowless-chunk

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes nondeterministic insert deduplication block ids when a row-less chunk interleaves with data chunks during an INSERT SELECT (for example under parallel replicas). Such an insert can miss deduplication and produce duplicate rows on retry, and asserts deduplication_hashes.size() == 1 in debug and sanitizer builds.

Description

AddDeduplicationInfoTransform numbered every arriving chunk with an incrementing source block number, including row-less chunks (0 rows, with columns; these reach the transform because ISimpleTransform only skips chunks that have neither rows nor columns). A row-less chunk contributes no deduplication token (setUserToken with count 0 is a no-op) and is later dropped by squashing, so numbering it only leaves a gap in the source block numbers.

That gap breaks the contiguity check in TokenDefinition::canBeExtended (source number ranges must be adjacent), so squashing merges the two surrounding data blocks with do_concat instead of extending a single token. The squashed single part then carries several deduplication tokens, getDeduplicationHashes returns several hashes for one part, and ReplicatedMergeTreeSink asserts deduplication_hashes.size() == 1. In release builds the assert is compiled out and the part commits with two block ids whose values depend on where the row-less chunk interleaved (thread-timing dependent), so an identical retried insert computes different ids, misses deduplication, and duplicates rows.

Fix: do not consume a source block number for row-less chunks. Source numbers then stay contiguous arrival indices of data chunks, a squashed block keeps a single deduplication token and hash, and the assert holds.

The regression test is a unit test (gtest_dedup_source_block_number) rather than an SQL test: the interleaved row-less chunk only forms under real multi-host parallel-replicas timing, so no local single-node SQL shape delivers one to the transform (verified across six query shapes and eighty iterations). The test drives AddDeduplicationInfoTransform directly and fails without this fix (two tokens) and passes with it (one token).

Surfaced as Logical error: 'deduplication_hashes.size() == 1' by the Stress test (amd_msan) check on an unrelated docs-only PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111754&sha=79ec7ed9daf6348f4d886d723048dbacf5a4324a&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

groeneai and others added 2 commits July 25, 2026 07:59
…duplication

AddDeduplicationInfoTransform numbered every arriving chunk with an
incrementing source block number, including row-less chunks. A row-less
chunk contributes no deduplication token (setUserToken with a zero row
count is a no-op) and is later dropped by squashing, so numbering it only
leaves a gap in the source block numbers.

That gap breaks the contiguity check in TokenDefinition::canBeExtended
(source number ranges must be adjacent), so squashing merges the two
surrounding data blocks with do_concat instead of extending a single
token. The resulting single part then carries several deduplication
tokens, getDeduplicationHashes returns several hashes for one part, and
ReplicatedMergeTreeSink asserts deduplication_hashes.size() == 1.

Guard the source block numbering so row-less chunks do not consume a
number; the numbers then stay contiguous across data chunks and a
squashed block keeps a single deduplication token and hash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Covers the insert deduplication bug where a row-less chunk consumed a
source block number, leaving a gap that broke token merging on squashing
and produced several deduplication hashes for a single part (which trips
deduplication_hashes.size() == 1 in ReplicatedMergeTreeSink).

The test drives AddDeduplicationInfoTransform directly with the shape
data / row-less / data / data. Two adjacent data chunks separated only by
the row-less chunk must merge into one token: without the guard they get
non-adjacent source numbers (0 and 2), mergeSelf concatenates into two
tokens (getCount() == 2) and the test fails; with the guard they get 0
and 1 and extend into one token (getCount() == 1). A second assertion
merges two data chunks separated by another data chunk and requires two
tokens, so the test also fails if source numbering is silently removed
altogether. Two companion tests pin the hash-layer behavior for the gap
(two hashes) and for contiguous numbers (one hash).

This is a unit test rather than an SQL test because the interleaved
row-less chunk only forms under real multi-host parallel-replicas timing;
a local single-node run never delivers one to the transform (verified
across six query shapes and eighty iterations), so no SQL shape can
demonstrate the failure deterministically.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 review rounds, final round 0 findings; plus the reviewer's own cold pass each round).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test would still pass if source-number assignment were removed entirely (identical SOURCE_ID-only tokens extend), so it under-pinned the numbering invariant (gtest_dedup_source_block_number.cpp) AGREE — fixed Added a non-adjacent-merge assertion: data chunks separated by another data chunk must merge into two tokens; verified it fails on a numbering-removed mutant build, and the original assertion still fails on the merge-base build
2 💡 Test comments repeated the full PR mechanism per test; literal identifiers unformatted AGREE — fixed Trimmed to one invariant statement + per-test one-liners; kept the assertion-choice gotcha; backticked identifiers; dropped a needless test helper
3 💡 Guard comment in the transform restated downstream failure mechanics that already live in the commit message AGREE — fixed Trimmed to the local invariant (row-less chunks contribute no token and must not consume a source number); mechanism stays in the commit message
4 💡 Draft changelog entry used past tense against the changelog guidelines AGREE — fixed Entry rewritten in present tense per docs/changelog_entry_guidelines.md

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. All findings this PR were AGREEd and fixed pre-publication.

Session id: cron:clickhouse-review-slot-9:20260725-080500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='DedupSourceNumberHole.*' — on-demand, 0 ms, no timing dependence.
b Root cause explained? Yes. A row-less chunk consumed a source block number in AddDeduplicationInfoTransform, leaving a gap; the two surrounding data chunks then got non-adjacent numbers, TokenDefinition::canBeExtended rejected the merge, squashing did do_concat into two tokens, getDeduplicationHashes returned two hashes for one part, and ReplicatedMergeTreeSink asserted deduplication_hashes.size() == 1.
c Fix matches root cause? Yes. The fix stops row-less chunks from consuming a number at the layer that owns the counter, restoring contiguous source numbers. The chassert is kept (not softened) and canBeExtended is not relaxed (relaxing would leave the dedup id dependent on how many empty chunks interleaved — pinned by HoleProducesTwoHashes).
d Test intent preserved / new tests added? Yes. New regression unit test (3 tests) added; no existing test weakened or removed. RowlessChunkDoesNotBreakTokenMerge pins both sides of the invariant: adjacent data chunks separated by a row-less chunk must merge into one token, and data chunks separated by another data chunk must stay two — so the test also fails if source numbering is silently removed altogether.
e Both directions demonstrated? Yes. Without the fix RowlessChunkDoesNotBreakTokenMerge fails on the adjacent assertion (getCount() is 2, expected 1); with the fix all three pass. Removing numbering entirely fails the non-adjacent assertion (getCount() is 1, expected 2). All runs on Build-ID-verified binaries (unfixed 043f3cb4..., numbering-removed 853441ce..., fixed 4841479107f0...); the suite is green 50/50 under --gtest_repeat=50.
f Fix is general across code paths? Yes. The symmetric carrier UpdateDeduplicationInfoWithViewIDTransform (view numbers) has the same pattern but is unreachable by row-less chunks: every caller places SquashingTransform directly upstream and squashing drops or never emits empty chunks. No speculative guard added there. Async inserts are immune (source number is normalized to 0). Downstream consumers (MergeTreeSink, the *SinkPatch variants) are healed by the same numbering fix.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type wrappers/formats (no type gating, no persisted format). The relevant axis is chunk shape: data / row-less-with-columns (fully-empty chunks are skipped before the transform). The regression test exercises the exact incident shape (data, row-less, data).
h Backward compatible? (maintainer-approved exception only) Yes. No setting default change (no SettingsChangesHistory.cpp entry needed), no format versioning. Block ids are transient Keeper nodes / dedup-log entries. Only inserts that today interleave empty chunks see their (already timing-nondeterministic) ids change; there was no stable behavior to preserve.
i Invariants and contracts preserved? Yes. Row-less chunks still get a DeduplicationInfo created and attached, so getSafe<DeduplicationInfo> never throws on non-squashing paths; setRootViewID/updateOriginalBlock on a token-less info are no-ops. Sinks already handle 0-row chunks. No durability re-entry concern (block ids are recomputed from data, not persisted process state).

Session id: cron:clickhouse-impl-slot-5:20260725-075700

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema - could you review this? AddDeduplicationInfoTransform numbered row-less chunks, leaving a gap in source block numbers that makes canBeExtended fall back to concat, so one squashed part ends up with two deduplication hashes (asserts deduplication_hashes.size() == 1 in sanitizer builds, nondeterministic dedup ids in release).

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

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff60399]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR fixes insert deduplication so a 0-row chunk no longer advances the source block counter before squashing drops it, which keeps later data chunks contiguous and prevents timing-dependent deduplication hashes. I reviewed the current diff, the surrounding deduplication/squashing/sink code paths, and the existing PR discussion, and I did not find a remaining issue that warrants an inline review comment.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 49/49 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ff60399

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

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Cannot start clickhouse-server fuzzer-produced columnless view in metadata hits Invalid storage definition in metadata file at DatabaseOnDisk.cpp:138 and aborts the whole startup #110906 (ours, open)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found a cancelled countMatches over an 11M-char haystack keeps scanning (is_cancelled = 1, elapsed = 1612s) — no cancellation checkpoint in the match loop a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Stress test (arm_asan_ubsan) / Check failed rollup of the two above resolved via the owners above
Upgrade check (amd_release) / Error message in clickhouse-server.log version-metadata parse error on part all_1_2_2_1 (expected '\n' before: 'version: 1 storing_version: 0 ...'), from no-object-storage tests running against the object-storage-default upgrade server #111772 (ours, open)
Mergeable Check / PR rollup resolved via the owners above

Startup abort, from fatal.log (repeats on every restart attempt, hence "Cannot start"):

<Fatal> : Logical error: 'Invalid storage definition in metadata file: it's a bug or result of
manual intervention in metadata files'
  src/Databases/DatabaseOnDisk.cpp:138 createTableFromAST
  <- src/Databases/DatabaseOrdinary.cpp:388 loadTableFromMetadata (AsyncLoader parallel table load)

Hung check, the single hung row in hung_check.log:

query:        SELECT countMatches(repeat('\0\0\0\0\0\0\0\0\0\0a', 1000000), 'a');
elapsed:      1612.79
is_cancelled: 1

is_cancelled = 1 with 1612s elapsed is the point: the query was cancelled and kept running, so this
is an uncancellable function body rather than a deadlock. Same class as #109257 and #111909, different
function. #88401 fixed the quadratic complexity of countMatches but added no cancellation checkpoint,
so it is not the fix here.

Not caused by this PR: the diff is one if (chunk.getNumRows() > 0) guard in
DeduplicationTokenTransforms.cpp plus a gtest. It touches no metadata loading, no regex function,
and no part serialization.

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111881&sha=ff60399af8498b3ce3db0df35c2317474779b732&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111881&sha=ff60399af8498b3ce3db0df35c2317474779b732&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Session id: cron:our-pr-ci-monitor:20260726-083000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the hung check on this run: #112003

The processlist text recorded for that hung row (countMatches(...)) is misleading - the row had ASTFuzzerQueries: 4 and the stack of the thread that was actually running named CountSubstringsImpl<NameCountSubstringsCaseInsensitiveUTF8, PositionCaseInsensitiveUTF8>. The defect is quadratic complexity in countSubstringsCaseInsensitiveUTF8, not in countMatches.

jh0x pushed a commit to jh0x/ClickHouse that referenced this pull request Jul 29, 2026
Follow-up to the previous commit on this branch, addressing review feedback.

The comment above the incremental cursor in `CountSubstringsImpl::vectorConstant`
justified the row-identity check with "rows never share a start offset". That is
not true of `ColumnString`: its strings carry no terminator, `sizeAt` permits
`offsets[i] == offsets[i - 1]`, and a zero-length insert pushes the unchanged
offset, so adjacent empty rows do share a start offset. The check is still exact
for a narrower reason, which the comment now states: only a row that contains a
match ever sets the cursor, and such a row is non-empty because the index scan
leaves `haystack_offsets[i - 1] <= pos < haystack_offsets[i]`. The change to the
header is comment-only - the preprocessed token stream is unchanged.

`04648_count_substrings_utf8_complexity` pinned the complexity but not the
cursor arithmetic. Its multi-row query uses a 10-character, 11-byte chunk with
`start_pos` thresholds of 1 to 4, i.e. below both the character and the byte
distance between matches, so a per-match delta cursor and a byte-offset cursor
produce the same numbers as the correct one. Two small cases are added where
multibyte characters precede the matches and `start_pos` exceeds the distance
between matches. Each is verified against three wrong implementations: a
per-match delta cursor returns 0 and 0, a byte-offset cursor returns 2 and 2,
and a cursor that never restarts on a row change returns 3 for the second case,
against a reference of 1 and 1. Reverting the whole cursor hunk still makes the
file time out, so the complexity assertions are unaffected by the addition.

The reference was regenerated with `clickhouse-test --record`. Existing suites
`01590_countSubstrings`, `02346_position_countsubstrings_zero_byte`,
`01163_search_case_insensetive_utf8`, `03278_enum_string_functions`,
`03666_count_matches_complexity` and `00233_position_function_family` pass with
unchanged references, and 50 runs of `04648` pass at 0.23 to 0.28 s each.

CI reports for the hung check that led to this branch:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111881&sha=ff60399af8498b3ce3db0df35c2317474779b732&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
ClickHouse#111881
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108977&sha=852e60ed1f6b4b834b49e4421043f1edf1adb501&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#108977
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. label Sep 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Yes, it is still needed. Checked on current master (ea30d777):

It is rare in CI: Stress test (amd_msan) on 2026-07-24 and Stress test (arm_msan) on 2026-08-11, none on master. The added gtest fails without the fix (Bugfix validation (unit tests) passed), and the branch still merges cleanly.

This branch has not been deployed

No deployments
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 comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants