Skip to content

Do not retry a failed WAL writer after a fatal background error - #15820

Open
xingbowang wants to merge 6 commits into
meta:mainfrom
xingbowang:export-D134907307
Open

xingbowang wants to merge 6 commits into
meta:mainfrom
xingbowang:export-D134907307

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, #12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since #15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). #12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:

  1. The fatal WAL error comes first, then a retryable error (for example, a
    retryable MANIFEST write error in SetOptions()). The fatal error stays,
    because a less severe error does not replace it. But
    StartRecoverFromRetryableBGIOError() did not check the severity, so it
    set recovery_in_prog_ and started a recovery thread, which can never
    succeed.
  2. A retryable error starts a recovery first, and the WAL buffer write fails
    while that recovery is still in progress.
  3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
    wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
    which needs the DB mutex. A recovery memtable switch that runs in this
    window still sees a hard error, not a fatal one, so it resets the writer.
    The same window exists during a recovery from a soft error (for example,
    a retryable SST write error in a flush). Such a recovery does not stop the
    DB, so a user Flush() can switch the memtable in the window and reset the
    writer. This change fixes the third way for a recovery from a hard error,
    but not for a soft-error recovery (S7 below, a known gap):
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:

  • With manual_wal_flush, FlushWAL() returns the background error, without
    writing the WAL buffer, while a background error of kHardError or worse
    stops writes after a buffer write or sync of the current WAL failed. The
    returned error is the current background error, which can come from an
    earlier failure. A recovery memtable switch may have reset the failed WAL
    writer and moved to a new WAL, so success on the new WAL would hide lost
    writes. The error is cleared only after a recovery flush succeeds, and
    that flush has written all memtables, including any dropped records, to
    SST files.
  • During a recovery that can still succeed, a memtable switch resets a failed
    WAL writer, as on master. During a soft-error recovery, which does not stop
    the DB, this includes the window where a FlushWAL() call (call A) has failed
    its buffer write but has not yet recorded the error. FlushWAL() refuses to
    write the buffer because of the WAL-failure mark (see Implementation) only
    while the DB is stopped, so in that window the reset can still hide the
    dropped buffer, as on master (S7 below, a known gap). The switch does not skip
    the reset there. Without the reset, the switch would fail on the writer with
    "Seen error", an IOError, which is a fatal error with manual_wal_flush. The
    switch would have to record that error: it has already marked the active
    memtable immutable, and only a stopped DB keeps writes out of that memtable.
    Then the recovery could not keep the dropped records, also when A's error is
    only a hard error, where master keeps them (S9, S10, S12 and S13 below).
  • In A's window, another FlushWAL() (call B) fails on the failed writer
    with "Seen error", if no switch has reset that writer. It returns that
    error but does not record it, and A records its own status. This also
    holds when A records its error and stops the DB after B's stop checks but
    before B's buffer write. B then sees the mark, and the mark always comes
    from a call that records its own error. SyncWalImpl() follows the same
    rule for a sync that fails on the error of an earlier sync.
  • With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
    when asked, as before, also while the DB is stopped (for example, by a
    MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
    by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
    write with sync=true). So the synced records survive a crash. A closed
    WAL had its buffer written by the memtable switch that closed it, so a
    failed sync of a closed WAL drops no buffered records. A write with
    sync=true fsyncs the WAL directory only after it has written and synced
    the WAL files, so a failed directory fsync drops no records either. The
    next WAL sync tries the directory fsync again.
  • The flush code that syncs closed WALs retries a failed closed WAL only
    during a recovery that can still succeed. Once the background error is
    fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
    as well.
  • No recovery thread starts for a retryable error that comes after a fatal
    error, and listeners are not told that a recovery begins.
  • A retry during a recovery that can still succeed keeps working. So a WAL
    buffer error that is only a hard error (a retryable or file-scoped status
    that is not an IOError), and the third way when the recovery flush finishes
    before FlushWAL() records its error, still end in a recovery that keeps the
    dropped writes. This also holds during a soft-error recovery when a
    memtable switch or another FlushWAL() runs before the failed FlushWAL()
    records its hard error (S9 to S14 below).

Implementation:

  • db/error_handler.h, db/error_handler.cc:
    • New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
      recovery_in_prog_ is set and the background error is below kFatalError.
    • New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush, DBImpl
      sets it when it records a failed buffer write or sync of the current WAL as
      a background error, with the DB mutex held, next to SetBGError(): the
      memtable switch marks every failed buffer write, and the other sites use the
      WALIOStatusCheck() condition (see db_impl.h below). FlushWAL() also sets it
      right after a failed buffer write, before it records the error, so that a
      concurrent FlushWAL() sees it in that window. Setting it again next to
      SetBGError() covers a recovery whose ClearBGError() runs in that window. A
      failure that does not become a background error (paranoid_checks off, or a
      Busy or Incomplete status) only resets the WAL writer, and RocksDB keeps
      using the WAL, so it sets no mark. ClearBGError() clears the mark with the
      background error. The mark is never cleared in other places: a later
      successful buffer write, even with a sync, or a switch to a new WAL does not
      bring back the dropped records, and clearing the mark there would bring back
      the false OK of the third way (S1 in the table below).
    • New GetErrorBlockingManualWALFlush() returns the background error when
      the DB is stopped and the mark is set.
    • StartRecoverFromRetryableBGIOError() returns early when the background
      error is kFatalError or worse. A new sync point right after it sets
      recovery_in_prog_ lets tests wait until the recovery is marked.
    • The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
      OnBackgroundError() listeners when the background error is fatal, because
      no recovery starts then.
  • db/db_impl/db_impl.cc:
    • FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
      take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
      OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
      the DB mutex held, but no background error stops the DB then. The DB
      mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
      wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
      failed, since the first check, it releases wal_write_mutex_ and checks
      again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
      buffer write. A failed buffer write sets the mark. When the mark is set
      and the current WAL writer has an error, the buffer write fails with
      "Seen error" and does no I/O, and FlushWAL() returns that error without
      marking or recording it. The call that set the mark records its own
      error: every call that sets the mark records its error as a background
      error. The DB may already be stopped then, because that call can record
      its error after the stop checks; the stop checks let a call through
      with the DB stopped only while the mark is clear. So the check does not
      look at IsDBStopped(). An OnBackgroundError() listener can lower the
      error of that call. Then the writer error stays until ClearBGError() or
      until a memtable switch during a recovery resets the writer, as on
      master. Until then, FlushWAL() returns an error.
    • Three new sync points in FlushWAL() are used by the race tests.
  • db/db_impl/db_impl_write.cc:
    • SwitchMemtable(): reset the error of the failed WAL writer only when
      CanRetryFailedWALWrites() returns true, instead of whenever a recovery
      is in progress. The switch records every failed buffer write as a
      background error, also with paranoid_checks off or a Busy or Incomplete
      status, so it marks every one.
    • WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
      error becomes a background error (WALErrorBecomesBGError()) and the failure
      may have lost records of the current WAL. SyncWAL(), the flush that syncs
      closed WALs, and a write with sync=true can fail on a closed WAL, and a
      write with sync=true can fail at the WAL directory fsync. They set no mark
      then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
      when the caller knows that the current WAL lost no records (kHealthy):
      WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
      wrote, and a failed WAL directory fsync, for normal and pipelined writes.
      SyncWalImpl() reports a failed WAL older than the WAL that was current when
      it started. Its own directory fsync failure does not reach
      WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
      WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
      that a switch closed after the caller started. The failed WAL number that
      the write path passes, which the file-scoped WAL recovery uses, is
      unchanged.
  • db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
    WALIOStatusCheck() already used to decide whether a WAL error becomes a
    background error. FlushWAL() uses it too for its early mark. New enum
    DBImpl::CurrentWALState (see above).
  • db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
    flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
    before they reset the error of a closed WAL. The parameter of
    SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
    its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:

  • With manual_wal_flush, FlushWAL() fails in the case above. It used to
    write the buffer, to a new WAL if a recovery switch had reset the failed
    writer, and, with sync=true, sync the WAL. LockWAL() calls
    FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
    get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
    directory and no backup behind. LockWAL(), checkpoints and
    FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
    With two_write_queues, a write with sync=true first adds its record to
    the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
    (SyncWALAndApplyToManifest()); a write that skips the memtable calls
    FlushWAL(sync=true). So such a write fails with the background error in
    this case, and its record stays in the WAL buffer. A later successful
    recovery writes that record to the WAL file, so the WAL then holds a write
    that reported failure. Master leaves the same kind of record when the
    sync fails after the buffer write, so this is not a new kind of
    inconsistency. DBs without manual_wal_flush are not affected.
  • The buffered records that such a call does not write stay in the buffer. A
    successful recovery (automatic or DB::Resume()) writes them, and the calls
    succeed again. If no recovery succeeds, the WAL writer writes its buffer to
    the WAL file, without a sync, when the DB is closed, unless the failed
    write or sync left the writer with an error. A writer with an error skips
    that write (log::Writer::WriteBuffer()).
  • On master, after a WAL buffer write fails with a hard error, a later
    FlushWAL() writes to the failed writer again, and that "Seen error"
    IOError makes the error fatal, so DB::Resume() fails. With this change,
    FlushWAL() returns the hard error instead, so DB::Resume() can recover.
    This holds only if no memtable switch runs outside a recovery before
    Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
    default log_size_for_flush=0, or a backup with flush_before_backup
    switches the memtable. That switch does not reset the failed writer, so
    it records "Seen error" as a new fatal error, and Resume() fails. This is
    the same on master.

Safety and cases not changed:

  • A fatal or unrecoverable background error is never lowered: ResumeImpl()
    rejects errors above kHardError, ClearBGError() does not clear a fatal
    error on either of its paths (after a successful ResumeImpl(), and directly
    for a soft error that needs no flush), and OverrideNoSpaceError() returns
    early for a fatal error. Any error during a recovery attempt leaves
    recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
    call), and ClearBGError() clears nothing while it is non-OK. So a recovery
    that starts while the error is fatal can never succeed, and the new
    CanRetryFailedWALWrites() checks block no recovery that could succeed.
  • The lost WAL buffer cases from review, all with manual_wal_flush. A's
    buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
    without a flush, as a stand-in for a crash. Each cell shows B's result,
    then whether the write in A's buffer (k1) is kept after reopen.
Case master this diff
S0: retryable error first, then A's FlushWAL() err, lost err, lost
S1: race, A records its error after the switch OK, lost err, lost
S2: race, the whole recovery runs before A records OK, kept err, kept
S3: retryable TimedOut on the buffer write OK, kept OK, kept
S4: file-scoped Aborted on the buffer write OK, kept OK, kept
S5: paranoid_checks=false plus the race (S2 order) OK, kept OK, kept
S6: S1, B passed its first check before A failed OK, lost err, lost
S7: soft-error recovery, a user Flush() switches the memtable in A's window (the S1 window) OK, lost OK, lost
S8: S7, but A's error sets no background error (paranoid_checks off, Busy, Incomplete) OK, kept OK, kept
S9: S7, but A's error is a hard error (retryable TimedOut or file-scoped Aborted), B after the recovery OK, kept OK, kept
S10: S9, but B runs in A's window after the switch OK, kept OK, kept
S11: S9, B runs in A's window, no switch err, lost err, kept
S12: S9, but a Put() of a new key follows the switch in A's window (cells: the Put()) OK, kept OK, kept
S13: S12, but the Put() uses disableWAL OK, kept OK, kept
S14: S11, but A records its error and stops the DB between B's stop checks and its buffer write err, lost err, kept

In S0, A's FlushWAL() writes the buffer during the recovery, the write
fails and drops it, and the error becomes fatal, as on master (see the
alternative above). In S2, the recovery clears the error and the mark. A
then records its WAL error, which is fatal and sets the mark again, so B
fails although the recovery flush kept k1. No write is lost there, and the
DB stays stopped by the fatal error anyway. In S7, the switch resets A's
failed writer, B syncs the new WAL and returns OK, A then records a fatal
error, and the recovery cannot keep k1. That is a known gap, the same as
on master (see "Not changed" below). A FlushWAL() after A records its
error fails, where master returns OK. In S9, S10, S12 and S13, the switch
also resets the writer, and A's hard error lets the recovery keep k1, as
on master. A FlushWAL() there also fails until the recovery ends. Master's
OK there does not mean that k1 is durable, so the error is intended. In
S11 and S14, B writes A's failed writer and fails, but it leaves the
recording to A, so A's hard error stays, the recovery keeps k1, and a
FlushWAL(sync=true) after the recovery returns OK. On master, B records
its "Seen error" as a fatal error, so the recovery cannot keep k1.

Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
DB is closed with all unsynced data dropped, so k1 is kept only if B synced
it:

Case master this diff
H1: retryable MANIFEST error, recovery gave up OK, kept OK, kept
H2: the same, while the failing recovery still runs OK, kept OK, kept
H3: fatal MANIFEST error OK, kept OK, kept
H4: a WAL error that sets no background error (paranoid_checks off, Busy, Incomplete), then a fatal MANIFEST error OK, kept OK, kept

One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
closed WAL (the flush that would sync it is held), which gives a fatal error.
Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
system fails all writes while the DB closes. On master and with this change,
FlushWAL() returns OK and k1 is kept after reopen.

Another one: a write with sync=true fails at the WAL directory fsync, which
gives a fatal error. On master and with this change, FlushWAL(sync=false),
FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
the directory fsync again.

Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
the current WAL, and a user Flush() switches the memtable before SyncWAL()
records the error. On master and with this change, the switch resets the
writer, the recovery clears the error, and later writes succeed.

