Skip to content

Fix "Cannot write to finalized buffer" in MergeTreeDeduplicationLog::rotate - #110429

Closed
alexey-milovidov wants to merge 83 commits into
masterfrom
fix-dedup-log-rotate-finalized-buffer
Closed

alexey-milovidov wants to merge 83 commits into
masterfrom
fix-dedup-log-rotate-finalized-buffer

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #118089 (a minimal reimplementation of the original fix, opened after the review found this pull request too complex)

Fixes a server abort with the logical error Cannot write to finalized buffer that was hit by the stress test.

MergeTreeDeduplicationLog::rotate finalized the current log writer and only afterwards created the writer for the new log file. If creating the new writer threw - a transient I/O error, or, in the CI failure, a memory-tracker fault injection hitting the WriteBufferFromS3 allocation after finalize had already succeeded - current_writer was left pointing at the already finalized buffer while stopped was still false, and the next write to the deduplication log aborted. In the CI failure that write came from the background MergeTreeCleanupThread:

MergeTreeCleanupThread::iterate
-> MergeTreeData::clearEmptyParts
-> StorageMergeTree::dropPartNoWaitNoThrow
-> MergeTreeDeduplicationLog::dropPart
-> writeRecord -> WriteBuffer::write  ->  Logical error: 'Cannot write to finalized buffer'

It reproduces on a disk that does not support writing with append (s3_plain_rewritable), where the deduplication log is rotated on every operation, so a failing writeFile during rotation is easy to hit.

rotate now opens the writer for the new log file first, before any state changes. If that throws, nothing has changed and current_writer still points at the previous, live writer, so the log stays usable and the operation can be retried; only once the new writer is ready is the previous one finalized and swapped out.

Making rotation exception-safe was not enough on its own. A failed write, flush, fsync or rotation used to leave the on-disk log and the in-memory deduplication map describing different states, and every such divergence silently breaks deduplication afterwards: a client retry deduplicated against a part that never committed (dropping the retry's data), or a committed insert forgotten after a restart (duplicating it). The rest of the change closes them:

  • Inserts and drops are all-or-nothing. addPart publishes its block IDs into the in-memory map, and dropPart erases them, only once every record is durable; on any failure both write compensating records and undo their in-memory effect. Publication is split so that nothing which can throw runs after the records are durable.
  • Rolled-back records are cancelled out on replay. Each rollback record is elided together with the exact record it undoes, so a rolled-back operation consumes neither a deduplication-window slot nor a retention budget. The encoding needs no format version: an older server replays every rollback record with the correct net effect - a DROP carrying a reserved part name for a failed insert, a CANCEL carrying the real part name for a failed drop.
  • A rollback-heavy history is compacted rather than grown. Retention can only drop an oldest prefix, so it cannot reclaim the cancelled-out record pairs. Once enough have piled up, the live state - which the in-memory map holds exactly - is rewritten into a single fresh log file and every older file is dropped. This also bounds the history on a disk without append support, where every operation rotates.
  • A history that cannot be repaired fails closed. When the compensating records cannot be persisted and the live state cannot be snapshotted either, a durable marker is armed so that the next start discards the suspect history instead of replaying it; while it cannot be armed, every later operation fails, retryably. Losing at most one deduplication window of best-effort insert deduplication is recoverable; replaying a history known to be wrong is not. A graceful shutdown is the last moment that knowledge exists, so it escalates once more: if neither the snapshot nor the marker can be written, the diverged log files are removed outright, which needs no writable disk and leaves the next start with nothing to replay.
  • A shutdown does not stop the log under an insert that can still roll back. Nothing else quiesces a sink that is inside its part commit with its block IDs already published, and only a running log can cancel their durable records precisely, so the log now waits for every such publication to report its outcome before it stops.
  • The sink rolls its publication back too. MergeTreeSink::commitPart publishes the block IDs before the part becomes active, so when renameTempPartAndAdd or the transaction commit throws it now unpublishes them with the same cancelled-add semantics. The deduplication window is enforced only once the part commit is resolved, so an insert that fails to commit cannot evict an unrelated, already committed block ID from a full window. If deduplication is disabled while such a commit is still in flight, the block IDs it commits are kept until deduplication is re-enabled instead of being evicted by the zero window, so a later repair of the on-disk history from the live state cannot forget an insert that did commit.

Gtests cover each of these paths by injecting writeFile, flush, fsync and unlink failures at the corresponding points, and check the resulting state both in the same process and after reloading the log from disk: that the log stays usable, that a retry of a failed operation is accepted while unrelated committed block IDs keep deduplicating, that a downgraded server replays the rollback records with the same net effect, that the number of retained files and of replayed records stays bounded by the deduplication window rather than by the number of failures, and that a start after a failed compaction discards the suspect history instead of replaying it. The on-disk record definitions were moved into their own header, MergeTreeDeduplicationLogRecord.h, so that the tests also compile against the merge-base sources for the Bugfix validation (unit tests) CI job; the tests that exercise machinery this fix introduces are compiled only when that header is present. Two stateless tests cover the sink-side rollback through the new merge_tree_sink_fail_part_commit_after_dedup failpoint.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a63a425c48d3123d28bef2ad60511c9fc0583468&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_tsan%29

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed a logical error Cannot write to finalized buffer (an abort in debug and sanitizer builds) in the non-replicated MergeTree deduplication log when log rotation fails, for example after a transient I/O error on the deduplication log's disk. Failed deduplication-log writes, flushes, syncs, and compactions now roll back safely, so retries of failed inserts or part drops are not wrongly deduplicated against parts that never committed, committed block IDs are not forgotten after a restart, and rollback-heavy histories are compacted instead of growing without bound.


Workflow [PR]
Sync PR [sync-upstream/pr/110429]

…rotate

`MergeTreeDeduplicationLog::rotate` finalized the current writer and only
then created the writer for the new log file. When creating the new writer
threw (for example a transient I/O error, or an injected memory fault under
a stress test), `current_writer` was left pointing at the already finalized
buffer while `stopped` was still `false`. A subsequent write - in the CI
failure, the background `MergeTreeCleanupThread` calling
`clearEmptyParts` -> `dropPartNoWaitNoThrow` -> `MergeTreeDeduplicationLog::dropPart`
- then wrote to that finalized buffer and aborted with the logical error
`Cannot write to finalized buffer`.

Make `rotate` exception-safe: open the writer for the new log file first,
before touching any state. If that throws, nothing has changed and
`current_writer` still points to the previous, live writer, so the log
stays usable and the operation can be retried. Only after the new writer is
ready do we finalize the previous one and switch over. This preserves the
invariant that `current_writer` is never a finalized buffer.

The failure was hit on a disk that does not support writing with append
(`s3_plain_rewritable`), where the log is rotated on every operation.

Add a gtest that injects a `writeFile` failure during rotation and checks
that the log remains usable afterwards.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a63a425c48d3123d28bef2ad60511c9fc0583468&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_tsan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2271642]

Summary: ✅


AI Review

Summary

This PR substantially hardens MergeTreeDeduplicationLog against write, rotation, compaction, and shutdown failures, and the current head closes the earlier same-version correctness bugs I checked. One compatibility problem remains: the new CANCEL rollback record for failed part drops is still not downgrade-safe for the FIFO order that defines the deduplication window, so a restart on an older binary can accept retries of committed inserts that the live upgraded server would still deduplicate.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeDeduplicationLogRecord.h:14-24] [dismissed by author -- https://github.com/Fix "Cannot write to finalized buffer" in MergeTreeDeduplicationLog::rotate #110429#discussion_r3602364904] The new CANCEL encoding preserves the immediate key set on downgrade, but not the insertion order that drives LimitedOrderedHashMap eviction. A concrete deduplication_window = 2 trace is: commit block1, commit block2, then hit the failed-drop path that leaves DROP block1 followed by CANCEL block1 on disk. The current server keeps the live state as block1, block2, but an older server replays the same history as ADD block1, ADD block2, DROP block1, ADD block1, rebuilding block2, block1. The next committed insert then evicts block2 instead of block1, so a retry of committed block2 is accepted after downgrade even though the upgraded server would still deduplicate it. That is still an on-disk compatibility break, not just a documentation tradeoff.
    Suggested fix: either give failed-drop rollback an encoding older servers ignore exactly, or add an explicit version / incompatibility path for logs containing CANCEL records. The current RollbackRecordsReplaySafelyOnOlderServers coverage only checks membership immediately after replay, not the next eviction choice on the downgraded server.
Final Verdict

I would not approve this as-is because CANCEL records still change deduplication behavior after downgrade on a reachable failed-drop path.

LLVM Coverage Report

Measured on commit 2271642.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 2061/2135 (96.53%) · Uncovered code

Full report · Diff report

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

Address review: making rotate exception-safe kept the log usable, but a
failed rotation still aborted the insert after addPart had already
published the block IDs into deduplication_map, while MergeTreeSink
commits the part only after addPart returns. A client retry of the same
insert was then wrongly deduplicated against a part that never became
active, and the data was silently dropped.

Now publication in addPart is all-or-nothing: if writing a record or the
rotation throws, the already published block IDs are removed from the
in-memory map (which cannot throw), and compensating DROP records are
written to the still-live writer (best effort) so that replaying the log
on server startup does not re-publish them either.

The gtest now verifies that a retry of the failed insert is accepted and
only then deduplicates as usual, both within the same process and after
a reload of the log from disk.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CI failures on e5101ad are unrelated to this change:

…DROP records

The previous rollback in `addPart` wrote compensating `DROP` records
directly to `current_writer` after a failure, assuming it was still a
live writer. That only holds when the failure came from `rotate` inside
`rotateAndDropIfNeeded`. If instead one of the `ADD` records itself
failed to write, `WriteBuffer::next()` cancels the buffer on any
`nextImpl` exception, so `current_writer` is left canceled and refuses
any further writes - the compensating `DROP` records were silently lost,
and after a restart a retry of the failed insert could be wrongly
deduplicated against a part that never became active.

Rotate to a fresh writer whenever `current_writer` is canceled before
writing the compensations. `rotate` already tolerates an already
canceled `current_writer` (it only logs when finalizing it fails) and
unconditionally opens a new log file, so this is also safe - if
redundant - when `current_writer` is still the live writer from before
the failed `rotate` call.

Two new gtests inject the failure into a `next()` call on the currently
open writer (as opposed to the existing tests, which inject it into
`writeFile` while opening a new one for rotation), covering both the
in-process retry and the reload-from-disk replay after a restart.
`rotate`'s rollback path called `WriteBuffer::finalize` on `current_writer`
unconditionally, but by the time `addPart`'s rollback calls `rotate` after a
canceled write, `current_writer` is already canceled. `finalize` disallows
calling it on an already-canceled buffer and throws a `LOGICAL_ERROR`, which
aborts the process immediately in debug and sanitizer builds - before the
surrounding `try`/`catch` even runs. This turned the previous fix for the
canceled-writer rollback case into a new abort, caught by the CI's own gtests
added for that fix (`MergeTreeDeduplicationLog.WriteFailureRollsBackPublishedBlockIds`
aborted with `SIGABRT` in the `asan_ubsan`/`tsan`/`msan` unit test jobs).

`rotate` and `shutdown` now skip `finalize` when `current_writer` is already
canceled, since a canceled buffer has nothing left to flush or sync anyway.
`addPart`'s all-or-nothing rollback only erased the block IDs the failing
call had itself published into `deduplication_map`, but `LimitedOrderedHashMap::insert`
evicts the oldest entry once the map is at capacity - and that eviction was
never undone. With a small deduplication window, a failed insert could
therefore evict an unrelated, already-active part's block ID from memory;
a retry of that unrelated block ID would then be wrongly accepted instead of
deduplicated, until the log was replayed from disk on the next restart.

`addPart` now defers every `deduplication_map.insert` call until the durable
writes and the rotation that follows them have both succeeded, so the
in-memory map is never mutated on a path that might still need to roll back.
Added a gtest that fills the map, injects a rotation failure on the next
insert, and verifies the previously committed block ID still deduplicates.
…rom rotate

`rotate` logged and suppressed exceptions from `finalize`/`sync` of the
previous log file's writer. But `rotateAndDropIfNeeded` is the success
boundary of `addPart`: if the just-written `ADD` records never reached
durable storage, `addPart` still published the block IDs and `MergeTreeSink`
committed the part, so after a restart the deduplication log forgot a
committed insert and a client retry of the same block was wrongly accepted,
duplicating the data.

Now `rotate` rethrows the failure after switching over to the new writer
(so the log itself stays usable), `addPart` treats the insert as failed and
writes compensating `DROP` records into the new log file during its rollback,
and the caller aborts the insert instead of committing the part.

Two new gtests inject an fsync failure into the old writer's `sync` during
rotation and check that the insert fails, is retryable in-process, and stays
rolled back after replaying the logs across a restart; both fail without the
fix and pass with it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…pping them

A review finding: the rollback of a failed insert wrote compensating
`DROP` records, which fix the final presence of the rolled-back block on
replay but not the deduplication window. On restart, `loadSingleLog`
still replays the failed insert's `ADD` record before the compensating
`DROP`, and `LimitedOrderedHashMap::insert` evicts the oldest committed
block once the map is full. With `deduplication_window = 1`, a committed
`block1` followed by a failed insert of `block2` replays as `ADD block1`,
`ADD block2`, `DROP block2` and ends with an empty map, so after a
restart a retry of `block1` is wrongly accepted and its data duplicated.
Larger windows drop the oldest committed block the same way.

Rolled-back inserts are now written with a new `CANCEL` record (op 3)
instead of `DROP`. Replay is done in two passes: each `CANCEL` first
cancels the matching preceding `ADD` and both are skipped, then the
surviving `ADD`/`DROP` records are applied exactly as they happened live.
A rolled-back insert therefore never touches the in-memory map on replay
and consumes no deduplication-window slot, so replay reconstructs the
same state as live memory.

New gtests `RotationFailureDoesNotEvictUnrelatedBlockIdsAfterRestart` and
`RotationSyncFailureDoesNotEvictUnrelatedBlockIdsAfterRestart` reproduce
the reviewer's `deduplication_window = 1` scenario across a restart;
verified they fail without the `CANCEL` change and pass with it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The remaining CI red on 9f29a69d is unrelated to this change: the Stress test (amd_tsan) failure Logical error: Block structure mismatch in A stream: different columns is an AST-fuzzer finding in UnionStep::updateOutputHeader during executeASTFuzzerQueries (query planning), with nothing touching the deduplication log. It is already tracked as #107953 (and the CI auto-labels it as such).

A sixth review finding on the previous fix: rolled-back inserts are written
with `CANCEL` records so that a replay cancels each `CANCEL` against its
matching preceding `ADD` and consumes no deduplication-window slot. But log
retention (`dropOutdatedLogs`) decides which older log files are redundant by
summing each file's `entries_count` - the raw number of records written to it -
from the newest backwards until the deduplication window is covered.

A cancelled `(ADD, CANCEL)` pair contributes nothing to the reconstructed
in-memory map, yet each of its records still inflated `entries_count`. So a
failed multi-block insert could make retention treat those transient records as
consumed deduplication-window slots and drop an older log that still held live,
committed block IDs. With `deduplication_window = 2`, committed `block1` /
`block2` in the first log and a failed `addPart({"block3", "block4", "block5",
"block6"}, ...)` whose rollback wrote four `CANCEL`s into the second log: the
first restart rebuilt `{block1, block2}` correctly but, seeing the inflated raw
counts, rotated and dropped the first log; a second restart then replayed only
the `CANCEL`-only log and forgot `block1` / `block2`, wrongly accepting - and
duplicating - a retry of those committed inserts.

Retention accounting is now based on the records that survive cancel-pair
elimination:

- On replay, `applyRecords` recomputes each log's `entries_count` from only the
  non-cancelled records (`record_log_numbers` maps each record back to its
  file), so the count matches what a replay actually reconstructs. `load` and
  `loadSingleLog` are adjusted to collect the per-record log numbers.
- On the live rollback path, `addPart` undoes the retention count of the
  rolled-back `ADD` records (always written to the log that was current when the
  insert started) and does not count the `CANCEL` records, so the in-memory
  accounting stays consistent with a replay even before any restart.

New gtest `RotationSyncFailureRetainsCommittedLogsAfterTwoRestarts` reproduces
the reviewer's exact scenario (`deduplication_window = 2`, four block IDs, an
injected `sync` failure) and restarts twice; it fails without this change
(the committed blocks are forgotten after the second restart) and passes with
it. All ten deduplication-log gtests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`MergeTreeDeduplicationLog::dropPart` used to write a `DROP` record, erase
the block id from the in-memory map, and run `rotateAndDropIfNeeded` for
each covered block id, one at a time. Since `rotate` now rethrows a failure
to finalize or fsync the previous log file (so `addPart` can trust that
durability boundary), a multi-block drop can throw partway through, after
some block ids have already been erased but before the rest are - leaving
the map in a partial state. The caller `StorageMergeTree::dropPartNoWaitNoThrow`
has already taken the part out of the active set and never retries the drop,
so the remaining block ids stay published against a part that no longer
exists, and any non-durable `DROP` records resurrect the erased ids after a
restart.

