Repository navigation
Fix "Cannot write to finalized buffer" in MergeTreeDeduplicationLog::rotate - #118089
Conversation
…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]>
|
Workflow [PR], commit [396922a] Summary: ✅
AI ReviewSummaryThis PR fixes the immediate Findings❌ Blockers
Tests
Final Verdict❌ Not ready to merge. LLVM Coverage ReportMeasured on commit 396922a.
Changed lines: Changed C/C++ lines covered: 51/53 (96.23%) · Uncovered code |
…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]>
|
Addressed in 396922a: a failure of the rotation that follows 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 |
| /// 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. |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units20 translation units recompiled, 157 s compile time in total, 20 of them have a recent master baseline. |
|
The remaining piece is already written, as a draft: #102215 (@ vitlibar) replaces both It does not cover the The 2026-08-14 report only shows that second half, because the So the increment is No preference between the two from me: they touch the same lines in |
…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]>
`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]>
Related: #110429
Fixes a server abort with the logical error
Cannot write to finalized bufferhit by the stress test.MergeTreeDeduplicationLog::rotatefinalized 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 theWriteBufferFromS3allocation),current_writerwas 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 backgroundMergeTreeCleanupThreadcallingdropPart.Now
rotateopens 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
addPartordropPartno 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
writeFilecall 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):
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 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]