Repository navigation
Cherry pick #111103 to 26.5: Cache deduplication data hashes before the Alias hop - #112583
Merged
robot-clickhouse-ci-1 merged 21 commits intoJul 31, 2026
Merged
Conversation
An INSERT flowing through a dependent materialized view whose target is an Alias and whose inner query changes the number of rows (e.g. GROUP BY), with a deduplicating table reachable behind the alias hop, aborted with the logical error 'block.rows() == getRows()' in DeduplicationInfo::calculateDataHashColumnWise on debug/sanitizer builds (found by the stress test / AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109000&sha=8b985cd485da90dab58920295e4886aaefbd3682&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29 on #109000, STID 1288-3bd5). AliasSink runs a full nested INSERT pipeline for the alias target and passes the chunk's DeduplicationInfo through it. The nested pipeline's squashing and AddDeduplicationInfoTransform call updateOriginalBlock, re-anchoring original_block to the current chunk. When the sink is fed by a materialized view whose inner query changed the row count (the view chain's RestoreChunkInfosTransform restores the source-level info, whose offsets describe the source rows, onto the view-output chunks), the re-anchored original_block no longer matches the offsets. A deduplicating sink behind the hop then computes the data hash lazily over the token's row range of the wrong block: an abort on the chassert in debug/sanitizer builds, an out-of-bounds read producing a garbage deduplication hash - i.e. broken, non-deterministic insert deduplication behind the alias - in release builds. Compute and cache the data hashes of all tokens in AliasSink::consume, while original_block still matches the offsets. The cached hashes are carried by clones and merges of the info, so every later hash lookup returns the cached value and never touches the drifted block. Closes: #111100 Co-Authored-By: Claude Fable 5 <[email protected]>
Address review: the cached data hashes from AliasSink::consume did not survive DeduplicationInfo::mergeSelf. When the row-count-changing materialized view emits multiple output chunks for one source block (RestoreChunkInfosTransform clones the same one-token DeduplicationInfo onto each chunk and UpdateDeduplicationInfoWithViewIDTransform gives the clones consecutive VIEW_NUMBERs), the nested squashing behind the Alias hop merges them through TokenDefinition::doExtend, which cleared data_hash_batch. The next deduplication lookup then recomputed the hash against the re-anchored view-output block: the same out-of-bounds read and broken deduplication as the single-chunk case. A VIEW_NUMBER range extension merges chunks a view produced from the same source block (canBeExtended requires all preceding extras, including SOURCE_NUMBER, to be equal), and the cached hash is computed over the source block's token range, so it stays valid: keep it when both sides carry the same cached value, and invalidate otherwise. The regression test now also covers the multi-chunk path: a small max_block_size and min_insert_block_size_rows make the view-level squashing emit each 10-row GROUP BY output block as its own stamped chunk, while min_insert_block_size_rows_for_materialized_views restores the default threshold on the target side so the nested squashing merges them (verified: without this change the merged token shows the extended view-block-0-10 range and the second insert is not deduplicated at the final target, 200 rows instead of 100). Co-Authored-By: Claude Fable 5 <[email protected]>
… hop Caching the data hashes was not enough: on a deduplication collision, DeduplicationInfo::filterImpl still walked the source-row offsets over the re-anchored (smaller) view-output block. The stress tests reproduced it with this PR's own test under randomized settings, through MergeTreeSink::finishDelayedChunk -> deduplicateBlock -> filterImpl, as a PODArray bounds-check abort: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=1eb23f8f1d3f7bc1e08f8fc2be1286ae1107c8eb&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 filterImpl now handles the "all tokens collided" case first - for any token count and for async inserts too - dropping the whole block without any row-level access, which is the only row-accurate result that exists after the re-anchoring. A partial collision has no mapping from the tokens' source rows to the drifted block's rows at all, so it throws a clear NOT_IMPLEMENTED exception instead of reading out of the block's bounds; the row-accurate handling of that case needs the deeper redesign flagged in issue #111100. The test now covers the async regressions from the review: a repeated identical flushed async insert is deduplicated as a whole (deduplicateBlock), and two identical async inserts batched into one flush are rejected with the new exception (self-deduplication hits the partial-collision case). max_threads/max_insert_threads are pinned in the test so the merged token identity behind the alias hop does not depend on thread scheduling.
Address the review finding on the deduplication-hash caching added for the `Alias` hop. `RestoreChunkInfosTransform` clones the same source-level `DeduplicationInfo` onto every output chunk of a row-count-changing view, and the clones do not share `data_hash_batch` (tokens are copied by value). Caching the hashes in `AliasSink::consume` per chunk therefore re-hashed the whole source block once per emitted chunk - O(source_rows * output_chunks), a severe regression for a large `GROUP BY` insert that explodes into many chunks. All those clones carry the same `original_block` and `offsets` and differ only in view-block numbers, which do not enter the hashed range, so `cacheDataHashes` now takes a per-sink `DataHashCache`: the per-token hashes are computed once for a given source block and copied onto its sibling clones. The cost returns to O(source_rows). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The scenarios in `04613_deduplication_alias_hop_row_drift` pin the deduplication path exactly: the async batch busy timeout, the view-level squash thresholds and the insert/thread counts decide how the deduplication tokens merge behind the `Alias` hop and whether two identical inserts join one async flush. Settings randomization perturbs that - an early async flush breaks the batched self-deduplication, so the final two inserts succeed instead of failing with `NOT_IMPLEMENTED` - which made the test fail across the flaky-check jobs. Add `no-random-settings, no-random-merge-tree-settings`. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=b2d5481adc075e6ef6bba99e6432be540666430f&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The last scenario of `04613_deduplication_alias_hop_row_drift` needs two identical async inserts to join one flush so the deduplicating sink behind the alias hop attempts self-deduplication over the drifted view-output block and rejects it with `NOT_IMPLEMENTED`. It relied on a fixed 5000 ms busy timeout to guarantee the two inserts batch together, but on a loaded CI runner the first insert's window can elapse before the second arrives, so they flush separately, each deduplicates on its own without an exception, and the test prints `0`/`0` instead of `1`/`1`. The failure reproduced across the flaky-check, targeted and parallel stateless jobs. Trigger the flush by count instead of by a wall-clock window: `async_insert_max_query_number=2` flushes the buffer exactly when the second insert is queued (the `has_enough_queries` path, which requires deduplication to be enabled), so the two inserts join one flush no matter how slowly the runner starts the second client. Identical inserts share the async-queue key and therefore the same shard, so the count is reached deterministically; the large busy timeout only keeps the first insert from flushing alone before the second arrives. Verified that the count trigger deterministically joins the two inserts into a single flush (one shared `flush_query_id` with two entries, 5/5 runs). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=3580debd0beaaa8eaedd07c8bc6bb97579381378&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… splits the batch The batched self-deduplication scenario in 04613 needs its two async inserts to join one flush. The count trigger (`async_insert_max_query_number=2`) removed the wall-clock race, but in parallel runs other tests execute `SYSTEM FLUSH ASYNC INSERT QUEUE`, which flushes the whole queue server-wide and can flush the first insert alone before the second is queued. A split batch made the scenario print `0 0` instead of `1 1`: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=b74605874199975e7e436da9bba1f4abdfa22575&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 #111103 Detect the split (the outputs are not both 1) and retry the attempt; a regression of the fix keeps failing every attempt because a joined flush then never reports NOT_IMPLEMENTED. The busy timeout drops from 600 s to a bounded 5 s fallback so a stranded insert of a split attempt flushes promptly instead of hanging the test.
…lock Address the AI review Blocker: master gained `DeduplicationInfo::filterToPartition` (#11370cc3a22 fixed the async-insert dedup token bleed across partitions), which the sinks call before `deduplicateSelf`/`deduplicateBlock` when splitting an insert by partition. It walks each token's source-row range over the partition scatter selector, so behind an `Alias` hop over a row-count-changing materialized view - where the info still describes the source rows but the block (and thus the selector) is the smaller view output - the walk read out of the selector's bounds. Fail closed there like in `filterImpl`: when the selector size does not match the rows the deduplication info describes, throw `NOT_IMPLEMENTED` instead of reading out of bounds. The new test 04621 covers a partitioned deduplicating target behind the alias hop: single-token sync and async inserts must still deduplicate per partition via the cached data hashes, and a two-token batched async flush must be rejected by the new guard. #111103
…s-hop-row-drift # Conflicts: # src/Interpreters/InsertDeduplication.cpp
…-token one The batched-async scenario relied on two separate client processes joining one async insert flush. Even with the count trigger and a retry loop, all 10 attempts split on loaded runners (both inserts flushed alone and printed 0/0 instead of 1/1), e.g. in the `Stateless tests (arm_asan_ubsan, targeted)` and `(amd_msan, WasmEdge, parallel)` runs of https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=0cd9617802748b684b85c62f203f7fdc144a3844&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 (#111103). Cross-process timing cannot be pinned, so the scenario was structurally flaky. The same guards are reachable deterministically with a single sync insert: `min_insert_block_size_rows=400` re-blocks the 800 input rows into two 400-row source blocks, i.e. two deduplication tokens, which the nested INSERT behind the alias hop concatenates into one drifted block (distinct source numbers prevent the token extension path). In 04613 a second insert repeating exactly one of the two blocks makes one token collide with the deduplication window - the partial-collision guard in `DeduplicationInfo::filterImpl` rejects it with `NOT_IMPLEMENTED`. In 04621 the partitioned target rejects the very first two-token insert in `DeduplicationInfo::filterToPartition`. No second client, no timing, no retries. Verified 10/10 locally against a release build, plus the neighbouring deduplication and `Alias` tests. Co-Authored-By: Claude Fable 5 <[email protected]>
… hop The private CI of the sync PR (check `CH Inc sync`, `Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper)`, STID: 1288-3e19) aborted with a logical error: a bare `std::out_of_range` from `unordered_map::at` escaped `InsertDependenciesBuilder::createRetry` while the table behind the `Alias` engine deduplicated a repeated insert. There the deduplicating table is the direct target of the nested INSERT the `AliasSink` runs, and the deduplication info restored onto the nested chain keeps the visited views of the outer insert chain, which the nested chain's `InsertDependenciesBuilder` does not know about - looking them up in its maps threw. The stress environment converts the tables to `SharedMergeTree`, which deduplicates by default, which is why the public stateless runs never reached this path. Two fixes: - `DeduplicationInfo::goRetry` does not build the retry chain at all when nothing is left to retry (all tokens collided - the usual case for a repeated identical insert): the callers only check that the result is empty, and the chain, which would never be executed, cannot even be constructed behind the hop. The repeated block is deduplicated cleanly. - `InsertDependenciesBuilder::createRetry` rejects a retry path whose final view does not belong to the insert chain with a clean `NOT_IMPLEMENTED` instead of the bare `std::out_of_range` (reported as a logical error and an abort in sanitizer builds). The new test `04635_deduplication_alias_hop_deduplicating_inner` reproduces both: pre-fix it fails with `Code: 1001 ... std::out_of_range: unordered_map::at: key not found` on the exact stack from the stress report. Related: #111100 Co-Authored-By: Claude Fable 5 <[email protected]>
…ilder The retry-chain guard in `InsertDependenciesBuilder::createRetry` only checked that the last element of the retry path belongs to the current builder. When the outer insert goes directly into a materialized view whose chain crosses a table with the `Alias` engine, the deduplication info can anchor its original block at a view of the outer chain while the end of the path belongs to the nested chain the `AliasSink` runs. Rebuilding such a retry is unsound: foreign path elements are silently skipped (dropping their transformations on a longer chain), and when the foreign anchor is the first path element, `createPreSink` fails with a bare `std::out_of_range` from `unordered_map::at`, reported as a logical error. Require `start_from` to be owned by the builder too and fail closed with `NOT_IMPLEMENTED` otherwise. The new test 04638 pins the deterministic shape: `INSERT INTO` a materialized view feeding a chain that crosses the alias hop, with the deduplicating table behind a dependent view of the alias inner table, so the retry path ends in the nested builder while its anchor is the outer chain's view. Co-Authored-By: Claude Fable 5 <[email protected]>
The ownership guard in `InsertDependenciesBuilder::createRetry` checked only `path.back()` and `start_from`. Every builder stores its empty root in `inner_tables`, so `isView` is trivially true for an empty id — a retry anchored at a foreign empty root (a regular-table outer insert) would pass the guard, and the retry loop then silently skipped the outer chain's intermediate views, dropping their transformations; `goRetry` would then lose the surviving rows because the rebuilt chunk's tokens no longer match. Require every element of the retry path to be owned by the builder that rebuilds it, and remove the now-dead silent skip from the rebuild loop. The new test 04639_deduplication_alias_hop_regular_table_root pins the regular-table-root variant (retry path `<empty>/mv1` behind the hop is rejected with a clean NOT_IMPLEMENTED and no rows are lost). The exact anchor-owned/foreign-middle shape is not deterministically reachable in sync mode - the deduplication info always re-anchors its original block at the first dependent view, which the anchor check already rejects (verified empirically, including a double alias hop chain) - but randomized async paths can produce it, and the guard now covers it fail-closed.
Address review: `MergeTreeSink::consume` and `ReplicatedMergeTreeSink::consume` call `DeduplicationInfo::filterToPartition` unconditionally, while the fail-close consistency check inside it (added for the drifted info behind the `Alias` hop) fired even when the destination table does not deduplicate at all (deduplication window = 0). A multi-token insert through a row-count-changing materialized view and an `Alias` hop into a partitioned non-deduplicating target was then rejected with `NOT_IMPLEMENTED`, although the sink skips deduplication entirely and never registers the tokens. `filterToPartition` now takes `deduplication_enabled` (the sink's `deduplicate` flag), mirroring `deduplicateSelf`, and passes the info through untouched when the sink does not deduplicate. New test `04645_deduplication_alias_hop_partitioned_no_dedup`: the two-token drifted insert of 04621 with the deduplication window of the partitioned target set to 0 must succeed and fill both partitions. Co-Authored-By: Claude Fable 5 <[email protected]>
…t tests
The `Bugfix validation (unit tests)` job builds a "before" binary from the
merge base with only the pull request's unit-test files overlaid, so every
unit test in `src/**/tests` has to compile against the code *without* the
fix. Passing the new `deduplication_enabled` flag as the first argument of
`DeduplicationInfo::filterToPartition` required changing the call sites in
`gtest_async_inserts.cpp`, and those three-argument calls do not compile
against the two-argument signature of the merge base:
gtest_async_inserts.cpp:230:80: error: too many arguments to function
call, expected 2, have 3
A compile failure of the before-binary is reported as inconclusive (the job
cannot attribute it to the regression test), so the check went red.
Move `deduplication_enabled` to the end of the parameter list and default it
to the fail-close value (`true`, the drift check active). The unit tests call
`filterToPartition` with two arguments again, which compiles both with and
without the fix, and the sinks keep passing their `deduplicate` flag. No
behavior change.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=3f3b9b37f88b4e86ac145eb78a137339ed9b5444&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29
…ow-drift Cache deduplication data hashes before the Alias hop
…ypick/26.5/111103 # Conflicts: # src/Interpreters/InsertDeduplication.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #111103
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job