Repository navigation
Fix Cannot write to canceled buffer after a failed deduplication log flush - #118350
Conversation
`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]>
`dropPart` writes records through the same buffer as `addPart`, and it is reached from `DROP`/`DETACH PARTITION` with no insert involved, so an insert that died on a failed flush can be followed into the canceled writer through `dropPart` rather than through another insert. The existing test only reached `dropPart` after an `addPart` had already replaced the writer, so reverting the recovery call at that site left the whole suite green and left the site effectively untested. The comment that claimed otherwise is corrected. The new test makes `dropPart` the first deduplication log operation after the injected flush failure. Reverting only that one call now aborts with "Cannot write to canceled buffer" from `dropPart`, while the older test keeps passing, so the two entry points are covered separately. The reload scope asserts that the drop record written through the replaced writer reached the disk, and that the record added after it did too. Co-Authored-By: Claude Opus 5 <[email protected]>
`dropPart` called `prepareToWrite()` before deciding whether any record is needed. Both throwing operations of its loop body, `getPartNameAndCheckFormat` and `writeRecord`, sit inside the `drop_part_info.contains(part_info)` branch, so a drop that covers no retained block ID previously had no throwing operation at all after the `stopped` check. The unconditional call gave it one: `rotate` opens the next log through `disk->writeFile` whenever the writer happens to be dead, which can fail and which also creates a log file nobody needed. That matters because of the interface this reaches. `MergeTreeData::dropPartNoWaitNoThrow` is documented to drop a part "in background without any waits or throwing exceptions in case of errors", and `StorageMergeTree` implements it by calling `deduplication_log->dropPart` directly; the background callers in `clearEmptyParts` and `clearUnusedPatchParts` do not wrap it, and covering no retained block ID is their common case, because an empty part's block IDs have usually aged out of the window. On the user-facing path the part transaction is committed before `dropPart` runs, so a throw there reports a `DROP`/`DETACH PARTITION` that already succeeded as failed. Calling it once per matching entry is also stronger than calling it once per operation: the live-writer invariant becomes local to each `writeRecord` instead of resting on the whole-loop argument that the rotation after each write always leaves a live writer. `addPart` keeps its call before the loop. Its only caller guards on a non-empty list of deduplication hashes and there is one block ID per hash, so the loop always writes, and it returns a value the caller acts on rather than implementing a non-throwing interface. The new test arms the fake disk to fail the `writeFile` call that any log the drop would open has to make, so the drop's silence is asserted rather than assumed: after an injected flush failure has canceled the writer, a drop that covers nothing must not throw. Reverting the move alone makes `FAULT_INJECTED` escape `dropPart` at that assertion. Deleting the moved call instead brings back the "Cannot write to canceled buffer" abort in the sibling test, so the site stays covered. Co-Authored-By: Claude Opus 5 <[email protected]>
`rotate` records the path of the new log in `existing_logs` as soon as `writeFile` returns. On a `DiskObjectStorage` nothing exists at that path yet: `writeFile` hands back a `WriteBufferInlineOrBlob` whose metadata is created by the finalize callback, and `cancelImpl` cancels the underlying blob buffer without ever invoking it. A writer that a failed flush canceled therefore leaves behind an entry naming a path that holds nothing. `dropOutdatedLogs` removed such an entry with the strict overload, which throws `CANNOT_UNLINK` on a missing file, and erased the entry only after the removal returned. The first retention pass that reached the entry threw before the erase, so the entry survived and every later pass threw on the same entry: retention dropped no log again for the lifetime of the object, because only `load` rebuilds `existing_logs`, from a directory listing in which an unpublished path does not appear. The wedge belongs to this change even though the entry itself predates it. `prepareToWrite` deliberately advances past a canceled writer so that inserts keep succeeding, and every successful write then runs `rotateAndDropIfNeededAfterWrite`; on a disk that cannot append, `rotateAndDropIfNeeded` rotates unconditionally, so retention runs on every write there. Before, the table stopped accepting inserts instead, and retention was reached only through `ALTER ... MODIFY SETTING` or a restart. The description of this change also states that ordinary retention removes those logs at a later rotation, which is only true once the removal tolerates a missing path. `removeFileIfExists` is threaded properly on object storage, `DiskObjectStorageTransaction::removeFileIfExists` passing `if_exists=true` into `unlinkFile`, and `DiskLocal::removeFileIfExists` swallows `ENOENT` only, so a real removal failure still propagates. Two alternatives were rejected. Wrapping the removal in `try`/`catch` would swallow a transient object-storage failure that has to stay retryable, orphaning real files and hiding a real outage. Discarding the canceled writer's entry in `rotate` instead would be wrong on a local disk, where `writeFile` creates the file eagerly: the entry there names a file that really exists and may hold replayable records, so forgetting it would orphan a real file forever and make retention under-count. The tolerance belongs at the removal, not in the bookkeeping. The new test models deferred publication on a local disk with a writer that removes its file when it is canceled, and drives retention through `setDeduplicationWindowSize`, the `ALTER` path, which reports a failure instead of logging it and retrying forever. Restoring the strict overload alone makes `CANNOT_UNLINK` escape that call, and leaves the log that has fallen out of the window on the disk, so the wedge and the recovery of retention are both covered. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Four rounds before publication, each by an independent model with no access to the implementation
Severity: ❌ blocker / Also noticed and not raised: a Session id: cron:clickhouse-review-slot-9:20260905-235300 |
|
cc @CheSema @tiandiwonder, could you review this? A failed flush cancels the deduplication log's writer, and both write entry points only asserted it was non-null, so every later |
|
Workflow [PR], commit [d698df8] Summary: ✅
AI ReviewSummaryThis PR fixes the immediate " Findings
Tests
Final VerdictStatus: LLVM Coverage ReportMeasured on commit d698df8.
Changed lines: Changed C/C++ lines covered: 142/144 (98.61%) · Uncovered code |
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, 149 s compile time in total, 20 of them have a recent master baseline. |
| /// Nothing below can throw. | ||
| if (current_writer) | ||
| /// `finalize` throws a logical error on a canceled buffer, which has nothing left to flush. | ||
| if (current_writer && !current_writer->isCanceled()) |
There was a problem hiding this comment.
On the object-storage modes where a log becomes visible to load() only from finalize() (the WriteBufferInlineOrBlob path this PR is modeling), rotating past a canceled writer still leaves restart semantics wrong. addPart has already inserted the earlier successful block IDs into deduplication_map, but skipping finalize() here means that whole log never gets published, so a restart within non_replicated_deduplication_window forgets them and accepts duplicates that were still supposed to be deduplicated.
A concrete trace is block1 written successfully, block2 flush fails and cancels the writer, the next write reaches prepareToWrite() and rotate() skips finalize() here, then after restart load() cannot replay the canceled log at all. Could we either replay the surviving entries from the dead writer into the replacement log, or drop them from deduplication_map / surface the failure instead of continuing silently?
There was a problem hiding this comment.
Both halves of the premise check out. Publication happens only in WriteBufferInlineOrBlob::finalizeImpl via finalize_callback (src/Disks/IO/WriteBufferInlineOrBlob.cpp:59-77), cancelImpl (:79-83) never invokes it, and addPart has indeed already run deduplication_map.insert for the earlier block IDs (MergeTreeDeduplicationLog.cpp:320).
The conclusion does not follow, because the outcome is decided one level lower, at cancel(). WriteBuffer::finalize() throws on a canceled buffer (src/IO/WriteBuffer.cpp:89, "Cannot finalize buffer after cancellation."), so finalizeImpl is unreachable once the buffer is canceled and no code path can publish that log. This holds on master too: its rotate() and shutdown() both call finalize() inside a try and land in cancel(). A restart already forgets those entries today, without this change.
What this change does to that window is narrow it. On master no replacement writer is installed, so every later addPart/dropPart on the table throws at WriteBuffer.cpp:67, and in debug and sanitizer builds that LOGICAL_ERROR aborts, which is the failure this PR is about. Nothing written after the flush failure is recorded either. With the replacement writer the later block IDs land in a fresh log that does get published. The set of unbacked block IDs is the same in both cases.
"Continuing silently" is also not what happens. WriteBuffer::next() cancels and rethrows (WriteBuffer.h:63-72), so the INSERT whose flush failed fails with the underlying error at the moment it fails. The only failure this PR suppresses is the second one, raised against a later and unrelated insert. On a disk that publishes a file when it is created there is no loss at all: writeRecord ends in out.next() (:51), so every complete record is already in the file and load() replays it. The window you describe is specific to metadata-on-finalize disks.
On the three remedies:
- Replaying is not implementable. A canceled
WriteBuffercannot be read back, andexisting_logsstores only{path, entries_count}(MergeTreeDeduplicationLog.h:16-23), so nothing records which block IDs a given log held. Reconstructing fromdeduplication_mapwould rewrite entries that are already durable in older logs and double count them indropOutdatedLogs's window sum, dropping logs that are still needed. - Dropping from
deduplication_mapis unscopable for the same reason, and the only implementable version discards entries that are durably published elsewhere. That weakens deduplication rather than making it honest. It is also the wrong direction: an in-memory entry with no durable backing still rejects the duplicate while the process lives, whereas the inverse would not. - Surfacing the failure is already covered above. Escalating a housekeeping failure into a later user INSERT is what
rotateAndDropIfNeededAfterWritedeliberately refuses to do.
So I am keeping this PR to the crash fix. I am not raising the metadata-on-finalize window separately either: I have not reproduced it, and it is not introduced here.
Related: #118089
Related: #110429
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed one failed write to a non-replicated
MergeTreetable's deduplication log (withnon_replicated_deduplication_windowgreater than zero) making every followingINSERTinto that table fail withCannot write to canceled bufferuntil the server was restarted. The log now replaces a writer that a failed flush left unusable, no longer finalizes such a writer while rotating or shutting down, and no longer stops removing its outdated files, which could also makeALTER TABLE ... MODIFY SETTING non_replicated_deduplication_windowfail.Description
WriteBuffer::nextcancels the buffer in its catch before rethrowing, so one failed flush insidewriteRecordleavescurrent_writercanceled but non-null.chassert(current_writer != nullptr)at both write entry points checked only the null half of that invariant, and nothing replaced the
writer, so in a release build every later
INSERTinto that table failed until a restart.The fix widens that predicate from null to null or dead at the two methods that write records,
recovering through
rotate, which also works without append support. The samedead writer makes
finalizethrow, sorotateandshutdownno longer call it on a canceledbuffer;
rotateneeds that guard because the recovery reaches it precisely when the writer is dead.Retention needs one more tolerance.
rotaterecords a log's path before anything is written to it,and on object storage the path is published by the callback
finalizeruns, which cancellation neverreaches; removing such an entry with the strict overload threw before the erase, so every later
pass threw on it again and no log was dropped.
A retry whose own flush also fails leaves the empty log it opened behind, one per attempt; retention
removes them at a later rotation. I did not add deletion on an already-failing disk.
This is the producer @ alexey-milovidov named as remaining after #118089
(comment), distinct
from the one #102215 was closed over. Observed in CI on #110997, an unrelated PR
of mine:
report.
The new gtests go into the file #118089 added for this class, driven by a disk whose writer fails a
chosen flush: no failpoint fails a buffer's flush, and a fault-injecting disk cannot be declared
from SQL. Each guard was checked by reverting it alone.
Workflow [PR]
Sync PR [sync-upstream/pr/118350]
Version info
26.10.1.242-master(included in26.10and later)