Skip to content

Accept obsolete missing blob files in secondary catch-up (#15824) - #15824

Open
xingbowang wants to merge 10 commits into
meta:mainfrom
xingbowang:export-D134907311
Open

xingbowang wants to merge 10 commits into
meta:mainfrom
xingbowang:export-D134907311

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:

  • A blob file below every blob file that an SST references. An SST's oldest
    blob file is never newer than any blob file it references.
  • A blob file that no SST links and whose values all count as garbage. An SST
    that references a blob file either links it as its oldest blob file or
    keeps some of its values live.
    When no SST references any blob file, the Version keeps no blob file, so
    every missing blob file is accepted. A missing blob file that the Version
    would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:

  • the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
    which covers every SST whose oldest blob file has metadata in the builder;
  • the smallest blob file that best-efforts BlobDB repair recorded as dropped
    (in the base Version and in the edits read so far). A builder that
    tracks missing files starts from the empty initial Version. In catch-up,
    the first builder keeps a reference to that Version, so later builders
    start from it too. So the base Version has no dropped blob files for all
    current builders. The code reads them anyway, so the bound stays right if
    that changes. After a repair with
    best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
    oldest blob file. That file has no metadata, so the SST links nothing.
    The bound is never higher than the save rule's number. Without the dropped
    files, a repaired DB whose remaining SST still references a missing blob
    file that no SST links would count as complete, and reads would fail with
    Corruption.

Safety and unchanged cases:

  • A normal DB::Open does not track missing files and is unchanged.
  • Best-efforts recovery outside an atomic group is unchanged in effect.
    OnlyMissingL0Suffix() already accepts any missing blob file that no SST
    links. Inside an atomic group, a point with only obsolete missing blob
    files now counts as complete, so recovery reaches the newest point (see
    Previous behavior).
  • HasMissingFiles(), which best-efforts recovery reports, still counts any
    missing blob file. Opens with best_efforts_blob_db_repair, which record
    missing blob files as dropped, are unchanged.
  • Known limit: the dropped blob file list read from the edits is not pruned
    within one builder. After a repair, the bound can stay lower than needed
    until the next MANIFEST. A missing blob file between the bound and the
    oldest blob file of the saved SSTs then still counts as missing, and
    rocksdb.secondary-has-missing-files can return 1 for a point that the
    save rule could build. This errs on the strict side and never accepts a
    needed file.
  • RepairDB of a DB with blob files is not supported here, because it drops
    all blob file metadata. After it, a missing blob file that is still needed
    may not be reported.
  • Cost: each validity check walks missing_blob_files_, which holds every
    blob file added and found missing while reading one MANIFEST. The check
    already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
    the first blob file that an SST links, so the order of cost is the same.
    The walk runs only while some blob file is missing.
  • The trigger needs a blob file that loses its last linked SST and all live
    values and is deleted by the primary while a secondary tails a MANIFEST
    that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311

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

@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 1823.3s.

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use.

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks all blob file metadata in GetMinOldestBlobFileNumber(), so
  the order of cost is the same. The walk runs only while some blob file is
  missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count, and notes the strict limit above after a repair. The property and
this limit come from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
@meta-codesync meta-codesync Bot changed the title Accept obsolete missing blob files in secondary catch-up Accept obsolete missing blob files in secondary catch-up (#15824) Nov 30, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
@meta-codesync meta-codesync Bot changed the title Accept obsolete missing blob files in secondary catch-up (#15824) Accept obsolete missing blob files in secondary catch-up Nov 30, 2026
@meta-codesync meta-codesync Bot changed the title Accept obsolete missing blob files in secondary catch-up Accept obsolete missing blob files in secondary catch-up (#15824) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
@meta-codesync meta-codesync Bot changed the title Accept obsolete missing blob files in secondary catch-up (#15824) Accept obsolete missing blob files in secondary catch-up 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

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

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.

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.

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.
  - `CompactionJob::Install()` takes `versions_->io_status()` as the job's
    I/O status only when the commit itself failed. 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.
  Without this part, a debug build then fails the assert in
  `ErrorHandler::ClearBGError()` that the quarantine is empty, and a release
  build clears the error while the old MANIFEST may still hold the failed edit.
  Upstream already fails the assert after a failed `PromoteL0()` followed by a
  soft error, and this change fixes that case too. With the rest of this change,
  a `SetOptions()` between them keeps the quarantine, so without this part the
  assert would fire in that case as well.

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. This is needed because
  the older failed write may still be in the old MANIFEST, and clearing the
  error without a new MANIFEST would forget that. 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 two cases above (an atomic flush that does not wait, and a
  compaction that fails before its commit). 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 the old `IOError` with
    reason `kManifestWrite` instead of its own `Corruption`. 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.
  A complete fix tracks the MANIFEST I/O status of each batch, and lets a
  caller report `versions_->io_status()` only when its own commit failed on
  MANIFEST I/O. 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.

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.

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:

```
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
…a#15821)

Summary:
Pull Request resolved: meta#15821

Background: `GetUpdatesSince()` returns a `TransactionLogIterator` that reads the WAL files from a given sequence number (the target). It lists the WAL files (`WalManager::GetSortedWalFiles()`), and `WalManager::RetainProbableWalFiles()` picks the first WAL to read: the last WAL whose start sequence is at or below the target. The start sequence of a WAL comes from its first record (`ReadFirstRecord()` / `ReadFirstLine()`).

With `wal_compression`, every WAL starts with a compression type record, which has no sequence number. A WAL that holds only this record and no write batch (a "no-write WAL" below) gets the placeholder start sequence 1, so that the listing still includes it. This placeholder comes from meta#10130 (RocksDB 7.4.0). Common no-write WALs are:
- the current WAL right after any WAL switch, for example after a flush, until the next write;
- a WAL from a reopen that got no writes before the next reopen or switch. With WAL archiving (`WAL_ttl_seconds` or `WAL_size_limit_MB`), such a WAL stays in the archive, and in the list, until the archive purge removes it.

The problem: `RetainProbableWalFiles()` used a binary search, which assumes that the start sequences are sorted. A placeholder 1 after a WAL with writes breaks that order. The search could then pick a WAL after the one that holds the target, and the iterator skipped those writes and still returned OK. A user of `GetUpdatesSince()`, for example a replication tool, silently misses writes. This bug exists in current releases; it is not caused by a recent change.

For example (the file numbers are only an example), the WAL list can look like this after a reopen with `avoid_flush_during_recovery`, a flush of one column family, and one more write:

```
WAL file   start sequence     holds
4          1                  writes 1-2
7          1 (placeholder)    no writes
8          3                  write 3
```

A search for target 1 finds start sequence 1 at WAL 7 and starts there, so it drops WAL 4, and the iterator returns only write 3. The simplest case needs no special option: after a flush with WAL archiving, the list is the archived WAL with writes 1-2 and the current no-write WAL with placeholder 1. `GetUpdatesSince(2)` then picked the current WAL and returned no batches, with OK.

In addition, `ReadFirstRecord()` cached the placeholder, so a WAL that later got writes kept the start sequence 1 in the cache. A later listing then reported the wrong start sequence for that WAL.

The start sequences can also be out of order without WAL compression. A point-in-time recovery (`WALRecoveryMode::kPointInTimeRecovery`, the default) can stop in a WAL that is not the last one, for example when a crash cut off the unsynced tail of that WAL but a later WAL survived. Recovery does not replay the later WALs, but they can stay listed: in the WAL archive with WAL archiving, or as live WALs when recovery does not flush (`avoid_flush_during_recovery`). New writes then reuse their sequence numbers in a newer WAL that starts lower. For example (the file numbers are only an example):

```
WAL file   start sequence     holds
4          1                  writes 1-166 (recovery stops here)
8          301                writes 301-600, which recovery discarded
10         167                the new writes 167-666
```

For a target from 167 to 300, the binary search picked WAL 4, and the iterator returned the discarded write 301 from WAL 8 as the first batch, under a sequence number that now belongs to another write. For target 301, the search picked WAL 8 itself. Targets above 301 read WAL 10 and were correct. The example was reproduced with a simulated crash that drops unsynced data (not a committed test). The regression test below builds a smaller case. The root cause, that WALs which recovery did not replay stay listed, is older than this diff and is not changed here.

Fix:
- `RetainProbableWalFiles()` scans the list from the end and picks the last WAL whose start sequence is above 1 and at or below the target. If there is no such WAL, it picks the first WAL in the list. The scan cannot tell a placeholder 1 from a real start sequence 1, so it skips both. Either way, the iterator starts at an earlier WAL, which the iterator change below makes safe. The scan goes from the end because, after a point-in-time recovery as above, the new WALs come after the WALs that recovery did not replay. In the example, targets 167-666 all start at WAL 10 and return the new writes. A target below 167 starts at WAL 4, and the run ends with a "Gap in sequence numbers" status at WAL 8, before any discarded write is returned (derived from the code, not tested). This relies on the empty batch that `DB::Open()` writes to the new WAL after a recovery that found a corrupted WAL. That batch has the next sequence number after recovery, 167 in the example, so WAL 10 starts at 167 even when the first new write skips the WAL (`disableWAL`).
- The iterator drops batches that end below the target in every file it reads until it reaches the target. Before this change, it dropped them only in the first file, and returned the first batch of the next file without a check. This makes an early start safe. With the scan above, an early start comes only from start sequence 1 and the fallback to the first WAL: the scan skips every WAL that starts at 1, so it can start at a WAL before the one that holds the target. For example, with WAL compression, a no-write WAL can be listed before the WAL that holds sequence 1, and both start at 1. Or the first write of the DB is an empty `WriteBatch`, which takes no sequence number, so the WAL that holds it and the next WAL both start at 1. Without this iterator change, `GetUpdatesSince(seq)` could return batches below `seq` in these cases (and debug builds hit an assertion).
- When the first seek (in `GetUpdatesSince()`) reads all listed files and no listed file holds a batch at or after the target, for example because the target was written without the WAL (`disableWAL` or ingestion), the iterator is not valid and its status is OK. This matches the case where the list has one file. Without this, an early start with WAL compression would return `TryAgain` where the same steps without WAL compression return OK. An early start is expected, so the iterator logs a plain info message and does not set a Corruption status.
- An iterator in this state (not valid, status OK) is polled with `Next()`, and each `Next()` seeks to the target again. The fixes on this path:
  - The seek starts the walk at the first listed file again, with the file index reset. Without the reset, it reopens the first file but keeps the file index of the earlier walk, so it cannot move on to the next files.
  - When the seek finds a batch at or after the target, `Next()` returns that batch. Without this fix, `Next()` read one more batch after it, so it skipped the first batch at or after the target (or returned nothing when that batch was the last one). This bug exists in current releases too, also without WAL compression.
  - When the seek fails (for example, a WAL file cannot be opened), `Next()` returns at once and keeps the error status of the seek, so that reading on does not overwrite it.
  - When the seek finds no batch at or after the target, `Next()` returns at once and does not read on. As in current releases, it ends the run with `TryAgain` when the DB has written past the iterator's files (for example after a WAL switch), so the caller builds a new iterator. This also happens when the target itself was written without the WAL and is the last write, until the next write. Otherwise the iterator is caught up and its status stays OK. Returning at once also covers a seek that opened no file, because no WAL is listed (for example without WAL archiving, after a flush). In current releases, `Next()` on such an iterator hits an assertion in debug builds and uses a null log reader in release builds (derived from the code, not run).
  - In this seek, a WAL file that the listing gave as archived and that does not exist anymore (for example, the archive purge deleted it) is read as empty, and the seek goes on to the next listed file. This cannot skip a file that holds the target, unless the first seek hit a read error: the first seek already read every listed file to its end without finding a batch at or after the target, and an archived WAL never changes. The exception is older than this diff and is not changed here: `log::Reader` treats a read error as the end of the file, and the iterator does not check for it. If the first seek hit a read error in a file that held the target, and the purge then deletes that file, the run ends with `TryAgain` (or caught up) instead of with an error. For example, with WAL compression an unstarted iterator can start at an archived no-write WAL and reopen it on every `Next()`. If the seek then reaches the end of the files without finding the target, the rules above apply (`TryAgain`, or caught up). Every other failure keeps its error: a real I/O error, a missing file in the first seek inside `GetUpdatesSince()`, and a missing file that the listing gave as live. A live WAL may have received the target after the first seek. With `manual_wal_flush`, the target can still be in the WAL buffer at the first seek and reach that live WAL later. If that WAL is then archived and deleted, the error stays, because the file was listed as live. Reading it as empty, or ending the run with `TryAgain`, would make the caller build a new iterator that silently starts after the target. A live WAL that was only moved to the archive is still found there.
- `ReadFirstLine()` reports a no-write WAL through a new `no_write_batch` flag. `ReadFirstRecord()` does not cache the placeholder of a live no-write WAL, because the WAL can still get its first write. It caches the placeholder of an archived no-write WAL, because an archived WAL never changes.

Unchanged: `GetSortedWalFiles()` still lists every WAL, including no-write WALs. A copy of the DB needs them: the next WAL names a no-write WAL as its predecessor, and with `track_and_verify_wals_in_manifest` the MANIFEST can require it.

Who is affected: users of `GetUpdatesSince()` with `wal_compression` enabled, when a no-write WAL is listed after a WAL with writes. Without `wal_compression`, a no-write WAL holds no record, or only the predecessor WAL record with `track_and_verify_wals`, so it gets start sequence 0 and is not listed. Users of `GetUpdatesSince()`, with or without `wal_compression`, after a point-in-time recovery that stopped before the last WAL, while the later WALs stay listed (archived or live). The fixes for `Next()` before the target is found affect all users of `GetUpdatesSince()` who poll such an iterator, with or without `wal_compression`.

Compatibility: no format, option or public API change. The iterator may start reading at an earlier WAL file, and it skips the batches below the target there. If no listed file holds a batch at or after the target, `GetUpdatesSince()` returns OK with an iterator that is not valid, whether the list has one file or more. Without this diff, a list of more than one file returned `TryAgain` in this case. A batch that takes no sequence number (for example one with only `PutLogData()`) and has the target as its sequence ends below the target, so the iterator does not return it when it reads such a batch before the target. The iterator handles the first file the same way, so this rule holds in every file. Without this diff, such a batch was returned when it was the first batch of a later file. `Next()` on an iterator that has not found its target reads a deleted archived WAL file of the iterator as empty, instead of ending the run with an I/O error. The search for the first WAL is linear in the number of WAL files; the listing already reads the first record of every WAL, so this adds no I/O. A live no-write WAL is not cached, so each listing reads it again. The current WAL is read again until it gets its first write. A live no-write WAL that is not the current WAL (for example one left by a reopen) never gets a write, so it is read on every listing until it is archived or deleted.

Differential Revision: D134907308
meta#15822)

Summary:
Pull Request resolved: meta#15822

Background: DisableFileDeletions() promises that files do not get deleted until
deletions are enabled again. Backups and checkpoints rely on this: they disable
deletions, list the live files and the WAL files, and then copy them.
GetSortedWalFilesImpl() lists the WAL files in two steps: it reads the names
in the WAL directory, and then reads the size of each WAL file. A WAL file
that disappears between the two steps fails the listing with an IOError (No
such file or directory), unless the file moved to the archive directory.

With async_wal_precreate, a background job creates the file of the next WAL
ahead of time. A WAL switch takes this file and writes its first records
(StartWALFile()). When that write fails, the file was never published as a
WAL and holds no data, so SwitchMemtableImpl() deletes it. The switch also
sets a background error, and the recovery from it switches to a new WAL and
flushes all memtables.

Previous behavior: SwitchMemtableImpl() deleted the unstarted file at once
with Env::DeleteFile(), also while file deletions were disabled. A listing
that had already read the name of that file then failed on the size read, so
the backup or checkpoint failed. A db_stress crash test hit this with
async_wal_precreate=1, backups and injected write errors: an injected write
error on the compression type record, the first record that StartWALFile()
writes, made 4 concurrent backups fail. db_crashtest.py can pick the same
options. No data is lost; the backup fails.

New behavior: while file deletions are disabled and track_and_verify_wals is
off, the unstarted file stays on disk. It is deleted by the next obsolete-file
cleanup after deletions are enabled again, or at close. Otherwise the file is
still deleted at once.

An unstarted file that waits holds only the compression type record of
wal_compression, if any, and no writes. The WAL listing and GetUpdatesSince()
handle such a WAL in the middle of the WAL list (the previous diff in this
stack fixes GetUpdatesSince() for it). This diff only names the unstarted
file in the comment of WalManager::RetainProbableWalFiles().

Implementation:
- SwitchMemtableImpl() calls the new DBImpl::DeleteOrDeferUnstartedWAL().
  Under the DB mutex, it checks whether deletions are enabled.
  - If they are disabled and track_and_verify_wals is off, it records the WAL
    number in the new list DBImpl::deferred_unstarted_wal_numbers_.
  - Otherwise it counts the delete as a pending purge
    (pending_purge_obsolete_files_), deletes the file without the mutex, and
    then lowers the count. GetSortedWalFilesImpl() disables deletions and then
    waits for pending purges before it lists, so a listing through it either
    does not see the file or sees it until deletions are enabled again.
- FindObsoleteFiles(), when deletions are enabled, moves these numbers to the
  new list JobContext::unstarted_wal_delete_files, which
  HaveSomethingToDelete() counts. It also marks them as grabbed for purge
  (MarkAsGrabbedForPurge()), as it does for obsolete SST and blob files. A
  full scan skips files that are grabbed for purge, so neither its own full
  scan nor a full scan in another thread takes these files as obsolete WALs.
  The full scan of a separate wal_dir also checks ShouldPurge(), as the scan
  of the DB paths already does.
- PurgeObsoleteFiles() deletes these files in the calling thread, also with
  schedule_only, and does not archive them under WAL_ttl_seconds or
  WAL_size_limit_MB, because they hold no data. Then it removes them from the
  grabbed set, also when the delete fails. A failed delete (other than
  NotFound) logs a warning. A later full scan, once the file is older than
  the oldest WAL to keep, then handles it as an obsolete WAL: it deletes the
  file, or archives it under WAL_ttl_seconds or WAL_size_limit_MB.
  EnableFileDeletions() runs FindObsoleteFiles() and PurgeObsoleteFiles()
  when the counter reaches 0. The info LOG has one line when the delete is
  deferred, and one line when the file is deleted.
- CloseHelper() deletes the files that still wait, even when deletions are
  still disabled, because the promise of DisableFileDeletions() ends at close.
  This is only cleanup. The list is not persisted, so otherwise only a later
  full scan would find such a file. With WAL_ttl_seconds or
  WAL_size_limit_MB, that scan would archive the file instead of deleting
  it.

Alternatives not taken:
- Leave the file for the normal purge. The purge never learns about the file
  from the WAL list, because the file was never published. Only a full
  directory scan finds it, and only once it is older than the oldest WAL to
  keep. With WAL_ttl_seconds or WAL_size_limit_MB, that purge moves it to the
  archive directory instead of deleting it. An explicit list deletes the file
  as soon as deletions are enabled again.
- Make the listing skip a WAL file that disappears when its number is above
  the current WAL. This fixes only the size read in the listing. A backup or
  checkpoint that copies the listed files later still races with the delete.

Safety:
- track_and_verify_wals: the delete is not deferred with this option. After a
  crash while the delete waits, the open would replay the unstarted file. A
  later WAL can name the WAL before the unstarted file as its predecessor, for
  example with allow_2pc and a prepared transaction in an older WAL, after a
  crash inside the recovery, or when a listener suppresses the background
  error. The predecessor check would then fail the open, or, under
  kPointInTimeRecovery, stop the replay and drop later writes. So with this
  option, the backup failure on a vanished unstarted WAL remains.
- The CreateWAL() path of a switch without a precreated WAL leaves its file on
  disk when the start fails, before and after this change. That file has the
  same problem with track_and_verify_wals. A possible follow-up fixes both at
  open: a WAL with no data records and no predecessor record would not replace
  the predecessor that the open observed.
- Crash while the delete waits, without track_and_verify_wals: the unstarted
  file stays on disk. The open skips it when it is older than the oldest WAL
  to keep, or replays it as a WAL with no records. The open does not check
  WAL predecessors without this option.
- Listings while the delete waits: with wal_compression, GetSortedWalFiles()
  can return the unstarted file, also while it is still the newest WAL file.
  The file then has the placeholder start sequence 1, which GetUpdatesSince()
  handles. Without wal_compression, the file is empty, and GetSortedWalFiles()
  skips empty WAL files. GetLiveFilesStorageInfo() reads no start sequences,
  so when it does not flush memtables, it returns the file, empty or not,
  once it is older than the current WAL. A backup or checkpoint then copies a
  WAL that holds no writes, which the open of the copy skips or replays as a
  WAL with no records.
- Not covered: GetLiveFilesStorageInfo() with a wal_size_for_flush between 0
  and the maximum, for example a checkpoint with log_size_for_flush, first
  lists the WAL files only to add up their sizes. That listing does not wait
  for pending purges, so a WAL deleted during it fails the checkpoint. This
  holds for the unstarted WAL on the immediate delete path and for any
  obsolete WAL, before and after this change. Backups pass 0 or the maximum
  and do not take this listing.

Unchanged cases: a started WAL that a later step of the switch fails to
publish is not changed.

Changes visible to existing users:
- Only with async_wal_precreate=1, track_and_verify_wals off, and a failed WAL
  start while file deletions are disabled: the unstarted WAL file stays on
  disk until the next obsolete-file cleanup after deletions are enabled again,
  or until the DB closes. A WAL listing in that time can return it.
- With a separate wal_dir, a full scan skips the files that are queued for
  background purge or grabbed for purge, as the scan of the DB paths already
  does. Without async_wal_precreate, this affects only WAL files queued for
  background purge, with avoid_unnecessary_blocking_io or
  background_purge_on_iterator_cleanup. The background purge deletes these
  files as before. The only visible effect is fewer info LOG lines about a
  delete of a file that no longer exists.

Differential Revision: D134907309
Summary:
Pull Request resolved: meta#15823

Background: The DB remembers its current OPTIONS file in
VersionSet::options_file_number(). GetLiveFilesStorageInfo() reports this
file, and checkpoints and backups copy it. A remote compaction sends this
number to the worker (CompactionServiceInput::options_file_number), and
OpenAndCompact() on the worker opens that OPTIONS file first. With
track_options_file_number_in_manifest = false (the default), this number is
the file that the last successful OPTIONS write created, or the file chosen
at open. It is not committed in the MANIFEST.

An OPTIONS write can fail after it renames the temp file to OPTIONS-<number>:
RenameTempFileToOptionsFile() opens and fsyncs the DB directory after the
rename. PersistOptionsFile() then deletes only the temp file name, so the
renamed OPTIONS file stays on disk. The write reports an error, and
options_file_number() still names the older OPTIONS file.

Previous behavior: a full scan for obsolete files (FindObsoleteFiles(force =
true) followed by PurgeObsoleteFiles()) keeps the two highest OPTIONS file
numbers on disk, plus the number committed in the MANIFEST. Many things run
this full scan: EnableFileDeletions() (also at the end of every checkpoint
and backup), GetSortedWalFiles() and GetLiveFilesStorageInfo(), the periodic
scan (delete_obsolete_files_period_micros), a failed flush or compaction, and
Resume(). Without track_options_file_number_in_manifest, no number is
committed, so only the two highest numbers are kept. After two failed writes
like the one above, both are higher than the current file, and the scan
deletes the current OPTIONS file. Until the next successful OPTIONS write:
- GetLiveFilesStorageInfo(), CreateCheckpoint() and backups fail with "No
  such file or directory: while stat a file for size: .../OPTIONS-<number>".
  The first checkpoint after the two failed writes can still succeed, because
  its own EnableFileDeletions() runs the scan only at the end. The next one
  fails.
- A remote compaction fails on the worker, because the OPTIONS file is gone.
  If the compaction service reports this failure to the primary (instead of
  asking for a local compaction with kUseLocal), the compaction fails. With
  the default paranoid_checks = true, this is a fatal background error: writes
  stop, and only a reopen clears it.
A db_stress crash test hit this: two SetOptions() calls failed with injected
metadata write errors, TestDisableFileDeletions() ran the scan, and the next
checkpoint failed.

New behavior: both places that delete OPTIONS files always keep the current
OPTIONS file (options_file_number()), in both modes. They still keep the two
highest OPTIONS files and delete the others. The two places are the full
scan (PurgeObsoleteFiles()) and DeleteObsoleteOptionsFiles().

Implementation:
- JobContext::manifest_options_file_number is renamed to
  current_options_file_number. FindObsoleteFiles() sets it to
  versions_->options_file_number() in both modes.
- PurgeObsoleteFiles() keeps an OPTIONS file whose number is
  current_options_file_number, as before for the committed number.
- DeleteObsoleteOptionsFiles() protects versions_->options_file_number() in
  both modes, not only when the number is committed. In normal cases this
  function does not delete the current file: it runs after a successful
  OPTIONS write, at the end of open, and in tracked mode after column family
  create and drop (where a committed number always exists). One rare open
  path can delete it: the highest OPTIONS file cannot be read, a lower file is
  picked, and the open-time write fails. That open fails anyway. Protecting
  the number in both places covers this path too and gives both places the
  same rule.
- The comment on VersionSet::options_file_number() describes what the number
  holds in each mode.

Safety and cases not changed:
- With track_options_file_number_in_manifest = true, options_file_number()
  is the committed number once one exists, so nothing changes there. The one
  new case is a full scan that runs in open after the open-time OPTIONS write
  failed, before any number was committed: the scan now also keeps the file
  chosen at open.
- After a failed OPTIONS write, the current OPTIONS file does not hold the
  options that the DB runs with. SetOptions() installs the new options before
  it writes the OPTIONS file, and a failed write only marks the file as stale.
  So after this fix, checkpoints and backups succeed, but their OPTIONS file
  holds the options from before the failed call. This is not changed here.
- The OPTIONS files that a failed write leaves behind are not deleted at the
  time of the failure. The scan deletes them later, once they are not among
  the two highest numbers. Deleting them right away would change which file
  the next open loads (a legacy open picks the highest OPTIONS file on disk),
  so it is not part of this change.
- No API, format or option change.

Differential Revision: D134907310
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311
@meta-codesync meta-codesync Bot changed the title Accept obsolete missing blob files in secondary catch-up Accept obsolete missing blob files in secondary catch-up (#15824) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
Summary:
Pull Request resolved: meta#15824

Background: A secondary instance follows the primary by tailing its MANIFEST
(ManifestTailer, which TryCatchUpWithPrimary() runs). For each MANIFEST point
(the state after one MANIFEST edit), catch-up checks that the point's table
and blob files exist. It installs the point's Version only when the point is
complete (VersionBuilder::ContainsCompleteVersion(); the tailer uses
allow_incomplete_valid_version=false). The same check runs when a secondary
instance opens and in follower instances. Best-efforts recovery uses it too,
and it is the only check there once the column family was edited in an
atomic group (for example with atomic_flush and more than one column family).

The primary deletes a blob file as soon as the Version no longer keeps it.
For example, when compaction drops the last live values of a blob file, the
file loses its only linked SST and all its values count as garbage, so the
primary deletes it. If the secondary did not catch up between that file's
addition and its deletion, catch-up applies the addition when the file is
already gone.

Previous behavior: VersionBuilder keeps missing_blob_files_high_, the highest
missing blob file number seen while reading one MANIFEST. A missing blob file
raises it, and nothing lowers it. A point counts as complete only when this
number is below the oldest blob file that an SST links. So one deleted
obsolete blob file that is newer than a still-linked blob file keeps the
column family incomplete. The secondary keeps serving the Version from before
that file's addition and leaves out the SSTs added after it. This lasts until
the primary starts a new MANIFEST or rewrites every SST that links an older
blob file. Meanwhile TryCatchUpWithPrimary() returns OK,
rocksdb.secondary-has-missing-files returns 1, and keys in the left-out SSTs
read as NotFound once their WAL is deleted. A point where no SST links any
blob file (for example after DeleteFilesInRange() or after the only blob
values are overwritten and compacted) was always incomplete while any blob
file was missing. In best-efforts recovery inside an atomic group, the same
rule made recovery stop at the point before the deleted file's addition, so
the writes flushed after it were lost in every column family of the group.
db_stress hit the secondary case in crash test runs with blob files, blob
garbage collection and test_secondary=1 (tools/db_crashtest.py does not
combine blob files with test_secondary; enabling that is a separate
follow-up).

New behavior: a point is complete when every missing blob file is one that
the save rule (SaveBlobFilesTo()) would leave out of the Version anyway. No
SST references such a file:
- A blob file below every blob file that an SST references. An SST's oldest
  blob file is never newer than any blob file it references.
- A blob file that no SST links and whose values all count as garbage. An SST
  that references a blob file either links it as its oldest blob file or
  keeps some of its values live.
When no SST references any blob file, the Version keeps no blob file, so
every missing blob file is accepted. A missing blob file that the Version
would keep still makes the point incomplete, as before.

Implementation: a new VersionBuilder::Rep::MissingBlobFilesAreObsolete()
checks each file in missing_blob_files_ with the save rule, using the
builder's metadata for that file (garbage count and linked SSTs) at this
point. ContainsCompleteVersion() uses it in place of the comparison with
missing_blob_files_high_. The save rule's "no linked SSTs and all garbage"
test moves into one helper, HasNoLinkedSstsAndOnlyGarbage(), that both rules
use. An edit that carries dropped blob file records marks the builder as
updated, so the cached validity result is computed again with the new bound
(see below).

The lower bound for the first kind comes from
GetMinReferencedBlobFileNumberBound(). The save rule uses the oldest blob
file of the saved SSTs, which the builder knows only while it saves. The
bound uses the smallest of:
- the oldest blob file that an SST links (GetMinOldestBlobFileNumber()),
  which covers every SST whose oldest blob file has metadata in the builder;
- the smallest blob file that best-efforts BlobDB repair recorded as dropped
  (in the base Version and in the edits read so far). A builder that
  tracks missing files starts from the empty initial Version. In catch-up,
  the first builder keeps a reference to that Version, so later builders
  start from it too. So the base Version has no dropped blob files for all
  current builders. The code reads them anyway, so the bound stays right if
  that changes. After a repair with
  best_efforts_blob_db_repair, an SST can keep a dropped blob file as its
  oldest blob file. That file has no metadata, so the SST links nothing.
The bound is never higher than the save rule's number. Without the dropped
files, a repaired DB whose remaining SST still references a missing blob
file that no SST links would count as complete, and reads would fail with
Corruption.

Safety and unchanged cases:
- A normal DB::Open does not track missing files and is unchanged.
- Best-efforts recovery outside an atomic group is unchanged in effect.
  OnlyMissingL0Suffix() already accepts any missing blob file that no SST
  links. Inside an atomic group, a point with only obsolete missing blob
  files now counts as complete, so recovery reaches the newest point (see
  Previous behavior).
- HasMissingFiles(), which best-efforts recovery reports, still counts any
  missing blob file. Opens with best_efforts_blob_db_repair, which record
  missing blob files as dropped, are unchanged.
- Known limit: the dropped blob file list read from the edits is not pruned
  within one builder. After a repair, the bound can stay lower than needed
  until the next MANIFEST. A missing blob file between the bound and the
  oldest blob file of the saved SSTs then still counts as missing, and
  rocksdb.secondary-has-missing-files can return 1 for a point that the
  save rule could build. This errs on the strict side and never accepts a
  needed file.
- RepairDB of a DB with blob files is not supported here, because it drops
  all blob file metadata. After it, a missing blob file that is still needed
  may not be reported.
- Cost: each validity check walks missing_blob_files_, which holds every
  blob file added and found missing while reading one MANIFEST. The check
  already walks the blob file metadata in GetMinOldestBlobFileNumber(), up to
  the first blob file that an SST links, so the order of cost is the same.
  The walk runs only while some blob file is missing.
- The trigger needs a blob file that loses its last linked SST and all live
  values and is deleted by the primary while a secondary tails a MANIFEST
  that still has its addition.

Public header comment: the rocksdb.secondary-has-missing-files comment in
include/rocksdb/db.h says that a blob file the newest state no longer keeps does
not count. It notes the strict limit above after a repair: a missing blob file
that no SST links and that still holds live values (for example after
DeleteFilesInRange()) can still count. The property and this limit come
from the change that added rocksdb.secondary-has-missing-files.

Differential Revision: D134907311

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