Skip to content

Keep the current OPTIONS file in the obsolete file purge - #15823

Open
xingbowang wants to merge 9 commits into
meta:mainfrom
xingbowang:export-D134907310
Open

xingbowang wants to merge 9 commits into
meta:mainfrom
xingbowang:export-D134907310

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
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-:
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-".
    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.

Reviewed By: pdillinger

Differential Revision: D134907310

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

@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

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

Completed in 1433.3s.

Summary by check

Check Count
bugprone-argument-comment 1
Total 1

Details

db/version_set_test.cc (1 warning(s))
db/version_set_test.cc:1831:42: warning: argument name 'file_number' in comment does not match parameter name 'file' [bugprone-argument-comment]

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 29, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Nov 30, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge (#15823) Keep the current OPTIONS file in the obsolete file purge Nov 30, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 30, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge (#15823) Keep the current OPTIONS file in the obsolete file purge Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge (#15823) Keep the current OPTIONS file in the obsolete file purge Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Dec 1, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Dec 1, 2026
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
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge (#15823) Keep the current OPTIONS file in the obsolete file purge Dec 1, 2026
@xingbowang
xingbowang force-pushed the export-D134907310 branch 2 times, most recently from a7b5b34 to 8c01aee Compare December 1, 2026 16:52
@meta-codesync meta-codesync Bot changed the title Keep the current OPTIONS file in the obsolete file purge Keep the current OPTIONS file in the obsolete file purge (#15823) Dec 1, 2026
… atomic compaction unit covers it (meta#15814)

Summary:
Pull Request resolved: meta#15814

## Background

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

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

## The problem

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

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

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

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

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

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

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

## The fix

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

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

## Changes visible to existing users

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

## Paths checked

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

## Possible follow-ups

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

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

Reviewed By: pdillinger

Differential Revision: D134698940
…on inputs

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

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

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

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

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

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

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

Reviewed By: pdillinger

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

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

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

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

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

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

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

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

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

Reviewed By: pdillinger

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

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

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

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

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

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

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

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

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

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

Reviewed By: pdillinger

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

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

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

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

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

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

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

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

Reviewed By: pdillinger

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Reviewed By: pdillinger

Differential Revision: D134907307
Summary:
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 that has writes and whose start sequence is at or below the target. If there is no such WAL at listing time, the scan picks the first WAL in the list. The scan skips a no-write WAL, because its placeholder 1 says nothing about where the target is. It tells a placeholder 1 from a real start sequence 1 through a flag that the listing keeps for each file (see the last bullet). A real start sequence 1 is not skipped. It is found, for example, in the first WAL of a DB, and in the new WAL after a point-in-time recovery that stopped before the first write of the DB. 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 and replayed at least one write. 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`). When recovery replays no write (for example, the first record of the DB's first WAL is cut off), `DB::Open()` writes no empty batch. The new WAL then gets its real start sequence from its first write to the WAL (1 in this example), and the scan picks it. If the first new writes skip the WAL, the new WAL starts above that sequence. A target below that start then starts at an older WAL (the last WAL that starts at or below the target, or the first listed WAL if there is none), which can be a WAL that recovery did not replay (see "Known gaps").
- 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. A file after the first can hold such batches. With `manual_wal_flush`, a WAL that the listing gives as having no writes can get buffered writes after `GetUpdatesSince()`, also writes below the target, and the next `Next()` reads them.
- 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, the same steps return `TryAgain` with WAL compression, where the list also holds the current no-write WAL, and OK without WAL compression. A missing target 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 then ends the run with `TryAgain`, so the caller builds a new iterator. `GetUpdatesSince()` accepts only a target at or below the DB's last sequence, so the DB has always written past the iterator's files, also when the target was written without the WAL and is the last write. The only exception is target 0 when the DB's last sequence is 0; then the 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` instead of with an error. For example, the purge can delete an archived WAL of the iterator while the iterator waits for its target. If the seek then reaches the end of the files without finding the target, the rule above applies (`TryAgain`). 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. `ReadFirstRecord()` passes the flag on, the cache keeps it with the start sequence, and each listed file (`WalFileImpl`, an internal class) carries it, so that `RetainProbableWalFiles()` can tell a placeholder 1 from a real start sequence 1.

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 skips the batches below the target in every file it reads, not only in the first one. 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.

Reviewed By: pdillinger

Differential Revision: D134907308
Summary:
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 switch leaves the unstarted file on disk. A later full-scan purge
deletes it as an obsolete WAL, or archives it under WAL_ttl_seconds or
WAL_size_limit_MB, once it is older than the oldest WAL to keep. Otherwise
the file is still deleted at once.

An unstarted file that stays 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::DeleteOrKeepUnstartedWAL().
  Under the DB mutex, it checks whether deletions are enabled.
  - If they are disabled and track_and_verify_wals is off, it leaves the file
    and logs one info LOG line.
  - 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.
- A file that stays needs no new purge code. Only the obsolete-file purge can
  delete it, and FindObsoleteFiles() returns early while deletions are
  disabled. The purge finds the file only in a full scan, because the file
  was never published as a WAL. The scan takes it once its number is below
  the oldest WAL to keep. Full scans run, for example, at the end of the
  recovery from the background error (ResumeImpl()), in
  EnableFileDeletions() when the counter reaches 0, at open, at close, and
  at the first flush or compaction after each
  delete_obsolete_files_period_micros.
- How long the file stays: the recovery moves all column families to a
  newer WAL, so usually the full scan at the end of the recovery deletes the
  file. The file stays longer in three cases:
  - With allow_2pc and a prepared transaction in an older WAL, the oldest
    WAL to keep only moves at a flush. The file then stays until the next
    full scan after that flush.
  - When no recovery runs, for example after a non-retryable error without
    a manual Resume(), or when a listener suppresses the error, the file
    stays until a full scan after a later WAL switch, at the latest until
    the next open. A close deletes it only when such a switch came first.
  - After a close or crash before the recovery, an open with
    avoid_flush_during_recovery uses the file as a live WAL. The first flush
    then deletes it.
  No writes are lost in these cases; only the empty file stays longer.

Alternatives not taken:
- Keep a list of the files that stay, and delete them as soon as deletions
  are enabled again, without archiving them, and at close. That needs a list
  in DBImpl and in JobContext, a grabbed-for-purge mark so that a concurrent
  full scan does not archive the file, and special cases in the purge and at
  close. The file is empty, and RocksDB already leaves the same kind of file
  behind in other paths (see Safety), so the faster cleanup is not worth that
  code.
- 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 file is never left with this option. After a
  crash while the file stays, 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.
- Other paths leave the same kind of file on disk, before and after this
  change. The CreateWAL() path of a switch without a precreated WAL leaves its
  file when the start fails, and close leaves an unused precreated WAL file.
  The CreateWAL() 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 or close while the file stays, 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. A full-scan
  purge deletes it once it is older than the oldest WAL to keep. When an
  open with avoid_flush_during_recovery uses it as a live WAL, the first
  flush deletes it. The open does not check WAL predecessors without this
  option. A file that stays can be between published WALs at the next open.
  If that open turns on track_and_verify_wals, the file has the same problem
  as the CreateWAL() file above, with the same possible follow-up.
- Listings while the file stays: 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, and the listing marks
  it as a WAL with no writes, so GetUpdatesSince() skips it when it picks
  the first WAL to read. 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 a full-scan purge finds it older than the oldest WAL to keep
  (see "How long the file stays" above). A WAL listing in that time can
  return it. The file holds no writes. Compared with the delete at once:
  - With WAL_ttl_seconds or WAL_size_limit_MB, the purge moves the file to
    the archive directory, as it does with any obsolete WAL. The file is
    empty, or holds only the compression type record of wal_compression.
  - A close while deletions are still disabled leaves the file. When the
    recovery ran before the close, the next open usually deletes it.
  - When deletions are enabled again before the recovery from the background
    error, the file stays at least until the full scan at the end of the
    recovery.

Differential Revision: D134907309
Summary:
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.

Reviewed By: pdillinger

Differential Revision: D134907310

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