One more case: a hard WAL buffer error (a retryable TimedOut) with no
automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
to the failed writer again and makes the error fatal, so Resume() fails.
With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
k1 is kept.

  • The acknowledged write is still lost when the recovery flush cannot keep it,
    for example when the error becomes fatal right after the recovery memtable
    switch (the diagram above). That is expected for a fatal error. The change
    makes the loss visible instead of reporting success. Recovering these
    errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
    follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
    recovery does.
  • Not changed: with paranoid_checks=false, a failed WAL write sets no
    background error, and WALIOStatusCheck() resets the writer. If nothing else
    stops the DB, a later FlushWAL() can return OK for a lost write. Such a
    failure sets no mark, because RocksDB keeps using the WAL after it. Busy
    and Incomplete statuses from a WAL write are handled the same way in all
    modes. These are separate problems. Such a failure resets its writer in
    WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
    or without a soft-error recovery in progress. If a memtable switch runs
    between such a failed FlushWAL() buffer write and that reset, the result
    is the same as on master. Without a recovery, the switch fails on the
    writer and records a fatal error. During a soft-error recovery, the switch
    resets the writer, the recovery flush keeps the dropped records, and a
    later FlushWAL(sync=true) returns OK.
  • Not changed: with manual_wal_flush, a failed sync of the current WAL sets
    the mark only when WALIOStatusCheck() records it. If a soft-error recovery
    switch runs before that, the switch resets the writer, as on master. The
    sync failure dropped no buffered records. The recovery flush may then
    retry the fsync of that WAL file, as on master. Whether a retried fsync
    can be trusted is a separate, existing problem.
  • Not changed: with manual_wal_flush, a user write (for example, a Put())
    in the window of a failed FlushWAL(), with no memtable switch before it in
    that window, adds its record to A's failed WAL writer, fails with "Seen
    error", and records it as a fatal error, as on master. Only FlushWAL()
    leaves the recording to the failed FlushWAL() call. After a switch in
    that window, the write goes to the new WAL, as on master (S12, S13).
  • Not changed (known gap, S7): during a soft-error recovery, a memtable
    switch in the window of a failed FlushWAL() (call A) resets A's failed
    writer and moves to a new WAL, as on master. A FlushWAL() in that window,
    after the switch, can return OK although k1 is in no WAL file. If A's
    error is fatal (an IOError), the recovery cannot keep k1. Once A records
    its error, FlushWAL() fails. Keeping the failed writer at the switch would
    make the switch record a fatal error and lose writes that master keeps
    (S9, S10, S12, S13). A fix needs the switch to finish and abandon the
    failed WAL, as the file-scoped WAL recovery does, and FlushWAL() to refuse
    OK while A's failure is not recorded. That is the open TODO in
    ErrorHandler::SetBGErrorImpl(), and a possible follow-up.
  • No API, option or format change.

Reviewed By: pdillinger

Differential Revision: D134907307

@meta-cla meta-cla Bot added the CLA Signed label Nov 28, 2026
@meta-codesync

meta-codesync Bot commented Nov 28, 2026

Copy link
Copy Markdown

@xingbowang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D134907307.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

⚠️ clang-tidy: 4 warning(s) on changed lines

Completed in 873.1s.

Summary by check

Check Count
bugprone-argument-comment 1
clang-analyzer-optin.performance.Padding 1
performance-inefficient-vector-operation 2
Total 4

Details

db/error_handler_fs_test.cc (3 warning(s))
db/error_handler_fs_test.cc:3744:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/error_handler_fs_test.cc:4210:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/error_handler_fs_test.cc:5376:10: warning: Excessive padding in 'struct WindowCase' (8 padding bytes, where 0 is optimal). Optimal fields order: name, put, switch_in_window, flush_wal_in_window, switch_severity, b_code, consider reordering the fields or adding explicit padding members [clang-analyzer-optin.performance.Padding]
db/version_set_test.cc (1 warning(s))
db/version_set_test.cc:1831:42: warning: argument name 'file_number' in comment does not match parameter name 'file' [bugprone-argument-comment]

