Skip to content

Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore (#15748) - #15748

Open
xingbowang wants to merge 3 commits into
meta:mainfrom
xingbowang:export-D133564196
Open

xingbowang wants to merge 3 commits into
meta:mainfrom
xingbowang:export-D133564196

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the ManifestStore interface (include/rocksdb/manifest_store.h), and the option DBOptions::manifest_store. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:

  • Store mode: DBOptions::manifest_store is set and the DB row says that the store is the authority (ManifestAuthority::kStore).
  • Stub: in store mode, CURRENT names a small file MANIFEST-<number>, the stub. Its one record starts with the new tag kManifestStoreStub (500). The tag does not have the kTagSafeIgnoreMask bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
  • Copy: an optional MANIFEST-format file MANIFEST_COPY-<number> that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
  • Enter: DB::Open() with the new option DBOptions::manifest_store_migrate moves a file-mode DB into the store.
  • Switch: an enter writes all rows of a new generation with ManifestStore::WriteGeneration(). The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
  • Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
  • Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: DB::Open() and DB::OpenForReadOnly() return NotSupported when manifest_store is set.

New behavior, in short:

  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store

New behavior:

  • Open: for a done stub, DB::Open() checks that the DB row belongs to this DB (the db id of the stub), claims the DB with ManifestStore::Open() (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets ManifestStoreOpenOptions::expected_commit_sequence and expected_last_commit_id to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. DB::OpenForReadOnly() and DB::ListColumnFamilies() with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in db/manifest_store_state.h.

  • Create: with create_if_missing and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.

  • Write path: each batch of VersionSet::ProcessManifestWrites() becomes one ManifestCommit, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.

  • Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.

  • Commit results (the full table and a diagram of the retry loop are at ManifestStoreState::CommitBatch()):

    First Commit() result CommitBatch() does CommitBatch() returns
    OK records that the store applied the batch OK
    IOFenced stops the DB IOFenced (fatal)
    TryAgain nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch retryable IOError
    NotSupported (the store rejects the commit for good) nothing, no resend; the store state does not stop. A caller that sets it as the background error (a flush or compaction does) gets a fatal error, so DB::Resume() returns it without a store call and the DB must be opened again IOError, not retryable
    Busy or other error reads the DB row; may resend (see below) OK, IOFenced (fatal), or a stop: a plain IOError (fatal)
    • RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
    • It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
    • It makes at most max_bgerror_resume_count retries (resends or repeated reads), bgerror_resume_retry_interval apart.

    After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

    With the default max_bgerror_resume_count (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During DB::Open() and during a close, a commit with an unknown outcome gives up at the first failed ReadDbRow() or resend. So DB::Open() returns the error (as a failed MANIFEST write fails DB::Open() in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.

  • Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.

  • Copy (DBOptions::manifest_store_copy_mode, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in db/manifest_store_state.h.

  • Enter store mode (DBImpl::EnterManifestStore(), seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without manifest_store_migrate. manifest_store_migrate also lets Open change the copy mode.

  • Roll back: the new function RollBackManifestStore() moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it keeps every complete record outside an atomic group and every complete atomic group. It drops two kinds of torn tail that a crash can leave: a last record that was cut short (the log reader stops before it) and an atomic group that is still open at the end of the copy. A damaged record (a bad checksum or a record that cannot be decoded), or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.

  • Option checks: with a store, best_efforts_recovery, best_efforts_blob_db_repair and a manifest_store_copy_mode above kSync give InvalidArgument, and compaction_service gives NotSupported.

  • Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, DB::OpenAndCompact(), RepairDB(), DestroyDB() on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:

  • The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
  • The row changes of a batch come from its edits and its new Versions (BuildManifestRowChanges() in db/manifest_rows.h), so a commit carries only the rows that change.
  • A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
  • The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:

  • db/manifest_store_state.{h,cc} (new): the overview comment; the stub record; the copy marker and pointer file; ScanManifestStore(); CheckManifestDbRowOwner() and CheckOwnerAndClaim(); class ManifestStoreState with CommitBatch(); RollBackManifestStore().
  • db/manifest_rows.cc: VersionSet::BuildManifestBatchRowChanges() and VersionSet::CommitBatchToStore().
  • db/version_set.{h,cc}: the store branch of ProcessManifestWrites(), RecoverFromStore() with the shared replay helper ReplayManifest(), and the copy writer.
  • db/db_impl/db_impl_open.cc: RecoverFromManifestStore(), create, enter, and CheckManifestStoreOptions().
  • db/db_impl/db_impl_files.cc: DBImpl::MinFileNumberInUse() gives the in-flight file number. DBImpl::pending_ingestion_outputs_ becomes a std::map, so it reads the smallest reserved number of the running ingestions at once. db/blob/blob_file_partition_manager.{h,cc}: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (NewTrackedBlobFileNumber()), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (MinTrackedBlobFileNumber()), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
  • RollBackManifestStore() returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
  • Guards: db/db_filesnapshot.cc, db/repair.cc, DestroyDB(), DB::ListColumnFamilies().
  • db/manifest_ops.{h,cc}: ManifestReporter and NewManifestReader() move here from db/experimental.cc, so that the stub reader and the copy reader use them too.
  • db/db_test_util.{h,cc}: with ENCRYPTED_ENV, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with Env::Default(), which the encrypted env cannot read, and DestroyDB() reads CURRENT (see "Changes visible to existing users").

How to read this diff:

  1. Overview: db/manifest_store_state.h, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the RollBackManifestStore() comment in include/rocksdb/manifest_store.h for the third mode change.
  2. Stub and owner check: in db/manifest_store_state.h and .cc, read ManifestStub and its encode, decode and read functions, then ScanManifestStore(), CheckScannedStoreRows(), CheckManifestDbRowOwner() and CheckOwnerAndClaim(). They depend on nothing else in this diff.
  3. Write-path state: class ManifestStoreState in db/manifest_store_state.h, then CommitBatch() in .cc. Read the results table, the diagram and the retry loop.
  4. Write-path glue: db/manifest_rows.cc (CommitBatchToStore()), then db/version_set.cc. In ProcessManifestWrites(), read the store branch, the quarantine and io_status_ block, then RecoverFromStore() and ReplayManifest().
  5. Copy: in db/version_set.cc, read StartManifestCopyAtOpen(), WriteNewManifestCopy() and UpdateManifestCopy(), then the copy sync in VersionSet::Close().
  6. Open, create and enter: first read the step lists in db/db_impl/db_impl.h. Then in db/db_impl/db_impl_open.cc read DBImpl::Recover() and RecoverFromManifestStore() (together they call the others), then CreateDbInManifestStore() and CommitNewDbRows(), then EnterManifestStore(), ClaimForEnter() and FinishEnterManifestStore().
  7. Rollback and guards: read RollBackManifestStore() at the end of db/manifest_store_state.cc. Then the guards in db/db_impl/db_impl.cc (DestroyDB(), DB::ListColumnFamilies(), the files that ingestion and import keep), db/db_filesnapshot.cc, db/repair.cc, the blob file number change in db/blob/blob_file_partition_manager.cc, and the option comments in include/rocksdb/options.h.
  8. Tests: db/db_manifest_store_test.cc, by its "Section:" comments.

Safety:

  • File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
  • On the write path, no store call and no blocking I/O runs under the DB mutex. During DB::Open(), the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
  • Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
  • An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above. An open or a column family listing through a done stub refuses a DB row with authority kShadow. An enter from a normal MANIFEST accepts a kShadow row of the same DB (EnterFromShadowAuthority). db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:

  • RocksDB does not split a batch that is larger than the transaction limit of the store.
  • RocksDB treats every Commit() status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After DB::Open(), RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default max_bgerror_resume_count (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in include/rocksdb/manifest_store.h says so.
  • Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next DB::Open() (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of enable_blob_direct_write says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
  • The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
  • A close gives up at the first failed ReadDbRow() or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
  • There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
  • A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
  • In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
  • The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
  • After a rollback, the rows stay in the store until ManifestStore::Destroy() removes them.
  • A file that a failed ingestion or import keeps can be a hard link to the input file (with move_files or link_files); the option comments say not to change such an input file in place.
  • reuse_manifest_on_open and verify_manifest_content_on_close have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:

  • The new options manifest_store_migrate and manifest_store_copy_mode, the function RollBackManifestStore(), and the store-mode notes in the comments of max_bgerror_resume_count, bgerror_resume_retry_interval and DB::ListColumnFamilies().
  • Best-efforts recovery (VersionSet::TryRecover()) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. RepairDB() reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
  • DestroyDB() now reads CURRENT and the first record of the MANIFEST that it names, also in file mode, and checks the result of the folder listing before it deletes anything. An error while reading CURRENT or the MANIFEST, for example an I/O error or a timeout, returns that error and deletes nothing when the folder can be listed (when the listing fails, no file of the folder is deleted). Two errors are not such a case, and the DB is deleted as a file-mode DB: a missing MANIFEST (it cannot be a stub, because RocksDB points CURRENT to a new stub before it deletes the old one) and Corruption. A listing error other than a missing folder is returned for a stub or when a store is in the options, and nothing changes. For a file-mode DB without a store, the listing error is ignored. No file of the folder is deleted, but the other DB folders (db_paths, the cf_paths of the given column families, the WAL folder and the archive folder) are still cleaned. A stub returns NotSupported, with or without a store. DestroyDB() also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196

@meta-codesync

meta-codesync Bot commented Nov 20, 2026

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

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

Completed in 1142.2s.

Summary by check

Check Count
bugprone-argument-comment 7
cert-err58-cpp 2
clang-analyzer-optin.core.EnumCastOutOfRange 3
cppcoreguidelines-special-member-functions 1
modernize-use-emplace 1
performance-inefficient-string-concatenation 3
performance-inefficient-vector-operation 5
Total 22

Details

db/db_impl/db_impl.cc (1 warning(s))
db/db_impl/db_impl.cc:7625:51: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]
db/db_manifest_store_test.cc (6 warning(s))
db/db_manifest_store_test.cc:44:7: warning: class 'DBManifestStoreTest' defines a non-default destructor but does not define a move constructor or a move assignment operator [cppcoreguidelines-special-member-functions]
db/db_manifest_store_test.cc:581:14: warning: The value '129' provided to the cast expression is not in the valid range of values for 'ManifestDbField' [clang-analyzer-optin.core.EnumCastOutOfRange]
db/db_manifest_store_test.cc:586:14: warning: The value '193' provided to the cast expression is not in the valid range of values for 'ManifestDbField' [clang-analyzer-optin.core.EnumCastOutOfRange]
db/db_manifest_store_test.cc:589:14: warning: The value '193' provided to the cast expression is not in the valid range of values for 'ManifestDbField' [clang-analyzer-optin.core.EnumCastOutOfRange]
db/db_manifest_store_test.cc:2795:56: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]
db/db_manifest_store_test.cc:3259:11: warning: use emplace_back instead of push_back [modernize-use-emplace]
db/manifest_store_state.cc (3 warning(s))
db/manifest_store_state.cc:405:48: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]
db/manifest_store_state.cc:633:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/manifest_store_state.cc:636:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/version_set_test.cc (9 warning(s))
db/version_set_test.cc:1462:48: warning: argument name 'db_directory' in comment does not match parameter name 'dir_contains_current_file' [bugprone-argument-comment]
db/version_set_test.cc:3404:39: warning: argument name 'count' in comment does not match parameter name 'garbage_blob_count' [bugprone-argument-comment]
db/version_set_test.cc:3404:52: warning: argument name 'bytes' in comment does not match parameter name 'garbage_blob_bytes' [bugprone-argument-comment]
db/version_set_test.cc:3628:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/version_set_test.cc:3680:9: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/version_set_test.cc:4630:37: warning: argument name 'count' in comment does not match parameter name 'garbage_blob_count' [bugprone-argument-comment]
db/version_set_test.cc:4630:50: warning: argument name 'bytes' in comment does not match parameter name 'garbage_blob_bytes' [bugprone-argument-comment]
db/version_set_test.cc:4636:39: warning: argument name 'count' in comment does not match parameter name 'garbage_blob_count' [bugprone-argument-comment]
db/version_set_test.cc:4636:52: warning: argument name 'bytes' in comment does not match parameter name 'garbage_blob_bytes' [bugprone-argument-comment]
file/filename.cc (2 warning(s))
file/filename.cc:179:19: warning: initialization of 'kManifestCopyPrefix' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
file/filename.cc:180:19: warning: initialization of 'kManifestCopyPointerName' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
test_util/mock_manifest_store.cc (1 warning(s))
test_util/mock_manifest_store.cc:66:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]

@xingbowang
xingbowang force-pushed the export-D133564196 branch 5 times, most recently from cba322c to 9f755be Compare November 22, 2026 13:53
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 22, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter (below). Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; resends only after any other error; at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). The mode table is in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not support store mode.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- Two DBs configured with the same store: when the store already holds a DB row at the enter's check (a placeholder from a failed enter, or the row of this DB after a rollback), and another DB takes that row before the enter's claim, the enter fails, but its claim has set the other DB's authority to kFile. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 22, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter (below). Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; resends only after any other error; at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). The mode table is in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not support store mode.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- Two DBs configured with the same store: when the store already holds a DB row at the enter's check (a placeholder from a failed enter, or the row of this DB after a rollback), and another DB takes that row before the enter's claim, the enter fails, but its claim has set the other DB's authority to kFile. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 22, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter (below). Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; resends only after any other error; at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). The mode table is in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not support store mode.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- Two DBs configured with the same store: when the store already holds a DB row at the enter's check (a placeholder from a failed enter, or the row of this DB after a rollback), and another DB takes that row before the enter's claim, the enter fails, but its claim has set the other DB's authority to kFile. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 22, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter (below). Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; resends only after any other error; at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). The mode table is in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not support store mode.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- Two DBs configured with the same store: when the store already holds a DB row at the enter's check (a placeholder from a failed enter, or the row of this DB after a rollback), and another DB takes that row before the enter's claim, the enter fails, but its claim has set the other DB's authority to kFile. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Claude Code Review - OBSOLETE

Superseded by a newer AI review. Expand to see the original review.

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit 9f755be


Summary

This PR adds "store mode" to RocksDB, allowing MANIFEST metadata to be kept in an external ManifestStore instead of MANIFEST files. The design is well-structured with a clear state machine (creating/entering/done stubs), idempotent commits via commit IDs, and fencing via epochs. The change is large (12K+ lines, 47 files) but the scope is appropriate given the feature's complexity.

High-severity findings (3):

  • [src.mk] New source files db/manifest_rows.cc, db/manifest_store_state.cc, test_util/mock_manifest_store.cc, and test db/db_manifest_store_test.cc are added to BUCK, CMakeLists.txt, and Makefile but appear to be missing from src.mk, which is the canonical source list that Make uses via LIB_SOURCES and TEST_MAIN_SOURCES.
  • [db/db_impl/db_impl.cc:7529-7560] DestroyDB() behavior change for file-mode DBs: now reads CURRENT and the first MANIFEST record for every call, even in file mode. An I/O error reading these (other than PathNotFound or Corruption) blocks deletion entirely when the directory can be listed. This is a silent behavior regression for existing users.
  • [db/db_impl/db_impl.h:~2038] The new closing_ atomic is the 5th shutdown-related flag (shutting_down_, shutdown_initiated_, closed_, closing_status_, and now closing_). The semantic distinction between closing_ and shutdown_initiated_ is subtle and error-prone.
Full review (click to expand)

Findings

🔴 HIGH

H1. Missing src.mk updates — src.mk
  • Issue: The diff adds db/manifest_rows.cc and db/manifest_store_state.cc to BUCK (lines 93-94), CMakeLists.txt (lines 841-842), and Makefile (line 2267), but the diff (truncated) does not show corresponding additions to src.mk (which lists LIB_SOURCES after line 2 and TEST_MAIN_SOURCES after line 487). Similarly, test_util/mock_manifest_store.cc appears in BUCK and CMakeLists.txt test lib sources but not in src.mk's TEST_LIBRARY_SOURCES, and db/db_manifest_store_test.cc is not in TEST_MAIN_SOURCES. Per CLAUDE.md: "When a new .cc file is added, update Makefile, CMakeLists.txt, src.mk, BUCK."
  • Root cause: Build system files not kept in sync.
  • Suggested fix: Add db/manifest_rows.cc and db/manifest_store_state.cc to LIB_SOURCES in src.mk, add test_util/mock_manifest_store.cc to TEST_LIBRARY_SOURCES, add db/db_manifest_store_test.cc to TEST_MAIN_SOURCES, then run python3 buckifier/buckify_rocksdb.py to regenerate BUCK. (If the diff was simply truncated and these changes exist, this finding can be dismissed.)
H2. DestroyDB behavior change for file-mode users — db/db_impl/db_impl.cc:7529-7560
  • Issue: DestroyDB() now reads CURRENT and the first record of the MANIFEST file it names, even for file-mode DBs that have no store. If this read returns an IOError (not PathNotFound, not Corruption), and the directory listing succeeded, DestroyDB returns that error and deletes nothing. Previously, DestroyDB would proceed to delete all files. This is a behavior change visible to existing users who never set manifest_store.
  • Root cause: The stub detection logic runs unconditionally.
  • Suggested fix: Consider gating the CURRENT+MANIFEST read on a heuristic (e.g., only when options.manifest_store is set, or when the MANIFEST file is suspiciously small). Alternatively, document this behavior change prominently in release notes and ensure the "Changes visible to existing users" section in the PR description covers the failure-mode change. The current description mentions DestroyDB reads CURRENT but does not emphasize the new failure mode where transient I/O errors during CURRENT/MANIFEST reading can now block DestroyDB entirely.
H3. Proliferation of shutdown flags — db/db_impl/db_impl.h:~2038
  • Issue: The codebase already has shutting_down_, shutdown_initiated_, closed_, and closing_status_. This PR adds a 5th flag: closing_. The comment explains the distinction from shutting_down_ (set earlier to shorten retry loops during close), but the naming is confusingly similar to closed_ and closing_status_. Future maintainers will struggle to understand which flag to check.
  • Root cause: Each flag was added for a specific use case, but the overall design lacks a unified shutdown state machine.
  • Suggested fix: Consider reusing shutdown_initiated_ (which is already set at the beginning of shutdown) instead of adding closing_. If the semantic difference (CancelAllBackgroundWork vs Close) requires a separate flag, at minimum rename to something more descriptive like close_initiated_ and add a comment that explicitly contrasts it with ALL other shutdown flags.

🟡 MEDIUM

M1. MinFileNumberInUse() allocates under DB mutex — db/db_impl/db_impl_files.cc:143-170
  • Issue: MinFileNumberInUse() is called under the DB mutex (as documented). It creates an UnorderedSet<uint64_t> blob_files on the stack, then iterates all column families calling GetActiveBlobFileNumbers() and GetProtectedBlobFileNumbers(), which likely acquire file_partition_mutex_ (a read lock) and insert into the set. With many column families using blob direct write, this involves repeated hash set insertions and lock acquisitions under the DB mutex. This runs on every store-mode commit.
  • Root cause: Per-commit work that scales with the number of column families.
  • Suggested fix: Consider caching or batching this computation. At minimum, reserve capacity in the UnorderedSet or use a simpler container (a plain uint64_t minimum tracking). Also consider whether the min can be maintained incrementally rather than recomputed on every commit.
M2. KeepFilesAfterStoreError is broader than necessary — db/db_impl/db_impl.h:1467-1480
  • Issue: KeepFilesAfterStoreError() returns true for ANY IOError in store mode, including cases where the store definitely did not apply the commit (TryAgain from first send, IOFenced from first send). The comment acknowledges this ("The check is broader than needed") and says it's safe because orphaned files get cleaned up later. However, this means file leaks can accumulate between opens in pathological failure scenarios.
  • Root cause: Intentional simplification for safety, but could be tightened.
  • Suggested fix: Consider narrowing the check for the ingestion/import paths to exclude cases where the commit definitely did not reach the store. The current approach is safe but wasteful.
M3. ClaimForEnter race window — db/db_impl/db_impl_open.cc (ClaimForEnter)
  • Issue: The PR description documents a known limitation: "Two DBs configured with the same store: when the store already holds a DB row at the enter's check... and another DB takes that row before the enter's claim, the enter fails, but its claim has set the other DB's authority to kFile." This means a misconfigured enter can disrupt another DB's authority. The code handles it (returns InvalidArgument), but the side effect on the other DB persists.
  • Root cause: The ManifestStore interface has no compare-and-swap claim that checks a specific commit sequence.
  • Suggested fix: This is documented as a known limitation. Consider whether the ManifestStore interface should support conditional claims (e.g., "claim only if commit sequence is X") to close this race. At minimum, the error message should warn the user that the other DB's authority may have been changed.
M4. Potential for PermitUncheckedError misuse — db/db_impl/db_impl.cc:7544-7549
  • Issue: In the DestroyDB stub detection path, current_s.PermitUncheckedError() is called after the stub check and before the IOError check. If current_s is a non-IOError, non-PathNotFound error (e.g., Corruption of the MANIFEST), it's silently ignored and deletion proceeds. This is intentional (Corruption = not a stub), but the PermitUncheckedError() pattern makes it easy to accidentally suppress real errors.
  • Root cause: Complex error classification logic.
  • Suggested fix: Add a brief comment at the PermitUncheckedError() call explaining why it's safe to ignore non-IOError errors (Corruption and PathNotFound are treated as "not a stub, proceed with file-mode deletion").
M5. RecoverFromManifestStore consistent vs non-consistent scan — db/db_impl/db_impl_open.cc (RecoverFromManifestStore)
  • Issue: The read-only path uses a consistent scan, but the read-write path uses a non-consistent scan with the comment "After the claim this instance is the only writer, so no commit runs during the scan." This assumption is correct if the claim (Open with epoch) truly fences all other writers. However, if a writer's in-flight commit lands between the claim and the scan, the non-consistent scan could see partial state. The claim raises the commit sequence, which causes in-flight commits to get TryAgain or be fenced, but there's a window where the commit was already accepted by the store before the claim raised the sequence.
  • Root cause: Reliance on the claim-fencing guarantee of the ManifestStore interface.
  • Suggested fix: Verify that the ManifestStore contract guarantees that after Open() returns, no previously in-flight commit can land. If this is guaranteed, add a comment citing the contract. If not, use a consistent scan.

🟢 LOW / NIT

L1. Missing ASSERT_STATUS_CHECKED consideration
  • Issue: The PR adds many new Status objects and error paths. Per CLAUDE.md, ASSERT_STATUS_CHECKED=1 make check should be run to verify all Status objects are properly checked. Some paths in the new code use patterns like checking io_s.ok() then branching, but intermediate Status objects from ReadDbRow, PublicRowsToManifestRows, etc. need to be verified as checked.
  • Suggested fix: Ensure the full test suite passes with ASSERT_STATUS_CHECKED=1.
L2. desc_status.PermitUncheckedError() in EnterManifestStore — db/db_impl/db_impl_open.cc
  • Issue: In EnterManifestStore(), desc_status from versions_->Recover() is immediately permitted unchecked. This is consistent with how Recover() is called elsewhere, but should be verified.
  • Suggested fix: No action needed if consistent with existing patterns.

Cross-Component Analysis

Context Store mode affected? Assessment
WritePreparedTxnDB YES - same ProcessManifestWrites path The store branch replaces MANIFEST I/O, not Version semantics. Should be safe.
ReadOnly DB YES - scans store without claim Correctly handles read-only semantics.
SecondaryInstance Blocked (NotSupported) Appropriate.
CompactionService Blocked (NotSupported) Appropriate - remote worker opens from MANIFEST.
BestEffortsRecovery Blocked (InvalidArgument) Appropriate - no old MANIFESTs to try.
FollowerInstance Blocked (NotSupported) Appropriate.
User-defined timestamps Allowed RowsToRewriteAfterOpen handles timestamp_size changes.
Concurrent blob direct write Addressed NewTrackedBlobFileNumber ensures atomicity of number allocation + tracking.

Positive Observations

  1. Idempotent commits via commit IDs: The design correctly handles unknown-outcome store commits by checking the commit ID in the DB row, preventing double-applies.
  2. Stub design: Using a MANIFEST file with an unknown tag (kManifestStoreStub = 500, without kTagSafeIgnoreMask) ensures old binaries fail loudly rather than reading an empty DB. This is elegant.
  3. Quarantine for failed commits: The error handler's quarantine prevents premature file deletion when a commit's outcome is unknown.
  4. Comprehensive test coverage: The ~3200-line test file covers create, enter, rollback, interrupted operations, DB row checks, copy modes, and many edge cases.
  5. Clear documentation: The overview comment in manifest_store_state.h and the "How to read this diff" section in the PR description show exceptional attention to reviewer experience.
  6. Feature-off cost: For file-mode users, the only new cost is in DestroyDB (reading CURRENT + first MANIFEST record). The write path and read path are unaffected.

ℹ️ About this response

Generated by Claude Code.
Review methodology: claude_md/ci_review_prompt.md

Limitations:

  • Claude may miss context from files not in the diff
  • Large PRs may be truncated
  • Always apply human judgment to AI suggestions

Commands:

  • /claude-review [context] — Request a code review
  • /claude-query <question> — Ask about the PR or codebase

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome. This includes a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- Two DBs configured with the same store can race during an enter. Example: the store holds a DB row (a placeholder from a failed enter, or the row of DB A after a rollback). The enter of DB A reads the DB row. DB B takes that row. The claim of DB A then sets the authority of the row to kFile, and the enter of DB A fails. DB B keeps its rows, but needs an operator before it opens in store mode again. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome. This includes a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- Two DBs configured with the same store can race during an enter. Example: the store holds a DB row (a placeholder from a failed enter, or the row of DB A after a rollback). The enter of DB A reads the DB row. DB B takes that row. The claim of DB A then sets the authority of the row to kFile, and the enter of DB A fails. DB B keeps its rows, but needs an operator before it opens in store mode again. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude Code Review - OBSOLETE

Superseded by a newer AI review. Expand to see the original review.

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit edee7c1


Summary

This is a large, well-structured PR (51 files, ~12.7K lines) that adds "store mode" to RocksDB, allowing MANIFEST metadata to be kept in an external ManifestStore. The design is thorough with explicit error handling, crash recovery at each step, and clear separation between file mode and store mode. The PR description is excellent and follows the reading-order guidance well.

High-severity findings (2):

  • [src.mk] src.mk is not updated with new source files db/manifest_rows.cc, db/manifest_store_state.cc, and test_util/mock_manifest_store.cc -- Make builds will fail.
  • [db/db_impl/db_impl_files.cc:143-166] MinFileNumberInUse() takes ReadLock on each column family's file_partition_mutex_ while holding DB mutex, on every store-mode commit. With many CFs and blob direct write enabled, this nests locks and may regress DB mutex hold time.
Full review (click to expand)

Findings

🔴 HIGH

H1. Missing src.mk updates — src.mk
  • Issue: The diff adds db/manifest_rows.cc and db/manifest_store_state.cc to BUCK, CMakeLists.txt, and Makefile, but src.mk (which defines LIB_SOURCES) is not updated. Similarly, test_util/mock_manifest_store.cc is added to BUCK and CMakeLists.txt test libraries but not to TEST_LIB_SOURCES in src.mk. The test binary db_manifest_store_test is added to Makefile and BUCK but not to TEST_MAIN_SOURCES in src.mk.
  • Root cause: The PR description's "Build system" section says to update Makefile, CMakeLists.txt, src.mk, and BUCK. src.mk was missed.
  • Impact: make builds (the primary build for git clones) will fail to link due to missing object files. CI and local builds will break.
  • Suggested fix: Add the following to src.mk:
    • db/manifest_rows.cc and db/manifest_store_state.cc to LIB_SOURCES (after db/manifest_ops.cc)
    • test_util/mock_manifest_store.cc to TEST_LIB_SOURCES
    • db/db_manifest_store_test.cc to TEST_MAIN_SOURCES
H2. Lock nesting in MinFileNumberInUse() — db/db_impl/db_impl_files.cc:143-166
  • Issue: MinFileNumberInUse() is called under DB mutex and iterates all column families, calling GetActiveBlobFileNumbers() and GetProtectedBlobFileNumbers() on each. These functions take a ReadLock on file_partition_mutex_ (confirmed at blob_file_partition_manager.cc:762,771). This creates a nested lock pattern: DB mutex → file_partition_mutex_ (ReadLock) for each CF.
  • Root cause: The function needs to enumerate all in-flight blob file numbers to compute the minimum file number in use. It does this by iterating all CFs' blob managers.
  • Impact: (a) Performance: With many column families (100+), this extends DB mutex hold time significantly on every store commit. The UnorderedSet<uint64_t> allocation and insertion per call adds heap allocation pressure. (b) Lock ordering: The write path in BlobFilePartitionManager::NewTrackedBlobFileNumber() takes file_partition_mutex_ (WriteLock) and then calls file_number_allocator_() which is versions_->NewFileNumber() (atomic, no lock). So the ordering is consistent (DB mutex → file_partition_mutex_). But if any future code takes file_partition_mutex_ then DB mutex, it deadlocks.
  • Suggested fix: Consider caching the minimum tracked blob file number in BlobFilePartitionManager (updated atomically on allocation and release), so MinFileNumberInUse() can read it without taking the lock. Alternatively, pre-allocate the UnorderedSet or use a thread-local minimum.

🟡 MEDIUM

M1. DestroyDB regression for file-mode users — db/db_impl/db_impl.cc:7529-7563
  • Issue: DestroyDB() now reads CURRENT and the first record of the MANIFEST file even for file-mode DBs. The PR description documents this as a "Changes visible to existing users" item. If the MANIFEST read hits an I/O error (and the directory listing succeeds), DestroyDB returns the error and deletes nothing. Previously, DestroyDB would succeed regardless of MANIFEST readability.
  • Root cause: Store mode detection requires reading the first MANIFEST record to check for the stub tag.
  • Impact: A DB with a corrupted MANIFEST that was previously destroyable now returns an I/O error from DestroyDB. The PathNotFound exception and Corruption exception are handled (fall through to file-mode deletion), but other IOErrors block deletion. This is a behavioral change for existing users.
  • Suggested fix: Consider limiting the new behavior to only check for stubs when manifest_store is set in the Options, rather than unconditionally reading CURRENT and MANIFEST. If unconditional detection is required, document the new failure mode prominently and ensure the IOError handling is as narrow as possible (only block on errors that genuinely indicate a possible stub).
M2. KeepFilesAfterStoreError is broader than needed — db/db_impl/db_impl.h:1467-1480
  • Issue: KeepFilesAfterStoreError() returns true for any IOError in store mode, including cases where the store definitely did NOT apply the commit (TryAgain wrapped as IOError, IOFenced from first send, errors before any send). The PR acknowledges this is safe but broader than needed.
  • Root cause: Simplification — checking the exact store error state would require exposing more internal state.
  • Impact: Leaked ingested/imported files accumulate until the next full-scan purge or DB reopen. For ingestions with move_files or link_files, the leaked file may be a hard link to the input file, preventing the caller from modifying the original. The PR documents this in known limitations.
  • Suggested fix: This is acceptable as documented. Consider adding a metric (ticker) to track the count of files kept due to this check, so operators can monitor accumulation.
M3. CommitNewDbRows race with concurrent creates — db/db_impl/db_impl_open.cc:490-570
  • Issue: In CommitNewDbRows(), when the initial Commit() returns Busy or unknown, the code reads the DB row, checks the db_id, and if it's an empty placeholder row, it claims with Open() and commits over it. Between ReadDbRow() and Open(), another writer can change the DB row, and the Open() claim would take over those rows with authority kFile set.
  • Root cause: The store interface lacks a conditional claim (claim only if commit_sequence matches). The PR acknowledges this in "Known limitations."
  • Impact: Two DBs configured with the same store can race during create/enter, potentially setting the authority of another DB's row to kFile. The affected DB needs operator intervention. This is a known limitation, not a bug.
  • Suggested fix: Document this limitation clearly in the ManifestStore interface. Consider adding a Claim(expected_sequence) method in a future version.
M4. closing_ set before live tuner stop — db/db_impl/db_impl.cc:1140
  • Issue: The diff sets closing_.store(true, std::memory_order_release) at the very start of CloseHelper(), before the live tuner stop (which can call SetOptions() and trigger MANIFEST writes). If a store commit is in-flight when closing_ is set, the retry loop will give up early, potentially causing the commit to be treated as failed even though it was about to succeed.
  • Root cause: The PR comment explains this is intentional — during close, the retry loop gives up at first failure to avoid blocking on an unresponsive store. The tradeoff: a short store failure during shutdown flush can stop the DB, losing unflushed WAL-less data.
  • Impact: Acceptable tradeoff as documented. But setting closing_ before the live tuner could cause the tuner's SetOptions flush to fail unexpectedly if it triggers a store commit.
  • Suggested fix: Consider moving closing_.store() to after the live tuner stop, or at least after shutdown_initiated_ = true in the mutex-held section.
M5. ParseManifestCopyFileName in DestroyDB file loop — db/db_impl/db_impl.cc:7598-7604
  • Issue: A new else if branch calls ParseManifestCopyFileName() for every filename that doesn't match the existing ParseFileName path. This adds a string comparison/parse for every non-standard file in every file-mode DestroyDB call.
  • Root cause: Copy files from a rollback need to be cleaned up by DestroyDB.
  • Impact: Minor performance regression for file-mode DestroyDB with many files. Negligible in practice.

🟢 LOW / NIT

L1. PermitUncheckedError() usage in EnterManifestStore — db/db_impl/db_impl_open.cc:593
  • Issue: desc_status.PermitUncheckedError() after versions_->Recover(). Consistent with file-mode open pattern. No action needed.
L2. Test fixture DestroyDir in destructor — db/db_manifest_store_test.cc
  • Issue: ~DBManifestStoreTest() uses DestroyDir(env_, dbname_) because DestroyDB refuses stubs. DestroyDir may not clean up db_paths or WAL directories if configured. Acceptable for tests since they use default paths.
L3. kCreatingStubNumber = 1 and kFirstDoneStubNumber = 2 as constants — db/db_impl/db_impl_open.cc:456-461
  • Issue: These are file numbers in the anonymous namespace. The assumption that a new DB starts with file numbers 1 and 2 is fragile if the number allocation scheme changes. No immediate action needed — the create path controls the entire number space for a new DB.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
WritePreparedTxnDB YES (same ProcessManifestWrites) YES None
ReadOnly DB YES (scan without claim) YES None
CompactedDBImpl YES (read-only open) YES (tested) None
Secondary/Follower NO (refused at open) N/A Properly guarded
Best-efforts recovery NO (refused at open) N/A Properly guarded
Compaction service NO (refused at open) N/A Properly guarded
User-defined timestamps YES YES (rewrite on mismatch) None
Blob direct write YES YES (atomicity fix) H2 perf concern
FIFO/Universal compaction YES YES (format-agnostic) None

DB Mutex claim verification: "No store call and no blocking I/O runs under the DB mutex on the write path" is mostly correct. Store commit and copy write run with mutex released. MinFileNumberInUse() runs under DB mutex but does no I/O — it does take ReadLocks on blob partition managers (see H2).

Positive Observations

  1. Excellent PR description with reading order, terms, step lists, tables, and diagrams.
  2. Sound crash recovery design: stub state machine resumable from any step; stub tag without kTagSafeIgnoreMask ensures old binaries fail loudly.
  3. Clean separation: file-mode behavior unchanged except DestroyDB stub check (M1).
  4. Fencing via epochs: claim/epoch mechanism prevents stale instances from corrupting the store.
  5. BlobFilePartitionManager atomicity fix: combining file number allocation with tracking under one lock correctly addresses a real race condition.
  6. Comprehensive option validation: all open functions check store options before modifying disk state.
  7. Good test infrastructure: MockManifestStore with shared data and epoch-based fencing.

ℹ️ About this response

Generated by Claude Code.
Review methodology: claude_md/ci_review_prompt.md

Limitations:

  • Claude may miss context from files not in the diff
  • Large PRs may be truncated
  • Always apply human judgment to AI suggestions

Commands:

  • /claude-review [context] — Request a code review
  • /claude-query <question> — Ask about the PR or codebase

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it visits every column family.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not wait for a store that does not answer.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- Two DBs configured with the same store can race during an enter. Example: the store holds a DB row (a placeholder from a failed enter, or the row of DB A after a rollback). The enter of DB A reads the DB row. DB B takes that row. The claim of DB A then sets the authority of the row to kFile, and the enter of DB A fails. DB B keeps its rows, but needs an operator before it opens in store mode again. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it visits every column family.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not wait for a store that does not answer.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- Two DBs configured with the same store can race during an enter. Example: the store holds a DB row (a placeholder from a failed enter, or the row of DB A after a rollback). The enter of DB A reads the DB row. DB B takes that row. The claim of DB A then sets the authority of the row to kFile, and the enter of DB A fails. DB B keeps its rows, but needs an operator before it opens in store mode again. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it visits every column family.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | Store result | RocksDB does | The writer gets |
  |---|---|---|
  | OK | installs the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not wait for a store that does not answer.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and that then succeeds clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). An Open that finds an entering stub finishes or restarts the enter. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- Two DBs configured with the same store can race during an enter. Example: the store holds a DB row (a placeholder from a failed enter, or the row of DB A after a rollback). The enter of DB A reads the DB row. DB B takes that row. The claim of DB A then sets the authority of the row to kFile, and the enter of DB A fails. DB B keeps its rows, but needs an operator before it opens in store mode again. The store interface has no claim that applies only at a given commit sequence. When the store holds no DB row at the check, the enter makes no claim before its creating commit, so a DB that appears in that gap is not touched.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit 0dcf5d6


Summary

This is a large, well-structured PR (51 files, ~12.9K insertions) that adds "store mode" to RocksDB, allowing MANIFEST metadata to be kept in an external ManifestStore instead of the MANIFEST file. The design is thorough with detailed documentation, careful error handling, and extensive test coverage. The code quality is high and follows RocksDB conventions.

High-severity findings (1):

  • [db/db_impl/db_impl.cc:7540] DestroyDB() reads CURRENT and the MANIFEST under the DB lock but before listing the directory; a new I/O error path can return without deleting any files even when the MANIFEST is simply corrupt (not a stub), which is a behavioral change from the previous unconditional-delete behavior for non-stub corruption.
Full review (click to expand)

Findings

🔴 HIGH

H1. DestroyDB behavioral change for corrupt MANIFEST — db/db_impl/db_impl.cc:7540
  • Issue: The new code in DestroyDB() reads CURRENT and the first MANIFEST record. When the MANIFEST read returns an I/O error (not PathNotFound) and the directory listing succeeds, DestroyDB returns the I/O error and deletes nothing. Previously, DestroyDB unconditionally listed and deleted files regardless of MANIFEST readability. The PR description says "A damaged record, or… returns Corruption" and distinguishes Corruption from IOError, but the boundary is subtle: a transient I/O error reading the MANIFEST (e.g., EIO from disk) now prevents DestroyDB from cleaning up files, which could surprise users who call DestroyDB specifically to clean up a damaged DB directory. The PR's own "Changes visible to existing users" section documents this, but the behavior change deserves careful scrutiny since DestroyDB is often called as a cleanup/recovery mechanism.
  • Root cause: The check if (current_s.IsIOError() && !current_s.IsPathNotFound() && list_s.ok()) treats all non-PathNotFound I/O errors as "we can't tell if it's a stub, so refuse to delete." A corrupt MANIFEST record would return Corruption (which is allowed through), but a filesystem error reading a perfectly normal MANIFEST file would block destruction.
  • Suggested fix: Consider narrowing the guard: only return the error when current.is_stub could plausibly be true (i.e., the file exists but couldn't be read), or document more prominently that this is an intentional safety measure. At minimum, ensure the behavioral change note in HISTORY.md is explicit about this new failure mode.

🟡 MEDIUM

M1. PermitUncheckedError() on current_s in DestroyDB stub detection — db/db_impl/db_impl.cc:7533
  • Issue: When current.is_stub is true, the code calls current_s.PermitUncheckedError() and returns NotSupported. But current_s could carry a decode error (e.g., NotSupported for an unknown stub version). The PermitUncheckedError is correct from ASSERT_STATUS_CHECKED perspective, but the error information is lost—the user sees a generic "does not support store mode" message rather than the specific decode failure. This matches the documented intent ("A stub that this binary cannot decode is still a stub") but may hamper debugging.
  • Suggested fix: Consider including the original error in the NotSupported message when current_s is not OK.
M2. KeepFilesAfterStoreError is broader than necessary — db/db_impl/db_impl.h:1479
  • Issue: The comment explicitly acknowledges this: "The check is broader than needed: it is also true when the store surely did not apply the commit (a TryAgain, an IOFenced from the first send, or an error before any send)." While the comment says this is safe (files are cleaned up eventually), it means ingestion/import files may linger unnecessarily after clearly-failed commits. With link_files, these could be hard links to user input files, consuming extra disk space.
  • Suggested fix: This is documented and safe, but a narrower check (e.g., only for unknown-outcome errors) would reduce the window where orphaned files persist. Low priority given the safety argument.
M3. MinFileNumberInUse() visits all column families with blob direct write — db/db_impl/db_impl_files.cc:143
  • Issue: The function iterates over all column families and collects blob file numbers when any CF uses blob direct write. This runs under the DB mutex on every store-mode commit. For a DB with many column families (hundreds) and blob direct write enabled, this adds work under the mutex. The PR acknowledges this ("Without a column family that uses blob direct write, the computation is a few lookups; with one, it visits every column family").
  • Suggested fix: Consider caching or tracking the minimum across blob partition managers incrementally, rather than recomputing on every commit. This is acceptable for the initial implementation but should be revisited if blob direct write with store mode becomes common.
M4. closing_ set before shutdown flush — db/db_impl/db_impl.cc:1142
  • Issue: closing_.store(true) is set at the very start of CloseHelper(), before the shutdown flush. This means the shutdown flush's store commit uses the "opening or closing" retry policy, which gives up at the first failed ReadDbRow or resend. The PR documents this tradeoff ("The cost: a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost"). This is a reasonable design choice but represents a data-loss risk during transient store failures at close time.
  • Suggested fix: Document this more prominently in the public API (e.g., in the manifest_store option comment). Users who write without WAL and use store mode should be aware.
M5. Race window in ClaimForEnter without existing DB row — db/db_impl/db_impl_open.cc:647
  • Issue: When entering store mode and no DB row exists, ClaimForEnter creates one via Commit() with expected sequence 0. If this returns a non-Busy, non-TryAgain, non-IOFenced error, it reads the DB row to check outcome. Between the failed commit and the read, another writer could create and modify the row. The code checks last_commit_id to verify, but if the read itself fails, it returns a generic IOError. The PR documents this race in "Limits" but it could leave the store in an inconsistent state if two enters race.
  • Suggested fix: This is documented and inherent to the store interface's lack of conditional claims. Acceptable as-is.
M6. options_settable_test coverage for manifest_store_copy_mode — options/options_settable_test.cc:431
  • Issue: manifest_store_copy_mode is listed in the offsetof table in OptionsSettableTest::DBOptionsAllFieldsSettable but is not set via the string-based options parser (the manifest_row_feature_version=1; line in the options string test). This is correct because manifest_store_copy_mode is not serialized to OPTIONS, but verify that the test framework handles this correctly for the enum type.
  • Suggested fix: Verify test passes with ASSERT_STATUS_CHECKED. No code change likely needed.

🟢 LOW / NIT

L1. CommitNewDbRows error message inconsistency — db/db_impl/db_impl_open.cc:507
  • Issue: When CommitNewDbRows fails to read the DB row after an unknown outcome, it returns Status::TryAgain("Store mode: the outcome of creating the DB row is unknown"). But the IOError path at line 517 says "cannot read the DB row". These are different root causes for the same conceptual problem. The TryAgain allows retry on next Open, which is correct.
  • Suggested fix: No change needed; the distinction is intentional (TryAgain = safe to retry, IOError = store unreachable).
L2. kCreatingStubNumber and kFirstDoneStubNumber constants — db/db_impl/db_impl_open.cc:456
  • Issue: These are constexpr uint64_t values (1 and 2) in an anonymous namespace. The comment "A new DB has no other file yet, so the first DB row starts the next file number after them" is clear. However, if any future code creates files before the stubs, these would need updating.
  • Suggested fix: No change needed; the invariant is well-documented.
L3. encrypted_env_base_ test infrastructure change — db/db_test_util.cc:92
  • Issue: The change to destroy the DB with the base env below the encrypted env is a workaround for DestroyDB now reading CURRENT, which the encrypted env cannot read when files were written with Env::Default(). This is a reasonable fix but couples test infrastructure to the new DestroyDB behavior.
  • Suggested fix: Acceptable as-is. The comment explains the rationale.
L4. Build system completeness — BUCK, CMakeLists.txt, Makefile, src.mk
  • Issue: All four build systems are updated consistently: db/manifest_rows.cc, db/manifest_store_state.cc added to LIB_SOURCES; test_util/mock_manifest_store.cc added to test libs; db/db_manifest_store_test.cc added to test targets. This follows the CLAUDE.md build system guidance correctly.
  • Suggested fix: None needed—this is a positive observation.
L5. Missing RollBackManifestStore in db.h grep — include/rocksdb/db.h
  • Issue: The diff shows RollBackManifestStore documented in the db.h comments but the actual function declaration is in include/rocksdb/manifest_store.h as a free function, which is a reasonable location.
  • Suggested fix: Verify the function is declared and accessible. No issue if it's in manifest_store.h.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
WritePreparedTxnDB YES (uses same ProcessManifestWrites) YES (store mode is orthogonal to txn type) None
ReadOnly DB YES (scan without claim) YES (never commits) None
CompactionService NO (rejected at open) N/A Correctly guarded
User-defined timestamps YES (timestamp rewrite mechanism) YES (SetRewrite handles UDT changes) None
BlobDB / blob direct write YES (NewTrackedBlobFileNumber) YES (atomic alloc+track under same lock) None
FIFO / Universal compaction YES (same ProcessManifestWrites) YES (orthogonal to store mode) None
Best-efforts recovery NO (rejected at open) N/A Correctly guarded
Secondary / Follower NO (rejected at open) N/A Correctly guarded
Checkpoints / Backups NO (GetLiveFiles returns NotSupported) N/A Correctly guarded

DB Mutex analysis:

  • MinFileNumberInUse(): called under mutex, as documented. Cost is O(1) without blob direct write, O(CFs) with it.
  • Store commit in ProcessManifestWrites: correctly runs with mutex released. The min_file_number_in_use is captured under mutex before release.
  • BlobFilePartitionManager::NewTrackedBlobFileNumber(): combines allocation and tracking under file_partition_mutex_, preventing a window where a number is allocated but not tracked. This is a correctness improvement over the split AddFilePartitionMapping.
  • opening_ / closing_ / shutting_down_: use acquire/release ordering, which is sufficient for the flag-checking pattern in the retry loop.

Positive Observations

  • Excellent documentation: The overview comments in db/manifest_store_state.h and throughout the code provide a comprehensive roadmap. The step-by-step state diagrams for create, enter, and rollback are particularly valuable.
  • Defensive error handling: The commit retry loop in CommitBatch is carefully designed with explicit handling for every possible store response. The separation between "applied", "not applied", and "unknown outcome" is clean.
  • Feature isolation: Store mode is well-gated. File-mode behavior is unchanged (no new code runs without manifest_store set). The IsStoreMode() checks are minimal and placed correctly.
  • Quarantine mechanism: Using the existing error handler's quarantine for store-mode commit failures is an elegant reuse of existing infrastructure.
  • Debug checks: The two-phase DebugCheckRows mechanism provides strong correctness validation in debug builds without adding cost to release builds.
  • Test coverage: The 3336-line test file covers create, enter, rollback, copy modes, error injection, and many edge cases including concurrent operations and crash recovery.
  • Refactoring: ManifestReporter and NewManifestReader moved from db/experimental.cc to db/manifest_ops.{h,cc} for reuse—clean separation.
  • BlobFilePartitionManager atomicity fix: NewTrackedBlobFileNumber combines allocation and tracking under one lock, closing a potential gap for the in-flight file number computation.

ℹ️ About this response

Generated by Claude Code.
Review methodology: claude_md/ci_review_prompt.md

Limitations:

  • Claude may miss context from files not in the diff
  • Large PRs may be truncated
  • Always apply human judgment to AI suggestions

Commands:

  • /claude-review [context] — Request a code review
  • /claude-query <question> — Ask about the PR or codebase

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 24, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it also reads the smallest tracked blob file number of every column family (one lock each). The time is not measured.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager also keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@meta-codesync meta-codesync Bot changed the title Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore (#15748) Nov 24, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 24, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it also reads the smallest tracked blob file number of every column family (one lock each). The time is not measured.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager also keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 24, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it also reads the smallest tracked blob file number of every column family (one lock each). The time is not measured.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager also keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 24, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: the `ManifestStore::WriteGeneration()` call of an enter. Before it the MANIFEST file holds the metadata, after it the rows do.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation is a few lookups; with one, it also reads the smallest tracked blob file number of every column family (one lock each). The time is not measured.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: the new files of every failed batch go to the quarantine of the error handler, because a failed commit may still apply in the store. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `db/blob/blob_file_partition_manager.{h,cc}`: blob direct write takes a blob file number and starts to track the file in one step under `file_partition_mutex_` (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager also keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy and TryAgain as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. After `DB::Open()`, RocksDB resends such a commit until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@meta-codesync meta-codesync Bot changed the title Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore (#15748) Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore Nov 25, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; a caller that sets it as the background error (a flush or compaction does) gets a hard error, and no auto-resume starts | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; a caller that sets it as the background error (a flush or compaction does) gets a hard error, and no auto-resume starts | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; a caller that sets it as the background error (a flush or compaction does) gets a hard error, and no auto-resume starts | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it drops only an incomplete atomic group at the end of the copy (a torn tail); a damaged record, or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above, and a DB row with authority kShadow. db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode. An I/O error while reading them (other than a missing file) returns that error and deletes nothing, when the folder can be listed. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
meta#15734)

Summary:
Pull Request resolved: meta#15734

Background
A planned feature stores the DB metadata (the MANIFEST content) as structured rows in an external metadata store, instead of as a log of VersionEdit records in a file. Each row holds the resulting values of one object: the DB, a column family, an SST file, a blob file or a WAL. A reader gets the whole state by reading all rows, with no history. To keep such rows up to date, each MANIFEST write (one batch of VersionEdits in `VersionSet::ProcessManifestWrites()`) must be turned into the rows it changes. This diff adds the in-memory row model, the conversions between rows and the existing VersionSet and VersionEdit code, and the row changes of each MANIFEST write. In debug builds it checks the row changes of every installed MANIFEST write against the Versions that the write installs. Only tests and this debug check use the rows.

The external store is not in this diff. This diff lands the row model and the conversion rules first, so that every debug test and debug crash test checks the rules on each MANIFEST write. When the store is added, it reuses these functions and their checks.

Previous behavior
RocksDB has no row form of the MANIFEST state.

New behavior
No change in release builds. In debug builds, every MANIFEST write that is installed also builds its row changes and applies them to a debug copy of the rows. The check then compares the number and level of every SST in each new Version, and the persisted SST fields of the files whose rows the write adds or updates. The phase table at `debug_manifest_rows_` in `db/version_set.h` lists the column family, blob file, DB and WAL checks. "In-memory differences" in `db/manifest_rows.h` lists the differences that the check allows. A mismatch stops the process with an assert.

Implementation
Key choices:
- The rules that turn one MANIFEST write into row changes are in the `BuildManifestRowChanges()` comment in `db/manifest_rows.h`.
- The debug check runs in two phases. Phase 1 does the work that grows with the number of files, and it runs without the DB mutex, before the new Versions are installed. Phase 2 checks the values that only the installed in-memory state has (the DB row, the WAL rows, the log number, `full_history_ts_low`, the dropped flag), with the DB mutex held. With the DB mutex held, phase 2 costs a few lookups for each edit, a compare of the WAL rows with the live WAL set in place (O(live WALs), with no copy), and O(levels) for an added column family. For a dropped column family, phase 1 frees its file and blob file rows from the debug copy, and phase 2 erases only its small column family row.
- When the WAL set rejects a WAL edit, the MANIFEST write has happened but the write is not installed. The debug rows are then dropped and filled again from the installed state at the next write, so the check keeps comparing with what memory holds.
- Some values change in memory without a MANIFEST write (for example the log number of an empty column family). The rows keep the values from the edits. The "In-memory differences" paragraph at the top of `db/manifest_rows.h` lists these values.

Safety
No format change, no public API change and no behavior change in release builds.
- `VersionSet::GetManifestRows()` requires the caller to hold the DB mutex, and it copies the metadata of every live file while the mutex is held, so the function is meant for tests, debug checks and tools, not for the write path.
- In debug builds, `ProcessManifestWrites()` copies the metadata of every live file into `debug_manifest_rows_` on its first call in a VersionSet and on its first call after a rejected WAL edit. It holds the DB mutex while it makes this copy. The cost of this copy was not measured. The first call is the first `LogAndApply()` of the VersionSet. That call is often the MANIFEST write of `DB::Open()`. It can also be a call that writes no MANIFEST record, such as the dummy edit of `DB::SetOptions()`.
- On each later write, the work that grows with the number of files runs without the DB mutex, and reads only file fields that no other thread changes. With the DB mutex held, the check costs a few lookups for each edit, an in-place compare of the WAL rows (O(live WALs), with no copy), and O(levels) for a column family that the write adds.
- Secondary and follower instances do not write the MANIFEST, so they never run the check.

Known limitations:
- `VersionSet::GetManifestRows()` never produces rows of dropped column families; `ManifestRowsToRecords()` skips such rows when they are given.
- Rows of the files and blob files of a dropped column family stay in the rows after `ApplyManifestRowChanges()`; `ManifestRowsToRecords()` skips them. The comment of `ManifestCfRow::dropped` describes these rows.
- Recovery from the records of `ManifestRowsToRecords()` sets the next file number to the recorded value plus one, as after every reopen.

Changes visible to existing users: none in release builds. Debug builds do more work per MANIFEST write and stop with an assert when the row changes do not match. Debug builds also keep a copy of the metadata of all live files in memory. The copy is made under the DB mutex on the first `LogAndApply()` of the VersionSet, and again after a rejected WAL edit.

How to read this diff
1. `db/manifest_rows.h`: the overview comment at the top ("Background", the VersionEdit content that has no row field, "In-memory differences"), then the row structs from `ManifestDbRow` to `ManifestRows`, with the layout diagram.
2. State to rows: the `VersionSet::GetManifestRows()` declaration in `db/version_set.h`, then in `db/manifest_rows.cc` `MakeManifestCfRow()`, `MakeBlobFileRow()`, `MakeFileRow()`, `SetManifestCfRows()` and `VersionSet::GetManifestRows()`.
3. Rows to records and comparison: `ManifestRowsToRecords()` (its comment gives the record order and the differences from `VersionSet::WriteCurrentStateToManifest()`), read next to `WriteCurrentStateToManifest()` in `db/version_set.cc`; then `SameCfRow()`, `SameFileRow()` and `ManifestRowsEqual()`.
4. Row changes: `ManifestRowChanges` and `ApplyManifestRowChanges()`; then `ManifestBatchVersion` and the `BuildManifestRowChanges()` comment, which holds all rules, and its code. `BaseReferencedVersionBuilder::version()` in `db/version_builder.h` is a one-line accessor for the base Version.
5. Debug check: the `debug_manifest_rows_` comment in `db/version_set.h` (timeline, phase table, threads); the three `#ifndef NDEBUG` hooks in `VersionSet::ProcessManifestWrites()`; then in `db/manifest_rows.cc` `MakeManifestBatchVersions()`, `DebugCheckRowsBeforeInstall()`, `AssertCfRowsMatchVersion()` and `DebugCheckRowsAfterInstall()`.
6. Tests in `db/version_set_test.cc`: `ManifestRowFieldOfTag()` and `ManifestRowFieldOfNewFileTag()` (the checklist for new tags), then `ManifestRowsRoundTrip` and `ManifestRowChangesMatchVersions`.
The build files (`src.mk`, `CMakeLists.txt`, `BUCK`) only add the new source file.

Differential Revision: D133208529
… for MANIFEST metadata stores (meta#15738)

Summary:
Pull Request resolved: meta#15738

Background: RocksDB keeps its metadata (the live files of each level, the column families, the WAL state and counters such as the next file number) in the MANIFEST file. An application may want to keep the same metadata in its own database instead, an external metadata store. The store then holds structured rows: one DB row, one row per column family, SST file, blob file and WAL. Each row has a key and a set of fields, and each field has a stable small integer, its field ID. The internal row model in `db/manifest_rows.h` already holds these rows in memory. A store needs three more things: a public, stable description of the rows and their bytes; an interface to implement; and an option to give its store object to RocksDB. Unit tests also need a store that keeps rows in memory and can fail on purpose. This diff adds these building blocks. The header defines the field IDs, values and byte encodings that store authors can implement and test against, including values that no DB code path writes in this diff (the authority, the copy mode, and the copy and in-flight file numbers). The format and the interface stay experimental and may change. RocksDB does not support store mode (a DB whose metadata lives in a store) at this diff, so every DB open function refuses a store.

Terms: the "Terms" list in the store interface part of `include/rocksdb/manifest_store.h` defines epoch, claim, commit sequence, commit id and generation. The application must give each DB instance that takes over a DB a newer epoch than all earlier instances. Only such a claim fences the older instance; a claim with the same epoch fences nothing; a `Commit()` prepared before it gets Busy, because the claim raised the commit sequence.

Previous behavior: RocksDB has no public description of its metadata as rows, no store interface and no store options.

New behavior:
This diff adds four things: (1) a public row form of MANIFEST metadata with a fixed byte encoding, (2) converters between it and the internal `ManifestRows`, (3) the `ManifestStore` interface and two DB options, and (4) a test store. Nothing in RocksDB calls the store in this diff, and every DB open function refuses a store.
- The new public header `include/rocksdb/manifest_store.h` defines:
  - the public rows: the row types and keys, the authority values (where the real metadata lives, the MANIFEST file or the store) and copy mode values (whether RocksDB also writes a MANIFEST file copy when the store is the authority), and the field IDs of each row type with the value encoding and the default of each field;
  - the "must understand" bit (bit 6 of a field ID), the same rule and bit that a MANIFEST file uses for the custom fields of a new SST file record (see "Schema evolution" at the top of the header for why the rows use it instead of a version bump per field);
  - the canonical encoding of the fields of a row (see "Canonical encoding"), with `ParseManifestRowFields()` and `EncodeManifestRowFields()`;
  - the `ManifestStore` interface (a `Customizable`): `Open()` claims the DB, `Commit()` applies one atomic change of rows, `ReadDbRow()` reads the DB row, `Scan()` reads all rows, `WriteGeneration()` installs a full replacement set of column family, SST, blob file and WAL rows and updates the DB row in the same atomic switch, and `Destroy()` removes all rows. `Open()` and `Destroy()` take an optional expected commit sequence: when it is set and the stored commit sequence differs, the call returns Busy and changes nothing. A missing DB row has commit sequence 0, but `Open()` returns NotFound first when there is no DB row, and a fenced object gets IOFenced before this check. They also take an expected last commit id: when it is not empty, the stored last_commit_id must equal it too, else the call returns Busy. The commit sequence alone cannot tell the read DB row from a row that was destroyed and created again and reached the same commit sequence; the new row never has the same last commit id, because commit ids are unique. A caller uses both to claim or destroy a DB only if the DB row is still the one it read and checked, so that it does not fence another writer that changed the row after that read. Without either precondition, `Open()` claims unconditionally. The claim of a DB open is designed to set both (step 2 of "Call order" in the header): read the DB row, check that it belongs to this DB, claim with the commit sequence and last commit id of that read, and read again and retry after Busy. For `Commit()` and `WriteGeneration()`, the comment above the class defines the meaning of each status, so that RocksDB can tell a request that the store did not apply (IOFenced, Busy, TryAgain, NotSupported) from a request with an unknown outcome, such as a timeout. `Open()` and `Destroy()` list their own results at their declarations. `ManifestStore::CreateFromString()` creates a store from a registered class. RocksDB has no built-in store.
- Internal converters in `db/manifest_rows.h`: `ManifestRowsToPublicRows()` turns `ManifestRows` into public rows, and `PublicRowsToManifestRows()` turns them back. The comment of `PublicRowsToManifestRows()` lists every NotSupported and Corruption case and their order. `ManifestDbRowExtraFields` holds the RocksDB-owned DB row fields that `ManifestDbRow` does not hold, other than the row format version, which the writer always writes as `kManifestRowFormatVersionLatest`.
- `DBOptions::manifest_store` (default null) holds the store object. It is not written to the OPTIONS file, because the object belongs to one DB instance, and it is never compared with a reloaded OPTIONS file.
- `DBOptions::manifest_row_feature_version` (default 1) is the newest feature version of the rows that RocksDB may write. It is an immutable option and is written to the OPTIONS file. In this diff 1 is its only valid value, and it changes nothing; it exists so that a later release can add row fields under a higher value.
- `DB::Open()`, `DB::OpenForReadOnly()`, `DB::OpenAsSecondary()`, `DB::OpenAsFollower()` and `DB::OpenAndCompact()` return NotSupported when `manifest_store` is set, or InvalidArgument when `manifest_store` is set and `manifest_row_feature_version` is not from 1 to `kManifestRowFeatureVersionLatest`. The check runs before the open changes anything on disk (for example before `create_if_missing` creates the directory). Without a store, the feature version is not checked.
- `MockManifestStore` (`test_util/mock_manifest_store.h`, test code only) keeps rows in memory. Several store objects share one `MockManifestStoreData`, each with its own epoch (two DB instances that take over the same DB) or no epoch (a read-only object, for example for a secondary instance). A request that the mock keeps pending after a timeout keeps the epoch of the object that made it, so it can still run after that object is destroyed. A test can make `Open()`, `Commit()` and `WriteGeneration()` fail on purpose (the fault list is in the mock header). `ReadDbRow()`, `Scan()` and `Destroy()` fail only for the reasons that the `ManifestStore` comments give.

Implementation:
- `db/manifest_rows.cc` implements the encoding functions, the two converters and `ManifestStore::CreateFromString()` (with `LoadSharedObject()`), in a "Public rows" section after the internal row code. It has one encode function and one read function per row type. Each read function has a switch over the field ID enum of its row type with no default case, so the build fails when a field ID is added without a reader. A field ID that is not in the enum falls through to the unknown-field rule.
- One shortest-form varint reader reads field IDs, value sizes and value varints, so every accepted varint has one byte form. The unique id uses the same helpers as a MANIFEST file (`EncodeUniqueIdBytes()` and `DecodeUniqueIdBytes()`).
- A compaction cursor level above 65536 is rejected as Corruption. The internal row keeps cursors in a vector indexed by level, so a corrupt level must not make the reader allocate a huge vector. The bound is a sanity limit, far above any real number of levels; at the bound the vector takes about 2 MB (an estimate).
- The key length check runs after all rows are read, because a column family row may come after its file rows.
- `DBImpl::CheckManifestStoreOptions()` holds the open check. `DBImpl::Open()` calls it first (for `DB::Open()`), and so do both `DB::OpenForReadOnly()` functions, `DBImplSecondary::OpenAsSecondaryImpl()` (which `DB::OpenAsSecondary()` and `DB::OpenAndCompact()` use) and `DB::OpenAsFollower()`.
- `manifest_store` is registered like `statistics` (`AsCustomSharedPtr`, with `kCompareNever`, `kDontSerialize` and `kAllowNull`). `options.h` only forward-declares `ManifestStore`.
- The test of the VersionEdit tags (`db/version_set_test.cc`) names, for each tag and each custom field of a new file record, the public field ID that holds it, or "no row field".

<details><summary>**Notable implementation details**</summary>

- The C API generator skips both options (two "deferred" entries in `tools/c_api_gen/auto_simple_bindings_blocklist.json`), so this diff adds no C API function.
- `MockManifestStore` checks the epoch and the expected commit sequence under one lock. `WriteGeneration()` writes the rows in chunks of 2 rows, so that tests with a few rows get several chunks. Each chunk checks the epoch, and the switch checks the row count and a checksum of the rows (a sum of row hashes). `Scan()` copies the rows under the lock and calls the visitor without it, so every scan returns the rows of one commit.
</details>

How to read this diff:
1. `include/rocksdb/manifest_store.h`: the Background comment, the row types, `ManifestRowKey`, the field ID enums, then "Canonical encoding"; then in `db/manifest_rows.cc` (section "Public rows"): `GetShortestVarint()`, `ParseManifestRowFields()` and `EncodeManifestRowFields()`.
2. `db/manifest_rows.h`: `ManifestDbRowExtraFields` and the two converter declarations at the end; `db/manifest_rows.cc`: `FieldWriter`, the `Encode*Row()` functions and `ManifestRowsToPublicRows()`.
3. `db/manifest_rows.cc`: the reader, bottom-up, as the "reader of public rows" comment maps it: the `Get*Value()` helpers, `ReadRowFields()`, the `Read*Field()` functions, the `Decode*Row()` functions and `DecodeRow()`, then `PublicRowsToManifestRows()`.
4. `include/rocksdb/manifest_store.h`: the "store interface" part at the end (background, terms, call order, structs, result meanings, `ManifestStore`).
5. `include/rocksdb/options.h`, `options/db_options.h`, `options/db_options.cc` and `options/options_helper.cc` for the two options; then `db/db_impl/db_impl.h` and `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` and its call in `DBImpl::Open()`, then the other callers in `db_impl_readonly.cc`, `db_impl_secondary.cc` and `db_impl_follower.cc`.
6. `test_util/mock_manifest_store.h`, then `test_util/mock_manifest_store.cc`.
7. Row tests in `db/version_set_test.cc`: `ManifestRowFieldsTest`, the public-row part of `VersionSetTest.ManifestRowsRoundTrip`, and `ManifestPublicRowsTest`.
8. Store and option tests: the `MockManifestStoreTest` part of `db/version_set_test.cc`, `options/options_test.cc`, `options/options_settable_test.cc` and `db/db_basic_test.cc`.
The build files (`src.mk`, `CMakeLists.txt`, `BUCK`) only add the new test source file. `tools/c_api_gen/auto_simple_bindings_blocklist.json` only adds the two options.

Safety: Nothing in RocksDB calls the store or the converters outside tests. Existing DBs open as before, because the open check passes without a store. No file format changes. The header is marked EXPERIMENTAL. The header defines the row types, the authority and copy mode values, the field IDs and the encodings before any RocksDB code writes them, so that store authors can implement and test against them. This is why the header has values that no DB code path uses in this diff (the authority and copy mode values, the copy and in-flight file numbers, `ManifestScanOptions::consistent`, and the feature version); only the converters, the open check and tests read them. The format and the interface stay experimental and may change until store mode is supported. A new OPTIONS file has a `manifest_row_feature_version` line. An older binary that loads such a file skips the unknown line only when the caller sets `ignore_unknown_options` and the file was written by a newer RocksDB release version, as for every new DB option.

Known limitations:
- The converter checks each row, the links from file and blob file rows to their column family, and the key length against the timestamp size of the column family. It does not check other meaning across rows: for example, that file numbers are below the next file number, that file keys are in order under the comparator, or that a blob file that a file refers to exists. A caller that reads these rows must do those checks.
- This diff writes no store data. So no DB has its metadata in a store, and an older binary that does not know the store cannot meet such a DB.
- `db_stress`, `db_bench` and the crash test have no flags for `manifest_store` or `manifest_row_feature_version`. Every DB open function returns NotSupported when `manifest_store` is set, so these tools cannot test store mode.

Changes visible to existing users: the new public header, the two new options, the new line in the OPTIONS file, and two new lines in the LOG options dump. No other behavior change.

Differential Revision: D133307302
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; the store state does not stop. A caller that sets it as the background error (a flush or compaction does) gets a fatal error, so `DB::Resume()` returns it without a store call and the DB must be opened again | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it keeps every complete record outside an atomic group and every complete atomic group. It drops two kinds of torn tail that a crash can leave: a last record that was cut short (the log reader stops before it) and an atomic group that is still open at the end of the copy. A damaged record (a bad checksum or a record that cannot be decoded), or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above. An open or a column family listing through a done stub refuses a DB row with authority kShadow. An enter from a normal MANIFEST accepts a kShadow row of the same DB (`EnterFromShadowAuthority`). db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode, and checks the result of the folder listing before it deletes anything. An error while reading CURRENT or the MANIFEST, for example an I/O error or a timeout, returns that error and deletes nothing when the folder can be listed (when the listing fails, no file of the folder is deleted). Two errors are not such a case, and the DB is deleted as a file-mode DB: a missing MANIFEST (it cannot be a stub, because RocksDB points CURRENT to a new stub before it deletes the old one) and Corruption. A listing error other than a missing folder is returned for a stub or when a store is in the options, and nothing changes. For a file-mode DB without a store, the listing error is ignored. No file of the folder is deleted, but the other DB folders (db_paths, the cf_paths of the given column families, the WAL folder and the archive folder) are still cleaned. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
@meta-codesync meta-codesync Bot changed the title Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore (#15748) Nov 25, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; the store state does not stop. A caller that sets it as the background error (a flush or compaction does) gets a fatal error, so `DB::Resume()` returns it without a store call and the DB must be opened again | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it keeps every complete record outside an atomic group and every complete atomic group. It drops two kinds of torn tail that a crash can leave: a last record that was cut short (the log reader stops before it) and an atomic group that is still open at the end of the copy. A damaged record (a bad checksum or a record that cannot be decoded), or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above. An open or a column family listing through a done stub refuses a DB row with authority kShadow. An enter from a normal MANIFEST accepts a kShadow row of the same DB (`EnterFromShadowAuthority`). db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode, and checks the result of the folder listing before it deletes anything. An error while reading CURRENT or the MANIFEST, for example an I/O error or a timeout, returns that error and deletes nothing when the folder can be listed (when the listing fails, no file of the folder is deleted). Two errors are not such a case, and the DB is deleted as a file-mode DB: a missing MANIFEST (it cannot be a stub, because RocksDB points CURRENT to a new stub before it deletes the old one) and Corruption. A listing error other than a missing folder is returned for a stub or when a store is in the options, and nothing changes. For a file-mode DB without a store, the listing error is ignored. No file of the folder is deleted, but the other DB folders (db_paths, the cf_paths of the given column families, the WAL folder and the archive folder) are still cleaned. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; the store state does not stop. A caller that sets it as the background error (a flush or compaction does) gets a fatal error, so `DB::Resume()` returns it without a store call and the DB must be opened again | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it keeps every complete record outside an atomic group and every complete atomic group. It drops two kinds of torn tail that a crash can leave: a last record that was cut short (the log reader stops before it) and an atomic group that is still open at the end of the copy. A damaged record (a bad checksum or a record that cannot be decoded), or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above. An open or a column family listing through a done stub refuses a DB row with authority kShadow. An enter from a normal MANIFEST accepts a kShadow row of the same DB (`EnterFromShadowAuthority`). db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode, and checks the result of the folder listing before it deletes anything. An error while reading CURRENT or the MANIFEST, for example an I/O error or a timeout, returns that error and deletes nothing when the folder can be listed (when the listing fails, no file of the folder is deleted). Two errors are not such a case, and the DB is deleted as a file-mode DB: a missing MANIFEST (it cannot be a stub, because RocksDB points CURRENT to a new stub before it deletes the old one) and Corruption. A listing error other than a missing folder is returned for a stub or when a store is in the options, and nothing changes. For a file-mode DB without a store, the listing error is ignored. No file of the folder is deleted, but the other DB folders (db_paths, the cf_paths of the given column families, the WAL folder and the archive folder) are still cleaned. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 25, 2026
…meta#15748)

Summary:
Pull Request resolved: meta#15748

Background: the parent diff, "Add the public row form, the ManifestStore interface and a test store for MANIFEST metadata stores", adds the public row form of the MANIFEST metadata and the `ManifestStore` interface (`include/rocksdb/manifest_store.h`), and the option `DBOptions::manifest_store`. Every DB open function still refuses a store. This diff adds store mode: the rows in the store are the authority for the metadata of the DB, instead of the MANIFEST file. An application that keeps its own replicated, fenced metadata database can then keep the RocksDB metadata there too.

Terms:
- Store mode: `DBOptions::manifest_store` is set and the DB row says that the store is the authority (`ManifestAuthority::kStore`).
- Stub: in store mode, CURRENT names a small file `MANIFEST-<number>`, the stub. Its one record starts with the new tag `kManifestStoreStub` (500). The tag does not have the `kTagSafeIgnoreMask` bit (1 << 13), so a reader that does not know store mode fails on it instead of skipping it. The stub records the db id and a state: done, creating (a new DB is being created in the store) or entering (a file-mode DB is being moved into the store).
- Copy: an optional MANIFEST-format file `MANIFEST_COPY-<number>` that RocksDB also writes in store mode, so that a DB can go back to file mode without the store. Only a copy written in sync mode ("sync-marked") is used for that.
- Enter: `DB::Open()` with the new option `DBOptions::manifest_store_migrate` moves a file-mode DB into the store.
- Switch: an enter writes all rows of a new generation with `ManifestStore::WriteGeneration()`. The switch is the moment when the store makes that generation visible and, in the same commit, sets the authority in the DB row to kStore. Before it the MANIFEST file holds the metadata, after it the rows do. A read-write open that finds an entering stub reads the authority in the DB row to decide whether to start the enter again or to finish it.
- Stopped: the DB stays open, but every later MANIFEST write fails at once with the same error and without a store call.
- Placeholder DB row: a DB row with authority kFile, no db id, and every counter (next file number, last sequence, and the others) at 0. An enter writes it to claim a store that has no DB row. When the enter fails before its switch, the row stays. It belongs to no DB, so a later create or enter may take it over.

Previous behavior: `DB::Open()` and `DB::OpenForReadOnly()` return NotSupported when `manifest_store` is set.

New behavior, in short:
```
  no DB --(Open with create_if_missing)------------------> store mode
  file mode --(Open with manifest_store_migrate: enter)--> store mode
  store mode --(RollBackManifestStore())-----------------> file mode
  store mode: every MANIFEST write = one ManifestCommit to the store
  optional MANIFEST file copy, for a rollback without the store
```

New behavior:
- Open: for a done stub, `DB::Open()` checks that the DB row belongs to this DB (the db id of the stub), claims the DB with `ManifestStore::Open()` (this fences older instances), scans all rows, checks the scanned DB row, and replays the rows as full-state VersionEdit records with the normal recovery code. The owner check runs before the claim, so a store object of another DB (a configuration error) does not fence the primary of that DB. The claim sets `ManifestStoreOpenOptions::expected_commit_sequence` and `expected_last_commit_id` to the values that the check read, so it applies only to the checked row, also when a row was removed and created again. When the row changed in between, the store returns Busy (or NotFound when the row is gone) and changes nothing. After Busy, Open reads, checks and claims again, with at most 10 claims in total, then returns TryAgain. `DB::OpenForReadOnly()` and `DB::ListColumnFamilies()` with a store scan without a claim, and check the scanned DB row in the same way. The steps are in the "Store mode: overview" comment in `db/manifest_store_state.h`.
- Create: with `create_if_missing` and no CURRENT, Open writes a creating stub, commits the first rows, then replaces the stub with a done stub. An Open that finds a creating stub finishes the create.
- Write path: each batch of `VersionSet::ProcessManifestWrites()` becomes one `ManifestCommit`, sent with the DB mutex released, in place of the MANIFEST append. The commit also writes the in-flight file number: the smallest file number that a running job may still use, so that a service that deletes unused files keeps those files. It is computed under the DB mutex for each commit. Without a column family that uses blob direct write, the computation reads the smallest entry of a few ordered containers; with one, it also reads the smallest tracked blob file number of every column family, under a small lock of each blob partition manager that is never held during blob cache work. The Test Plan has the measured DB mutex hold times.
- Sync copy retention: in sync copy mode, the copy gets a batch only after its store commit, so until then the copy still names the files whose rows the commit deletes, and a rollback without the store needs them. So such a commit also caps the in-flight file number by the smallest of these file numbers. The next commit is sent only after the copy holds the batch, and its own value releases them. A copy error stops the DB, and the next open writes a new copy from the rows before its first commit. A background copy needs no cap, because a rollback without the store never uses it.
- Commit results (the full table and a diagram of the retry loop are at `ManifestStoreState::CommitBatch()`):

  | First Commit() result | CommitBatch() does | CommitBatch() returns |
  |---|---|---|
  | OK | records that the store applied the batch | OK |
  | IOFenced | stops the DB | IOFenced (fatal) |
  | TryAgain | nothing; when the caller sets it as the background error (a flush or compaction does), auto-resume commits an empty batch | retryable IOError |
  | NotSupported (the store rejects the commit for good) | nothing, no resend; the store state does not stop. A caller that sets it as the background error (a flush or compaction does) gets a fatal error, so `DB::Resume()` returns it without a store call and the DB must be opened again | IOError, not retryable |
  | Busy or other error | reads the DB row; may resend (see below) | OK, IOFenced (fatal), or a stop: a plain IOError (fatal) |

  - RocksDB resends only after a status other than Busy. A resend that gets NotSupported stops the DB, because the first send can still apply.
  - It stops the DB when a send got Busy but the DB row still holds the expected commit sequence.
  - It makes at most `max_bgerror_resume_count` retries (resends or repeated reads), `bgerror_resume_retry_interval` apart.

  After CommitBatch() returns OK, VersionSet updates the copy (when the copy mode is not off) and installs the batch. A sync copy error stops the DB, and the batch is not installed, although the store holds it.

  With the default `max_bgerror_resume_count` (INT_MAX), RocksDB retries until the outcome is known or the DB starts to close, and later MANIFEST writes wait during that time. During `DB::Open()` and during a close, a commit with an unknown outcome gives up at the first failed `ReadDbRow()` or resend. So `DB::Open()` returns the error (as a failed MANIFEST write fails `DB::Open()` in file mode), and a close does not start more retries. A close still waits for a store call that is already running, so the store must end each call in bounded time.
- Quarantine: when the store commit or the copy update returns an I/O error to a batch, the new files of the batch go to the quarantine of the error handler, because a failed commit may still apply in the store. A batch that fails before any store call (for example a WAL edit that the row changes reject) adds no files. Only a later batch that the store applies and whose later steps (also the copy update) succeed clears it. A failed external file ingestion or import keeps the files that it wrote into the DB on any IOError in store mode, because its own cleanup does not respect the quarantine.
- Copy (`DBOptions::manifest_store_copy_mode`, stored in the DB row): off, background (not synced per commit; a copy error drops the copy) or sync (appended and synced after each commit, before install; a copy error stops the DB). A failed delete of an old copy writes a WARN line. The mode table and a layout diagram are in `db/manifest_store_state.h`.
- Enter store mode (`DBImpl::EnterManifestStore()`, seven steps), for a DB whose CURRENT names a normal MANIFEST: it refuses when the store holds the rows of another DB, or already holds this DB in store mode (the folder is then a copy, or the folder of an unfinished rollback without the store). Its claim applies only to the DB row that its check read (it expects the commit sequence and last commit id that the check read), so when another writer changed the DB row in between, the enter fails with InvalidArgument and the store changes nothing (no epoch, authority or commit id change). An Open that finds an entering stub finishes or restarts the enter, also without `manifest_store_migrate`. `manifest_store_migrate` also lets Open change the copy mode.
- Roll back: the new function `RollBackManifestStore()` moves a DB back to file mode, with the store (from the rows) or without it (from the sync-marked copy). With the store it first checks that the DB row belongs to this DB. The db id comes from the stub, or for a MANIFEST file from its records, else from the IDENTITY file; an IDENTITY read error other than a missing file is returned, and without a db id it returns InvalidArgument. The new MANIFEST number and next file number are above every file in the folder and at or above the next file number of the store or of the copy. Without the store, it keeps every complete record outside an atomic group and every complete atomic group. It drops two kinds of torn tail that a crash can leave: a last record that was cut short (the log reader stops before it) and an atomic group that is still open at the end of the copy. A damaged record (a bad checksum or a record that cannot be decoded), or an atomic group with a wrong number of records or with a normal record inside it, returns Corruption. The cases are in a table at the function comment. A rollback without the store writes a normal MANIFEST file and points CURRENT to it, but it cannot update the store, so the DB row still says kStore. A file-mode open works then. A later call with the store records kFile in the DB row and keeps the current MANIFEST file, with any file-mode writes in it. Until then, an enter refuses the DB, because the row still says kStore.
- Option checks: with a store, `best_efforts_recovery`, `best_efforts_blob_db_repair` and a `manifest_store_copy_mode` above kSync give InvalidArgument, and `compaction_service` gives NotSupported.
- Paths that do not support store mode return NotSupported: the live file functions (so checkpoints and backups), secondary and follower instances, `DB::OpenAndCompact()`, `RepairDB()`, `DestroyDB()` on a stub, and the readers of the MANIFEST file (through the stub tag).

How and why:
- The stub, not an empty CURRENT, marks store mode, so that every existing MANIFEST reader fails loudly instead of reading an empty DB.
- The row changes of a batch come from its edits and its new Versions (`BuildManifestRowChanges()` in `db/manifest_rows.h`), so a commit carries only the rows that change.
- A commit with an unknown outcome is resolved by the commit id in the DB row, not by a blind resend, so a commit never applies twice. Later MANIFEST writes wait in the queue behind it.
- The claim of each Open raises the commit sequence, so a commit of a stopped instance can never apply later.

Implementation:
- `db/manifest_store_state.{h,cc}` (new): the overview comment; the stub record; the copy marker and pointer file; `ScanManifestStore()`; `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`; `class ManifestStoreState` with `CommitBatch()`; `RollBackManifestStore()`.
- `db/manifest_rows.cc`: `VersionSet::BuildManifestBatchRowChanges()` and `VersionSet::CommitBatchToStore()`.
- `db/version_set.{h,cc}`: the store branch of `ProcessManifestWrites()`, `RecoverFromStore()` with the shared replay helper `ReplayManifest()`, and the copy writer.
- `db/db_impl/db_impl_open.cc`: `RecoverFromManifestStore()`, create, enter, and `CheckManifestStoreOptions()`.
- `db/db_impl/db_impl_files.cc`: `DBImpl::MinFileNumberInUse()` gives the in-flight file number. `DBImpl::pending_ingestion_outputs_` becomes a `std::map`, so it reads the smallest reserved number of the running ingestions at once. `db/blob/blob_file_partition_manager.{h,cc}`: in store mode, blob direct write takes a blob file number and starts to track it in one step under a new small lock (`NewTrackedBlobFileNumber()`), so that a commit never misses a blob file whose number is below its next file number. The manager keeps the tracked numbers in order (`MinTrackedBlobFileNumber()`), so the commit reads the smallest one without a pass over all tracked files. The lock is held only for one set operation or one file number allocation, never during blob cache evictions. Without a store, the manager keeps no such set.
- `RollBackManifestStore()` returns a failed unlock of the folder lock when the rollback itself worked, and writes a WARN line otherwise. A failed close of a copy writer also writes a WARN line.
- Guards: `db/db_filesnapshot.cc`, `db/repair.cc`, `DestroyDB()`, `DB::ListColumnFamilies()`.
- `db/manifest_ops.{h,cc}`: `ManifestReporter` and `NewManifestReader()` move here from `db/experimental.cc`, so that the stub reader and the copy reader use them too.
- `db/db_test_util.{h,cc}`: with `ENCRYPTED_ENV`, the test fixture destroys its DB with the env below the encrypted env. Some tests write files with `Env::Default()`, which the encrypted env cannot read, and `DestroyDB()` reads CURRENT (see "Changes visible to existing users").

How to read this diff:
1. Overview: `db/manifest_store_state.h`, the "Store mode: overview" comment (stub, stub state diagram, open steps, write path rules, errors, limits) and the "MANIFEST file copy" comment. Then the `RollBackManifestStore()` comment in `include/rocksdb/manifest_store.h` for the third mode change.
2. Stub and owner check: in `db/manifest_store_state.h` and `.cc`, read `ManifestStub` and its encode, decode and read functions, then `ScanManifestStore()`, `CheckScannedStoreRows()`, `CheckManifestDbRowOwner()` and `CheckOwnerAndClaim()`. They depend on nothing else in this diff.
3. Write-path state: `class ManifestStoreState` in `db/manifest_store_state.h`, then `CommitBatch()` in `.cc`. Read the results table, the diagram and the retry loop.
4. Write-path glue: `db/manifest_rows.cc` (`CommitBatchToStore()`), then `db/version_set.cc`. In `ProcessManifestWrites()`, read the store branch, the quarantine and `io_status_` block, then `RecoverFromStore()` and `ReplayManifest()`.
5. Copy: in `db/version_set.cc`, read `StartManifestCopyAtOpen()`, `WriteNewManifestCopy()` and `UpdateManifestCopy()`, then the copy sync in `VersionSet::Close()`.
6. Open, create and enter: first read the step lists in `db/db_impl/db_impl.h`. Then in `db/db_impl/db_impl_open.cc` read `DBImpl::Recover()` and `RecoverFromManifestStore()` (together they call the others), then `CreateDbInManifestStore()` and `CommitNewDbRows()`, then `EnterManifestStore()`, `ClaimForEnter()` and `FinishEnterManifestStore()`.
7. Rollback and guards: read `RollBackManifestStore()` at the end of `db/manifest_store_state.cc`. Then the guards in `db/db_impl/db_impl.cc` (`DestroyDB()`, `DB::ListColumnFamilies()`, the files that ingestion and import keep), `db/db_filesnapshot.cc`, `db/repair.cc`, the blob file number change in `db/blob/blob_file_partition_manager.cc`, and the option comments in `include/rocksdb/options.h`.
8. Tests: `db/db_manifest_store_test.cc`, by its "Section:" comments.

Safety:
- File mode keeps its MANIFEST content and format. The new tags appear only in stubs and copies.
- On the write path, no store call and no blocking I/O runs under the DB mutex. During `DB::Open()`, the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.
- Every acknowledged MANIFEST write is in the store (and in sync mode also in the copy) before its caller gets OK.
- An older binary fails on the stub with Corruption "unknown tag".

Unsupported cases: the NotSupported paths above. An open or a column family listing through a done stub refuses a DB row with authority kShadow. An enter from a normal MANIFEST accepts a kShadow row of the same DB (`EnterFromShadowAuthority`). db_stress and the crash test do not cover store mode in this diff; the last diff of this stack ("Add db_stress and crash test lanes for store mode and shadow mode") adds that coverage.

Known limitations:
- RocksDB does not split a batch that is larger than the transaction limit of the store.
- RocksDB treats every `Commit()` status other than OK, IOFenced, Busy, TryAgain and NotSupported as an unknown outcome, including a status that means the commit can never apply, for example InvalidArgument for a commit that is too large. A store should return NotSupported for that. After `DB::Open()`, RocksDB resends a commit with an unknown outcome until the outcome is known, the retries run out, or the DB starts to close. With the default `max_bgerror_resume_count` (INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract in `include/rocksdb/manifest_store.h` says so.
- Blob direct write files after a crash: a blob direct write file that only the WAL referred to at a crash is not named by any row after the next `DB::Open()` (an enter or a store-mode reopen), and its number is below the in-flight file number. Base RocksDB does not add such a file to the Version either (the comment of `enable_blob_direct_write` says that WAL replay of active direct-write blob files is not supported); its own purge keeps the file. A service that deletes unused files by the rows and the in-flight file number can delete it, and the value is then lost.
- The DB mutex hold time of a commit grows with the number of column families when one of them uses blob direct write (one small lock each). The Test Plan has the measured times.
- A close gives up at the first failed `ReadDbRow()` or resend. So a short store failure during the shutdown flush can stop the DB, and data written without the WAL is then lost.
- There are no store-specific statistics (tickers or histograms) for commit latency, resends, stops or copy errors. The LOG has a line for each resend, stop and copy error.
- A rollback without the store cannot claim the DB. It relies on the folder lock and on the application having stopped the old primary.
- In sync mode, a crash after the switch of an enter and before the first copy leaves no copy until the next Open.
- The OPTIONS readers that take only a path return NotSupported on a stub DB when the newest OPTIONS file is tracked in the MANIFEST.
- After a rollback, the rows stay in the store until `ManifestStore::Destroy()` removes them.
- A file that a failed ingestion or import keeps can be a hard link to the input file (with `move_files` or `link_files`); the option comments say not to change such an input file in place.
- `reuse_manifest_on_open` and `verify_manifest_content_on_close` have no effect in store mode. The rollover options apply only to the copy.

Changes visible to existing users:
- The new options `manifest_store_migrate` and `manifest_store_copy_mode`, the function `RollBackManifestStore()`, and the store-mode notes in the comments of `max_bgerror_resume_count`, `bgerror_resume_retry_interval` and `DB::ListColumnFamilies()`.
- Best-efforts recovery (`VersionSet::TryRecover()`) reads the first record of each MANIFEST file that it tries. At a stub it stops with NotSupported and does not try older MANIFEST files. `RepairDB()` reads CURRENT and the first record of the MANIFEST that it names before it repairs, and returns NotSupported for a stub.
- `DestroyDB()` now reads CURRENT and the first record of the MANIFEST that it names, also in file mode, and checks the result of the folder listing before it deletes anything. An error while reading CURRENT or the MANIFEST, for example an I/O error or a timeout, returns that error and deletes nothing when the folder can be listed (when the listing fails, no file of the folder is deleted). Two errors are not such a case, and the DB is deleted as a file-mode DB: a missing MANIFEST (it cannot be a stub, because RocksDB points CURRENT to a new stub before it deletes the old one) and Corruption. A listing error other than a missing folder is returned for a stub or when a store is in the options, and nothing changes. For a file-mode DB without a store, the listing error is ignored. No file of the folder is deleted, but the other DB folders (db_paths, the cf_paths of the given column families, the WAL folder and the archive folder) are still cleaned. A stub returns NotSupported, with or without a store. `DestroyDB()` also deletes leftover copy files. No other file-mode behavior changes.

Differential Revision: D133564196

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