Skip to content

Cache deduplication data hashes before the Alias hop - #111103

Merged
CheSema merged 19 commits into
masterfrom
fix/dedup-info-alias-hop-row-drift
Jul 30, 2026
Merged

CheSema merged 19 commits into
masterfrom
fix/dedup-info-alias-hop-row-drift

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fix a logical error block.rows() == getRows() (an out-of-bounds read and broken insert deduplication in release builds) when an INSERT flows through a dependent materialized view whose target is an Alias and whose inner query changes the number of rows, with a deduplicating table reachable behind the alias hop.

Documentation entry for user-facing changes

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 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 DeduplicationInfo::calculateDataHashColumnWise in debug/sanitizer builds, and an out-of-bounds read via IColumn::updateHashWithValueRange producing a garbage (non-deterministic) deduplication hash in release builds.

The fix computes and caches the data hashes of all tokens in AliasSink::consume, while original_block still 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 consecutive VIEW_NUMBERs, and the squashing behind the alias hop merges them through TokenDefinition::doExtend — which now keeps the cached hash for a VIEW_NUMBER range 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 test 04613_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 both deduplicateBlock — retry filtering in MergeTreeSink::finishDelayedChunk — and deduplicateSelf — async self-deduplication) still walked the source-row offsets over the drifted block, writing past the filter column. The stress tests on this PR reproduced exactly that (PODArray bounds-check abort in filterImpl, 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 — 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 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 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 nested INSERT behind 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 master gained 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 with NOT_IMPLEMENTED, while single-token inserts (the common case) still deduplicate per partition via the cached data hashes. Covered by the new test 04621_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 filterToPartition unconditionally, while DeduplicationInfo is attached whenever insert_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. filterToPartition now takes deduplication_enabled (the sink's deduplicate flag), mirroring deduplicateSelf, and passes the info through untouched when the sink does not deduplicate. Covered by the new test 04645_deduplication_alias_hop_partitioned_no_dedup (the two-token scenario of 04621 with 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 sync check 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 nested INSERT the AliasSink runs — in the private stress environment every table is a SharedMergeTree, 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's InsertDependenciesBuilder maps, and a bare std::out_of_range from unordered_map::at escaped createRetry (reported as a logical error, an abort in sanitizer builds). Fixed twice over: DeduplicationInfo::goRetry no 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; and InsertDependenciesBuilder::createRetry rejects a retry path whose final view does not belong to the insert chain with a clean NOT_IMPLEMENTED. Covered by the new test 04635_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_range in createPreSink. createRetry now also requires the retry's starting view (start_from) to be owned by the current builder and fails closed with NOT_IMPLEMENTED otherwise. Covered by the new test 04638_deduplication_alias_hop_insert_into_mv, which drives the chain via INSERT INTO a 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 InsertDependenciesBuilder stores its empty root (a regular-table insert) in inner_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. createRetry now 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 test 04639_deduplication_alias_hop_regular_table_root (the same chain as 04638, driven through a regular source table): the partial collision behind the hop is rejected with a clean NOT_IMPLEMENTED and 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

  • Backported to: 26.7.2.40, 26.6.2.145, 26.5.6.102

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

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff6fea4]

Summary: ✅


AI Review

Summary

This PR hardens insert deduplication across an Alias hop by caching token data hashes before original_block is re-anchored, fail-closing retry and partition-attribution paths that no longer have a valid row mapping, and adding focused regression coverage for the previously discussed shapes. I reviewed the current head against the full PR diff, prior review threads, and the current Praktika summary, and I did not find a remaining correctness issue that still merits an inline comment.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
Comment thread src/Storages/StorageAlias.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_tsan) failure (Cannot start clickhouse-server: part all_5_6_1_0 of test_7.t_plt_evict_reinsert intersects a previous part and the transaction metadata could not be read) is unrelated to this PR — it is the known issue #111053, with a fix in progress in #111055. The Stateless tests (amd_llvm_coverage, ...) job errored at the infrastructure level (StopTesting: test run was stopped after 2.5 h with no test results), and LLVM Coverage was dropped as a consequence.

Comment thread src/Storages/StorageAlias.cpp Resolved
… 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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for commit 1eb23f8:

