Repository navigation
Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore (#15748) - #15748
xingbowang wants to merge 3 commits into
Conversation
|
@xingbowang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D133564196. |
d57ca73 to
2f22ed4
Compare
|
| 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]
cba322c to
9f755be
Compare
…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
…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
…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
…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
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 9f755be SummaryThis PR adds "store mode" to RocksDB, allowing MANIFEST metadata to be kept in an external High-severity findings (3):
Full review (click to expand)Findings🔴 HIGHH1. Missing src.mk updates —
|
| 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
- 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.
- 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.
- Quarantine for failed commits: The error handler's quarantine prevents premature file deletion when a commit's outcome is unknown.
- Comprehensive test coverage: The ~3200-line test file covers create, enter, rollback, interrupted operations, DB row checks, copy modes, and many edge cases.
- Clear documentation: The overview comment in
manifest_store_state.hand the "How to read this diff" section in the PR description show exceptional attention to reviewer experience. - 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
9f755be to
edee7c1
Compare
…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
…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
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit edee7c1 SummaryThis 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):
Full review (click to expand)Findings🔴 HIGHH1. Missing src.mk updates —
|
| 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
- Excellent PR description with reading order, terms, step lists, tables, and diagrams.
- Sound crash recovery design: stub state machine resumable from any step; stub tag without
kTagSafeIgnoreMaskensures old binaries fail loudly. - Clean separation: file-mode behavior unchanged except DestroyDB stub check (M1).
- Fencing via epochs: claim/epoch mechanism prevents stale instances from corrupting the store.
- BlobFilePartitionManager atomicity fix: combining file number allocation with tracking under one lock correctly addresses a real race condition.
- Comprehensive option validation: all open functions check store options before modifying disk state.
- Good test infrastructure:
MockManifestStorewith 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
edee7c1 to
0dcf5d6
Compare
…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
…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
…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
✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 0dcf5d6 SummaryThis 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 High-severity findings (1):
Full review (click to expand)Findings🔴 HIGHH1. DestroyDB behavioral change for corrupt MANIFEST —
|
| 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. Themin_file_number_in_useis captured under mutex before release. BlobFilePartitionManager::NewTrackedBlobFileNumber(): combines allocation and tracking underfile_partition_mutex_, preventing a window where a number is allocated but not tracked. This is a correctness improvement over the splitAddFilePartitionMapping.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.hand 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
CommitBatchis 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_storeset). TheIsStoreMode()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
DebugCheckRowsmechanism 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:
ManifestReporterandNewManifestReadermoved fromdb/experimental.cctodb/manifest_ops.{h,cc}for reuse—clean separation. - BlobFilePartitionManager atomicity fix:
NewTrackedBlobFileNumbercombines 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
0dcf5d6 to
36680ba
Compare
…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
36680ba to
9ddc17c
Compare
…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#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#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
9ddc17c to
36e1a2f
Compare
…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#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#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
36e1a2f to
f7c4ec7
Compare
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
f7c4ec7 to
91dd4cb
Compare
…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#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#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
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
ManifestStoreinterface (include/rocksdb/manifest_store.h), and the optionDBOptions::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:
DBOptions::manifest_storeis set and the DB row says that the store is the authority (ManifestAuthority::kStore).MANIFEST-<number>, the stub. Its one record starts with the new tagkManifestStoreStub(500). The tag does not have thekTagSafeIgnoreMaskbit (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).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.DB::Open()with the new optionDBOptions::manifest_store_migratemoves a file-mode DB into the store.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.Previous behavior:
DB::Open()andDB::OpenForReadOnly()return NotSupported whenmanifest_storeis set.New behavior, in short:
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 withManifestStore::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 setsManifestStoreOpenOptions::expected_commit_sequenceandexpected_last_commit_idto 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()andDB::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 indb/manifest_store_state.h.Create: with
create_if_missingand 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 oneManifestCommit, 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()):DB::Resume()returns it without a store call and the DB must be opened againmax_bgerror_resume_countretries (resends or repeated reads),bgerror_resume_retry_intervalapart.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. DuringDB::Open()and during a close, a commit with an unknown outcome gives up at the first failedReadDbRow()or resend. SoDB::Open()returns the error (as a failed MANIFEST write failsDB::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 indb/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 withoutmanifest_store_migrate.manifest_store_migratealso 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_repairand amanifest_store_copy_modeabove kSync give InvalidArgument, andcompaction_servicegives 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:
BuildManifestRowChanges()indb/manifest_rows.h), so a commit carries only the rows that change.Implementation:
db/manifest_store_state.{h,cc}(new): the overview comment; the stub record; the copy marker and pointer file;ScanManifestStore();CheckManifestDbRowOwner()andCheckOwnerAndClaim();class ManifestStoreStatewithCommitBatch();RollBackManifestStore().db/manifest_rows.cc:VersionSet::BuildManifestBatchRowChanges()andVersionSet::CommitBatchToStore().db/version_set.{h,cc}: the store branch ofProcessManifestWrites(),RecoverFromStore()with the shared replay helperReplayManifest(), and the copy writer.db/db_impl/db_impl_open.cc:RecoverFromManifestStore(), create, enter, andCheckManifestStoreOptions().db/db_impl/db_impl_files.cc:DBImpl::MinFileNumberInUse()gives the in-flight file number.DBImpl::pending_ingestion_outputs_becomes astd::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.db/db_filesnapshot.cc,db/repair.cc,DestroyDB(),DB::ListColumnFamilies().db/manifest_ops.{h,cc}:ManifestReporterandNewManifestReader()move here fromdb/experimental.cc, so that the stub reader and the copy reader use them too.db/db_test_util.{h,cc}: withENCRYPTED_ENV, the test fixture destroys its DB with the env below the encrypted env. Some tests write files withEnv::Default(), which the encrypted env cannot read, andDestroyDB()reads CURRENT (see "Changes visible to existing users").How to read this diff:
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 theRollBackManifestStore()comment ininclude/rocksdb/manifest_store.hfor the third mode change.db/manifest_store_state.hand.cc, readManifestStuband its encode, decode and read functions, thenScanManifestStore(),CheckScannedStoreRows(),CheckManifestDbRowOwner()andCheckOwnerAndClaim(). They depend on nothing else in this diff.class ManifestStoreStateindb/manifest_store_state.h, thenCommitBatch()in.cc. Read the results table, the diagram and the retry loop.db/manifest_rows.cc(CommitBatchToStore()), thendb/version_set.cc. InProcessManifestWrites(), read the store branch, the quarantine andio_status_block, thenRecoverFromStore()andReplayManifest().db/version_set.cc, readStartManifestCopyAtOpen(),WriteNewManifestCopy()andUpdateManifestCopy(), then the copy sync inVersionSet::Close().db/db_impl/db_impl.h. Then indb/db_impl/db_impl_open.ccreadDBImpl::Recover()andRecoverFromManifestStore()(together they call the others), thenCreateDbInManifestStore()andCommitNewDbRows(), thenEnterManifestStore(),ClaimForEnter()andFinishEnterManifestStore().RollBackManifestStore()at the end ofdb/manifest_store_state.cc. Then the guards indb/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 indb/blob/blob_file_partition_manager.cc, and the option comments ininclude/rocksdb/options.h.db/db_manifest_store_test.cc, by its "Section:" comments.Safety:
DB::Open(), the store calls and the copy write run under the DB mutex, as the MANIFEST reads of file mode do.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:
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. AfterDB::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 defaultmax_bgerror_resume_count(INT_MAX), the retries do not run out, and later MANIFEST writes wait. The contract ininclude/rocksdb/manifest_store.hsays so.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 ofenable_blob_direct_writesays 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.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.ManifestStore::Destroy()removes them.move_filesorlink_files); the option comments say not to change such an input file in place.reuse_manifest_on_openandverify_manifest_content_on_closehave no effect in store mode. The rollover options apply only to the copy.Changes visible to existing users:
manifest_store_migrateandmanifest_store_copy_mode, the functionRollBackManifestStore(), and the store-mode notes in the comments ofmax_bgerror_resume_count,bgerror_resume_retry_intervalandDB::ListColumnFamilies().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