Skip to content

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

Merged
alexey-milovidov merged 2 commits into
masterfrom
fix-dedup-log-rotate-exception-safety
Sep 5, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
fix-dedup-log-rotate-exception-safety

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Related: #110429

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

MergeTreeDeduplicationLog::rotate finalized the writer of the current log and only then opened the writer for the next log. When opening the next log threw (a transient I/O error, or, in the CI failure, a memory-tracker fault injection hitting the WriteBufferFromS3 allocation), current_writer was left pointing at a finalized buffer, and the next write to the deduplication log failed with the logical error. In the CI failure that write came from the background MergeTreeCleanupThread calling dropPart.

Now rotate opens the writer for the next log before touching any state. If that throws, the current writer is still live and the log stays usable. Only after the new writer is ready, the old one is finalized and swapped out; nothing after that point can throw.

In addition, a failure of the rotation that follows addPart or dropPart no longer fails the operation. Its records are already written and applied to the in-memory map at that point, so reporting the failure would make the insert fail after its block IDs were published, and a retry of the insert would be wrongly deduplicated against a part that never became active. Rotation is housekeeping; the failure is logged and the rotation is retried on the next operation.

This is a minimal reimplementation of #110429, which grew far beyond the original defect.

A unit test injects a failure into the writeFile call of the rotation and checks that the insert which triggered it succeeds, that the log keeps accepting records and rotates successfully afterwards, and that the records written around the failed rotation are replayed on reload.

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):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 opening the next log file during rotation failed, for example after a transient I/O error on the deduplication log's disk. Such a failure no longer fails the insert that triggered the rotation, so a retry of that insert is not wrongly deduplicated.


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

…rotate

`MergeTreeDeduplicationLog::rotate` finalized the writer of the current log
and only then opened the writer for the next log. When opening the next log
threw (a transient I/O error, or a memory-tracker fault injection in the
stress test), `current_writer` was left pointing at a finalized buffer, and
the next write to the deduplication log failed with the logical error
`Cannot write to finalized buffer`.

Now `rotate` opens the writer for the next log before touching any state.
If that throws, the current writer is still live and the log stays usable.
Only after the new writer is ready, the old one is finalized and swapped out.

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 Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [396922a]

Summary: ✅


AI Review

Summary

This PR fixes the immediate Cannot write to finalized buffer exception in MergeTreeDeduplicationLog::rotate by opening the next segment before finalizing the current one, and it changes post-write rotation failures into logged housekeeping errors. The first part is correct, but the new non-fatal path breaks the dedup-log durability contract on non-append object-storage disks: a successful addPart or dropPart can now disappear after restart if opening the next segment fails.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeDeduplicationLog.cpp:247-251] rotateAndDropIfNeededAfterWrite assumes the record is already safely persisted once writeRecord returns, but that is not true for the non-append object-storage path that uses WriteBufferFromS3. supportWritingWithAppend(disk) is false there, so every operation rotates immediately; if opening the next segment throws, the code now returns success with the current segment still unfinalized. A restart before the next successful rotation or shutdown() can therefore lose the just-committed ADD/DROP record on reload, so deduplication forgets a successful insert or a part drop. Suggested fix: use a separate path for non-append object-storage disks that still guarantees the current segment is finalized before success is reported, or keep the failure fatal there and pair it with rollback of the published dedup state.
Tests
  • ⚠️ The new DiskLocal unit test only proves the append-capable local-file path. Add a focused regression test with a non-append writer that buffers data until finalize (a small fake disk/writer is enough) and verify that a failed rotation after addPart and after dropPart is either reported as failure or still survives load() after restart.
Final Verdict

❌ Not ready to merge.

LLVM Coverage Report

Measured on commit 396922a.

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