Make `dropPart` transactional like `addPart`: collect every covered block
id first, write all the `DROP` records, rotate, and only then erase the
block ids from the map. If any write or the rotation throws, no block id is
erased, so a failed drop leaves every covered block id published (the
deduplicating, safe direction) instead of a half-applied mixture.

Add gtest `DropPartRotationSyncFailureIsAllOrNothing`, which drops a range
covering two block ids while injecting an fsync failure into the rotation
the first `DROP` triggers. It reproduces the reviewer's scenario: the old
code erased the first block id before the rotation threw, so a retry of it
was wrongly accepted; the transactional version keeps both published.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`dropPart` wrote its `DROP` records one flush at a time (`writeRecord`
flushes every record), so a write failure partway through a multi-block
drop left a durable prefix of `DROP` records on disk with no rollback,
while no block id had been erased from the in-memory map. After a
restart, replaying that prefix erased only part of the failed drop: a
block id whose `DROP` record reached the disk stopped deduplicating
while its siblings still did - a half-applied drop that matches neither
the live map nor a completed drop, and that the caller
`StorageMergeTree::dropPartNoWaitNoThrow` never repairs. Worse, the
failed write left `current_writer` canceled, and a canceled buffer
silently discards all further writes, so the `ADD` records of later,
successfully committed inserts never reached the disk either and those
inserts were forgotten after a restart, wrongly accepting and
duplicating their retries.

`dropPart` now mirrors `addPart`'s rollback: on any failure it writes a
compensating `CANCEL` record for each `DROP` record that was written
(rotating to a fresh writer first when the failed write canceled the
current one) and undoes their retention count. Replay pairing in
`applyRecords` is extended accordingly: a `CANCEL` cancels the most
recent preceding un-cancelled `ADD` or `DROP` of the same block id, so
a failed drop keeps every covered block id published both live and
across a restart, and the log stays usable and durable afterwards.

The new gtest `DropPartWriteFailureIsAllOrNothingAfterRestart` fails
the write of the second of two `DROP` records and verifies - both live
and after reloading the log on a restart - that neither covered block
id is forgotten and that a record written after the failed drop is
durable. It fails without this fix and passes with it.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CI failure on 965f853 in Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) (report) is unrelated to this change: the server died with the logical error Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64' in 03915_exchange_tables_race.sh — the known race between EXCHANGE TABLES and SELECT, tracked in #110133, with a fix in progress in #110048. Nothing in that failure touches the deduplication log.

…m correctly

The rollback of a failed insert was persisted as a new `CANCEL` operation
that a server from before this change replays as an insert: after a
downgrade with such records on disk, the never-committed block id stayed
published, and a client retry of the failed insert was wrongly
deduplicated - silently dropping its data.

Write it as a plain `DROP` record carrying the reserved part name `cancel`
instead (the part name of a `DROP` record is never parsed, on any server
version, and `cancel` can never collide with a real part name): an older
server replays it as the erase that unpublishes the never-committed block
id, so a retry of the failed insert is accepted, while replay in this code
recognizes the marker and cancels the (ADD, DROP) pair out entirely,
keeping the deduplication-window and retention guarantees. `CANCEL`
remains only as the rollback of a failed drop, where it carries the real,
parseable part name, so an older server replays it as the insert that
restores the still-published block id - the rollback's intended net
effect, with only the entry's position in the eviction order diverging.

A new gtest replays the on-disk logs left behind by a rolled-back insert
and a rolled-back drop with the exact pre-change replay logic and verifies
both downgrade properties.
alexey-milovidov and others added 2 commits July 18, 2026 05:38
`MergeTreeDeduplicationLog::rotate` finalized the previous writer and only
then registered the new log file with `existing_logs.emplace`. `std::map::emplace`
allocates a node and can throw; if it did, the old writer had already been
finalized while `current_writer` still pointed at it, so the next `writeRecord`
from `addPart` or `dropPart` aborted with the very "Cannot write to finalized
buffer" logical error this pull request eliminates - and no rollback path could
recover, because the buffer is finalized, not canceled, so `isCanceled` returns
false.

Register the new log file before finalizing the old writer, so the only
remaining throwing bookkeeping step runs while the old writer is still live and
usable. The switch-over to the new writer (an integer store and a `unique_ptr`
move) is non-throwing, so once the bookkeeping has succeeded the rotation always
completes; if it throws, `emplace` has no effect and the log stays fully usable
and the operation retryable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ability

`addPart` deferred `deduplication_map.insert` until after the ADD records were
durable, to keep a rollback from having to undo an eviction. But that insert is
itself a throwing step running after durability: `LimitedOrderedHashMap::insert`
allocates a `std::list` node and an `unordered_map` entry, and it evicts the
oldest entry once the map is full before it inserts. If the allocation threw, the
ADD records were already durable but `addPart` propagated an exception, so the
caller aborted the insert without writing compensating rollback records - and a
retry could then be deduplicated against a part that never committed, silently
dropping the retry's data. In the window-full case the throw also left an
unrelated, still-active block id evicted from the live map.

Split publication so that nothing which can throw runs after the records are
durable:

- `LimitedOrderedHashMap::insertWithoutEviction` inserts a new entry without
  enforcing the size limit. This is the only part of publishing that allocates,
  it is strongly exception-safe (on failure the map is left exactly as it was),
  and it never evicts - so a rollback needs only `erase`, which never allocates
  and never drops an unrelated entry.
- `LimitedOrderedHashMap::trimToMaxSize` evicts the oldest entries down to the
  limit. It only pops entries, so it never allocates and cannot throw. `insert`
  and `setMaxSize` are expressed in terms of these two primitives, so their
  observable behavior is unchanged.

`addPart` now inserts the block ids without eviction before the durable writes
(a failure there aborts with nothing on disk and is rolled back by a
non-throwing `erase`), and enforces the deduplication window with
`trimToMaxSize` only after the writes and the rotation have both succeeded -
where the insert could no longer be rolled back.

Adds a unit test for the new `LimitedOrderedHashMap` primitives and a regression
test that a successful multi-insert still enforces the deduplication window
(evicting the oldest block id) exactly as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits August 23, 2026 05:17
…abled

The AI review found that `rollbackPublishedPart` handled a zero deduplication
window - `ALTER TABLE ... MODIFY SETTING non_replicated_deduplication_window = 0`
landing between the publication in `addPart` and the failing part commit - by
skipping the rollback records and reporting the rollback as compensated. But the
`ADD` records of the published block ids were written while the window was still
non-zero, so they stayed durable, uncancelled and unfenced: a later start with
deduplication re-enabled replayed them and silently deduplicated - and dropped -
the retry of the insert that never committed.

Leave the rollback uncompensated in that case instead, so it repairs the on-disk
history from the live state or fences it off, the same way `unpublishFailedPart`
already handled a zero window. The new gtest drives the publication, the ALTER,
the rollback and a restart, and was verified to fail without the fix and pass
with it.

#110429

Co-Authored-By: Claude Fable 5 <[email protected]>
clang-tidy's `bugprone-bool-pointer-implicit-conversion` rejects testing a
`bool *` directly in a condition whose branch never dereferences it, which
failed `Build (arm_tidy)`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110429&sha=27d3b10a5a04785379b2fd8f8f3e0ead411aeb38&name_0=PR&name_1=Build%20%28arm_tidy%29

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
`discardHistoryAfterUnfinishedCompaction` wipes `block_id_log_numbers`
together with the on-disk files, so running it from the re-enable path of
`setDeduplicationWindowSize` while an in-flight insert still holds published
block ids left those ids alive only in `deduplication_map`, out of sync with
every other structure: their commit was forgotten by the next restart, and a
later rollback, drop, or eviction of such an entry looked up a log number
that no longer existed (compaction, for one, requires every map entry to
have one). Fail closed instead: the `ALTER` throws and can be retried once
the in-flight inserts have reported their outcome.
`RollbackCompensatesEveryBlockIdOfFailedInsert` covers both sink rollback
flavors (`rollbackPublishedPart` and `unpublishFailedPart`) with an insert of
two block ids, asserting every one of them becomes retryable - in-process and
across a restart - while an unrelated committed block id keeps deduplicating.

`ReenablingWithInFlightPublicationFailsClosed` pins the new guard: re-enabling
deduplication while the unfinished-compaction marker is active and an insert
is still in flight fails closed, and the retried `ALTER` after the commit
rewrites the live state - preserving the committed block id across a restart -
instead of discarding it. Verified to fail without the guard (the `ALTER`
does not throw, and the block id committed in flight is forgotten by the
restart).
…hutdown

`shutdown` can be rejected by `MergeTreeDeduplicationLog::shutdown` before it
has stopped anything. The destructor swallowed that exception and proceeded
to member destruction, which runs in reverse declaration order and destroys
`deduplication_log` before `cleanup_thread`; a cleanup pass still scheduled
could then reach the destroyed log through `dropPartNoWaitNoThrow`. Stop the
refresh tasks, the outdated-parts loading task, the assignees, and the
cleanup thread explicitly before member destruction begins; every call is
idempotent after a successful shutdown.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both red jobs on 445955bf0acf are unrelated to this pull request, and the branch has now been merged with master (f32c5a879b75):

Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…ublications resolve, and make the shutdown fence durable

Two shutdown-path findings from the review.

1. `StorageMergeTree::shutdown` stopped the deduplication log before the insert
sinks were quiesced. Nothing waits for a `MergeTreeSink` that is already inside
`commitPart` after `addPart` published its block ids - `Context::shutdown` kills
the running queries and proceeds straight into `DatabaseCatalog::shutdown` - so
that sink could still fail its commit with the log already stopped, where
`rollbackPublishedPart` can no longer write the compensating records and falls
back to fencing the whole history off. If the fence could not be persisted
either, the durable `ADD` records were left with nothing to cancel them and the
retry of the failed insert was deduplicated away after a restart.