@xingbowang
xingbowang force-pushed the export-D134907307 branch 2 times, most recently from 449ca8d to b1def3a Compare November 29, 2026 01:31
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error Do not retry a failed WAL writer after a fatal background error (#15820) Nov 29, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is still
in the WAL write buffer. The record reaches the WAL file only when FlushWAL()
or a memtable switch writes the buffer. If that buffer write fails, the WAL
writer drops the buffer, so the buffered records may be lost. For this reason
ErrorHandler::SetBGErrorImpl() makes a WAL I/O error with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. So a
recovery can reset a WAL writer whose dropped buffer held acknowledged writes.
This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It makes the error fatal later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one:

```
manual_wal_flush=true; a retryable MANIFEST error started a recovery
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way, and the new regression
test reproduces it.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error lose acknowledged
writes while FlushWAL() reports OK. Without manual_wal_flush, every write puts
its record into the WAL file at once, so a failed WAL write returns an error to
that writer. For those DBs, when a WAL write gets a fatal error while
recovery_in_prog_ is set (for example, a hard error during an automatic
recovery), the change only stops a retry that cannot help.

Previous behavior: after the reset, the memtable switch wrote the now empty
buffer with OK and moved to a new WAL. FlushWAL() then returned OK on the new
WAL writer, although the acknowledged write was in no WAL file. After reopen
the write was gone. The background error stayed fatal and writes stayed
stopped, but FlushWAL() and the WAL switch reported success, so a caller (or a
backup or checkpoint taken in that state) could not see the loss.

New behavior: with manual_wal_flush, a memtable switch never retries a failed
WAL buffer write. In all modes, a failed WAL writer is retried only during a
recovery that can still succeed. Once the background error is fatal, the
failed WAL writer keeps its error, and FlushWAL() keeps failing. No recovery
thread starts for a retryable error that comes after a fatal error, and
listeners are not told that a recovery begins.

Implementation:
- db/error_handler.h: new ErrorHandler::CanRetryFailedWALWrites(). It returns
  true when recovery_in_prog_ is set and the background error is below
  kFatalError.
- db/db_impl/db_impl_write.cc (SwitchMemtable()): reset the error of the
  failed WAL writer only when manual_wal_flush is off and
  CanRetryFailedWALWrites() returns true. The manual_wal_flush check covers
  the third way, where the error is not yet recorded as fatal. A buffer
  write with manual_wal_flush that fails with any status drops the buffer, so
  a retry can never help there.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning. These sites keep the reset during a recovery with
  manual_wal_flush, because a closed WAL's buffer was already written at its
  switch, so no buffered writes can be dropped there.
- db/error_handler.cc:
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc: a new sync point in FlushWAL() between the failed
  buffer write and WALIOStatusCheck(), used by the race test.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- Recovery from retryable and hard errors below kFatalError does not change,
  with one exception: with manual_wal_flush, a WAL write that fails with a
  retryable or file-scoped status that is not an IOError (for example, a
  retryable TimedOut) becomes a hard error, not a fatal one, so an automatic
  recovery or DB::Resume() can start. The memtable switch does not retry the
  failed writer, so this recovery fails at the switch, and the error becomes
  fatal. A retry would write an empty buffer and hide the lost writes in this
  case too. A plain TimedOut is fatal at once, as before.
- The acknowledged write is still lost after a fatal WAL buffer error. That
  is expected for a fatal error. The change makes the loss visible instead of
  reporting success. Recovering these errors is an open TODO in
  ErrorHandler::SetBGErrorImpl(). meta#15293 made the recovery flush atomic and
  is a possible base for that work.
- No API, option or format change.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and the writer is reset as before. The one exception is a
  narrow race with a recovery memtable switch, which then fails.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error (#15820) Do not retry a failed WAL writer after a fatal background error Nov 30, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a WAL buffer write or WAL sync failed with that error.
  A recovery memtable switch may have reset the failed WAL writer and moved
  to a new WAL, so success on the new WAL would hide lost writes. The error
  is cleared only after a recovery flush succeeds, and that flush has
  written all memtables, including any dropped records, to SST files. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer.
- With a healthy WAL, FlushWAL() writes and syncs the buffer as before, also
  while the DB is stopped (for example, by a MANIFEST error, during or after
  its recovery, or by a fatal MANIFEST error). So the records survive a
  crash.
- A failed WAL writer is retried only during a recovery that can still
  succeed. Once the background error is fatal, the failed WAL writer keeps its
  error, so a direct SyncWAL() fails as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed WAL buffer write or WAL sync as a
    background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use
    the WALIOStatusCheck() condition (see db_impl.h below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK in
    S1.
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true. The switch records every failed
    buffer write as a background error, also with paranoid_checks off or a
    Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when
    the error becomes a background error (WALErrorBecomesBGError()). This
    covers FlushWAL(), SyncWAL() and the write path.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In this diff, no case loses a write that master keeps, and no case fails a
sync on a healthy WAL that master does. So S0 keeps master's result. It is a
possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. With two_write_queues, a write with
  sync=true calls FlushWAL(sync=true), so such a write fails with the
  background error in this case, and its record stays buffered. DBs
  without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless a failed write
  already dropped it.
- After a WAL buffer write fails with a hard error, a later FlushWAL() used to
  write to the failed writer again, and that "Seen error" IOError made the
  error fatal, so DB::Resume() failed. FlushWAL() returns the hard error
  instead, so DB::Resume() can recover.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a WAL buffer write or WAL sync failed with that error.
  A recovery memtable switch may have reset the failed WAL writer and moved
  to a new WAL, so success on the new WAL would hide lost writes. The error
  is cleared only after a recovery flush succeeds, and that flush has
  written all memtables, including any dropped records, to SST files. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer.
- With a healthy WAL, FlushWAL() writes and syncs the buffer as before, also
  while the DB is stopped (for example, by a MANIFEST error, during or after
  its recovery, or by a fatal MANIFEST error). So the records survive a
  crash.
- A failed WAL writer is retried only during a recovery that can still
  succeed. Once the background error is fatal, the failed WAL writer keeps its
  error, so a direct SyncWAL() fails as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed WAL buffer write or WAL sync as a
    background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use
    the WALIOStatusCheck() condition (see db_impl.h below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK in
    S1.
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true. The switch records every failed
    buffer write as a background error, also with paranoid_checks off or a
    Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when
    the error becomes a background error (WALErrorBecomesBGError()). This
    covers FlushWAL(), SyncWAL() and the write path.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In this diff, no case loses a write that master keeps, and no case fails a
sync on a healthy WAL that master does. So S0 keeps master's result. It is a
possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. With two_write_queues, a write with
  sync=true calls FlushWAL(sync=true), so such a write fails with the
  background error in this case, and its record stays buffered. DBs
  without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless a failed write
  already dropped it.
- After a WAL buffer write fails with a hard error, a later FlushWAL() used to
  write to the failed writer again, and that "Seen error" IOError made the
  error fatal, so DB::Resume() failed. FlushWAL() returns the hard error
  instead, so DB::Resume() can recover.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a WAL buffer write or WAL sync failed with that error.
  A recovery memtable switch may have reset the failed WAL writer and moved
  to a new WAL, so success on the new WAL would hide lost writes. The error
  is cleared only after a recovery flush succeeds, and that flush has
  written all memtables, including any dropped records, to SST files. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer.
- With a healthy WAL, FlushWAL() writes and syncs the buffer as before, also
  while the DB is stopped (for example, by a MANIFEST error, during or after
  its recovery, or by a fatal MANIFEST error). So the records survive a
  crash.
- A failed WAL writer is retried only during a recovery that can still
  succeed. Once the background error is fatal, the failed WAL writer keeps its
  error, so a direct SyncWAL() fails as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed WAL buffer write or WAL sync as a
    background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use
    the WALIOStatusCheck() condition (see db_impl.h below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK in
    S1.
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true. The switch records every failed
    buffer write as a background error, also with paranoid_checks off or a
    Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when
    the error becomes a background error (WALErrorBecomesBGError()). This
    covers FlushWAL(), SyncWAL() and the write path.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In this diff, no case loses a write that master keeps, and no case fails a
sync on a healthy WAL that master does. So S0 keeps master's result. It is a
possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. With two_write_queues, a write with
  sync=true calls FlushWAL(sync=true), so such a write fails with the
  background error in this case, and its record stays buffered. DBs
  without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless a failed write
  already dropped it.
- After a WAL buffer write fails with a hard error, a later FlushWAL() used to
  write to the failed writer again, and that "Seen error" IOError made the
  error fatal, so DB::Resume() failed. FlushWAL() returns the hard error
  instead, so DB::Resume() can recover.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a WAL buffer write or WAL sync failed with that error.
  A recovery memtable switch may have reset the failed WAL writer and moved
  to a new WAL, so success on the new WAL would hide lost writes. The error
  is cleared only after a recovery flush succeeds, and that flush has
  written all memtables, including any dropped records, to SST files. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer.
- With a healthy WAL, FlushWAL() writes and syncs the buffer as before, also
  while the DB is stopped (for example, by a MANIFEST error, during or after
  its recovery, or by a fatal MANIFEST error). So the records survive a
  crash.
- A failed WAL writer is retried only during a recovery that can still
  succeed. Once the background error is fatal, the failed WAL writer keeps its
  error, so a direct SyncWAL() fails as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed WAL buffer write or WAL sync as a
    background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use
    the WALIOStatusCheck() condition (see db_impl.h below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK in
    S1.
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true. The switch records every failed
    buffer write as a background error, also with paranoid_checks off or a
    Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when
    the error becomes a background error (WALErrorBecomesBGError()). This
    covers FlushWAL(), SyncWAL() and the write path.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In this diff, no case loses a write that master keeps, and no case fails a
sync on a healthy WAL that master does. So S0 keeps master's result. It is a
possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. With two_write_queues, a write with
  sync=true calls FlushWAL(sync=true), so such a write fails with the
  background error in this case, and its record stays buffered. DBs
  without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless a failed write
  already dropped it.
- After a WAL buffer write fails with a hard error, a later FlushWAL() used to
  write to the failed writer again, and that "Seen error" IOError made the
  error fatal, so DB::Resume() failed. FlushWAL() returns the hard error
  instead, so DB::Resume() can recover.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a WAL buffer write or WAL sync failed with that error.
  A recovery memtable switch may have reset the failed WAL writer and moved
  to a new WAL, so success on the new WAL would hide lost writes. The error
  is cleared only after a recovery flush succeeds, and that flush has
  written all memtables, including any dropped records, to SST files. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer.
- With a healthy WAL, FlushWAL() writes and syncs the buffer as before, also
  while the DB is stopped (for example, by a MANIFEST error, during or after
  its recovery, or by a fatal MANIFEST error). So the records survive a
  crash.
- A failed WAL writer is retried only during a recovery that can still
  succeed. Once the background error is fatal, the failed WAL writer keeps its
  error, so a direct SyncWAL() fails as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed WAL buffer write or WAL sync as a
    background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use
    the WALIOStatusCheck() condition (see db_impl.h below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK in
    S1.
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true. The switch records every failed
    buffer write as a background error, also with paranoid_checks off or a
    Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when
    the error becomes a background error (WALErrorBecomesBGError()). This
    covers FlushWAL(), SyncWAL() and the write path.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark.
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In this diff, no case loses a write that master keeps, and no case fails a
sync on a healthy WAL that master does. So S0 keeps master's result. It is a
possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. With two_write_queues, a write with
  sync=true calls FlushWAL(sync=true), so such a write fails with the
  background error in this case, and its record stays buffered. DBs
  without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless a failed write
  already dropped it.
- After a WAL buffer write fails with a hard error, a later FlushWAL() used to
  write to the failed writer again, and that "Seen error" IOError made the
  error fatal, so DB::Resume() failed. FlushWAL() returns the hard error
  instead, so DB::Resume() can recover.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error Do not retry a failed WAL writer after a fatal background error (#15820) Nov 30, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- A memtable switch resets a failed WAL writer only while the DB is stopped
  during a recovery that can still succeed. During a soft-error recovery,
  the DB is not stopped, so FlushWAL() does not check for a failed WAL
  write. There, the switch keeps the error of the failed writer, so the
  switch fails and records it as a background error. So when FlushWAL()
  returns OK, it has not hidden a dropped WAL buffer whose failure became a
  background error. Failures that do not become a background error are
  listed under "Not changed" below.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  or by a failed sync of a closed WAL). So the synced records survive a
  crash. A closed WAL had its buffer written by the memtable switch that
  closed it, so a failed sync of a closed WAL drops no buffered records.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true and the DB is stopped. Every
    WAL failure that becomes a background error is a hard error or worse,
    which stops the DB, so a recovery from such a failure still gets the
    reset. A WAL failure that does not become a background error has
    already reset its writer in WALIOStatusCheck(). The switch records every
    failed buffer write as a background error, also with paranoid_checks off
    or a Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failed
    WAL is the current one. SyncWAL(), the flush that syncs closed WALs, and a
    write with sync=true can fail on a closed WAL, and they set no mark then. A
    new parameter of WALIOStatusCheck() (enum FailedWAL) says when the caller
    knows that a closed WAL failed: WriteGroupToWAL() reports a failed sync of a
    WAL that is not the one it wrote, for normal and pipelined writes, and
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. WALIOStatusCheck() also skips the mark when the failed WAL
    number is below cur_wal_number_ (the DB mutex is held there), for a WAL that
    a switch closed after the caller started. The failed WAL number that the
    write path passes, which the file-scoped WAL recovery uses, is unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::FailedWAL (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the switch
  fails on the writer and records a fatal error. Without a recovery, master
  does the same. During a soft-error recovery, master resets the writer at
  the switch instead.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- A memtable switch resets a failed WAL writer only while the DB is stopped
  during a recovery that can still succeed. During a soft-error recovery,
  the DB is not stopped, so FlushWAL() does not check for a failed WAL
  write. There, the switch keeps the error of the failed writer, so the
  switch fails and records it as a background error. So when FlushWAL()
  returns OK, it has not hidden a dropped WAL buffer whose failure became a
  background error. Failures that do not become a background error are
  listed under "Not changed" below.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  or by a failed sync of a closed WAL). So the synced records survive a
  crash. A closed WAL had its buffer written by the memtable switch that
  closed it, so a failed sync of a closed WAL drops no buffered records.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true and the DB is stopped. Every
    WAL failure that becomes a background error is a hard error or worse,
    which stops the DB, so a recovery from such a failure still gets the
    reset. A WAL failure that does not become a background error has
    already reset its writer in WALIOStatusCheck(). The switch records every
    failed buffer write as a background error, also with paranoid_checks off
    or a Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failed
    WAL is the current one. SyncWAL(), the flush that syncs closed WALs, and a
    write with sync=true can fail on a closed WAL, and they set no mark then. A
    new parameter of WALIOStatusCheck() (enum FailedWAL) says when the caller
    knows that a closed WAL failed: WriteGroupToWAL() reports a failed sync of a
    WAL that is not the one it wrote, for normal and pipelined writes, and
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. WALIOStatusCheck() also skips the mark when the failed WAL
    number is below cur_wal_number_ (the DB mutex is held there), for a WAL that
    a switch closed after the caller started. The failed WAL number that the
    write path passes, which the file-scoped WAL recovery uses, is unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::FailedWAL (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the switch
  fails on the writer and records a fatal error. Without a recovery, master
  does the same. During a soft-error recovery, master resets the writer at
  the switch instead.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- A memtable switch resets a failed WAL writer only while the DB is stopped
  during a recovery that can still succeed. During a soft-error recovery,
  the DB is not stopped, so FlushWAL() does not check for a failed WAL
  write. There, the switch keeps the error of the failed writer, so the
  switch fails and records it as a background error. So when FlushWAL()
  returns OK, it has not hidden a dropped WAL buffer whose failure became a
  background error. Failures that do not become a background error are
  listed under "Not changed" below.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  or by a failed sync of a closed WAL). So the synced records survive a
  crash. A closed WAL had its buffer written by the memtable switch that
  closed it, so a failed sync of a closed WAL drops no buffered records.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true and the DB is stopped. Every
    WAL failure that becomes a background error is a hard error or worse,
    which stops the DB, so a recovery from such a failure still gets the
    reset. A WAL failure that does not become a background error has
    already reset its writer in WALIOStatusCheck(). The switch records every
    failed buffer write as a background error, also with paranoid_checks off
    or a Busy or Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failed
    WAL is the current one. SyncWAL(), the flush that syncs closed WALs, and a
    write with sync=true can fail on a closed WAL, and they set no mark then. A
    new parameter of WALIOStatusCheck() (enum FailedWAL) says when the caller
    knows that a closed WAL failed: WriteGroupToWAL() reports a failed sync of a
    WAL that is not the one it wrote, for normal and pipelined writes, and
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. WALIOStatusCheck() also skips the mark when the failed WAL
    number is below cur_wal_number_ (the DB mutex is held there), for a WAL that
    a switch closed after the caller started. The failed WAL number that the
    write path passes, which the file-scoped WAL recovery uses, is unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::FailedWAL (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the switch
  fails on the writer and records a fatal error. Without a recovery, master
  does the same. During a soft-error recovery, master resets the writer at
  the switch instead.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error Do not retry a failed WAL writer after a fatal background error (#15820) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails and records the error as a background error. So
  when FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes.

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, and either the DB is stopped or
    the mark is not set. The switch reads the mark under wal_write_mutex_,
    and FlushWAL() sets its early mark under the same mutex. So a switch in
    the window of a failed FlushWAL() always sees the mark of that failure.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. The switch records every failed buffer
    write as a background error, also with paranoid_checks off or a Busy or
    Incomplete status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error (#15820) Do not retry a failed WAL writer after a fatal background error Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error Do not retry a failed WAL writer after a fatal background error (#15820) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer:

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a
  failed WAL writer, except in one case: a failure that becomes a
  background error has set the WAL-failure mark (see Implementation), and
  the DB is not stopped. This happens during a soft-error recovery, in the
  window where FlushWAL() has failed its buffer write but has not yet
  recorded the error. FlushWAL() checks the mark only while the DB is
  stopped, so a reset there could hide the dropped buffer. Without the
  reset, the switch fails on the writer with "Seen error", an IOError. With
  manual_wal_flush, that IOError would be a fatal error, whatever the status
  of the failed FlushWAL() was. So the switch does not record it. It returns
  the current background error (the soft error) and leaves the recording to
  the failed FlushWAL() call, which records its own status. So when
  FlushWAL() returns OK, it has not hidden a dropped WAL buffer whose
  failure became a background error. All other failures get the reset, as
  on master: failures that do not become a background error (see "Not
  changed" below), and all failures in DBs without manual_wal_flush.
- In the same window, another FlushWAL() also fails on the failed writer
  with "Seen error". It returns that error but does not record it, and the
  failed FlushWAL() call records its own status. SyncWalImpl() follows the
  same rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() writes the failed writer before the
  failed FlushWAL() records its hard error (S9 to S11 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush,
    DBImpl sets it when it records a failed buffer write or sync of the
    current WAL as a background error, with the DB mutex held, next to
    SetBGError(): the memtable switch marks every failed buffer write, and
    the other sites use the WALIOStatusCheck() condition (see db_impl.h
    below). FlushWAL()
    also sets it right after a failed buffer write, before it records the
    error, so that a concurrent FlushWAL() sees it in that window. Setting it
    again next to SetBGError() covers a recovery whose ClearBGError() runs in
    that window. A failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status) only resets the
    WAL writer, and RocksDB keeps using the WAL, so it sets no mark.
    ClearBGError() clears the mark with the background error. The mark
    is never cleared in other places: a later successful buffer write, even
    with a sync, or a switch to a new WAL does not bring back the dropped
    records, and clearing the mark there would bring back the false OK of
    the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When
    FailedFlushWALNotRecordedYet() is true (see db_impl.h below), the buffer
    write fails with "Seen error", and FlushWAL() returns it without marking
    or recording it.
  - Two new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer when
    CanRetryFailedWALWrites() returns true, unless
    FailedFlushWALNotRecordedYet() is true. The switch reads the mark under
    wal_write_mutex_, and FlushWAL() sets its early mark under the same
    mutex. So a switch in the window of a failed FlushWAL() always sees the
    mark of that failure. In that case, the switch does not record its own
    failed buffer write ("Seen error"). It returns the current background
    error, and the failed FlushWAL() records its own status.
    Every WAL failure that becomes a background error is a hard error or
    worse, which stops the DB once it is recorded, so a recovery from such a
    failure still gets the reset. A failure that sets no mark gets the
    reset, as on master: a failure that does not become a background error
    (paranoid_checks off, or a Busy or Incomplete status), any failure
    without manual_wal_flush, and a failed sync of the current WAL before
    WALIOStatusCheck() records it. Apart from the case above, the switch
    records every failed buffer write as a background error, also with
    paranoid_checks off or a Busy or Incomplete status, so it marks every
    one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New
  DBImpl::FailedFlushWALNotRecordedYet(), called with wal_write_mutex_ held:
  true when the mark is set, the DB is not stopped, and the current WAL
  writer has an error. Other failures set the mark and record a hard error
  or worse in one hold of the DB mutex, which stops the DB. So when the
  helper is true, the call that set the mark (a failed FlushWAL(), or a
  failure that is being recorded under the DB mutex) records its own status,
  unless an OnBackgroundError() listener lowers the error. In that case the
  mark stays set until ClearBGError(), so FlushWAL() keeps returning "Seen
  error" and a recovery switch keeps returning the soft error; none returns
  OK. New enum DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | err, lost |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | err, kept |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S10, B writes A's failed
  writer, because the switch kept it, so B fails. A then records its hard
  error, the recovery keeps k1, and a FlushWAL(sync=true) after the recovery
  returns OK. On master, B's OK is not backed by the WAL: k1 is only in the
  memtable, so a crash before the recovery flush ends would lose it. In S11,
  on master, B records its "Seen error" as a fatal
  error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL() adds its record to A's failed WAL
  writer, fails with "Seen error", and records it as a fatal error, as on
  master. Only the memtable switch and FlushWAL() leave the recording to
  the failed FlushWAL() call.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error (#15820) Do not retry a failed WAL writer after a fatal background error Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
…#15820)

Summary:
Pull Request resolved: meta#15820

Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer. This change fixes the third way for a recovery from a hard error,
   but not for a soft-error recovery (S7 below, a known gap):

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a failed
  WAL writer, as on master. During a soft-error recovery, which does not stop
  the DB, this includes the window where a FlushWAL() call (call A) has failed
  its buffer write but has not yet recorded the error. FlushWAL() refuses to
  write the buffer because of the WAL-failure mark (see Implementation) only
  while the DB is stopped, so in that window the reset can still hide the
  dropped buffer, as on master (S7 below, a known gap). The switch does not skip
  the reset there. Without the reset, the switch would fail on the writer with
  "Seen error", an IOError, which is a fatal error with manual_wal_flush. The
  switch would have to record that error: it has already marked the active
  memtable immutable, and only a stopped DB keeps writes out of that memtable.
  Then the recovery could not keep the dropped records, also when A's error is
  only a hard error, where master keeps them (S9, S10, S12 and S13 below).
- In A's window, another FlushWAL() (call B) fails on the failed writer
  with "Seen error", if no switch has reset that writer. It returns that
  error but does not record it, and A records its own status. This also
  holds when A records its error and stops the DB after B's stop checks but
  before B's buffer write. B then sees the mark, and the mark always comes
  from a call that records its own error. SyncWalImpl() follows the same
  rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() runs before the failed FlushWAL()
  records its hard error (S9 to S14 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush, DBImpl
    sets it when it records a failed buffer write or sync of the current WAL as
    a background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use the
    WALIOStatusCheck() condition (see db_impl.h below). FlushWAL() also sets it
    right after a failed buffer write, before it records the error, so that a
    concurrent FlushWAL() sees it in that window. Setting it again next to
    SetBGError() covers a recovery whose ClearBGError() runs in that window. A
    failure that does not become a background error (paranoid_checks off, or a
    Busy or Incomplete status) only resets the WAL writer, and RocksDB keeps
    using the WAL, so it sets no mark. ClearBGError() clears the mark with the
    background error. The mark is never cleared in other places: a later
    successful buffer write, even with a sync, or a switch to a new WAL does not
    bring back the dropped records, and clearing the mark there would bring back
    the false OK of the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When the mark is set
    and the current WAL writer has an error, the buffer write fails with
    "Seen error" and does no I/O, and FlushWAL() returns that error without
    marking or recording it. The call that set the mark records its own
    error: every call that sets the mark records its error as a background
    error. The DB may already be stopped then, because that call can record
    its error after the stop checks; the stop checks let a call through
    with the DB stopped only while the mark is clear. So the check does not
    look at IsDBStopped(). An OnBackgroundError() listener can lower the
    error of that call. Then the writer error stays until ClearBGError() or
    until a memtable switch during a recovery resets the writer, as on
    master. Until then, FlushWAL() returns an error.
  - Three new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true, instead of whenever a recovery
    is in progress. The switch records every failed buffer write as a
    background error, also with paranoid_checks off or a Busy or Incomplete
    status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | S0: retryable error first, then A's FlushWAL()     | err, lost | err, lost |
  | S1: race, A records its error after the switch     | OK, lost  | err, lost |
  | S2: race, the whole recovery runs before A records | OK, kept  | err, kept |
  | S3: retryable TimedOut on the buffer write         | OK, kept  | OK, kept  |
  | S4: file-scoped Aborted on the buffer write        | OK, kept  | OK, kept  |
  | S5: paranoid_checks=false plus the race (S2 order) | OK, kept  | OK, kept  |
  | S6: S1, B passed its first check before A failed   | OK, lost  | err, lost |
  | S7: soft-error recovery, a user Flush() switches   |           |           |
  |     the memtable in A's window (the S1 window)     | OK, lost  | OK, lost  |
  | S8: S7, but A's error sets no background error     |           |           |
  |     (paranoid_checks off, Busy, Incomplete)        | OK, kept  | OK, kept  |
  | S9: S7, but A's error is a hard error (retryable   |           |           |
  |     TimedOut or file-scoped Aborted), B after the  |           |           |
  |     recovery                                       | OK, kept  | OK, kept  |
  | S10: S9, but B runs in A's window after the switch | OK, kept  | OK, kept  |
  | S11: S9, B runs in A's window, no switch           | err, lost | err, kept |
  | S12: S9, but a Put() of a new key follows the      |           |           |
  |      switch in A's window (cells: the Put())       | OK, kept  | OK, kept  |
  | S13: S12, but the Put() uses disableWAL            | OK, kept  | OK, kept  |
  | S14: S11, but A records its error and stops the DB |           |           |
  |      between B's stop checks and its buffer write  | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S7, the switch resets A's
  failed writer, B syncs the new WAL and returns OK, A then records a fatal
  error, and the recovery cannot keep k1. That is a known gap, the same as
  on master (see "Not changed" below). A FlushWAL() after A records its
  error fails, where master returns OK. In S9, S10, S12 and S13, the switch
  also resets the writer, and A's hard error lets the recovery keep k1, as
  on master. In S11 and S14, B writes A's failed writer and fails, but it
  leaves the recording to A, so A's hard error stays, the recovery keeps
  k1, and a FlushWAL(sync=true) after the recovery returns OK. On master, B
  records its "Seen error" as a fatal error, so the recovery cannot keep
  k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

  | Case                                               | master    | this diff |
  |----------------------------------------------------|-----------|-----------|
  | H1: retryable MANIFEST error, recovery gave up     | OK, kept  | OK, kept  |
  | H2: the same, while the failing recovery still runs| OK, kept  | OK, kept  |
  | H3: fatal MANIFEST error                           | OK, kept  | OK, kept  |
  | H4: a WAL error that sets no background error      |           |           |
  |     (paranoid_checks off, Busy, Incomplete), then  |           |           |
  |     a fatal MANIFEST error                         | OK, kept  | OK, kept  |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL(), with no memtable switch before it in
  that window, adds its record to A's failed WAL writer, fails with "Seen
  error", and records it as a fatal error, as on master. Only FlushWAL()
  leaves the recording to the failed FlushWAL() call. After a switch in
  that window, the write goes to the new WAL, as on master (S12, S13).
- Not changed (known gap, S7): during a soft-error recovery, a memtable
  switch in the window of a failed FlushWAL() (call A) resets A's failed
  writer and moves to a new WAL, as on master. A FlushWAL() in that window,
  after the switch, can return OK although k1 is in no WAL file. If A's
  error is fatal (an IOError), the recovery cannot keep k1. Once A records
  its error, FlushWAL() fails. Keeping the failed writer at the switch would
  make the switch record a fatal error and lose writes that master keeps
  (S9, S10, S12, S13). A fix needs the switch to finish and abandon the
  failed WAL, as the file-scoped WAL recovery does, and FlushWAL() to refuse
  OK while A's failure is not recorded. That is the open TODO in
  ErrorHandler::SetBGErrorImpl(), and a possible follow-up.
- No API, option or format change.

Differential Revision: D134907307
@meta-codesync meta-codesync Bot changed the title Do not retry a failed WAL writer after a fatal background error Do not retry a failed WAL writer after a fatal background error (#15820) Dec 1, 2026
… atomic compaction unit covers it

Summary:
## Background

`TimedPut()` writes an entry of type `kTypeValuePreferredSeqno`. It carries its own sequence number and a smaller preferred sequence number, which comes from the write time through the seqno-to-time mapping. When a compaction proves that no older version of the key exists below the output level (`bottommost_level` or `KeyNotExistsBeyondOutputLevel()`), `CompactionIterator` swaps the entry to its preferred sequence number and writes it as a `kTypeValue`. Before the swap, it asks the compaction's range tombstone aggregator whether a tombstone would cover the entry at the preferred sequence number. If one would, it writes the entry unchanged, because a tombstone that is older than the entry must not delete it after the swap.

Compaction can cut its output between two versions of one user key: for example, when a snapshot keeps both versions and the file reaches its size limit, or at a grandparent or TTL cut, or at the start of a range tombstone. Adjacent files of one level that share a boundary user key form one atomic compaction unit (`Compaction::PopulateWithAtomicBoundaries()`). The exception is a file whose largest key is a range tombstone sentinel. When a range tombstone continues into the next file and the next file starts with a different user key, the earlier file ends at a sentinel key (the next file's first user key, `kMaxSequenceNumber`, `kTypeRangeDeletion`). Such a file ends its unit. When the cut falls between two versions of one user key, the earlier file ends at its last point key instead (`CompactionOutputs::AddRangeDels()`). Both files then share that user key and are one unit. When a later compaction reads a file of a unit with two or more files, it truncates the file's range tombstones at the bounds of the whole unit, not at the file's own bounds, because truncating at the shared user key could cut a tombstone between two versions of that key.

## The problem

A compaction reads each non-L0 input level through a `LevelIterator`. The `LevelIterator` adds the range tombstones of a file to the aggregator only when it opens that file. A tombstone in a later file of a multi-file unit is therefore not in the aggregator while the compaction is on a key in an earlier file of that unit, but after truncation at the unit bounds it can cover that key. The covered key can be the shared boundary key, a key before it in the earlier file, or a key from another input level whose range overlaps the unit. When such a key is a `TimedPut()` entry, the tombstone check of the swap passes, the entry is swapped to a preferred sequence number below the tombstone, and the tombstone, which goes to the same output, then covers it.

A worked example, reproduced by a new regression test (the sequence numbers are an example):

```
L6: [k6]
writes: DeleteRange [k2, k8) 102, snapshot S1
        TimedPut(k3) 103          preferred seqno 0 (an old write time)
        Put(k4, "old") 104, snapshot S2, Put(k4, "new") 105, Put(k7)
compaction 1 (L0 -> L5, cut between the two versions of k4):
  L5 file A: k3@103 (kTypeValuePreferredSeqno), k4@105
             tombstone dropped: no L6 data under A's range
  L5 file B: k4@104, k7, tombstone [k2, k8)102 kept: L6 has k6
  A and B share the user key k4, so they are one atomic compaction unit
release S1 and S2
compaction 2 (L5 -> L5, not bottommost):
  on k3@103, file B is not open, so the swap check sees no tombstone
  swap: k3@0 (kTypeValue)
  file B is opened; its tombstone, truncated to the unit start k3, covers k3@0
result: Get(k3) returns NotFound, and a later compaction drops k3@0
```

The value is lost even though the tombstone is older than the write. The crash test found it: a key written with `TimedPut()` was missing after recovery, and the MANIFEST showed a `TimedPut()` entry at the end of one L5 file and a range tombstone that starts at the same user key at the start of the next file, before the compaction that lost the value.

The bug needs all of these:
- a `TimedPut()` entry whose preferred sequence number is below the sequence number of an older range tombstone that covers its key;
- that tombstone in a file of a multi-file atomic compaction unit, in a later file than the entry's key position, with the entry's key inside the unit;
- a compaction with level compaction style whose output level is not the bottommost, and where no level below the output holds the key.

Only level compaction swaps below the bottommost level: `KeyNotExistsBeyondOutputLevel()` returns false for other compaction styles unless the compaction is bottommost. At the bottommost level the swap is safe: a tombstone that is older than the entry is also older than the earliest snapshot there, and bottommost compaction output drops such tombstones. A `Put()` is not affected, because it keeps its own sequence number.

Values that were already lost cannot be recovered. This change protects future compactions only.

## The fix

In a compaction that is not bottommost, `CompactionIterator` does not swap a `kTypeValuePreferredSeqno` entry whose user key is inside a multi-file atomic compaction unit of any non-L0 input level. It writes the entry unchanged, through the existing "not safe to swap" path. The entry keeps its own sequence number, which is newer than the tombstone, so the tombstone cannot cover it. It also keeps its packed preferred sequence number, so a later compaction can still swap it. A bottommost compaction swaps as before, because the swap is safe there (see above).

On the first entry that needs them, the iterator builds the user-key ranges of the units that have two or more files, over all non-L0 input levels, and merges them into sorted, disjoint ranges. A compaction without such entries does not build them. Each lookup is one binary search. The ranges come from `Compaction::boundaries()`, the unit bounds that each `LevelIterator` of this compaction passes with a file when it truncates the file's range tombstones. A file is in a multi-file unit when its unit bounds differ from its own smallest or largest key. So two files that only touch at a range tombstone sentinel stay separate units, as in `Compaction::PopulateWithAtomicBoundaries()`. The ranges also include the last file of each unit, where the swap would be safe, to keep the rule simple.

## Changes visible to existing users

Only for `TimedPut()` entries in a compaction that is not bottommost, with a key inside a multi-file atomic compaction unit: the entry is written unchanged until a later compaction swaps it. Until then:
- it keeps its packed preferred sequence number, 8 more bytes in the value;
- it is not passed to the compaction filter, because `InvokeFilterIfNeeded()` skips `kTypeValuePreferredSeqno`;
- it is not moved to a blob file, because `PrepareOutput()` extracts only `kTypeValue`;
- it is not counted in `num_timed_put_swap_preferred_seqno`.

## Paths checked

- L0 inputs: `VersionSet::MakeInputIterator()` opens every L0 input file when it builds the input iterator and adds its range tombstones at that time, so L0 cannot have the gap. The fix skips L0 units.
- Flush: `CompactionIterator` gets no compaction, so the swap branch never runs.
- Level compactions (automatic, manual, `CompactFiles()`) and remote compaction workers build their input in `MakeInputIterator()`, with one `LevelIterator` per non-L0 level. Subcompactions clip that iterator to their key range and can have the gap too. The ranges come from the inputs of the whole compaction, so they cover every subcompaction.
- `MergeHelper::MergeUntil()` and `CompactionOutputs::AddRangeDels()` also read the aggregator. With a tombstone that is loaded late, they can only keep an entry, or leave a copy of the tombstone out of an output file. A file drops its copy only when nothing older that the tombstone covers can remain.
- Other decisions that consult the aggregator do not lower a sequence number below an unseen tombstone. Sequence number zeroing in `PrepareOutput()` runs only at the bottommost level, where the tombstone is dropped as described above. The first tombstone check of the swap branch uses the entry's own sequence number; missing coverage there can only keep a covered entry, and that entry cannot come back to life, because the dropped copy of the tombstone already required that no snapshot needs the older data.

## Possible follow-ups

This change is a temporary fix that covers only the swap, and it skips some swaps that are safe. Either of the first two follow-ups can replace it.

- Root cause: when the compaction `LevelIterator` opens a file of a multi-file unit, it could also add the range tombstones of the remaining files of that unit to the aggregator. Every reader of the aggregator would then see the full coverage of the unit, at the cost of opening table readers earlier. This change does not touch the `LevelIterator` or tombstone loading.
- Smaller check: `IsInMultiFileUnit()` could binary-search each level's `Compaction::boundaries()` directly, instead of building a sorted, merged copy of the unit ranges. The behavior stays the same with less code.
- A compaction into a level that is not the bottommost could avoid cutting between a point entry and a range tombstone that start at the same user key, as the bottommost branch of `CompactionOutputs::AddToOutput()` already does. That would remove one source of splits, but not cuts between two versions of a point key, and it cannot repair existing files.

Reviewed By: pdillinger

Differential Revision: D134698940
…on inputs

Summary:
Background: in universal compaction, a compaction can start with a standalone range deletion file, which is a file that holds only one range tombstone (usually from an ingestion that replaces a key range). When that tombstone is visible to the earliest snapshot, `Compaction::FilterInputsForCompactionIterator()` leaves out each input file of the other input levels that the tombstone fully covers (whole-file filtering, added in PR meta#13078). `Compaction::input_levels(i)` then returns only the kept files, and the compaction reads only those.

The compaction reads each non-L0 input level with a `LevelIterator`. When it opens a file, it cuts the range tombstones of that file to the file's atomic compaction unit boundary. An atomic compaction unit is a run of files in one level that share user keys at their edges and must be compacted together. `Compaction::boundaries(i)` gives one boundary per file, and `LevelIterator` reads it by the file's position in `input_levels(i)`.

The problem: `boundaries(i)` follows the list of all input files of the level, not the list of kept files. After a file is left out, every later kept file in that level reads the boundary of a different (earlier) file. Its range tombstones are cut to that wrong key range and can stop covering keys they should hide. Two cases lose data:
- An older version of a key sits in a level below the kept file, under the kept file's range tombstone. The cut tombstone no longer hides it. If that level is below the output level, reads see the old value again. If that level is a lower input level of the same compaction, the compaction writes the old value to the output, also when the output is the last level. For example, with L5 files ["a", "b"] and ["c", "z"], where the second file holds a tombstone ["d", "e") that hides "d" in L6, a standalone deletion ["a", "d") leaves out the first file. The second file then reads the boundary ["a", "b"], its tombstone is dropped, and Get("d") returns the old L6 value. This happens both when the compaction writes into L5 and when it also reads the L6 file and writes into L6. The tests below reproduce both shapes.
- The kept file itself holds an older version of a key under its own range tombstone, for example because a snapshot kept it when the file was written and was released later. The cut tombstone does not hide that version, so it is written to the output and becomes visible again, also when the output is the last level.
A deleted key comes back in both cases. Keys that an earlier compaction already brought back stay visible; this change does not repair them.

Fix: when `FilterInputsForCompactionIterator()` checks the input files against a standalone range deletion, it also builds, for each input level, the list of boundaries of the kept files, in the same order as `input_levels(i)`. Each kept file keeps the boundary of its own unit, as computed from all input files, which is the same cut the compaction would use without filtering. When a left-out file was in the same unit as a kept file, that boundary is wider than the kept file. The extra key range lies inside the standalone deletion, which is newer than any key the kept file's tombstones could hide there, so the wider cut hides no extra live keys (derived from the code; one test below checks such a case). `boundaries(i)` returns the kept list when this check ran and the original list otherwise. A debug check in the `Compaction` constructor asserts that each non-L0 level has one boundary per file in `input_levels(i)`.

`CompactionIterator::BuildMultiFileUnitRanges()` also reads `boundaries(i)` and `input_levels(i)` by file position. It asserts that the two lists have the same size, and its comment says that both name the same files by position.

Who is affected: universal compaction where a standalone range deletion file starts the compaction and leaves out at least one file before a kept file in the same input level.
- On the primary, only delete-triggered and read-triggered universal compactions filter their inputs. Other universal compactions and `DB::CompactFiles()` on the primary do not. These two kinds read only the start level and the next non-empty level, so the hidden older value always sits below the output level or in the kept file itself.
- A remote compaction worker rebuilds every universal compaction with the earliest snapshot and filters its inputs, so on the worker any universal compaction that starts with a standalone range deletion file can be affected, including one from `DB::CompactFiles()`. Such a compaction can read three or more levels and write into the last level, so the hidden older value can also sit in a lower input level of the same compaction.
- Level and FIFO compaction do not filter inputs.
The fix is in `Compaction`, so it covers the primary and the remote worker.

Compatibility: no format, option or public API change. `boundaries()` has two callers: the compaction input iterator (`VersionSet::MakeInputIterator()`) and `CompactionIterator::BuildMultiFileUnitRanges()`. Both pair it with `input_levels(i)` by position. The subcompaction and stats code in `CompactionJob` uses `input_levels(i)` and does not read boundaries.

Reviewed By: pdillinger

Differential Revision: D134907303
Summary:
With `atomic_flush=true`, a retryable error from the directory sync of a flush
can make the DB hang. By default the automatic error recovery hangs. With
`max_bgerror_resume_count=0`, a manual `DB::Resume()` hangs instead. Then
`DB::Close()` hangs too, so the process has to exit. With the WAL off, a crash
can also lose the writes of the failed flush.

Background: `DBImpl::AtomicFlushMemTablesToOutputFiles()` runs one flush job
per column family, then syncs the output directories, and only then installs
all results in one MANIFEST write. If anything fails before the install, the
function rolls back the picked memtables
(`MemTableList::RollbackMemtableFlush()`), so that a later flush can pick them
again. One such flush is the flush of the
automatic error recovery (auto resume by `ErrorHandler`).

The problem: the directory sync runs inside the branch for "all jobs
succeeded". When the sync fails, the function sets the error status there, but
the rollback is in the `else` branch of that check. The later rollbacks run
only when the status is still OK: the one after a failed wait for the install
turn, and the one inside `InstallMemtableAtomicFlushResults()` when the
MANIFEST write fails. So no rollback runs. The picked memtables keep their
"flush in progress" mark, although nothing was installed and the new SST files
are later deleted as obsolete.

This is a regression of
[PR meta#6385](meta#6385) ("Atomic flush
rollback once on failure"), first released in RocksDB 6.8. Before that change,
the rollback ran at the end of the function for any error except a dropped
column family, which covered a failed directory sync. That change moved the
rollback into the `else` branch, to avoid a second rollback after a failed
MANIFEST write.

Which errors trigger the bug:
- A retryable error from the sync becomes a soft error that stops background
  work, and the automatic recovery starts. With `max_bgerror_resume_count=0`,
  it is a hard error instead, and writes stop until `DB::Resume()`. In both
  cases the DB later needs a flush of the stuck memtables.
- A non-retryable error from the sync is reported with
  `BackgroundErrorReason::kFlushNoWAL`, with the WAL on or off. With the
  default `paranoid_checks=true`, it is a fatal error, and `DB::Resume()`
  fails at once. The stuck memtables do not change that result.
- A failed flush job, or a failed MANIFEST write, is not affected: those paths
  roll back already. Non-atomic flushes sync the directory inside the flush
  job and roll back on error.

Effect of the stuck memtables:
- Later flushes skip that column family while it has no newer immutable
  memtable. A later atomic flush can still install the other column families
  and write a larger last sequence number to the MANIFEST. The automatic error
  recovery does this: it requests a flush of every column family with
  immutable memtables, but the stuck column family is skipped when the flush
  job picks memtables.
- The recovery then waits forever for the stuck memtable to be flushed
  (`WaitForFlushMemTables()` in `DBImpl::ResumeImpl()`). `DB::Close()` waits
  for the recovery: it joins the automatic recovery thread, or waits while a
  manual `DB::Resume()` is in progress. So `DB::Close()` hangs too.
- The stuck column family can never flush again. When a newer memtable is
  sealed, the next atomic flush picks only the newer one and then waits
  forever to install it, because the stuck memtable is older. Immutable
  memtables pile up until writes stop.
- With the WAL off (`WriteOptions::disableWAL`), a crash then loses the writes
  in the stuck memtables, while newer writes to other column families
  survive. That breaks the atomic flush promise that `DB::Open()` recovery
  without a WAL gives a consistent point in time across column families. With
  the WAL on, no data is lost, because the stuck column family keeps its old
  log number and `DB::Open()` replays its writes from the WAL.

A crash test found this with many small atomic flushes and injected metadata
write errors, with the WAL off.

Fix: run the rollback whenever the status is an error that is not
`ShutdownInProgress`, also when the directory sync set the error. The rollback
code itself is unchanged. A small side effect: when a flush job returned
`ShutdownInProgress` and the directory sync then fails, the rollback runs.
That is harmless, because the DB is closing.

Compatibility: no format, option or public API change. Only the error path of
atomic flush changes.

Reviewed By: pdillinger

Differential Revision: D134907304
Summary:
Background: when a MANIFEST write fails, RocksDB cannot know whether the
failed edit is in the MANIFEST that CURRENT names. For example, the record can
be written and synced before the error is reported. Or a batch can create a new
MANIFEST, rename CURRENT to it, and then get an error from the directory sync.
So `VersionSet::ProcessManifestWrites()` puts the new files of the failed batch
(the edits of one `ProcessManifestWrites()` call) in the error handler
quarantine, and the purge of obsolete files does not
delete them. When a MANIFEST write fails, `ProcessManifestWrites()` also resets
`descriptor_log_`, and a batch without a `descriptor_log_` sets
`new_descriptor_log`. So the next batch that writes the MANIFEST always starts
a new MANIFEST. Once that new MANIFEST is installed, the old one is no longer
used, and the quarantine is cleared. `VersionSet::io_status_` keeps the MANIFEST
write error until then.

How the code got into this state:
- Since meta#7034, `ProcessManifestWrites()` resets `io_status_` after any call
  whose MANIFEST I/O status is OK. It records only the first error.
- meta#12030 added the quarantine. It added the files of a failed batch only inside
  the "first error" block, and it cleared the quarantine together with the
  reset of `io_status_`. At that time `SetOptions()` still wrote to the
  MANIFEST.
- meta#13384 made `SetOptions()` skip the MANIFEST write. So every `SetOptions()`
  became a call with an OK MANIFEST I/O status that writes no new MANIFEST.

The problems:
1. Two kinds of calls have an OK MANIFEST I/O status but write no new MANIFEST:
   - `DBImpl::SetOptions()` installs a new Version through `LogAndApply()` with
     an edit that writes nothing to the MANIFEST (`skip_manifest_write`).
   - A batch can fail before any MANIFEST I/O, for example when
     `LoadTableHandlers()` fails with `paranoid_checks`. A compaction that is
     already running when a flush's MANIFEST write fails still commits,
     because the background error is checked only when the compaction starts.
   After such a call, the old MANIFEST can still hold the failed edit, but its
   files are no longer quarantined.
2. A second failed MANIFEST write, while `io_status_` already holds an earlier
   error, does not quarantine its own files. This is a problem when the second
   batch creates a new MANIFEST and renames CURRENT to it, and then reports an
   error. CURRENT names the new MANIFEST, and it lists the new files.

In both cases, the purge after the failed job, or the purge in a clean
`Close()`, deletes the files. When CURRENT names a MANIFEST that lists a
deleted file, every `DB::Open()` fails with "Corruption: IO
error: No such file or directory ... .sst The file MANIFEST-... may be
corrupted". A db_stress crash test hit problem 1: a flush's MANIFEST write got
an injected write error, a `SetOptions()` ran about 1.6 ms later and cleared
the quarantine, the flush job deleted its SST, and the harness killed the
process. This change cannot repair a DB that already lost such an SST.

Example of problem 2, reproduced by the new unit test:

```
1. DropColumnFamily(): the MANIFEST record is synced, then the write reports
   an error. io_status_ = that error. No background error is set.
2. (optional) SetOptions() succeeds.
3. Flush: starts a new MANIFEST that lists the flushed SST, renames CURRENT to
   it, then SetCurrentFile() reports an error.
   io_status_ is already bad, so the SST is not quarantined.
4. The flush job's purge deletes the SST. The next DB::Open() fails.
```

Without step 2, upstream fails this way. With step 2, upstream passes, because
`SetOptions()` resets `io_status_` before the flush, so the flush failure is
the "first" error. Fixing problem 1 alone would make the run with step 2 fail
too, because `SetOptions()` would no longer reset `io_status_`. So this change
fixes both problems.

New behavior:
- Every MANIFEST write failure adds the files of its batch to the quarantine.
  `io_status_` keeps the first error. A file number is added only once,
  because automatic recovery can retry many times, each retry adds the old
  MANIFEST again, and each `FindObsoleteFiles()` copies the list. The check
  uses a hash set of the numbers already in the list, so its cost stays
  linear in the number of files. A failed batch can have many files, for
  example a large ingestion or a refit of a whole level, and the check runs
  under the DB mutex.
- `io_status_` is reset and the quarantine is cleared only when the call wrote
  and installed a new MANIFEST (s is OK and `new_descriptor_log` is set). A
  batch that skips the MANIFEST write never sets `new_descriptor_log`. Until
  then, the files stay quarantined. This is enough for recovery: because
  `descriptor_log_` was reset, the next real MANIFEST write (for example, a
  non-atomic flush, a compaction, or the forced write in `DB::Resume()`)
  starts a new MANIFEST, and its success clears the whole quarantine.
- `DBImpl::SetOptions()` sets no background error after its `LogAndApply()`.
  This part is required, not a cleanup. Since meta#13384, that call does no
  MANIFEST I/O and is never grouped with other writers, so a non-OK
  `io_status()` there always belongs to another, earlier batch. The removed
  block was `if (!versions_->io_status().ok()) { assert(!s.ok());
  SetBGError(...); }`. With only the `VersionSet` change, `io_status()` stays
  non-OK after a successful `SetOptions()`. Then a debug build fails the
  assert, and a release build sets the old error as a fatal background error,
  so the next write fails. A backport must include this part.
- Two callers do not take the old error in `versions_->io_status()` as their
  own when they did not fail on MANIFEST I/O:
  - An atomic flush checks `versions_->io_status()` while it waits for its turn
    to install. The check stops the wait when the flush that it waits for failed
    its MANIFEST write. A flush that does not wait for another flush, while the
    DB is not stopped, ignores the error. With no background error, it installs
    its result. That install writes a new MANIFEST, and its success clears the
    old error and the quarantine. With a soft background error, a flush that is
    not for recovery gets that soft error from the code after the wait and does
    not install, so it reports its own error. A recovery flush installs, which
    writes the new MANIFEST. While the DB is stopped, the flush returns the
    error and does not install, as before this change while io_status() holds
    the error. The check must stay in that case: when the DB is stopped, the
    code after the wait checks only the recovery error, which is OK when no
    recovery runs.
    This also fixes an upstream case. Upstream, a `SetOptions()` after a
    failed MANIFEST write resets io_status(). A later atomic flush could
    then install its result after a fatal background error stopped the DB.
    With this change, io_status() keeps the error until a new MANIFEST is
    written, so that flush returns the error instead. Without any old
    MANIFEST error, an atomic flush that is already running can still
    install after a fatal background error. That is older than this change
    and not about the MANIFEST, so this change leaves it.
  - When the commit of a compaction fails while `versions_->io_status()` is not
    OK, `CompactionJob::Install()` takes the error of that commit as the job's
    I/O status, not `versions_->io_status()`, which keeps the first MANIFEST
    write error and can be older. So a retryable failure of the commit stays a
    hard error, and `DB::Resume()` recovers. A compaction that failed before its
    commit, for example when it could not write an output file, keeps its own
    I/O status.
- The SstFileManager recovers from a soft `NoSpace` error with a direct clear in
  `ErrorHandler::RecoverFromBGError()`, which does not go through
  `DBImpl::ResumeImpl()` and writes no MANIFEST. When the quarantine is not
  empty or `versions_->io_status()` is not OK, the direct clear first writes a
  new MANIFEST with an empty edit, as `DBImpl::ResumeImpl()` does. If that write
  fails, the direct clear sets the error of that write as a background error
  with reason `kManifestWrite`, does not clear, and returns. The SstFileManager
  then retries, unless that error is fatal. If shutdown has started, the direct
  clear does not write and returns `ShutdownInProgress`, as
  `DBImpl::ResumeImpl()` does. Some calls set no background error when their
  MANIFEST write fails, for example a failed `PromoteL0()` or
  `DropColumnFamily()`, so a later soft error can find files in the quarantine.
  Clearing the soft error without a new MANIFEST would be safe, because the
  files stay quarantined and `versions_->io_status()` keeps the error until the
  next new MANIFEST (see the relaxed assert below). The write is kept for its
  benefits: the purge below deletes files that were kept only because of the
  quarantine at once, and the window in which a caller can report the old error
  as its own ends sooner. A DB that keeps flushing would soon write a new
  MANIFEST anyway, so the write matters most for an idle DB and for a DB with
  atomic flush.
  After the new MANIFEST write succeeds, the direct clear runs a full purge of
  obsolete files, so files that were kept only because of the quarantine are
  deleted at once, for example the output of a failed compaction commit.
  Without the purge, such a file stays until the next full purge (a failed job,
  `delete_obsolete_files_period_micros`, or a reopen). The purge also deletes
  the MANIFEST files older than the new one, as the purge after a flush does:
  CURRENT names the new MANIFEST, so it cannot name an older one again. This
  includes a MANIFEST from an earlier failed write that CURRENT may have
  named for a moment. The purge in `DBImpl::ResumeImpl()` keeps every
  MANIFEST file; this change does not touch that older behavior.
  The direct clear also signals `bg_cv_` when it ends, as
  `DBImpl::ResumeImpl()` does. `DB::Close()` waits on `bg_cv_` until no recovery
  runs, and the new MANIFEST write releases the DB mutex, so a close that starts
  during that write would otherwise wait forever.
  If the direct clear fails after a close started (the close can start while the
  MANIFEST write or the purge releases the DB mutex), it returns
  `ShutdownInProgress` (or the fatal background error, if there is one), as
  `DBImpl::ResumeImpl()` does. That ends the recovery,
  so the close does not wait for a later retry by the SstFileManager, which may
  not come while the disk stays full. A foreground MANIFEST write, for example a
  failed `PromoteL0()`, can also fail in those windows. It sets no background
  error, and its files stay quarantined until a later new MANIFEST. So the debug
  assert in `ErrorHandler::ClearBGError()` allows a quarantine that is not empty
  while `versions_->io_status()` holds an error. Upstream's strict assert fires
  after a failed `PromoteL0()` followed by a soft error that the SstFileManager
  clears; this change fixes that case too.
  `SstFileManagerImpl::ClearError()` reads the background error of the DB only
  when it uses it. That changes no behavior. The direct clear can return a
  non-OK status, and an unused, unchecked copy of the error would fail the
  `ASSERT_STATUS_CHECKED` build.
- When the forced MANIFEST write in `DBImpl::ResumeImpl()` fails, it sets the
  error of that write as the background error, with reason `kManifestWrite`.
  `versions_->io_status()` keeps the first MANIFEST write error, which can be an
  older, non-retryable error. Reporting that older error would turn a retryable
  failure of the recovery's own write into a fatal error, and neither
  `DB::Resume()` nor automatic recovery could recover. Upstream has the same
  problem when no `SetOptions()` ran after the older error. With the rest of
  this change, the older error outlives `SetOptions()`, so without this part the
  same failure would go fatal also after a `SetOptions()`, where upstream
  recovers.
- The forced empty edit of `DBImpl::ResumeImpl()` and of the direct clear
  commits in a MANIFEST batch of its own. `ProcessManifestWrites()` gives every
  writer in a batch the status of the batch. So without this, a grouped writer
  that fails before MANIFEST I/O, for example a `PromoteL0()` whose table load
  fails with `Corruption` under `paranoid_checks`, would pass its error to the
  forced edit, and the recovery would set it with reason `kManifestWrite`, which
  makes it fatal. Upstream reports `versions_->io_status()` there, which such a
  failure does not change. A new in-memory flag on `VersionEdit`
  (`MarkNoGroupCommit()`) marks the forced edit, and the grouping loop of
  `ProcessManifestWrites()` stops after a marked writer and before one, as it
  does for a column family add or drop. The flag is never encoded and is not
  part of the MANIFEST record. Only an empty edit that is alone in its
  `LogAndApply()` call may be marked, so an atomic group is never split. A
  debug assert in `LogAndApply()` checks that a marked edit is the only edit
  of its call. The
  cost: during a recovery, writers queued behind the forced edit wait for one
  extra MANIFEST write.

This change closes both problems above: the `SetOptions()` trigger, the
"failure before MANIFEST I/O" trigger, and the second failed MANIFEST write,
with or without a `SetOptions()` in between. The same rule also covers a
running compaction whose commit fails at the CURRENT step after a flush's
MANIFEST write failed (derived from the code, not tested separately).

Consequences:
- Quarantined files can stay longer, until the next new MANIFEST or a reopen.
  This only delays their deletion.
- The automatic clear of a soft `NoSpace` error by the SstFileManager can take
  longer after an older failed MANIFEST write. It writes a new MANIFEST first,
  and it keeps the error if that write fails. The write deletes files that were
  kept only because of the quarantine at once, and it ends sooner the time in
  which another call can report the old error as its own (see the
  `versions_->io_status()` bullet below). If that MANIFEST write fails, its
  error becomes a hard error, so writes stop, and the later retry runs the full
  recovery of `DB::Resume()`, which flushes all column families. If the failed
  write has a non-retryable `IOError`, the error is fatal, and only a reopen
  recovers.
- `DB::Resume()` writes a new MANIFEST when `versions_->io_status()` is an
  `IOError`. Without this change, a `SetOptions()` before the `Resume()` made
  it skip that write. With this change the write happens, and it clears the
  quarantine.
- `versions_->io_status()` keeps an old MANIFEST write error until a new
  MANIFEST is written, and a `SetOptions()` call does not reset it. Several
  callers read it after their own failure and report it as their own error.
  This misattribution is older than this change: it already happened between a
  failed MANIFEST write and the next call with an OK MANIFEST I/O status. The
  worst case is an old non-retryable error that some call left without setting
  a background error. `DropColumnFamily()`, `CreateColumnFamily()`,
  `DeleteFilesInRanges()`, `PromoteL0()`, `IncreaseFullHistoryTsLow()`, the
  level refit of `CompactRange()`, and the file number reservation before an
  ingestion are such calls. A caller that takes that old error can set it as a
  fatal background error, and only a reopen recovers from that. This change
  fixes the cases above (an atomic flush that does not wait, a compaction that
  fails before its commit or in its own commit, and the forced MANIFEST write
  of `DBImpl::ResumeImpl()`). Known cases that stay, all older than this
  change:
  - An atomic flush that waits for another flush still returns the old
    error. This needs two atomic flushes at the same time.
  - A compaction whose commit fails before MANIFEST I/O, for example with
    `Corruption` from `LoadTableHandlers()`, reports its own `Corruption`, but
    with reason `kManifestWrite`, because `DBImpl::BackgroundCompaction()` picks
    the reason from `versions_->io_status()`. The outputs of that compaction
    were never committed.
  - A compaction or flush that fails for its own reason picks the reason
    `kManifestWrite` or `kManifestWriteNoWAL` when the old error exists. For a
    retryable error of a compaction, this makes it a hard error instead of a
    soft error. Automatic recovery or `DB::Resume()` then writes a new
    MANIFEST and recovers, unless an atomic flush is running at that time.
    The hard error stops the DB, so that atomic flush returns the old error.
    When the old error is not retryable, this makes it a fatal error, and
    neither automatic recovery nor `DB::Resume()` recovers. Upstream
    recovers in this case when a `SetOptions()` ran after the old error, and
    goes fatal already at the compaction when none ran. The worse case is
    with `paranoid_checks=false`. By
    the severity table, a non-retryable `IOError` is no error for
    `kCompaction` and `kFlushNoWAL`, but a fatal error for `kManifestWrite`
    and `kManifestWriteNoWAL`. A `NoSpace` error is no error for
    `kCompaction`, but a hard error for `kManifestWrite`.
  - Other calls that write the MANIFEST, such as `ApplyWALToManifest()` and
    the record of the OPTIONS file number in `WriteOptionsFile()`, set
    `versions_->io_status()` as a background error when their `LogAndApply()`
    fails, also when it failed before MANIFEST I/O. Three compaction paths in
    `DBImpl::BackgroundCompaction()` read `versions_->io_status()` after
    their `LogAndApply()` also when it succeeded: the FIFO deletion
    compaction, the FIFO trivial copy (a temperature change), and the
    trivial move. The MANIFEST write that persists a reserved sequence number
    in `DBImpl::ResumeImpl()` (file-scoped WAL write error recovery) still
    sets `versions_->io_status()` when it fails.
  A complete fix tracks the MANIFEST I/O status of each batch, and lets each
  caller report the error of its own batch. That touches `LogAndApply()`,
  flush, compaction and the DB callers above, and is planned as a follow-up.
- An ingestion whose MANIFEST write fails deletes its ingested file in the
  rollback, even when the file is quarantined. This gap is older than this
  change, and it is on a different code path. A follow-up will fix it.
- No API, option or format change.

Reviewed By: pdillinger

Differential Revision: D134907305
Summary:
Background: in the default write path (one write queue, no pipelined write),
the leader of a write group writes the group's record to the WAL with the
sequence numbers that follow `VersionSet::LastSequence()`. Then it inserts
the group into the memtables, and only then publishes the new last sequence
number with `SetLastSequence()`. The next group starts after the published
value.

The problem: a step after the WAL write can fail. With
`WriteOptions::sync=true` and `track_and_verify_wals_in_manifest=true`, the
group records the synced size of each inactive WAL in the MANIFEST
(`ApplyWALToManifest()`). If that MANIFEST commit fails, the group returns
an error, skips the memtable insert and does not publish its sequence
numbers. Its record stays in the WAL. `ApplyWALToManifest()` sets a
background error only when `VersionSet::io_status()` is an IO error. The
commit can fail with `io_status()` OK, for example when the WAL edit shares a
MANIFEST group commit with a compaction edit, and with `paranoid_checks` a
table open error in `LoadTableHandlers()` fails the whole group commit before
the MANIFEST write. Then writes continue in the same WAL, and two things go
wrong:
- The next group writes the same sequence numbers to the same WAL. At the
  next `DB::Open()`, WAL replay either fails with "Sequence number is being
  set backwards during recovery" (the failed group had more operations than
  the next one), or it gives two different entries the same sequence number.
  A db_stress crash test with injected MANIFEST write faults showed the
  reuse.
- The failed write is in the WAL but not in the memtables. `Get()` does not
  return it, but `GetUpdatesSince()` does, and a reopen replays it. For a
  batch that spans column families, a later flush of only some of them makes
  the reopen bring back only the part of the batch in the other column
  families.

Related cases:
- When the same MANIFEST commit fails with an IO error in `io_status()`,
  `ApplyWALToManifest()` sets a background error with it, for example a
  hard error for a retryable IO error. Recovery flushes every column
  family and switches to a new WAL, so the failed record is never replayed.
  meta#15111 fixed a race where that recovery skipped the WAL switch. This diff
  gives the `io_status()` OK case the same handling.
- When the WAL write itself fails with `paranoid_checks=true` and options
  that file-scoped WAL error recovery supports, that recovery keeps the
  failed sequence numbers reserved (`WALIOStatusCheck()` and
  `DBImpl::ResumeImpl()`), so later writes cannot reuse them while the DB stays
  open. With `paranoid_checks=false`, a WAL write error sets no background
  error, and writes continue in the same WAL. The same reuse can happen there.
  This diff does not cover that case.

Fix: after a write group's WAL write, the write path commits the synced WAL
sizes with `DBImpl::ApplyWALToManifestAfterWALWrite()` instead of
`ApplyWALToManifest()`. If that MANIFEST commit fails, it does two things,
with the DB mutex held:
1. It sets one background error with `BackgroundErrorReason::kManifestWrite`.
   The error is the MANIFEST IO error in `io_status()` when there is one, as in
   `ApplyWALToManifest()`, and otherwise the commit status. The severity follows
   the existing rules for that reason. A retryable or file-scope IO error
   becomes a hard error, and automatic recovery (or `DB::Resume()`) flushes
   every column family and switches to a new WAL. NoSpace follows the NoSpace
   rules: a hard error, and `SstFileManager` runs the recovery. Any other error
   becomes a fatal error or worse, and writes stay stopped until the DB is
   reopened. Examples are a plain non-retryable IO error (fatal), a non-IO
   status such as a `Corruption` from `LoadTableHandlers()` (fatal), and an IO
   error with data loss (unrecoverable).
2. It records the failed group's WAL number and sequence range with
   `WalManager::RecordIndeterminateWriteSequence()`, the fence that
   file-scoped WAL error recovery uses. The WAL number is the WAL file that
   the group wrote its record to. The write path keeps it in a local
   variable, because `WriteThread::Writer::wal_used` is not set when the
   group's batch is copied before the WAL write, for example for a batch with
   a WAL termination point, as a WriteCommitted transaction commit has. A
   `GetUpdatesSince()` iterator stops with NotFound before the failed record.
   An iterator that starts after the failed range returns the later writes.

In addition, the single write queue path of `DBImpl::WriteImpl()` publishes
the failed group's last sequence number when the WAL write succeeded but a
later step failed before the memtable insert. The memtable insert is still
skipped. While the DB stays open, a later group then never writes the same
sequence numbers to a WAL (see Limits for a reopen after recovery).

Write modes:
- Default single write queue: changed as above.
- Pipelined write (`enable_pipelined_write`): the background error and the
  fence apply. The sequence numbers are already safe: it takes them in
  `WriteThread::UpdateLastSequence()` before the WAL write.
- `two_write_queues`, write through `WriteImpl()`: the background error and
  the fence apply. It allocates the sequence numbers with
  `FetchAddLastAllocatedSequence()` during the WAL write, so they are already
  safe. A sync write there commits synced WAL sizes to the MANIFEST twice:
  once as above, and once more in the WAL sync that follows, which shares its
  code with `SyncWAL()` (`DBImpl::SyncWALAndApplyToManifest()`). A failure of
  the second commit gets the same background error and fence.
- `unordered_write`, and the WAL-only queue of `two_write_queues`
  (`WriteImplWALOnly()`): not changed. Its sync write calls `SyncWAL()`, and
  `SyncWAL()` calls `ApplyWALToManifest()` itself. `SyncWAL()` does not know
  the sequence range of the write's record, and it is also the public
  `DB::SyncWAL()`. With `paranoid_checks=true`, the existing
  `WriteStatusCheck()` sets a background error for the failure (it skips
  only Busy and Incomplete), so writes stop. No fence is added for
  `GetUpdatesSince()`. The sequence numbers are allocated with a fetch-add,
  so they are safe.
- WritePrepared and WriteUnprepared transactions with one write queue
  (`seq_per_batch`): they use the changed path. The group's sequence numbers
  count batches there, and the published value is the same last sequence
  number that the WAL record covers, so the advance is correct. When the
  MANIFEST commit fails, the pre-release callbacks have not run yet, so no
  prepared sequence number is registered for the failed group. The skipped
  sequence numbers hold no data and are not prepared, so readers see a gap.
  If a pre-release callback fails, the callbacks of earlier writers in the
  group have already run. Publishing the sequence numbers keeps a later group
  from reusing numbers that are already registered as prepared or committed.
  The built-in WritePrepared and WriteUnprepared callbacks always return OK,
  so only a custom callback can take this path. That failure gets no new
  background error or fence: the existing `WriteStatusCheck()` sets a
  background error with `paranoid_checks=true`.

Changes visible to existing users: no format, option or public API change.
- A failed MANIFEST commit of synced WAL sizes stops writes, also when
  `io_status()` is OK. Writes return the background error until recovery
  finishes, or, for an error that allows no recovery, until the DB is reopened.
  A failure that does not stop writes leaves the inconsistent state described
  above, so this cost is accepted. The failure needs a sync write with
  `track_and_verify_wals_in_manifest=true` and a failed MANIFEST group commit,
  so it is rare. The error can be a non-IO status, such as a `Corruption`
  from another edit in the same group commit (for example from the version
  builder). Without this diff and with `paranoid_checks=false`, the write
  path sets no background error for it: the write returns the error, and
  later writes continue in the same WAL. With this diff, the error becomes a
  fatal background error, also with `paranoid_checks=false`, so all later
  writes return that error until the DB is reopened.
- A write that returned an error can still be present after a crash or a
  reopen before recovery retires its WAL, like any failed write whose record
  reached the WAL. The writes and flushes stay stopped until then, so the
  reopen brings back the whole batch, never part of it.
- The published sequence number can skip values that no memtable holds.
  Gaps are already normal, for example with `two_write_queues`.
- `GetLatestSequenceNumber()` moves forward after a failed sync write whose
  WAL record was written, in the single write queue path. The base test
  `DBErrorHandlingFSTest.AutoRecoveryEscalationSwitchesWAL` asserted that the
  value stays the same after such a write; it now expects one more, for the
  one operation of the failed write. Its main checks (the recovery switches
  to a new WAL, and the deleted key stays deleted after a reopen) are
  unchanged.

Limits:
- The `GetUpdatesSince()` fence lasts while the DB is open. If obsolete WALs
  are kept in the archive (`WAL_ttl_seconds` or `WAL_size_limit_MB`),
  `GetUpdatesSince()` after a reopen can still read the failed record from
  the archived WAL. File-scoped WAL error recovery has the same limit.
- A failed WAL write with `paranoid_checks=false` is not covered (see
  Related cases).
- With `two_write_queues`, a sync write whose WAL sync fails records no
  `GetUpdatesSince()` fence. The sync runs in `SyncWalImpl()`, which does
  not pass the group's sequence range to `WALIOStatusCheck()`. So
  `GetUpdatesSince()` can return the failed record, also after recovery.
  With `paranoid_checks=false`, no background error is set and writes
  continue, so a flush of only some column families followed by a reopen
  can bring back part of the failed batch. The sequence numbers are not
  reused, because they come from a fetch-add. The fix for this case, and
  for the failed WAL write above, belongs in a separate change that handles
  WAL write errors.
- With `unordered_write` and `paranoid_checks=false`, a failed MANIFEST
  commit in `SyncWAL()` keeps the original problem: the failed record stays
  in the WAL, its sequence numbers are published, no background error is
  set, and writes continue in that WAL. The WAL-only queue of
  `two_write_queues` (for example a WritePrepared prepare) also keeps the
  failed record with no background error, but its sequence numbers are not
  reused, because they come from a fetch-add.
- After recovery retires the WAL that holds the failed record, the failed
  sequence numbers are reserved only in memory. A flush records in the
  MANIFEST the largest sequence number of its files. So a reopen after
  recovery and before any new write starts below the failed record, and
  later writes reuse its sequence numbers. This happens in every write mode.
  The failed record is only in the retired WAL, which a reopen does not
  replay, so no key shows a wrong value. With archived WALs,
  `GetUpdatesSince()` can read the failed record and then a later record
  with the same sequence numbers. Without this diff, the next write reuses
  the failed sequence numbers at once, with no reopen needed.

Reviewed By: pdillinger

Differential Revision: D134907306
Summary:
Background: With manual_wal_flush, Put() returns OK while its WAL record is
still in the WAL write buffer. The record reaches the WAL file only when
FlushWAL() or a memtable switch writes the buffer. If that buffer write fails,
the WAL writer drops the buffer, so the buffered records may be lost. For this
reason ErrorHandler::SetBGErrorImpl() makes a WAL IOError with manual_wal_flush
fatal (kFatalError, meta#12995). The failed WAL writer remembers its error, so a
later FlushWAL() fails, and the user learns that acknowledged writes may be
lost.

The dropped records are still in the memtables. Since meta#15293, the flush of a
recovery is atomic, so a recovery that succeeds writes them to SST files and
keeps them.

During an automatic recovery from a retryable error, RocksDB tries failed WAL
writes again (meta#10489): SwitchMemtable() resets the error of the failed WAL
writer and writes its buffer again, and the flush code that syncs closed WALs
resets the error before it syncs or closes them. These sites checked only that
a recovery was in progress (recovery_in_prog_). meta#12995 made the
manual_wal_flush errors fatal but did not change these sites. A reset writer
writes an empty buffer with OK, and the memtable switch moves to a new WAL.
FlushWAL() then wrote and synced the new WAL and returned OK, although the
acknowledged write was in no WAL file. If the recovery flush did not succeed,
the write was gone after reopen. This can happen in three ways:
1. The fatal WAL error comes first, then a retryable error (for example, a
   retryable MANIFEST write error in SetOptions()). The fatal error stays,
   because a less severe error does not replace it. But
   StartRecoverFromRetryableBGIOError() did not check the severity, so it
   set recovery_in_prog_ and started a recovery thread, which can never
   succeed.
2. A retryable error starts a recovery first, and the WAL buffer write fails
   while that recovery is still in progress.
3. A race with FlushWAL(). FlushWAL() writes the buffer while it holds only
   wal_write_mutex_. It records the error later, in WALIOStatusCheck(),
   which needs the DB mutex. A recovery memtable switch that runs in this
   window still sees a hard error, not a fatal one, so it resets the writer.
   The same window exists during a recovery from a soft error (for example,
   a retryable SST write error in a flush). Such a recovery does not stop the
   DB, so a user Flush() can switch the memtable in the window and reset the
   writer. This change fixes the third way for a recovery from a hard error,
   but not for a soft-error recovery (S7 below, a known gap):

```
manual_wal_flush=true
thread B:  Put(k1) -> OK, record in the WAL buffer
thread A:  FlushWAL() -> buffer write fails, buffer dropped
           (a retryable MANIFEST error starts a recovery here)
recovery:  SwitchMemtable() resets the writer, writes the empty buffer
           with OK, and moves to a new WAL
thread A:  WALIOStatusCheck() -> background error becomes fatal
recovery:  the recovery flush fails, so k1 is in no SST file
thread B:  FlushWAL(sync=true) -> OK, although k1 is in no WAL file
```

A db_stress crash test hit the first way with manual_wal_flush and retryable
MANIFEST write faults. A review found the third way. The new regression tests
reproduce all three ways.

Who is affected: DBs with manual_wal_flush=true that hit a WAL buffer write
error before or during a recovery from a retryable error. They can lose
acknowledged writes while FlushWAL() reports OK. Without manual_wal_flush,
every write puts its record into the WAL file at once, so a failed WAL write
returns an error to that writer. For those DBs, when a WAL write gets a fatal
error while recovery_in_prog_ is set, the change only stops a retry that
cannot help.

New behavior:
- With manual_wal_flush, FlushWAL() returns the background error, without
  writing the WAL buffer, while a background error of kHardError or worse
  stops writes after a buffer write or sync of the current WAL failed. The
  returned error is the current background error, which can come from an
  earlier failure. A recovery memtable switch may have reset the failed WAL
  writer and moved to a new WAL, so success on the new WAL would hide lost
  writes. The error is cleared only after a recovery flush succeeds, and
  that flush has written all memtables, including any dropped records, to
  SST files.
- During a recovery that can still succeed, a memtable switch resets a failed
  WAL writer, as on master. During a soft-error recovery, which does not stop
  the DB, this includes the window where a FlushWAL() call (call A) has failed
  its buffer write but has not yet recorded the error. FlushWAL() refuses to
  write the buffer because of the WAL-failure mark (see Implementation) only
  while the DB is stopped, so in that window the reset can still hide the
  dropped buffer, as on master (S7 below, a known gap). The switch does not skip
  the reset there. Without the reset, the switch would fail on the writer with
  "Seen error", an IOError, which is a fatal error with manual_wal_flush. The
  switch would have to record that error: it has already marked the active
  memtable immutable, and only a stopped DB keeps writes out of that memtable.
  Then the recovery could not keep the dropped records, also when A's error is
  only a hard error, where master keeps them (S9, S10, S12 and S13 below).
- In A's window, another FlushWAL() (call B) fails on the failed writer
  with "Seen error", if no switch has reset that writer. It returns that
  error but does not record it, and A records its own status. This also
  holds when A records its error and stops the DB after B's stop checks but
  before B's buffer write. B then sees the mark, and the mark always comes
  from a call that records its own error. SyncWalImpl() follows the same
  rule for a sync that fails on the error of an earlier sync.
- With a healthy current WAL, FlushWAL() writes the buffer, and syncs it
  when asked, as before, also while the DB is stopped (for example, by a
  MANIFEST error, during or after its recovery, by a fatal MANIFEST error,
  by a failed sync of a closed WAL, or by a failed WAL directory fsync in a
  write with sync=true). So the synced records survive a crash. A closed
  WAL had its buffer written by the memtable switch that closed it, so a
  failed sync of a closed WAL drops no buffered records. A write with
  sync=true fsyncs the WAL directory only after it has written and synced
  the WAL files, so a failed directory fsync drops no records either. The
  next WAL sync tries the directory fsync again.
- The flush code that syncs closed WALs retries a failed closed WAL only
  during a recovery that can still succeed. Once the background error is
  fatal, the failed WAL writer keeps its error, so a direct SyncWAL() fails
  as well.
- No recovery thread starts for a retryable error that comes after a fatal
  error, and listeners are not told that a recovery begins.
- A retry during a recovery that can still succeed keeps working. So a WAL
  buffer error that is only a hard error (a retryable or file-scoped status
  that is not an IOError), and the third way when the recovery flush finishes
  before FlushWAL() records its error, still end in a recovery that keeps the
  dropped writes. This also holds during a soft-error recovery when a
  memtable switch or another FlushWAL() runs before the failed FlushWAL()
  records its hard error (S9 to S14 below).

Implementation:
- db/error_handler.h, db/error_handler.cc:
  - New ErrorHandler::CanRetryFailedWALWrites(). It returns true when
    recovery_in_prog_ is set and the background error is below kFatalError.
  - New mark ManualWALWriteFailed(), an atomic. With manual_wal_flush, DBImpl
    sets it when it records a failed buffer write or sync of the current WAL as
    a background error, with the DB mutex held, next to SetBGError(): the
    memtable switch marks every failed buffer write, and the other sites use the
    WALIOStatusCheck() condition (see db_impl.h below). FlushWAL() also sets it
    right after a failed buffer write, before it records the error, so that a
    concurrent FlushWAL() sees it in that window. Setting it again next to
    SetBGError() covers a recovery whose ClearBGError() runs in that window. A
    failure that does not become a background error (paranoid_checks off, or a
    Busy or Incomplete status) only resets the WAL writer, and RocksDB keeps
    using the WAL, so it sets no mark. ClearBGError() clears the mark with the
    background error. The mark is never cleared in other places: a later
    successful buffer write, even with a sync, or a switch to a new WAL does not
    bring back the dropped records, and clearing the mark there would bring back
    the false OK of the third way (S1 in the table below).
  - New GetErrorBlockingManualWALFlush() returns the background error when
    the DB is stopped and the mark is set.
  - StartRecoverFromRetryableBGIOError() returns early when the background
    error is kFatalError or worse. A new sync point right after it sets
    recovery_in_prog_ lets tests wait until the recovery is marked.
  - The retryable branch of SetBGErrorImpl() passes auto_recovery = false to
    OnBackgroundError() listeners when the background error is fatal, because
    no recovery starts then.
- db/db_impl/db_impl.cc:
  - FlushWAL(): with manual_wal_flush, when the atomic IsDBStopped() is true,
    take the DB mutex and return GetErrorBlockingManualWALFlush() if it is not
    OK. The common path takes no DB mutex. DB::Open() calls FlushWAL() with
    the DB mutex held, but no background error stops the DB then. The DB
    mutex must be taken before wal_write_mutex_, so after FlushWAL() takes
    wal_write_mutex_, it checks again: if the DB stopped, or a WAL write
    failed, since the first check, it releases wal_write_mutex_ and checks
    again with the DB mutex. Otherwise it keeps wal_write_mutex_ through the
    buffer write. A failed buffer write sets the mark. When the mark is set
    and the current WAL writer has an error, the buffer write fails with
    "Seen error" and does no I/O, and FlushWAL() returns that error without
    marking or recording it. The call that set the mark records its own
    error: every call that sets the mark records its error as a background
    error. The DB may already be stopped then, because that call can record
    its error after the stop checks; the stop checks let a call through
    with the DB stopped only while the mark is clear. So the check does not
    look at IsDBStopped(). An OnBackgroundError() listener can lower the
    error of that call. Then the writer error stays until ClearBGError() or
    until a memtable switch during a recovery resets the writer, as on
    master. Until then, FlushWAL() returns an error.
  - Three new sync points in FlushWAL() are used by the race tests.
- db/db_impl/db_impl_write.cc:
  - SwitchMemtable(): reset the error of the failed WAL writer only when
    CanRetryFailedWALWrites() returns true, instead of whenever a recovery
    is in progress. The switch records every failed buffer write as a
    background error, also with paranoid_checks off or a Busy or Incomplete
    status, so it marks every one.
  - WALIOStatusCheck() sets the mark for a WAL write or sync error only when the
    error becomes a background error (WALErrorBecomesBGError()) and the failure
    may have lost records of the current WAL. SyncWAL(), the flush that syncs
    closed WALs, and a write with sync=true can fail on a closed WAL, and a
    write with sync=true can fail at the WAL directory fsync. They set no mark
    then. A new parameter of WALIOStatusCheck() (enum CurrentWALState) says
    when the caller knows that the current WAL lost no records (kHealthy):
    WriteGroupToWAL() reports a failed sync of a WAL that is not the one it
    wrote, and a failed WAL directory fsync, for normal and pipelined writes.
    SyncWalImpl() reports a failed WAL older than the WAL that was current when
    it started. Its own directory fsync failure does not reach
    WALIOStatusCheck(). WALIOStatusCheck() also skips the mark when the failed
    WAL number is below cur_wal_number_ (the DB mutex is held there), for a WAL
    that a switch closed after the caller started. The failed WAL number that
    the write path passes, which the file-scoped WAL recovery uses, is
    unchanged.
- db/db_impl/db_impl.h: new DBImpl::WALErrorBecomesBGError(), the condition
  WALIOStatusCheck() already used to decide whether a WAL error becomes a
  background error. FlushWAL() uses it too for its early mark. New enum
  DBImpl::CurrentWALState (see above).
- db/db_impl/db_impl_compaction_flush.cc (the two SyncClosedWals() callers in
  flush): use CanRetryFailedWALWrites() instead of IsRecoveryInProgress()
  before they reset the error of a closed WAL. The parameter of
  SyncClosedWals() and SyncWalImpl() is renamed to retry_failed_wals to match
  its meaning.

Alternative considered: FlushWAL() could also return the error while a
recovery is in progress, without writing the buffer, so that the recovery
switch writes it. That keeps the write in case S0 below, but it blocks
FlushWAL(sync=true) on a healthy WAL for as long as a recovery keeps failing
(max_bgerror_resume_count is INT_MAX by default), where master syncs the WAL.
In the cases below, no case loses a write that master keeps, and no case
fails a sync on a healthy WAL that master does. So S0 keeps master's
result. It is a possible follow-up.

Changes visible to existing users:
- With manual_wal_flush, FlushWAL() fails in the case above. It used to
  write the buffer, to a new WAL if a recovery switch had reset the failed
  writer, and, with sync=true, sync the WAL. LockWAL() calls
  FlushWAL(), so it fails then and undoes its lock. Checkpoints and backups
  get the error from GetLiveFilesStorageInfo(), and leave no checkpoint
  directory and no backup behind. LockWAL(), checkpoints and
  FlushWAL(sync=false) do not sync the WAL; they only write the buffer.
  With two_write_queues, a write with sync=true first adds its record to
  the WAL buffer, then calls FlushWAL(sync=false) and syncs the WAL
  (SyncWALAndApplyToManifest()); a write that skips the memtable calls
  FlushWAL(sync=true). So such a write fails with the background error in
  this case, and its record stays in the WAL buffer. A later successful
  recovery writes that record to the WAL file, so the WAL then holds a write
  that reported failure. Master leaves the same kind of record when the
  sync fails after the buffer write, so this is not a new kind of
  inconsistency. DBs without manual_wal_flush are not affected.
- The buffered records that such a call does not write stay in the buffer. A
  successful recovery (automatic or DB::Resume()) writes them, and the calls
  succeed again. If no recovery succeeds, the WAL writer writes its buffer to
  the WAL file, without a sync, when the DB is closed, unless the failed
  write or sync left the writer with an error. A writer with an error skips
  that write (log::Writer::WriteBuffer()).
- On master, after a WAL buffer write fails with a hard error, a later
  FlushWAL() writes to the failed writer again, and that "Seen error"
  IOError makes the error fatal, so DB::Resume() fails. With this change,
  FlushWAL() returns the hard error instead, so DB::Resume() can recover.
  This holds only if no memtable switch runs outside a recovery before
  Resume(). A user Flush(), a CompactRange() flush, a checkpoint with the
  default log_size_for_flush=0, or a backup with flush_before_backup
  switches the memtable. That switch does not reset the failed writer, so
  it records "Seen error" as a new fatal error, and Resume() fails. This is
  the same on master.

Safety and cases not changed:
- A fatal or unrecoverable background error is never lowered: ResumeImpl()
  rejects errors above kHardError, ClearBGError() does not clear a fatal
  error on either of its paths (after a successful ResumeImpl(), and directly
  for a soft error that needs no flush), and OverrideNoSpaceError() returns
  early for a fatal error. Any error during a recovery attempt leaves
  recovery_error_ non-OK (recovery_error_ is reset before each ResumeImpl()
  call), and ClearBGError() clears nothing while it is non-OK. So a recovery
  that starts while the error is fatal can never succeed, and the new
  CanRetryFailedWALWrites() checks block no recovery that could succeed.
- The lost WAL buffer cases from review, all with manual_wal_flush. A's
  buffer write fails. B is a later FlushWAL(sync=true). The DB is then closed
  without a flush, as a stand-in for a crash. Each cell shows B's result,
  then whether the write in A's buffer (k1) is kept after reopen.

| Case | master | this diff |
|---|---|---|
| S0: retryable error first, then A's FlushWAL() | err, lost | err, lost |
| S1: race, A records its error after the switch | OK, lost | err, lost |
| S2: race, the whole recovery runs before A records | OK, kept | err, kept |
| S3: retryable TimedOut on the buffer write | OK, kept | OK, kept |
| S4: file-scoped Aborted on the buffer write | OK, kept | OK, kept |
| S5: paranoid_checks=false plus the race (S2 order) | OK, kept | OK, kept |
| S6: S1, B passed its first check before A failed | OK, lost | err, lost |
| S7: soft-error recovery, a user Flush() switches the memtable in A's window (the S1 window) | OK, lost | OK, lost |
| S8: S7, but A's error sets no background error (paranoid_checks off, Busy, Incomplete) | OK, kept | OK, kept |
| S9: S7, but A's error is a hard error (retryable TimedOut or file-scoped Aborted), B after the recovery | OK, kept | OK, kept |
| S10: S9, but B runs in A's window after the switch | OK, kept | OK, kept |
| S11: S9, B runs in A's window, no switch | err, lost | err, kept |
| S12: S9, but a Put() of a new key follows the switch in A's window (cells: the Put()) | OK, kept | OK, kept |
| S13: S12, but the Put() uses disableWAL | OK, kept | OK, kept |
| S14: S11, but A records its error and stops the DB between B's stop checks and its buffer write | err, lost | err, kept |

  In S0, A's FlushWAL() writes the buffer during the recovery, the write
  fails and drops it, and the error becomes fatal, as on master (see the
  alternative above). In S2, the recovery clears the error and the mark. A
  then records its WAL error, which is fatal and sets the mark again, so B
  fails although the recovery flush kept k1. No write is lost there, and the
  DB stays stopped by the fatal error anyway. In S7, the switch resets A's
  failed writer, B syncs the new WAL and returns OK, A then records a fatal
  error, and the recovery cannot keep k1. That is a known gap, the same as
  on master (see "Not changed" below). A FlushWAL() after A records its
  error fails, where master returns OK. In S9, S10, S12 and S13, the switch
  also resets the writer, and A's hard error lets the recovery keep k1, as
  on master. A FlushWAL() there also fails until the recovery ends. Master's
  OK there does not mean that k1 is durable, so the error is intended. In
  S11 and S14, B writes A's failed writer and fails, but it leaves the
  recording to A, so A's hard error stays, the recovery keeps k1, and a
  FlushWAL(sync=true) after the recovery returns OK. On master, B records
  its "Seen error" as a fatal error, so the recovery cannot keep k1.

  Cases with a healthy WAL, where k1 was never in a failed buffer. Here the
  DB is closed with all unsynced data dropped, so k1 is kept only if B synced
  it:

| Case | master | this diff |
|---|---|---|
| H1: retryable MANIFEST error, recovery gave up | OK, kept | OK, kept |
| H2: the same, while the failing recovery still runs | OK, kept | OK, kept |
| H3: fatal MANIFEST error | OK, kept | OK, kept |
| H4: a WAL error that sets no background error (paranoid_checks off, Busy, Incomplete), then a fatal MANIFEST error | OK, kept | OK, kept |

  One more healthy-WAL case: a SyncWAL() or a write with sync=true fails on a
  closed WAL (the flush that would sync it is held), which gives a fatal error.
  Then FlushWAL(sync=false) writes the buffer of the current WAL, and the file
  system fails all writes while the DB closes. On master and with this change,
  FlushWAL() returns OK and k1 is kept after reopen.

  Another one: a write with sync=true fails at the WAL directory fsync, which
  gives a fatal error. On master and with this change, FlushWAL(sync=false),
  FlushWAL(sync=true) and LockWAL() return OK, and FlushWAL(sync=true) tries
  the directory fsync again.

  Without manual_wal_flush: during a soft-error recovery, a SyncWAL() fails on
  the current WAL, and a user Flush() switches the memtable before SyncWAL()
  records the error. On master and with this change, the switch resets the
  writer, the recovery clears the error, and later writes succeed.

  One more case: a hard WAL buffer error (a retryable TimedOut) with no
  automatic recovery, then DB::Resume(). On master, a later FlushWAL() writes
  to the failed writer again and makes the error fatal, so Resume() fails.
  With this diff, FlushWAL() returns the hard error, Resume() succeeds, and
  k1 is kept.
- The acknowledged write is still lost when the recovery flush cannot keep it,
  for example when the error becomes fatal right after the recovery memtable
  switch (the diagram above). That is expected for a fatal error. The change
  makes the loss visible instead of reporting success. Recovering these
  errors is an open TODO in ErrorHandler::SetBGErrorImpl(). A possible
  follow-up is to abandon the failed WAL at the switch, as the file-scoped WAL
  recovery does.
- Not changed: with paranoid_checks=false, a failed WAL write sets no
  background error, and WALIOStatusCheck() resets the writer. If nothing else
  stops the DB, a later FlushWAL() can return OK for a lost write. Such a
  failure sets no mark, because RocksDB keeps using the WAL after it. Busy
  and Incomplete statuses from a WAL write are handled the same way in all
  modes. These are separate problems. Such a failure resets its writer in
  WALIOStatusCheck(), so a later memtable switch and FlushWAL() work, with
  or without a soft-error recovery in progress. If a memtable switch runs
  between such a failed FlushWAL() buffer write and that reset, the result
  is the same as on master. Without a recovery, the switch fails on the
  writer and records a fatal error. During a soft-error recovery, the switch
  resets the writer, the recovery flush keeps the dropped records, and a
  later FlushWAL(sync=true) returns OK.
- Not changed: with manual_wal_flush, a failed sync of the current WAL sets
  the mark only when WALIOStatusCheck() records it. If a soft-error recovery
  switch runs before that, the switch resets the writer, as on master. The
  sync failure dropped no buffered records. The recovery flush may then
  retry the fsync of that WAL file, as on master. Whether a retried fsync
  can be trusted is a separate, existing problem.
- Not changed: with manual_wal_flush, a user write (for example, a Put())
  in the window of a failed FlushWAL(), with no memtable switch before it in
  that window, adds its record to A's failed WAL writer, fails with "Seen
  error", and records it as a fatal error, as on master. Only FlushWAL()
  leaves the recording to the failed FlushWAL() call. After a switch in
  that window, the write goes to the new WAL, as on master (S12, S13).
- Not changed (known gap, S7): during a soft-error recovery, a memtable
  switch in the window of a failed FlushWAL() (call A) resets A's failed
  writer and moves to a new WAL, as on master. A FlushWAL() in that window,
  after the switch, can return OK although k1 is in no WAL file. If A's
  error is fatal (an IOError), the recovery cannot keep k1. Once A records
  its error, FlushWAL() fails. Keeping the failed writer at the switch would
  make the switch record a fatal error and lose writes that master keeps
  (S9, S10, S12, S13). A fix needs the switch to finish and abandon the
  failed WAL, as the file-scoped WAL recovery does, and FlushWAL() to refuse
  OK while A's failure is not recorded. That is the open TODO in
  ErrorHandler::SetBGErrorImpl(), and a possible follow-up.
- No API, option or format change.

Reviewed By: pdillinger

Differential Revision: D134907307

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant