Repository navigation
Fix "Cannot write to finalized buffer" in MergeTreeDeduplicationLog::rotate - #110429
alexey-milovidov wants to merge 83 commits into
Conversation
…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]>
|
Workflow [PR], commit [2271642] Summary: ✅
AI ReviewSummaryThis PR substantially hardens Findings❌ Blockers
Final VerdictI would not approve this as-is because LLVM Coverage ReportMeasured on commit 2271642.
Changed lines: Changed C/C++ lines covered: 2061/2135 (96.53%) · Uncovered code |
…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.
…e-finalized-buffer
|
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.
…e-finalized-buffer
`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]>
|
The remaining CI red on |
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.
|
The CI failure on 965f853 in |
…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.
`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]>
…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]>
`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.
…e-finalized-buffer
|
🕵 Both red jobs on
|
…e-finalized-buffer
…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.
|
🕵 CI status for Master merged ( @groeneai, the MSan nested-report red above is yours in #112008; please link the follow-up here once it lands. |
|
#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: 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. |
…e-finalized-buffer
…-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`.
|
🕵 CI status of
The remaining AI-review blocker (window enforcement in |
|
The lookup was genuinely broken and the fix is already merged: #117580 (@ fm4v, merged 2026-09-01T22:06:23Z, merge commit 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 Your master merge at The lookup is not broken now, so I am not opening a separate PR. CIDB has 3945 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The complexity is staggering. Let's see what we can do.
|
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
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 That version concedes the un-flushed tail, so best-effort deduplication for one window. The file concedes it already: the pre-existing If the two split, the small half is what |
|
🕵 Thanks for tracing it. Confirmed on this side: both |
|
🕵 Thanks, this is exactly the data needed for the split. The small half now exists as #118089: Your second producer, a writer canceled by a failed flush inside Which of the two lands is left for human review. I added a |
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 bufferthat was hit by the stress test.MergeTreeDeduplicationLog::rotatefinalized 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 theWriteBufferFromS3allocation afterfinalizehad already succeeded -current_writerwas left pointing at the already finalized buffer whilestoppedwas stillfalse, and the next write to the deduplication log aborted. In the CI failure that write came from the backgroundMergeTreeCleanupThread: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 failingwriteFileduring rotation is easy to hit.rotatenow opens the writer for the new log file first, before any state changes. If that throws, nothing has changed andcurrent_writerstill 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:
addPartpublishes its block IDs into the in-memory map, anddropParterases 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.DROPcarrying a reserved part name for a failed insert, aCANCELcarrying the real part name for a failed drop.MergeTreeSink::commitPartpublishes the block IDs before the part becomes active, so whenrenameTempPartAndAddor 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 theBugfix 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 newmerge_tree_sink_fail_part_commit_after_dedupfailpoint.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):
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-replicatedMergeTreededuplication 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]