`MergeTreeDeduplicationLog::shutdown` now waits for every two-phase publication
to be resolved by its caller (`finishPartPublication` signals it) before it stops
the log, and `StorageMergeTree::shutdown` stops the log last, after the
background operations that write to it are finished. The wait is bounded by the
commit step itself, which renames the part and commits the transaction under the
parts lock.

2. Rejecting the shutdown when the history diverged and the discard marker could
not be written did not make it retryable: `DatabaseWithOwnTablesBase::shutdown`
logs the failure and releases the table regardless, and destructors swallow it.
The process-local knowledge that the history must not be replayed therefore has
to become durable during that shutdown or not at all.

Instead of the illusory retry contract, the shutdown now escalates to removing
the diverged log files themselves, which needs no writable disk - a full or
read-only-quota'd disk commonly rejects creating and flushing a file while still
allowing an unlink - and leaves the next `load` with nothing to replay, exactly
what the marker was meant to arrange. Only if unlinking fails too does the
shutdown complete with a loud error naming the directory to remove by hand,
because at that point nothing in the process can make the next start safe.

Three gtests in `src/Storages/tests/gtest_merge_tree_deduplication_log.cpp`
cover it: `ShutdownWaitsForInFlightPublications` (the precise rollback survives
a concurrent shutdown, so a committed block id keeps deduplicating while the
rolled-back one is retryable after a restart),
`UnfenceableDivergedHistoryIsDiscardedAtShutdown` and
`UnfenceableAndUnremovableDivergedHistoryCompletesShutdown`. The first two fail
against this branch without the fixes; all 53 deduplication-log gtests pass with
them.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status for f32c5a879b75: the only red job was Stress test (arm_msan) with MemorySanitizer: use-of-uninitialized-value (STID: None), whose whole report is MemorySanitizer: nested bug in the same thread, aborting. with no stack at all — the symbolizer aborts on a nested MSan report and every frame is lost. It is unrelated to this PR: the same signature fired on master (pull_request_number = 0) and on unrelated pull requests #115393, #110211, #105848, #43449 over the last week (CIDB), and it is the failure mode described in #106591. Fixes are in flight in #112008 (keep the stack when an async signal arrives during an MSan report) and #113107 (disable the sampling query profiler under MSan); neither is merged yet, so a base merge cannot clear it.

Master merged (e03e927ad636, no conflicts) and both AI-review blockers on the shutdown path addressed in f1e40679358a — see the two review threads.

@groeneai, the MSan nested-report red above is yours in #112008; please link the follow-up here once it lands.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

#112008 is the follow-up, and I will link it here when it merges.

It is still open because its gate is the library-side change it pins: contrib/llvm-project in #112008 points at the head of ClickHouse/llvm-project#118, and that pin has to be re-pointed at a commit on ClickHouse/release-22.x before #112008 can merge. #118 is clean and mergeable but has had no review since it was opened on 2026-07-27. The conflict currently shown on #112008 is only that submodule pin against master's newer one, and the re-point rewrites it anyway (@ nickitat routed the resolution to Copilot on 2026-08-12).

One expectation to set for when it lands: it does not stop this job from failing. The underlying uninitialized read still fires, it just arrives with a stack and a real STID instead of a one-line report, which is what makes it attributable at all.

…-flight part commit resolves

`finishPartPublication` enforced the deduplication window as soon as the outcome of
an insert was known. If deduplication had been disabled in the meantime (`ALTER ...
MODIFY SETTING non_replicated_deduplication_window = 0`), the zero window evicted
exactly the block ids this commit had just made durable, at the very moment their
bookkeeping stopped being needed for a rollback. When the on-disk history had been
fenced off (a rollback could not persist its records), the re-enabling `ALTER`
repaired the history from that live state and durably forgot an insert that did
commit, so a retry of it was accepted again.

Keep the block ids of publications that resolve under a zero window until
deduplication is re-enabled, which enforces the new window, or the log is shut
down. Nothing else is published under a zero window, so the map cannot grow beyond
the inserts that were in flight when deduplication was disabled.

Tests: `CommitResolvedWhileDisabledKeepsDeduplicating` (healthy disk, in-process)
and `CommitResolvedWhileDisabledSurvivesHistoryRepair` (fenced history, in-process
and after a restart) in `gtest_merge_tree_deduplication_log.cpp`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status of f1e40679358a (2026-09-01): every red job is unrelated to this PR.