Changed lines: Changed C/C++ lines covered: 51/53 (96.23%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 4, 2026
…fails

The records of `addPart` and `dropPart` are already written and applied
to the in-memory map when the log is rotated, so reporting a rotation
failure as a failure of the operation is wrong: for an insert, the block
IDs stay published for a part that never became active, and a retry of
the insert is wrongly deduplicated. Rotation is housekeeping, and it is
retried on the next operation, because `rotate` now leaves the state
untouched when it fails.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed in 396922a: a failure of the rotation that follows addPart or dropPart is now logged and retried on the next operation instead of failing the operation whose records are already written, and the test checks that the insert which triggers the failing rotation succeeds and deduplicates afterwards, both in the same process and after a reload.

The rollback alternative is what #110429 does, and it is out of scope here on purpose: the same publish-before-commit window exists for any failure between addPart and the part commit (an I/O error inside writeRecord, or renameTempPartAndAdd throwing), and it is not introduced by this change.

Comment on lines +247 to +251
/// The records are already written and applied to the in-memory map, so failing here would
/// report an operation that has actually succeeded as failed. For an insert this means that the
/// block IDs stay published for a part that never became active, and a retry of the insert
/// would be wrongly deduplicated. Rotation is only housekeeping, and it is retried on the next
/// operation, because `rotate` leaves the state untouched when it fails.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

On append-capable local files this is fine, but it is not safe on the object-storage path that motivated the PR. supportWritingWithAppend(disk) is false for DiskObjectStorage, so every addPart/dropPart immediately calls rotate. In that configuration writeRecord has only flushed into the still-open WriteBufferFromS3; nextImpl can keep small writes buffered in memory and does not make them durable until the writer is finalized.

If disk->writeFile for the next segment throws here, we now log and return success with the current segment still unfinalized. A restart before the next successful rotation or shutdown() loses the just-committed ADD/DROP record on reload, so deduplication can forget a successful insert or a part drop. That is a correctness regression from the old behavior, which forced this segment to be finalized before the operation returned.

This needs a non-append-object-storage-specific path: either keep the failure fatal there and do the heavier rollback fix, or otherwise guarantee the current segment is finalized/durable before addPart/dropPart can report success. The current DiskLocal test does not cover this buffering behavior.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 396922af0 with master bb1a20e15 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of da918ab89; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

20 translation units recompiled, 157 s compile time in total, 20 of them have a recent master baseline.

Job report

@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 5, 2026

Copy link
Copy Markdown
Collaborator

The remaining piece is already written, as a draft: #102215 (@ vitlibar) replaces both chassert(current_writer != nullptr) calls with an on-demand initCurrentWriter() at exactly the two write entry points. It also picks the mode from disk_supports_writing_with_append instead of always appending, which corrects what I wrote on the other thread: the two existing reopen sites hardcode WriteMode::Append and are only reachable when rotate did not run, so copying them verbatim would be wrong on a disk without append support.

It does not cover the addPart:281 row either, and the reason is a single predicate: initCurrentWriter opens with if (current_writer) return;. A canceled buffer is non-null, so master, this branch and #102215 all end at the same throw. On this branch: writeRecord at :303 reaches out.next() at :51, WriteBuffer::next calls cancel() at WriteBuffer.h:71 and rethrows, and a later write into that same buffer throws at WriteBuffer.cpp:67, having passed addPart:293. For dropPart it is :346 and :331.

The 2026-08-14 report only shows that second half, because the cancel belongs to an earlier call: it aborts at WriteBuffer.cpp:67 under writeChar at :46, writeRecord, addPart, MergeTreeSink::commitPart. That is why the row reads like a rotate victim at first glance, and it is the only one of the three that is not.

So the increment is null to null or dead, and isCanceled and isFinalized are public at WriteBuffer.h:107-108. It concedes the records lost with the canceled buffer, as noted. One thing worth knowing before counting #102215 as covering this: it is scoped to a different trigger (#86189, a mixed-metadata storage policy) and marked not for changelog because its own logical error is unreachable on master, so the canceled row is outside what it currently claims to fix.

No preference between the two from me: they touch the same lines in rotate and at both entry points, and they disagree on whether rotate's catch leaves current_writer null, so whichever lands first, the other needs rebasing on it.

@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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 7e64d44 Sep 5, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-dedup-log-rotate-exception-safety branch September 5, 2026 12:59
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
…getree

Resolves the conflict in `MergeTreeDeduplicationLog.cpp` with #118089, which
landed on `master` twenty seconds before the previous merge here, so the
pull request has been conflicting all day and no CI ran on today's commits.

The two sides change the same three places for unrelated reasons and are kept
together:

- `master` added `rotateAndDropIfNeededAfterWrite`, which swallows a rotation
  failure after the records of `addPart`/`dropPart` are already written and
  applied to the in-memory map, because reporting housekeeping as an operation
  failure republishes block IDs for a part that never became active.
- This branch fences every durable mutation of a shared log behind
  `assertMayWriteSharedState`, including the rotation that follows a record.

`addPart` and `dropPart` now keep the fence *in front of* the wrapper, so a
stale lease still fails closed with `TABLE_IS_READ_ONLY` before the rotation
touches the shared files, while a rotation that fails on its own remains
non-fatal. `load` and `setDeduplicationWindowSize` keep calling
`rotateAndDropIfNeeded` directly, matching `master`: no caller records are at
stake there, so a rotation failure must propagate.

`rotate` itself takes `master`'s version unchanged - this branch never
modified it, and its fail-closed lease check lives in `shutdown`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 20, 2026
`writeRecord` ends with `out.next()`, and `WriteBuffer::next` cancels the
buffer in its generic catch before rethrowing, so a single failed flush
leaves `MergeTreeDeduplicationLog::current_writer` canceled but non-null
while `stopped` stays false. Both methods that write records guarded only
the null half of that invariant with `chassert(current_writer != nullptr)`,
which a canceled writer satisfies, so the next record reached `writeChar`
and `WriteBuffer::write(char)` threw `LOGICAL_ERROR`, "Cannot write to
canceled buffer". The `write(const char *, size_t)` overload throws the
ordinary `CANNOT_WRITE_AFTER_BUFFER_CANCELED`, which is why the failure
presents as a logical error rather than as a write error.

Nothing replaced the writer afterwards, so in a release build every later
INSERT into that table failed the same way until the server was restarted:
`ALTER TABLE ... MODIFY SETTING non_replicated_deduplication_window`
recovers it only when `rotateAndDropIfNeeded` decides to rotate, which it
does not on an append-capable disk below `rotate_interval`. In a debug or
sanitizer build `LOGICAL_ERROR` aborts inside the `DB::Exception`
constructor, so neither `try`/`catch` around a `finalize()` call can
contain it.

`prepareToWrite` widens the predicate from null to null-or-dead at the two
write entry points and recovers through `rotate`, which is the one
replacement that also works on a disk that cannot append and which, since
ClickHouse#118089, leaves every field unchanged when it fails. The same dead writer
also makes `finalize` throw, so `rotate` and `shutdown` no longer call it
on a canceled buffer. The guard in `rotate` is required by the recovery
itself rather than defensive: `prepareToWrite` calls `rotate` precisely
when the writer is dead.

Observed once, on `Stress test (arm_debug)`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110997&sha=1b96aa460b8c20425bf793ad1df44085c53b9f31&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

Two gtests go into the file ClickHouse#118089 added for this class, driven by a disk
whose writer fails a chosen flush so that `WriteBuffer::next` cancels it
for real: one covers the recovery and what survives a reload, one covers
shutdown, which no later write can reach. Each of the three guards was
checked to be individually necessary by reverting it alone and watching the
abort come back at that site. A fault-injecting disk cannot be declared
from SQL, and no failpoint makes a buffer's flush fail, so this behaviour
is not reachable from a stateless test.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants