Repository navigation
Cache deduplication data hashes before the Alias hop - #111103
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]>
|
Workflow [PR], commit [ff6fea4] Summary: ✅
AI ReviewSummaryThis PR hardens insert deduplication across an Final Verdict✅ Approve |
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]>
|
The |
… 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.
|
CI triage for commit 1eb23f8:
|
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
|
CI triage for commit b746058: the only red, Also merged with |
…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]>
|
CI triage for commit 0cd9617 (the
|
|
Investigated. This variant fails with: That is the plain-rewritable concurrent-create race tracked as #111289, already fixed on master by #111353 ("Lower Plain-Rewritable Metadata Transactions Isolation", merged 2026-07-22 17:31 UTC, 8875e70). It changes exactly the Why the triage on 0cd9617 showed no tracking issue or fix: that commit had diverged from master and predated the merge (243 behind). The single master FAIL after the merge (a625cd1, 17:47 UTC) was a build 29 commits behind the fix, i.e. still pre-fix. No separate PR is needed. This PR's current head 02e57e0 already contains #111353 (22 ahead, 0 behind the merge commit), so the next CI run should clear this failure. |
… 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]>
|
CI triage for commit 02e57e0: the only red was the |
…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]>
|
CI triage for commit f49b961: public CI was fully green except Commit 5f9a7dc addresses the AI-review Blocker (retry-chain guard did not check the retry's starting view) — see the review-thread reply for details, including why the literal |
| # behind the alias hop squashes them into one block. The partitioned sink must then attribute each token's | ||
| # source rows to the partitions - impossible after mv1's GROUP BY collapsed the blocks - so the | ||
| # insert is rejected with NOT_IMPLEMENTED by filterToPartition (pre-fix this walked the |
There was a problem hiding this comment.
Are we sure that the squash behind the alias how should trigger NOT_IMPLEMENTED for the isert?
Is't it bettor not to have a squash here and be able to make correct insert?
There was a problem hiding this comment.
I do not understand why Alias hides entire executer under its consume method. Alias could be integrated into InsertDependency graph and be executed in the main pipeline. I see that executor tries do its own decisions on the pushed chunks, it tries to squash them. That wrapping introduces the difficulty, it only looks like a fast and simple solution. With that wrapping you have to write code and be ready to big variety of combinations which normally do not happen in all the places.
CheSema
left a comment
There was a problem hiding this comment.
But aside the Alias's architecture decision.
NOT_IMPLEMENTED better than segmentation fault. This PR at least fixed han segmentation fault.
Backport #111103 to 26.7: Cache deduplication data hashes before the Alias hop
Cherry pick #111103 to 26.5: Cache deduplication data hashes before the Alias hop
Cherry pick #111103 to 26.6: Cache deduplication data hashes before the Alias hop
Backport #111103 to 26.5: Cache deduplication data hashes before the Alias hop
Backport #111103 to 26.6: Cache deduplication data hashes before the Alias hop
|
This fix should be backported to 26.2 as well |
…ialized-view targets filterToPartition attributed each token to partitions by walking its source-row range over a partition selector sized to the sink block. When a materialized view changes the row count before a partitioned deduplicating target, the tokens describe the source rows while the selector describes the smaller view-output block, so the walk read out of bounds (a crash in release builds; a NOT_IMPLEMENTED rejection after ClickHouse#111103's guard). Per-partition attribution is only valid at the direct insert destination; for any materialized-view target (level == VIEW) keep every token in every partition instead. Related: ClickHouse#111100 Related: ClickHouse#111103 Caused by: ClickHouse#111049
Issue ClickHouse#112018: repeating an identical INSERT ... SELECT with the same insert_deduplication_token, into a MergeTree table whose column is a Tuple with a sparse-serialized element, raised the logical error "Block structure mismatch in function connect between SourceFromSingleChunk and ConvertingTransform". DeduplicationInfo::recalculateBlock builds the retry header with cloneEmpty(), which preserves the column implementation, so the sparse Tuple element stays sparse in the header. The retry chain's ConvertingTransform input header comes from the storage metadata sample block and is never sparse, so connect asserted. The nested sparse column escaped the top-level-only ColumnSparse unwrap in checkColumnStructure because ColumnTuple::getName renders element names recursively. Both source fixes merged on 2026-07-30 by different mechanisms, ClickHouse#111103 (goRetry returns early on empty input, before the retry pipeline is built) and ClickHouse#111191 (haveCompatibleColumnStructure recurses into ColumnTuple). Neither shipped a test for the sparse shape, and no test on master combines insert deduplication with sparse serialization, so this adds the missing coverage. The test covers a sparse element in a Tuple, a doubly nested Tuple and a materialized-view target, with controls for a top-level sparse column, an insert without deduplication, sparse serialization surviving on disk after the retry, and deduplication having dropped the rows. It guards the end-to-end behaviour rather than either fix individually: every deduplicating case uses one token per insert, so on the repeat all tokens collide and goRetry receives an empty block, which means ClickHouse#111103's guard returns before ClickHouse#111191's structure check is consulted. Reverting either fix alone leaves the test green; reverting both reproduces the reported message exactly. A partial deduplication case, which would deliver a non-empty sparse block and pin the Block.cpp side alone, is left as a follow-up. All nine MergeTree tables pin ratio_of_defaults_for_sparse_serialization so the test needs no no-random-merge-tree-settings tag. Verified with the real test runner: 100/100 under randomization, and a control that removes the pin from the one table whose sparseness is asserted fails 27/50, which confirms the pins are load-bearing. The test is parallel-safe without a no-parallel tag because every object lives in its own currentDatabase(). Co-Authored-By: Claude Fable 5 <[email protected]>
The final query built a single ~1.6 GiB block (100 rows, each with a 1-million-element `Array(Array(Int))` from `arrayWithConstant`), which fails with `MEMORY_LIMIT_EXCEEDED` on a loaded parallel test runner when the server is close to its total memory limit (the OvercommitTracker selects the query to stop). Cap `max_block_size` so the rows are processed in small blocks: the same code path is exercised with a peak allocation about a hundred times smaller. Failure example: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=5f9a7dc8a262eab4e2268940baf6eb4afd6b3cd8&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 (PR ClickHouse#111103)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fix a logical error
block.rows() == getRows()(an out-of-bounds read and broken insert deduplication in release builds) when anINSERTflows through a dependent materialized view whose target is anAliasand whose inner query changes the number of rows, with a deduplicating table reachable behind the alias hop.Documentation entry for user-facing changes
AliasSinkruns a full nestedINSERTpipeline for the alias target and passes the chunk'sDeduplicationInfothrough it. The nested pipeline's squashing andAddDeduplicationInfoTransformcallupdateOriginalBlock, re-anchoringoriginal_blockto the current chunk. When the sink is fed by a materialized view whose inner query changed the row count (the view chain'sRestoreChunkInfosTransformrestores the source-level info, whoseoffsetsdescribe the source rows, onto the view-output chunks), the re-anchoredoriginal_blockno longer matchesoffsets. 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 thechassertinDeduplicationInfo::calculateDataHashColumnWisein debug/sanitizer builds, and an out-of-bounds read viaIColumn::updateHashWithValueRangeproducing a garbage (non-deterministic) deduplication hash in release builds.The fix computes and caches the data hashes of all tokens in
AliasSink::consume, whileoriginal_blockstill matches the offsets. The cache also survives the nested squashing: when the materialized view emits multiple output chunks for one source block, each carries a clone of the same source-level info distinguished only by consecutiveVIEW_NUMBERs, and the squashing behind the alias hop merges them throughTokenDefinition::doExtend— which now keeps the cached hash for aVIEW_NUMBERrange extension (the merged chunks come from the same source block, so the source-data hash is unchanged) instead of clearing it and recomputing from the drifted block. With the fix, repeated identical inserts are deduplicated deterministically on the table behind the alias (covered by the new test04613_deduplication_alias_hop_row_drift, which exercises both the single-chunk and the multi-chunk view output paths: without the fix the second insert's deduplication hash at the final target comes from an out-of-bounds read; with it, the repeated block is dropped).Caching the hashes is not enough on its own: the collision filter/retry path (
DeduplicationInfo::filterImpl, reached from bothdeduplicateBlock— retry filtering inMergeTreeSink::finishDelayedChunk— anddeduplicateSelf— async self-deduplication) still walked the source-rowoffsetsover the drifted block, writing past the filter column. The stress tests on this PR reproduced exactly that (PODArraybounds-check abort infilterImpl, https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111103&sha=1eb23f8f1d3f7bc1e08f8fc2be1286ae1107c8eb&name_0=PR&name_1=Stress%20test%20%28amd_msan%29).filterImplnow handles the "all tokens collided" case — the only row-accurate result that exists after the re-anchoring — by dropping the whole block without any row-level access, for any token count and for async inserts too. A partial collision after the re-anchoring has no row mapping at all, so it now throws a clearNOT_IMPLEMENTEDexception instead of reading out of the block's bounds; the row-accurate handling of that case needs the deeper redesign flagged in the issue. The test covers both guards deterministically: a repeated identical flushed async insert is deduplicated as a whole (the all-collided path), and a sync insert carrying two deduplication tokens (the source-side squashing re-blocks the input into two source blocks, which the nestedINSERTbehind the alias hop concatenates into one drifted block) whose repetition makes exactly one token collide is rejected with the new exception (the partial-collision path). An earlier version of the test drove the partial-collision path with two async inserts batched into one flush, but joining a batch across two client processes is inherently timing-dependent and was flaky in CI, so it was replaced with the sync two-token scenario.The same drift also reaches the partition-splitting path that
mastergained meanwhile:DeduplicationInfo::filterToPartition(called by the sinks before deduplication when the target is partitioned) walks each token's source-row range over the partition scatter selector, which is sized to the actual (view-output) block. Behind the alias hop that walk read out of the selector's bounds. It now fails closed the same way: a multi-token insert whose selector no longer matches the described rows is rejected withNOT_IMPLEMENTED, while single-token inserts (the common case) still deduplicate per partition via the cached data hashes. Covered by the new test04621_deduplication_alias_hop_partitioned_target.A follow-up review round found that this fail-close check also fired when the destination table does not deduplicate at all: the sinks call
filterToPartitionunconditionally, whileDeduplicationInfois attached wheneverinsert_deduplicate = 1, even if the deduplication window of the target is 0 — so a multi-token drifted insert into a partitioned non-deduplicating target was rejected although the sink skips deduplication entirely and never registers the tokens.filterToPartitionnow takesdeduplication_enabled(the sink'sdeduplicateflag), mirroringdeduplicateSelf, and passes the info through untouched when the sink does not deduplicate. Covered by the new test04645_deduplication_alias_hop_partitioned_no_dedup(the two-token scenario of04621with the target's deduplication window set to 0: the insert succeeds and fills both partitions, and the repeated insert doubles every count).The
CH Inc synccheck surfaced one more latent hazard on the same hop (Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper), STID: 1288-3e19): when the table behind the alias deduplicates itself (it is the direct target of the nestedINSERTtheAliasSinkruns — in the private stress environment every table is aSharedMergeTree, which deduplicates by default), the deduplication retry path looked up the info's visited views — which belong to the outer insert chain — in the nested chain'sInsertDependenciesBuildermaps, and a barestd::out_of_rangefromunordered_map::atescapedcreateRetry(reported as a logical error, an abort in sanitizer builds). Fixed twice over:DeduplicationInfo::goRetryno longer builds the retry chain when nothing is left to retry (all tokens collided — the usual case for a repeated identical insert; the chain would never be executed and cannot even be constructed behind the hop), so the repeated block is deduplicated cleanly; andInsertDependenciesBuilder::createRetryrejects a retry path whose final view does not belong to the insert chain with a cleanNOT_IMPLEMENTED. Covered by the new test04635_deduplication_alias_hop_deduplicating_inner, which reproduces the exact failure stack pre-fix (Code: 1001 ... unordered_map::at: key not found).The review then caught a hole in that guard: it only checked the last element of the retry path. When the outer insert goes directly into a materialized view (a non-empty root view), the deduplication info can anchor its original block at a view of the outer chain while the end of the retry path belongs to the nested chain behind the alias hop — the guard passed, and the retry loop silently skipped the foreign path elements (dropping their transformations on a longer chain, e.g. a second alias hop), while a foreign anchor at the path front would still escape as an
std::out_of_rangeincreatePreSink.createRetrynow also requires the retry's starting view (start_from) to be owned by the current builder and fails closed withNOT_IMPLEMENTEDotherwise. Covered by the new test04638_deduplication_alias_hop_insert_into_mv, which drives the chain viaINSERT INTOa materialized view with the deduplicating table behind a dependent view of the alias inner table, makes the mid-chain view non-identity, and asserts that no rows skipping its transformation reach the destination (pre-fix the partially-collided retry silently rebuilt a chain that omitted every foreign view).One more round of review hardening: checking only the endpoints of the retry path is not enough, because every
InsertDependenciesBuilderstores its empty root (a regular-table insert) ininner_tables— so a retry anchored at a foreign empty root passes an endpoint-only ownership check, and the rebuild loop silently skipped the intermediate views it did not own, after which the rebuilt rows no longer matched the surviving tokens and were silently lost.createRetrynow requires every element of the retry path to be owned by the builder rebuilding it, and the silent skip is removed. Covered by the new test04639_deduplication_alias_hop_regular_table_root(the same chain as04638, driven through a regular source table): the partial collision behind the hop is rejected with a cleanNOT_IMPLEMENTEDand no rows are lost or skip the mid-chain view's transformation. (Deterministic sync inserts always re-anchor the deduplication info at the first dependent view — which the anchor check already rejects, verified empirically including a double alias hop — so the foreign-middle-with-owned-endpoints shape needs the async/randomized paths the stress runs kept producing; it is now covered fail-closed.)Found by the stress test (AST fuzzer) on #109000 (unrelated to that PR's changes — the crash reproduces with a plain single-stream insert): 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 (STID: 1288-3bd5).
Closes: #111100
Closes: #112018
Related: #109000
Version info
26.7.2.40,26.6.2.145,26.5.6.102