The remaining AI-review blocker (window enforcement in finishPartPublication under a zero window) is addressed in the commit pushed together with the master merge; see the reply in the review thread.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

The lookup was genuinely broken and the fix is already merged: #117580 (@ fm4v, merged 2026-09-01T22:06:23Z, merge commit 41b739a45086). It inserts Utils.normalize_string("MasterCI") into the master-artifact S3 URL in ci/jobs/scripts/bugfix_validation.py, which went stale when master build artifacts moved under a normalized-workflow-name path segment (REFs/master/<sha>/masterci/build_<bt>/clickhouse).

The run you linked is a pre-fix arm, established per tree rather than from the clock: those two jobs started 2026-09-01 10:52:47Z (aarch64) and 10:53:28Z (amd64), 11h13m before #117580 merged, and a content probe at f1e4067 counts normalize_string("MasterCI") 0 times with both controls valid (0 at the pre-fix parent 695469d13cd1, 1 at 41b739a45086).

Your master merge at 2271642 already carries it, and both functional jobs passed on that head today: aarch64 19:12:46Z, amd64 19:20:20Z.

The lookup is not broken now, so I am not opening a separate PR. CIDB has 3945 Bugfix validation% rows today with 0 carrying the assert (latest row 20:07:01Z, so the window is not empty). The last hit anywhere was 2026-09-02 13:10Z, and both of the final two trees probe 0, i.e. pre-fix arms rather than a live failure.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The complexity is staggering. Let's see what we can do.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Two measurements, in case they help with what to cut.

CIDB has three occurrences of this logical error in 180 days, and every one is writeRecord (MergeTreeDeduplicationLog.cpp:46) writing into a dead writer while stopped is still false:

  • master a63a425c48d3, the report in the description: finalized, dropPart:324 from MergeTreeCleanupThread;
  • an unrelated pull request, 2026-08-14, Stress test (arm_debug): canceled, addPart:281 under MergeTreeSink (report);
  • an unrelated pull request, 2026-09-02, Upgrade check (amd_release): finalized, dropPart:324 again (report).

Those are the only rows in the window where either buffer signature carries a deduplication-log frame.

The middle one names a second producer of that state, and it is not rotate: WriteBuffer::next calls cancel() in its generic catch and rethrows (src/IO/WriteBuffer.h:71), so a single failed flush inside writeRecord leaves current_writer non-null, canceled, with stopped still false, and chassert(current_writer != nullptr) at :271 and :309 cannot see that. The repair idiom is already in the file twice, at :143 and :361 (if (!current_writer), reopen with WriteMode::Append); widening that predicate from null to null-or-dead and running it at the two write entry points covers both producers, which is every row above.

That version concedes the un-flushed tail, so best-effort deduplication for one window. The file concedes it already: the pre-existing rotate catch logs lost recods and continues on a fresh writer (:181). The rest of the branch buys the strictly stronger property of no divergence between the log and the in-memory map, whose symptom is a wrongly deduplicated retry rather than a logical error, so CIDB holds no evidence either way.

If the two split, the small half is what pr-critical-bugfix and pr-must-backport are for, and it ports unchanged: MergeTreeDeduplicationLog.cpp is the same blob on 26.6, 26.7 and 26.8 as on master, and 26.3 differs from master only in two unrelated default initializers.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks for tracing it. Confirmed on this side: both Bugfix validation jobs are green on 227164242014, which carries the fix from #117580 through the master merge, so nothing further is needed for that item.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, this is exactly the data needed for the split.

The small half now exists as #118089: rotate opens the next log before finalizing the current one, and a rotation failure after the records are written no longer fails the operation. That covers the first producer in your list, a writer finalized by a failed rotate, which is both dropPart:324 rows.

Your second producer, a writer canceled by a failed flush inside writeRecord (the addPart:281 row), is not covered by the reordering alone, since chassert(current_writer != nullptr) cannot see a canceled buffer. The null-or-dead reopen at the two write entry points is the remaining piece of the minimal fix, and it belongs to the design discussion on #118089 rather than here. It concedes the un-flushed tail, as you say; this PR instead keeps the log and the in-memory map from diverging at all, which is where the extra machinery comes from.

Which of the two lands is left for human review. I added a Related: link to #118089 in the description; #118089 already links back here. The pr-critical-bugfix and pr-must-backport labels are for the small half, if that is the one chosen.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

#112008 merged in 8c57ab8. An async signal that arrives during an MSan report no longer cuts it down to the one-line nested bug in the same thread message, so these reports keep their stack and get a real STID.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants