Skip to content

Fix Cannot write to canceled buffer after a failed deduplication log flush - #118350

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-dedup-log-canceled-writer
Sep 20, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-dedup-log-canceled-writer

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118089
Related: #110429

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 one failed write to a non-replicated MergeTree table's deduplication log (with non_replicated_deduplication_window greater than zero) making every following INSERT into that table fail with Cannot write to canceled buffer until 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 make ALTER TABLE ... MODIFY SETTING non_replicated_deduplication_window fail.

Description

WriteBuffer::next cancels the buffer in its catch before rethrowing, so one failed flush inside
writeRecord leaves current_writer canceled 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 INSERT into 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 same
dead writer makes finalize throw, so rotate and shutdown no longer call it on a canceled
buffer; rotate needs that guard because the recovery reaches it precisely when the writer is dead.

Retention needs one more tolerance. rotate records a log's path before anything is written to it,
and on object storage the path is published by the callback finalize runs, which cancellation never
reaches; 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

  • Merged into: 26.10.1.242-master (included in 26.10 and later)

groeneai and others added 4 commits September 5, 2026 17:47
`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Four rounds before publication, each by an independent model with no access to the implementation
notes; the final round found nothing. Every guard was checked by reverting it alone.

Sev Finding Verdict Evidence / action
❌ Recovering past a canceled writer wedged retention on object storage: rotate records the new log's path, DiskObjectStorage publishes it only from the finalize callback, and dropOutdatedLogs erased its entry only after a strict removal succeeded, so it threw on that entry for the lifetime of the table AGREE, fixed removeFileIfExists plus a test that drives retention through ALTER ... MODIFY SETTING. Restoring the strict overload reddens it with CANNOT_UNLINK and leaves the outdated log on disk. Discarding the entry in rotate instead was rejected: on a local disk that path names a file that really exists
❌ dropPart prepared the writer before deciding whether any record was needed, so a drop covering no retained block ID could open a log and throw, on dropPartNoWaitNoThrow's documented non-throwing path and after the part transaction has committed AGREE, fixed The preparation moved inside the relevance check; the test arms the fake disk to fail the open that any log the drop would create has to make
⚠️ Reverting dropPart's recovery call left the whole suite green, so that site was effectively untested AGREE, fixed A test whose first log operation after the cancellation is dropPart; reverting only that call now reddens it while the older test stays green
⚠️ A multi-block-id INSERT whose later record fails leaves the earlier IDs published, so a retry is deduplicated against a part that never became active DISAGREE Real, and neither created nor widened here: the write loop is byte-identical to master, and the deduplication verdict returns before any writer interaction (MergeTreeDeduplicationLog.cpp:289-299). Before this change the same rows were filtered out and every later insert failed until a restart
💡 The dead-writer predicate also tests isFinalized(), which the current control flow cannot reach AGREE, kept rotate replaces the writer right after finalizing it and shutdown resets it, so only the canceled half fires. I kept it as the complete form of what WriteBuffer::write rejects, and it was the live signature in this class until #118089. Dropping the term changes no behaviour and no test verdict, so if you prefer the minimal form it is one line, your call

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts are terminal per finding and carry a
citation rather than an argument.

Also noticed and not raised: a dropPart that does cover a retained block ID can still throw part
way through its loop, leaving earlier IDs erased and later ones stale in the deduplication map. That
predates this change, which confines its one new throw site to the branch that already had two.

Session id: cron:clickhouse-review-slot-9:20260905-235300

@clickhouse-gh clickhouse-gh Bot closed this Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

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 INSERT into that table failed with Cannot write to canceled buffer until a restart. The writer is now replaced through rotate, finalize is no longer called on a canceled buffer, and retention tolerates a log whose path such a writer never published on object storage.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d698df8]

Summary: ✅


AI Review

Summary

This PR fixes the immediate "Cannot write to canceled buffer" poisoning of MergeTree deduplication logs by replacing dead writers, deferring dropPart recovery until a record is actually needed, and tolerating unpublished log paths during retention. The main remaining issue is that, on the object-storage modes whose log path is published only by finalize(), the recovery now keeps the in-memory dedup state but still loses the canceled log across restart, so the fix is incomplete.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeDeduplicationLog.cpp:183] Recovering past a canceled writer keeps deduplication_map entries that can no longer be replayed after restart on metadata-backed object storage. Once rotate() skips the only finalize() that publishes the log, load() has nothing to read back, so a restart within non_replicated_deduplication_window accepts duplicates for earlier successful inserts from that log.
    Suggested fix: when recovering from a canceled writer on the modes where unpublished logs are possible, either replay the surviving entries into the replacement log, or drop/disable those in-memory entries instead of silently continuing with state that is only valid until restart.
Tests
  • ⚠️ Add a reload step to the new unpublished-log regression coverage (CanceledWriterDoesNotWedgeRetention, or a sibling test) that verifies a block ID written before the failed flush is still deduplicated after load(). The current tests prove retention progress and runtime recovery, but they do not cover the restart behavior of the object-storage case this PR is explicitly handling.
Final Verdict

Status: ⚠️ Request changes
Minimum required action: keep the recovery and retention fixes, but also make the object-storage recovery path preserve restart-visible deduplication state (or intentionally drop/disable the affected in-memory entries) and cover that behavior with a reload test.

LLVM Coverage Report

Measured on commit d698df8.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 142/144 (98.61%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d698df888 with master 55c256363 (stripped binary size, per-symbol sizes and ThinLTO time; 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, 149 s compile time in total, 20 of them have a recent master baseline.

Job report

/// 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())

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 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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 WriteBuffer cannot be read back, and existing_logs stores only {path, entries_count} (MergeTreeDeduplicationLog.h:16-23), so nothing records which block IDs a given log held. Reconstructing from deduplication_map would rewrite entries that are already durable in older logs and double count them in dropOutdatedLogs's window sum, dropping logs that are still needed.
  • Dropping from deduplication_map is 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 rotateAndDropIfNeededAfterWrite deliberately 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.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit e6b360b Sep 20, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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