Comment thread src/Storages/StorageAlias.cpp Resolved
alexey-milovidov and others added 3 commits July 21, 2026 19:20
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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for commit b746058: the only red, Stateless tests (amd_asan_ubsan, distributed plan, parallel), was this PR's own test 04613 again — the batched-scenario lines printed 0 0 instead of 1 1, and the run passed 3/3 on rerun in isolation (report). The count trigger 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 — no client-side setting can prevent that. Commit 115ad06 makes the scenario detect the split batch (outputs are not both 1) and retry it, with a bounded 5 s busy-timeout fallback instead of 600 s so a stranded insert of a split attempt cannot hang the test; a regression of the fix still fails every attempt, because a joined flush then never reports NOT_IMPLEMENTED.

Also merged with master (e3bcb4f) and addressed the AI review Blocker on the partition-splitting path in 0cd9617 (see the review thread).

alexey-milovidov and others added 2 commits July 22, 2026 18:54
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for commit 0cd9617 (the 04613/04621 reds were this PR's own batched-async test scenario — inherently racy across two client processes; replaced with a deterministic sync two-token scenario in 02e57e0, see the review threads). The remaining failures are unrelated:

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. This variant fails with:

DB::Exception: Directory 'metadata_dropped' was created concurrently with remote path '...'

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 MetadataStorageFromPlainRewritableObjectStorage* / PlainRewritable transactions path and closed #111289.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for commit 02e57e0: the only red was the CH Inc sync check — Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) on the sync PR aborted with a logical error: a bare std::out_of_range (unordered_map::at: key not found, STID: 1288-3e19) escaped InsertDependenciesBuilder::createRetry while the table behind the alias hop deduplicated a repeated insert. In that environment every table is a SharedMergeTree, which deduplicates by default, so the table behind the alias deduplicates itself — and the deduplication retry looked up the info's visited views (which belong to the outer insert chain) in the nested chain's builder maps. Fixed in f49b961: DeduplicationInfo::goRetry no longer builds the retry chain when all tokens collided and nothing is left to retry (the repeated block is deduplicated cleanly), and createRetry rejects a retry path whose final view does not belong to the insert chain with a clean NOT_IMPLEMENTED. The new test 04635_deduplication_alias_hop_deduplicating_inner reproduces the exact failure stack pre-fix (Code: 1001 ... unordered_map::at: key not found) on a plain MergeTree with a deduplication window behind the alias.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for commit f49b961: public CI was fully green except Stress test (arm_asan_ubsan) — Cannot start clickhouse-server after restart because a fabricated part of test_7.t_plt_rb_contains (from 04241_part_loading_tree_rollback_contains) has corrupted transaction metadata. This is the known unrelated issue #111053, fix open in #111055 (not merged yet, so a master merge cannot clear it).

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 createPreSink escape is only reachable non-deterministically and what the new test 04638_deduplication_alias_hop_insert_into_mv pins instead.

Comment on lines +66 to +68
# 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

@CheSema CheSema Jul 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 CheSema left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

But aside the Alias's architecture decision.
NOT_IMPLEMENTED better than segmentation fault. This PR at least fixed han segmentation fault.

@CheSema
CheSema added this pull request to the merge queue Jul 30, 2026
Merged via the queue into master with commit 6f09e2e Jul 30, 2026
179 checks passed
@CheSema
CheSema deleted the fix/dedup-info-alias-hop-row-drift branch July 30, 2026 11:55
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 30, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 30, 2026
Backport #111103 to 26.7: Cache deduplication data hashes before the Alias hop
robot-clickhouse-ci-1 added a commit that referenced this pull request Jul 31, 2026
Cherry pick #111103 to 26.5: Cache deduplication data hashes before the Alias hop
robot-clickhouse-ci-2 added a commit that referenced this pull request Jul 31, 2026
Cherry pick #111103 to 26.6: Cache deduplication data hashes before the Alias hop
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 31, 2026
alexey-milovidov added a commit that referenced this pull request Aug 1, 2026
Backport #111103 to 26.5: Cache deduplication data hashes before the Alias hop
PedroTadim added a commit that referenced this pull request Aug 3, 2026
Backport #111103 to 26.6: Cache deduplication data hashes before the Alias hop
@alexbakharew

Copy link
Copy Markdown
Contributor

This fix should be backported to 26.2 as well

pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Aug 4, 2026
…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
Blargian pushed a commit to cwurm/ClickHouse that referenced this pull request Aug 4, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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)
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-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

8 participants