Repository navigation
Support checkpoints, backups, secondaries, followers, remote compaction, DestroyDB and ldb in store mode (#15751) - #15751
xingbowang wants to merge 4 commits into
Conversation
|
@xingbowang has exported this pull request. If you are a Meta employee, you can view the originating Diff in D133614698. |
|
| Check | Count |
|---|---|
cert-err58-cpp |
3 |
performance-inefficient-string-concatenation |
2 |
performance-inefficient-vector-operation |
3 |
performance-unnecessary-value-param |
1 |
| Total | 9 |
Details
db/db_impl/db_impl.cc (1 warning(s))
db/db_impl/db_impl.cc:7789:51: 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 (3 warning(s))
db/manifest_store_state.cc:424: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:653: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:656:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
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]
tools/ldb_cmd.cc (2 warning(s))
tools/ldb_cmd.cc:80:31: warning: initialization of 'ARG_MANIFEST_STORE' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
tools/ldb_cmd.cc:1790:52: warning: the parameter 'file' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
62a9a36 to
e0eb3e7
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms (defined in the parent diff, see `db/manifest_store_state.h`): - Store mode: `DBOptions::manifest_store` is set and the DB row names the store as the authority. - DB row: the one row in the store that holds the DB-wide fields, such as the db id and the commit sequence. - Authority: a DB row field that says which copy of the metadata RocksDB uses: kStore (the rows), kFile (the MANIFEST file, after a rollback) or kShadow (see Shadow mode below). - Consistent scan: a `ManifestStore::Scan()` with `ManifestScanOptions::consistent` set, which reads all rows at one commit sequence. - Stub: the file `MANIFEST-<number>` that CURRENT names in store mode. It holds no metadata. - Commit sequence: a number in the DB row of the store that grows by 1 with each commit or claim. - Epoch and claim: the application gives a store object an epoch, a number. A claim (`ManifestStore::Open()`) with a newer epoch fences (refuses) the later requests of objects with older epochs. A store object without an epoch can only read. It never claims the DB, so it never fences the primary. - Done stub: a stub in state done (`ManifestStubState::kDone`), with no mode change in progress. - Copy files: the MANIFEST file copies (`MANIFEST_COPY-<number>`) that `DBOptions::manifest_store_copy_mode` writes. - Applied commit sequence (new in this diff): the commit sequence of the last commit of the primary that applied (`ManifestStoreState::applied_commit_sequence()`). It equals the commit sequence that its next commit expects, because the store adds 1 to the commit sequence on each commit. - Shadow mode: the DB row names `kShadow` as the authority. RocksDB does not write this value. A reader that finds it refuses the DB with NotSupported. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When the primary deleted a file of the scan (after a newer commit) before the open checked it, the open returns TryAgain instead of an instance without that file's data, and the caller can open again. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. Only the SST and blob files that the instance does not hold yet are checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, records the files marked for compaction, and refs the current Version and the ColumnFamilyData of each column family (the references and marks are kept in `VersionSet::CheckpointRowsRefs`). After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open, and `Recover()` returns TryAgain when a scanned file is missing. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`: in store mode, `ManifestTailer::VerifyFile()` skips an SST file during catch-up when the current Version of the column family holds a file with the same number and size, and the new `ManifestTailer::VerifyBlobFile()` skips a blob file that the current Version holds with the same number and the same total blob count and bytes. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`), and the primary does not delete a live file. - `db/manifest_store_state.{h,cc}`: the commit sequence that the next commit expects is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: on the primary, the new work under the DB mutex in `GetLiveFilesStorageInfo()` in store mode is the copy of the DB row, the WAL rows and one row for each column family, a ref on the current Version and on the ColumnFamilyData of each column family (so that a column family dropped during the copy stays alive), and a pass over the live files that records the files marked for compaction (`FileMetaData::marked_for_compaction` changes under the DB mutex). The pass over the live files is O(live files), the same order as the loop that already lists the live files in that section; its cost is not measured. The file rows are built after the unlock, and a second short DB mutex section unrefs the Versions and column families. During catch-up, the secondary and follower call the store and build the records without the DB mutex. When an overlapping catch-up dropped a column family, `ApplyStoreCatchUp()` builds the records again with the DB mutex held; this is rare. A separate mutex makes concurrent catch-ups call the store one at a time, as the store interface requires. Each catch-up makes one `ReadDbRow()` call, and makes a full scan only when the commit sequence changed. Under the DB mutex, a catch-up lists the live column families twice (in the short section, and again in `ReadAndApply()` to find an overlapping drop), and the tailer replays the records. Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST), and a catch-up after a change holds the scanned rows and their records at the same time. An estimate for each is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It checks only the new files. An estimate is that the time under the DB mutex grows with the number of live files; it is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "How RocksDB uses a store in store mode" (the call order and "Not supported in store mode") in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()` and `Recover()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms (defined in the parent diff, see `db/manifest_store_state.h`): - Store mode: `DBOptions::manifest_store` is set and the DB row names the store as the authority. - DB row: the one row in the store that holds the DB-wide fields, such as the db id and the commit sequence. - Authority: a DB row field that says which copy of the metadata RocksDB uses: kStore (the rows), kFile (the MANIFEST file, after a rollback) or kShadow (see Shadow mode below). - Consistent scan: a `ManifestStore::Scan()` with `ManifestScanOptions::consistent` set, which reads all rows at one commit sequence. - Stub: the file `MANIFEST-<number>` that CURRENT names in store mode. It holds no metadata. - Commit sequence: a number in the DB row of the store that grows by 1 with each commit or claim. - Epoch and claim: the application gives a store object an epoch, a number. A claim (`ManifestStore::Open()`) with a newer epoch fences (refuses) the later requests of objects with older epochs. A store object without an epoch can only read. It never claims the DB, so it never fences the primary. - Done stub: a stub in state done (`ManifestStubState::kDone`), with no mode change in progress. - Copy files: the MANIFEST file copies (`MANIFEST_COPY-<number>`) that `DBOptions::manifest_store_copy_mode` writes. - Applied commit sequence (new in this diff): the commit sequence of the last commit of the primary that applied (`ManifestStoreState::applied_commit_sequence()`). It equals the commit sequence that its next commit expects, because the store adds 1 to the commit sequence on each commit. - Shadow mode: the DB row names `kShadow` as the authority. RocksDB does not write this value. A reader that finds it refuses the DB with NotSupported. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When the primary deleted a file of the scan (after a newer commit) before the open checked it, the open returns TryAgain instead of an instance without that file's data, and the caller can open again. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. Only the SST and blob files that the instance does not hold yet are checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, records the files marked for compaction, and refs the current Version and the ColumnFamilyData of each column family (the references and marks are kept in `VersionSet::CheckpointRowsRefs`). After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open, and `Recover()` returns TryAgain when a scanned file is missing. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`: in store mode, `ManifestTailer::VerifyFile()` skips an SST file during catch-up when the current Version of the column family holds a file with the same number and size, and the new `ManifestTailer::VerifyBlobFile()` skips a blob file that the current Version holds with the same number and the same total blob count and bytes. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`), and the primary does not delete a live file. - `db/manifest_store_state.{h,cc}`: the commit sequence that the next commit expects is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: on the primary, the new work under the DB mutex in `GetLiveFilesStorageInfo()` in store mode is the copy of the DB row, the WAL rows and one row for each column family, a ref on the current Version and on the ColumnFamilyData of each column family (so that a column family dropped during the copy stays alive), and a pass over the live files that records the files marked for compaction (`FileMetaData::marked_for_compaction` changes under the DB mutex). The pass over the live files is O(live files), the same order as the loop that already lists the live files in that section; its cost is not measured. The file rows are built after the unlock, and a second short DB mutex section unrefs the Versions and column families. During catch-up, the secondary and follower call the store and build the records without the DB mutex. When an overlapping catch-up dropped a column family, `ApplyStoreCatchUp()` builds the records again with the DB mutex held; this is rare. A separate mutex makes concurrent catch-ups call the store one at a time, as the store interface requires. Each catch-up makes one `ReadDbRow()` call, and makes a full scan only when the commit sequence changed. Under the DB mutex, a catch-up lists the live column families twice (in the short section, and again in `ReadAndApply()` to find an overlapping drop), and the tailer replays the records. Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST), and a catch-up after a change holds the scanned rows and their records at the same time. An estimate for each is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It checks only the new files. An estimate is that the time under the DB mutex grows with the number of live files; it is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "How RocksDB uses a store in store mode" (the call order and "Not supported in store mode") in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()` and `Recover()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
e0eb3e7 to
41e4af9
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms (defined in the parent diff, see `db/manifest_store_state.h`): - Store mode: `DBOptions::manifest_store` is set and the DB row names the store as the authority. - DB row: the one row in the store that holds the DB-wide fields, such as the db id and the commit sequence. - Authority: a DB row field that says which copy of the metadata RocksDB uses: kStore (the rows), kFile (the MANIFEST file, after a rollback) or kShadow (see Shadow mode below). - Consistent scan: a `ManifestStore::Scan()` with `ManifestScanOptions::consistent` set, which reads all rows at one commit sequence. - Stub: the file `MANIFEST-<number>` that CURRENT names in store mode. It holds no metadata. - Commit sequence: a number in the DB row of the store that grows by 1 with each commit or claim. - Epoch and claim: the application gives a store object an epoch, a number. A claim (`ManifestStore::Open()`) with a newer epoch fences (refuses) the later requests of objects with older epochs. A store object without an epoch can only read. It never claims the DB, so it never fences the primary. - Done stub: a stub in state done (`ManifestStubState::kDone`), with no mode change in progress. - Copy files: the MANIFEST file copies (`MANIFEST_COPY-<number>`) that `DBOptions::manifest_store_copy_mode` writes. - Applied commit sequence (new in this diff): the commit sequence of the last commit of the primary that applied (`ManifestStoreState::applied_commit_sequence()`). It equals the commit sequence that its next commit expects, because the store adds 1 to the commit sequence on each commit. - Shadow mode: the DB row names `kShadow` as the authority. RocksDB does not write this value. A reader that finds it refuses the DB with NotSupported. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When the primary deleted a file of the scan (after a newer commit) before the open checked it, the open returns TryAgain instead of an instance without that file's data, and the caller can open again. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. Only the SST and blob files that the instance does not hold yet are checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, records the files marked for compaction, and refs the current Version and the ColumnFamilyData of each column family (the references and marks are kept in `VersionSet::CheckpointRowsRefs`). After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open, and `Recover()` returns TryAgain when a scanned file is missing. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`: in store mode, `ManifestTailer::VerifyFile()` skips an SST file during catch-up when the current Version of the column family holds a file with the same number and size, and the new `ManifestTailer::VerifyBlobFile()` skips a blob file that the current Version holds with the same number and the same total blob count and bytes. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`), and the primary does not delete a live file. - `db/manifest_store_state.{h,cc}`: the commit sequence that the next commit expects is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: on the primary, the new work under the DB mutex in `GetLiveFilesStorageInfo()` in store mode is the copy of the DB row, the WAL rows and one row for each column family, a ref on the current Version and on the ColumnFamilyData of each column family (so that a column family dropped during the copy stays alive), and a pass over the live files that records the files marked for compaction (`FileMetaData::marked_for_compaction` changes under the DB mutex). The pass over the live files is O(live files), the same order as the loop that already lists the live files in that section; its cost is not measured. The file rows are built after the unlock, and a second short DB mutex section unrefs the Versions and column families. During catch-up, the secondary and follower call the store and build the records without the DB mutex. When an overlapping catch-up dropped a column family, `ApplyStoreCatchUp()` builds the records again with the DB mutex held; this is rare. A separate mutex makes concurrent catch-ups call the store one at a time, as the store interface requires. Each catch-up makes one `ReadDbRow()` call, and makes a full scan only when the commit sequence changed. Under the DB mutex, a catch-up lists the live column families twice (in the short section, and again in `ReadAndApply()` to find an overlapping drop), and the tailer replays the records. Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST), and a catch-up after a change holds the scanned rows and their records at the same time. An estimate for each is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It checks only the new files. An estimate is that the time under the DB mutex grows with the number of live files; it is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "How RocksDB uses a store in store mode" (the call order and "Not supported in store mode") in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()` and `Recover()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms (defined in the parent diff, see `db/manifest_store_state.h`): - Store mode: `DBOptions::manifest_store` is set and the DB row names the store as the authority. - DB row: the one row in the store that holds the DB-wide fields, such as the db id and the commit sequence. - Authority: a DB row field that says which copy of the metadata RocksDB uses: kStore (the rows), kFile (the MANIFEST file, after a rollback) or kShadow (see Shadow mode below). - Consistent scan: a `ManifestStore::Scan()` with `ManifestScanOptions::consistent` set, which reads all rows at one commit sequence. - Stub: the file `MANIFEST-<number>` that CURRENT names in store mode. It holds no metadata. - Commit sequence: a number in the DB row of the store that grows by 1 with each commit or claim. - Epoch and claim: the application gives a store object an epoch, a number. A claim (`ManifestStore::Open()`) with a newer epoch fences (refuses) the later requests of objects with older epochs. A store object without an epoch can only read. It never claims the DB, so it never fences the primary. - Done stub: a stub in state done (`ManifestStubState::kDone`), with no mode change in progress. - Copy files: the MANIFEST file copies (`MANIFEST_COPY-<number>`) that `DBOptions::manifest_store_copy_mode` writes. - Applied commit sequence (new in this diff): the commit sequence of the last commit of the primary that applied (`ManifestStoreState::applied_commit_sequence()`). It equals the commit sequence that its next commit expects, because the store adds 1 to the commit sequence on each commit. - Shadow mode: the DB row names `kShadow` as the authority. RocksDB does not write this value. A reader that finds it refuses the DB with NotSupported. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When the primary deleted a file of the scan (after a newer commit) before the open checked it, the open returns TryAgain instead of an instance without that file's data, and the caller can open again. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. Only the SST and blob files that the instance does not hold yet are checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, records the files marked for compaction, and refs the current Version and the ColumnFamilyData of each column family (the references and marks are kept in `VersionSet::CheckpointRowsRefs`). After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open, and `Recover()` returns TryAgain when a scanned file is missing. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`: in store mode, `ManifestTailer::VerifyFile()` skips an SST file during catch-up when the current Version of the column family holds a file with the same number and size, and the new `ManifestTailer::VerifyBlobFile()` skips a blob file that the current Version holds with the same number and the same total blob count and bytes. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`), and the primary does not delete a live file. - `db/manifest_store_state.{h,cc}`: the commit sequence that the next commit expects is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: on the primary, the new work under the DB mutex in `GetLiveFilesStorageInfo()` in store mode is the copy of the DB row, the WAL rows and one row for each column family, a ref on the current Version and on the ColumnFamilyData of each column family (so that a column family dropped during the copy stays alive), and a pass over the live files that records the files marked for compaction (`FileMetaData::marked_for_compaction` changes under the DB mutex). The pass over the live files is O(live files), the same order as the loop that already lists the live files in that section; its cost is not measured. The file rows are built after the unlock, and a second short DB mutex section unrefs the Versions and column families. During catch-up, the secondary and follower call the store and build the records without the DB mutex. When an overlapping catch-up dropped a column family, `ApplyStoreCatchUp()` builds the records again with the DB mutex held; this is rare. A separate mutex makes concurrent catch-ups call the store one at a time, as the store interface requires. Each catch-up makes one `ReadDbRow()` call, and makes a full scan only when the commit sequence changed. Under the DB mutex, a catch-up lists the live column families twice (in the short section, and again in `ReadAndApply()` to find an overlapping drop), and the tailer replays the records. Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST), and a catch-up after a change holds the scanned rows and their records at the same time. An estimate for each is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It checks only the new files. An estimate is that the time under the DB mutex grows with the number of live files; it is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "How RocksDB uses a store in store mode" (the call order and "Not supported in store mode") in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()` and `Recover()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 41e4af9 SummaryLarge, well-structured PR that enables store mode for checkpoints, backups, secondaries, followers, remote compaction, DestroyDB and ldb. The design is thorough with clear crash-recovery reasoning and careful mutex management. The diff is 15K+ lines but most are tests (4446 lines). Key concerns: a debug assertion in checkpoint code will fire for store-mode MANIFEST, a possible defaulted parameter addition to High-severity findings (1):
Full review (click to expand)Findings🔴 HIGHH1. Checkpoint assertion fires for store-mode MANIFEST replacement_contents --
|
| Context | Affected? | Assessment |
|---|---|---|
| WritePreparedTxnDB | No | Store mode is orthogonal to transaction type; metadata path only |
| ReadOnly DB | Yes | Handled: read-only open reads from store, no claim |
| CompactionService | Yes | Handled: worker gets store from override, floor check extended |
| User-defined timestamps | Indirect | RowsToRewriteAfterOpen handles timestamp_size changes |
| BlobDB (direct write) | Yes | Handled: NewTrackedBlobFileNumber ensures atomicity |
| Snapshots | No | Store mode does not change snapshot semantics |
Positive Observations
- Crash recovery reasoning is thorough: each multi-step operation documents what a crash between steps leaves and how the next open recovers.
- Owner checks in DestroyDB prevent accidentally destroying rows of a different DB.
- BlobFilePartitionManager atomicity fix closes a real window where a file number could be missed.
- TryAgain retry in OpenAndCompact for store mode integrates cleanly with the existing retry loop.
- DB mutex analysis is explicit about new work under mutex and its cost order.
- The separation of store read from mutex-held apply in secondary/follower catch-up follows the established pattern well.
- Extensive test coverage (4446 lines) with clear structure covering checkpoints, backups, secondary/follower, remote compaction, DestroyDB, and ldb.
ℹ️ 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
41e4af9 to
18c8c09
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. Only the SST and blob files that the instance does not hold yet are checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, records the files marked for compaction, and refs the current Version and the ColumnFamilyData of each column family (the references and marks are kept in `VersionSet::CheckpointRowsRefs`). After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit, else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`: in store mode, `ManifestTailer::VerifyFile()` skips an SST file during catch-up when the current Version of the column family holds a file with the same number and size, and the new `ManifestTailer::VerifyBlobFile()` skips a blob file that the current Version holds with the same number and the same total blob count and bytes. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`), and the primary does not delete a live file. - `db/manifest_store_state.{h,cc}`: the commit sequence that the next commit expects is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files); its time is not measured. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); a pass over the live files that records the files marked for compaction (the same O(live files) cost as the existing loop that lists the live files); a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a FileMetaData per file, checks of the new files, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change; its time is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "How RocksDB uses a store in store mode" (the call order and "Not supported in store mode") in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 18c8c09 SummaryLarge, well-structured diff that extends store mode to checkpoints, backups, secondaries, followers, remote compaction, DestroyDB, and ldb. The design is thorough with clear state machine transitions and crash recovery. The diff was truncated (~15.5K insertions across 64 files), so some changed files could not be fully reviewed (notably the full checkpoint_impl.cc changes and src.mk). High-severity findings (1):
Full review (click to expand)Findings🔴 HIGHH1. Assert fires for MANIFEST
|
| Context | Store mode support | Notes |
|---|---|---|
| Primary DB | YES | Full support via ManifestStoreState |
| ReadOnly DB | YES | Reads from store scan, no commits |
| Secondary | YES | New OpenStoreRead/ReadStoreForCatchUp |
| Follower | YES | Same mechanism as secondary |
| Remote compaction | YES | New min_store_commit_sequence floor |
| Checkpoint/Backup | YES | MANIFEST built from memory |
| DestroyDB | YES | Store rows destroyed before files |
| ldb | YES (truncated) | New --manifest_store flag |
| best_efforts_recovery | NO | Correctly rejected (InvalidArgument) |
| RepairDB | NO | Returns NotSupported |
Positive Observations
- Thorough crash recovery design: Every step of the enter/create state machine has a recovery path, and the stub states encode exactly where the process stopped.
- Owner verification: DestroyDB checks the db id before destroying store rows, preventing accidental destruction of another DB's metadata.
- Backwards-compatible serialization: The CompactionServiceInput field uses ignore_unknown_options, so older/newer workers interoperate correctly.
- Well-documented mutex costs: The PR description includes a mutex table showing what runs under the DB mutex for each path.
- BlobFilePartitionManager atomicity fix: Merging file number allocation and tracking prevents a race window where MinFileNumberInUse could miss a recently allocated number.
- Comprehensive test file: 4572 lines of tests covering checkpoints, backups, secondary, follower, remote compaction, DestroyDB, and ldb in store mode.
ℹ️ 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
18c8c09 to
5d124d7
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). The tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that list. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files); its time is not measured. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change; its time is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The stub and the MANIFEST file copies are never listed. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence changed. The new state replaces the old one, so files that the primary deleted leave the Version. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), `VersionSet::ReleaseCheckpointRowsRefs()` unrefs them in a second short DB mutex section, and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). The tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that list. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files); its time is not measured. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change; its time is not measured. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 5d124d7 SummaryLarge, well-structured diff that extends store mode to checkpoints, backups, secondaries, followers, remote compaction, DestroyDB and ldb. The design is careful about crash safety, ownership checks, and DB mutex hold time. The PR description is thorough. High-severity findings (1):
Full review (click to expand)Findings🔴 HIGHH1. Checkpoint assertion on
|
| Context | Affected | Assessment |
|---|---|---|
| Checkpoint + store mode | Yes | H1 assertion issue (likely fixed in truncated diff) |
| BackupEngine + store mode | Yes | Goes through same checkpoint path, same H1 concern |
| ReadOnly DB + store mode | Yes | Correctly skips state creation, reads from store |
| WritePreparedTxnDB + store mode | Unlikely affected | Store mode is metadata-only |
| User-defined timestamps + store mode | Yes | RowsToRewriteAfterOpen handles timestamp_size changes |
| FIFO compaction + store mode secondary | Needs verification | Aggressive file deletion + catch-up TryAgain |
| best_efforts_recovery + store | Explicitly rejected | Good |
Positive Observations
- Crash safety design: The multi-step operations (create, enter) have clear intermediate states and recovery paths. Each step's post-condition is documented.
- Owner checks: The db id comparison in DestroyDB prevents accidental cross-DB row destruction.
- Feature-off cost: For non-store-mode DBs, the cost is minimal — a few boolean checks (
MetadataInStore(),CheckManifestStoreOptions()) and two atomic stores (opening_,closing_). - Separation of mutex-held vs non-mutex-held work: The checkpoint row copy correctly splits into three steps (mutex: copy+ref, no mutex: build, mutex: unref). The secondary/follower catch-up reads the store outside the mutex.
- BlobFilePartitionManager atomicity fix:
NewTrackedBlobFileNumbercorrectly prevents the window where a file number is allocated but not yet tracked, which could causeMinFileNumberInUse()to miss it. - Well-documented invariants: The PR description's "Mutex" table and "Safety boundaries" section make the design reviewable.
- Serialization compatibility:
min_store_commit_sequencedefaults to 0 and older workers skip unknown fields — clean forward/backward compatibility.
ℹ️ 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
5d124d7 to
1614f95
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. When a file of the scan is missing or damaged, every column family that the scan does not drop keeps its current Version (a drop in the scan still applies), and the next catch-up scans and replays again, also at the same commit sequence. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadAndApply()` records the commit sequence of a catch-up scan as replayed only when the tailer installed the Versions of all column families (new `ManifestTailer::InstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files); its time is not measured. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change; its time is not measured. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. When a file of the scan is missing or damaged, every column family that the scan does not drop keeps its current Version (a drop in the scan still applies), and the next catch-up scans and replays again, also at the same commit sequence. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. The primary sends its applied commit sequence in the new compaction input field `min_store_commit_sequence`. The worker refuses a scan with a smaller commit sequence (Incomplete, so the job can run locally), like the existing MANIFEST floor in file mode. The primary sends this field only when `DBOptions::remote_compaction_manifest_floor` is true; otherwise it sends 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. `ldb manifest_dump` (without `--path`) and `ldb dump_live_files` with the flag print the metadata from a consistent scan of the store; `manifest_dump` refuses rows whose DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadAndApply()` records the commit sequence of a catch-up scan as replayed only when the tailer installed the Versions of all column families (new `ManifestTailer::InstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files); its time is not measured. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change; its time is not measured. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
1614f95 to
f0b56c0
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. A column family drop is different: the instance applies it as soon as it replays the drop record. When a file of the scan is missing or damaged, so that a column family has no valid new Version, the catch-up still returns OK: every column family that is not dropped keeps its current Version, the last installed commit sequence stays, and the next catch-up scans and replays the same store commit again if the primary made no newer commit. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. When `DBOptions::remote_compaction_manifest_floor` is true in store mode, the primary sends the stub number in the existing field `min_manifest_file_number` and its applied commit sequence in the new compaction input field `min_store_commit_sequence`. A nonzero stub number makes the worker open with `trust_manifest_recovery` (as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is below `min_store_commit_sequence` (Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. With the flag, `ldb manifest_dump` (without `--path`) prints the MANIFEST records from a consistent scan of the store. `ldb dump_live_files` makes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadAndApply()` records the commit sequence of a catch-up scan as replayed only when the tailer installed the Versions of all column families (new `ManifestTailer::InstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change: in the measurements of the Test Plan, a catch-up after a one-file flush holds the DB mutex for about 24 ms with 10,000 SSTs and about 230 to 260 ms with 100,000 SSTs (p50), about 2.1 to 2.5 times the time of a file-mode catch-up of the same DB. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. A column family drop is different: the instance applies it as soon as it replays the drop record. When a file of the scan is missing or damaged, so that a column family has no valid new Version, the catch-up still returns OK: every column family that is not dropped keeps its current Version, the last installed commit sequence stays, and the next catch-up scans and replays the same store commit again if the primary made no newer commit. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: the rows leave out dropped column families, so a column family that the instance opened and that the primary dropped gets a drop record, as from a MANIFEST file. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. When `DBOptions::remote_compaction_manifest_floor` is true in store mode, the primary sends the stub number in the existing field `min_manifest_file_number` and its applied commit sequence in the new compaction input field `min_store_commit_sequence`. A nonzero stub number makes the worker open with `trust_manifest_recovery` (as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is below `min_store_commit_sequence` (Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it calls `ManifestStore::Destroy()` first and then deletes the files, including the stub and the copy files. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. With the flag, `ldb manifest_dump` (without `--path`) prints the MANIFEST records from a consistent scan of the store. `ldb dump_live_files` makes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` frees the scanned rows. `ReadAndApply()` records the commit sequence of a catch-up scan as replayed only when the tailer installed the Versions of all column families (new `ManifestTailer::InstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, freeing the rows, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed) and building the records; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes until `ApplyStoreRead()` gives the bytes to the reader and frees the rows. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change: in the measurements of the Test Plan, a catch-up after a one-file flush holds the DB mutex for about 24 ms with 10,000 SSTs and about 230 to 260 ms with 100,000 SSTs (p50), about 2.1 to 2.5 times the time of a file-mode catch-up of the same DB. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
f0b56c0 to
930c88a
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
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. A column family drop is different: the instance applies it as soon as it replays the drop record. When a file of the scan is missing or damaged, so that a column family has no valid new Version, the catch-up still returns OK: every column family that is not dropped keeps its current Version, the last installed commit sequence stays, and the next catch-up scans and replays the same store commit again if the primary made no newer commit. Two catch-ups can overlap, so a catch-up skips a scan that another one made old. Two commit sequences decide this. The attempted one is the commit sequence of the scan that the instance replayed last. A replay changes the state of the MANIFEST reader of the instance (for example its last sequence number) even when it installs no Version, so an older scan must not replay after a newer one. The installed one is the commit sequence of the last scan whose Versions the instance installed. A scan below the attempted commit sequence, or at or below the installed one, is skipped; a scan at the attempted commit sequence replays again, so a missing file can be retried. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: store mode marks the row of a dropped column family as dropped, and later commits delete its rows, so a scan can list it as dropped or not list it. The replay adds a drop record for each column family that the instance still has and that the scan lists as dropped or does not list, as a MANIFEST file would. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. When `DBOptions::remote_compaction_manifest_floor` is true in store mode, the primary sends the stub number in the existing field `min_manifest_file_number` and its applied commit sequence in the new compaction input field `min_store_commit_sequence`. A nonzero stub number makes the worker open with `trust_manifest_recovery` (as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is below `min_store_commit_sequence` (Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it lists the folder, calls `ManifestStore::Destroy()`, and then deletes the files, including the stub and the copy files. A listing error (other than a missing folder) or an error while reading CURRENT or the stub (for example a timeout) is returned before the rows are removed or any file is deleted, so the call can be repeated. A missing or broken file-mode MANIFEST is not such an error, and the DB is deleted as a file-mode DB. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. With the flag, `ldb manifest_dump` (without `--path`) prints the MANIFEST records from a consistent scan of the store. `ldb dump_live_files` makes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` records the attempted commit sequence, and the catch-up callers free the scanned rows after they release the DB mutex. `ApplyStoreCatchUp()` skips a scan below the attempted commit sequence or at or below the installed one. `ReadAndApply()` records the commit sequence of a catch-up scan as installed only when the tailer installed the Versions of all column families (new `ManifestTailer::CanInstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed), building the records, and freeing the scanned rows after the replay; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes. The rows stay during the replay, and the caller frees them after it releases the DB mutex; the reader frees the bytes when the replay reaches their end. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change: in the measurements of the Test Plan, a catch-up after a one-file flush holds the DB mutex for about 24 ms with 10,000 SSTs and about 230 to 260 ms with 100,000 SSTs (p50), about 2.1 to 2.5 times the time of a file-mode catch-up of the same DB. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
930c88a to
a59eba9
Compare
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. A column family drop is different: the instance applies it as soon as it replays the drop record. When a file of the scan is missing or damaged, so that a column family has no valid new Version, the catch-up still returns OK: every column family that is not dropped keeps its current Version, the last installed commit sequence stays, and the next catch-up scans and replays the same store commit again if the primary made no newer commit. Two catch-ups can overlap, so a catch-up skips a scan that another one made old. Two commit sequences decide this. The attempted one is the commit sequence of the scan that the instance replayed last. A replay changes the state of the MANIFEST reader of the instance (for example its last sequence number) even when it installs no Version, so an older scan must not replay after a newer one. The installed one is the commit sequence of the last scan whose Versions the instance installed. A scan below the attempted commit sequence, or at or below the installed one, is skipped; a scan at the attempted commit sequence replays again, so a missing file can be retried. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: store mode marks the row of a dropped column family as dropped, and later commits delete its rows, so a scan can list it as dropped or not list it. The replay adds a drop record for each column family that the instance still has and that the scan lists as dropped or does not list, as a MANIFEST file would. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. When `DBOptions::remote_compaction_manifest_floor` is true in store mode, the primary sends the stub number in the existing field `min_manifest_file_number` and its applied commit sequence in the new compaction input field `min_store_commit_sequence`. A nonzero stub number makes the worker open with `trust_manifest_recovery` (as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is below `min_store_commit_sequence` (Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it lists the folder, calls `ManifestStore::Destroy()`, and then deletes the files, including the stub and the copy files. A listing error (other than a missing folder) or an error while reading CURRENT or the stub (for example a timeout) is returned before the rows are removed or any file is deleted, so the call can be repeated. A missing or broken file-mode MANIFEST is not such an error, and the DB is deleted as a file-mode DB. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. With the flag, `ldb manifest_dump` (without `--path`) prints the MANIFEST records from a consistent scan of the store. `ldb dump_live_files` makes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` records the attempted commit sequence, and the catch-up callers free the scanned rows after they release the DB mutex. `ApplyStoreCatchUp()` skips a scan below the attempted commit sequence or at or below the installed one. `ReadAndApply()` records the commit sequence of a catch-up scan as installed only when the tailer installed the Versions of all column families (new `ManifestTailer::CanInstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed), building the records, and freeing the scanned rows after the replay; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes. The rows stay during the replay, and the caller frees them after it releases the DB mutex; the reader frees the bytes when the replay reaches their end. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change: in the measurements of the Test Plan, a catch-up after a one-file flush holds the DB mutex for about 24 ms with 10,000 SSTs and about 230 to 260 ms with 100,000 SSTs (p50), about 2.1 to 2.5 times the time of a file-mode catch-up of the same DB. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
…on, DestroyDB and ldb in store mode (meta#15751) Summary: Pull Request resolved: meta#15751 Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with `DBOptions::manifest_store` set, the rows in a `ManifestStore` hold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction, `DestroyDB()` and `ldb` after it moves a DB into the store. Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see `db/manifest_store_state.h` and `include/rocksdb/manifest_store.h`). This diff adds one term: - Applied commit sequence: the commit sequence that the DB row has after the last commit (or claim) of the primary (`ManifestStoreState::applied_commit_sequence()`). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far. Previous behavior: on a DB in store mode, `GetLiveFiles()`, `GetLiveFilesStorageInfo()` (and so checkpoints, backups and the stacked BlobDB), `SplitDB()` and `MergeDB()` (which use a checkpoint), `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` with a store, `compaction_service` with a store, `DB::OpenAndCompact()`, and `DestroyDB()` return NotSupported. `ldb` has no way to get the store. New behavior: Two parts carry most of the design: (1) `GetLiveFilesStorageInfo()` builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small: `DestroyDB()`, the remote compaction floor, `ldb`, and split/merge. - Checkpoints and backups: in store mode, `GetLiveFilesStorageInfo()` gives the MANIFEST entry with its content in `LiveFileStorageInfo::replacement_contents`: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writes `replacement_contents` under that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed. `GetLiveFiles()` still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata. `SplitDB()` and `MergeDB()` work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source. - Secondary and follower: `DB::OpenAsSecondary()` and `DB::OpenAsFollower()` accept a store object (usually one without an epoch). - Open: they check that CURRENT names a done stub, do a consistent scan, and replay the rows. The scan is one point in time. When a file of the scan is missing or does not match, the open reads the DB row. If the primary made a newer commit, it may have deleted the file, so the open returns TryAgain instead of an instance without that file's data, and the caller can open again. If not, no commit explains the missing file, and the open returns Corruption with the missing file numbers. A file that exists but fails its check (for example a wrong size) also gives Corruption, because a commit deletes files but never changes them. If the DB row cannot be read, the open returns IOError. With `DBOptions::open_files_async`, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, and `DB::OpenAndCompact()` retries its TryAgain. - Catch-up: each catch-up reads the DB row, and scans again only when the commit sequence differs from the last scan whose Versions the instance installed. The new state replaces the old one, so files that the primary deleted leave the Version. One scan is one point in time of the primary, so the instance installs the new Versions of all column families together, or none of them, as file mode does for an atomic group. A column family drop is different: the instance applies it as soon as it replays the drop record. When a file of the scan is missing or damaged, so that a column family has no valid new Version, the catch-up still returns OK: every column family that is not dropped keeps its current Version, the last installed commit sequence stays, and the next catch-up scans and replays the same store commit again if the primary made no newer commit. Two catch-ups can overlap, so a catch-up skips a scan that another one made old. Two commit sequences decide this. The attempted one is the commit sequence of the scan that the instance replayed last. A replay changes the state of the MANIFEST reader of the instance (for example its last sequence number) even when it installs no Version, so an older scan must not replay after a newer one. The installed one is the commit sequence of the last scan whose Versions the instance installed. A scan below the attempted commit sequence, or at or below the installed one, is skipped; a scan at the attempted commit sequence replays again, so a missing file can be retried. For a file that the instance already holds ("held file": same number, size and unique id for an SST file; same number, blob count, bytes and checksum for a blob file), the catch-up reuses the metadata object of the current Version. So the open table readers and blob file readers stay, and only the new files are opened and checked, as in file mode. The steps and locks are in "Store mode in a secondary or follower" in `db/version_set.h`. - Column families: store mode marks the row of a dropped column family as dropped, and later commits delete its rows, so a scan can list it as dropped or not list it. The replay adds a drop record for each column family that the instance still has and that the scan lists as dropped or does not list, as a MANIFEST file would. As with a MANIFEST file, a column family that the primary creates after the open is not opened in the instance; its rows are left out of the replay. - Errors: they return InvalidArgument when the DB row names the MANIFEST file as the authority (for example after a rollback to file mode), and NotSupported for a DB in shadow mode. A failed read of the store changes nothing, and the next catch-up tries again. An error during the replay stays, as in file mode, until the instance is opened again. When the DB row has another db id than the DB that the instance opened (the DB was destroyed and created again at the same path with the same store), a catch-up returns Corruption, as file mode does, with the same hint to reopen the instance, also when the new DB row has a lower commit sequence. - Remote compaction: `compaction_service` works with a store. The worker gets the store from the new field `CompactionServiceOptionsOverride::manifest_store`, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. When `DBOptions::remote_compaction_manifest_floor` is true in store mode, the primary sends the stub number in the existing field `min_manifest_file_number` and its applied commit sequence in the new compaction input field `min_store_commit_sequence`. A nonzero stub number makes the worker open with `trust_manifest_recovery` (as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is below `min_store_commit_sequence` (Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field. - `DestroyDB()`: - Store mode: with the store in `DBOptions::manifest_store`, it lists the folder, calls `ManifestStore::Destroy()`, and then deletes the files, including the stub and the copy files. A listing error (other than a missing folder) or an error while reading CURRENT or the stub (for example a timeout) is returned before the rows are removed or any file is deleted, so the call can be repeated. A missing or broken file-mode MANIFEST is not such an error, and the DB is deleted as a file-mode DB. Without a store it still returns NotSupported. - The rows belong to the store key, not to a folder. A file copy of a store-mode DB folder holds a stub with the same db id, so `DestroyDB()` of such a copy with the store of the source removes the rows of the source DB. The `DestroyDB()` and `GetLiveFilesStorageInfo()` comments say to remove such a copy without the store (for example with `DestroyDir()`). - Owner check: before `Destroy()` it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows. - File mode after a rollback: with a store in the options, it reads the db id of the DB (from the MANIFEST file or the IDENTITY file). A MANIFEST file that cannot be read up to its db id falls back to the IDENTITY file. When it finds a db id, it reads the DB row, and it removes the rows that the rollback left when they have that db id and authority kFile; it leaves other rows alone. It returns an error of the IDENTITY file read, or of the DB row read or decode, before it deletes any file. - Conditional destroy: `Destroy()` gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) in `ManifestStoreDestroyOptions`. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, and `DestroyDB()` returns Busy without deleting any file. It does not retry. - Crash between the steps: the `ManifestStore::Destroy()` comment states that it returns OK when there is no DB row, so `DestroyDB()` can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, and `DB::Open()` refuses it. - `ldb`: the new global flag `--manifest_store=<store>` creates the store with `ManifestStore::CreateFromString()` and passes it to every DB open through `LDBCommand::OpenDB()` and to `DB::ListColumnFamilies()` (`remote_compaction_primary` and `remote_compaction_worker` build their own options and do not use it). An unknown store name fails before any DB access. With the flag, `ldb manifest_dump` (without `--path`) prints the MANIFEST records from a consistent scan of the store. `ldb dump_live_files` makes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback). - OPTIONS: in store mode, when the DB records the number of its committed OPTIONS file, `LoadLatestOptions()` and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With `--manifest_store`, `ldb` then loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption. <details> <summary>Implementation (file by file)</summary> - `db/db_filesnapshot.cc`, `db/manifest_rows.cc`: in `GetLiveFilesStorageInfoImpl()`, the new `VersionSet::GetManifestRowsWithoutFiles()` copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept in `VersionSet::CheckpointRowsRefs`. After the unlock, `VersionSet::AddManifestFileRows()` adds the file rows from those Versions (with a new `VersionEdit::AddExistingFile()` overload in `db/version_edit.{h,cc}` that takes the recorded mark), and `ManifestRowsToRecords()` and `RecordsToManifestBytes()` encode the rows. `VersionSet::ReleaseCheckpointRowsRefs()` unrefs the Versions and ColumnFamilyData in a second short DB mutex section when `GetLiveFilesStorageInfoImpl()` returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The new `DBImpl::MetadataInStore()` tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options. - `utilities/checkpoint/checkpoint_impl.cc`: the checkpoint accepts `replacement_contents` for the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode. - `db/version_set.{h,cc}`, `db/db_impl/db_impl_secondary.cc`, `db/db_impl/db_impl_follower.cc`: `ReactiveVersionSet::OpenStoreRead()` reads the store for the open. When a scanned file is missing, `Recover()` calls `MissingFilesAtStoreOpen()`, which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the new `ManifestTailer::NewestStateMissingFileNumbers()` and `VersionBuilder::GetMissingFileNumbers()`. `ApplyStoreRead()` records the attempted commit sequence, and the catch-up callers free the scanned rows after they release the DB mutex. `ApplyStoreCatchUp()` skips a scan below the attempted commit sequence or at or below the installed one. `ReadAndApply()` records the commit sequence of a catch-up scan as installed only when the tailer installed the Versions of all column families (new `ManifestTailer::CanInstallVersions()`, called by `VersionEditHandlerPointInTime::CheckIterationResult()`; it returns true outside a store-mode catch-up, so file mode does not change). `ReadStoreForCatchUp()` reads the store and builds the records without the DB mutex. `ReadAndApply()` calls `ApplyStoreCatchUp()` with the DB mutex held, in place of `MaybeSwitchManifest()`. The steps, locks and errors are in the comment "Store mode in a secondary or follower" at `ReadStoreForCatchUp()`. The records reach the tailer through `NewStringSequentialFile()`, whose file frees its bytes when a read reaches the end. `VersionSet::DumpManifestFromStore()` uses `BuildStoreManifestBytes()` and shares the print code with `DumpManifest()` (`DumpManifestRecords()`). - `db/version_edit_handler.{h,cc}`, `db/version_builder.cc`: the new virtual functions `VersionEditHandler::HeldFile()` and `HeldBlobFile()` return null, except in `ManifestTailer` during a store-mode catch-up, where they return the metadata object of a held file in the current Version. `VersionBuilder` then adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change. `ManifestTailer::VerifyFile()` and the new `VerifyBlobFile()` skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, with `DBOptions::open_files_async`). During the open in store mode, the tailer records the files whose check returns Corruption, and `MissingFilesAtStoreOpen()` uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" in `db/version_edit_handler.h` has the details. - `db/manifest_store_state.{h,cc}`: the applied commit sequence (`applied_commit_sequence_`) is a `std::atomic`, so that other threads can read it with `ManifestStoreState::applied_commit_sequence()`. The new helper `StoreModeOptions()` tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store. - `db/compaction/`: `CompactionJob` captures the applied commit sequence, and `CompactionServiceInput` serializes it as `min_store_commit_sequence`. - `db/db_impl/db_impl_secondary.cc`: the worker copies the store from the override and checks the floor. - `db/db_impl/db_impl_open.cc`: `DBImpl::CheckManifestStoreOptions()` accepts a store for every open function and with `compaction_service`; `best_efforts_recovery` and `best_efforts_blob_db_repair` with a store stay InvalidArgument. - `db/db_impl/db_impl.cc`: `DestroyDB()` and its helpers `DestroyManifestStoreRows()`, `ReadFileModeDbId()` (which reads the IDENTITY file with `ReadDbIdFromIdentityFile()` of the parent diff) and `DestroyRolledBackRows()`, with the rules table above them. - `tools/ldb_cmd.cc`, `include/rocksdb/utilities/ldb_cmd.h`, `tools/ldb_tool.cc`: they add `LDBCommand::ARG_MANIFEST_STORE` and the protected member `LDBCommand::manifest_store_`, load the committed OPTIONS file from the DB row, and dump the store. - `utilities/db_split_merge.cc`: the options of the checkpoint DB have no store, no migration and no copy mode. </details> Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up. | Path | Under the DB mutex | Without the DB mutex | |---|---|---| | `GetLiveFilesStorageInfo()` in store mode (primary) | copy of the DB row, the WAL rows and one row per column family; a ref on the current Version and ColumnFamilyData of each column family (so a column family dropped during the copy stays alive); the files marked for compaction, recorded in the existing loop that lists the live files; a second short section that unrefs them | the file rows, the records and the MANIFEST bytes | | Catch-up of a secondary or follower | listing the live column families (twice); the tailer replay of all live files: decode every record, a lookup of each file in the current Version, a new FileMetaData and a check only for each new file, and the release of the old Version's files and the obsolete file pass; rarely, a rebuild of the records when an overlapping catch-up dropped a column family | `ReadDbRow()`, the scan (only when the commit sequence changed), building the records, and freeing the scanned rows after the replay; a separate mutex makes concurrent catch-ups call the store one at a time | Safety boundaries and unsupported cases: - `GetLiveFiles()`, `RepairDB()`, and the tools that read or rewrite the MANIFEST file offline (`ldb reduce_levels`, `update_manifest`, `unsafe_remove_sst_file`, `file_checksum_dump`, `repair`) return NotSupported in store mode. - A store object without an epoch cannot remove rows, so `DestroyDB()` with it returns NotSupported. `DestroyDB()` also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows. - A caller of `GetLiveFilesStorageInfo()` that ignores `replacement_contents` for the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. The `GetLiveFilesStorageInfo()` comment says so. - An open of a checkpoint of a DB in store mode with the store of the source and `manifest_store_migrate` returns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source. `DestroyDB()` of such a copy with the store of the source keeps the rows of the source, because they have authority kStore. - With a store object that has an epoch, the `ldb` commands that open the DB for writing (for example `checkpoint` and `backup`) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so. - A worker without `CompactionServiceOptionsOverride::manifest_store` fails on the stub with NotSupported. - No code guard for a folder copy (see `DestroyDB()`). - Memory: a checkpoint holds at most two copies at a time (first the rows and their records, then the records and the built MANIFEST). A catch-up after a change holds three copies while it builds the records (the scanned rows, their records and the MANIFEST bytes), then the rows and the bytes. The rows stay during the replay, and the caller frees them after it releases the DB mutex; the reader frees the bytes when the replay reaches their end. An estimate for each copy is a few hundred bytes for each live file, about the size of a MANIFEST file right after a rollover. Known limitations: - Each catch-up of a secondary or follower after a commit scans all rows of the store. A change feed of the store would avoid this. - Each such catch-up also replays all live files of all column families under the DB mutex: it builds a new Version from all live files (file mode replays only the changed records). It reuses the metadata of held files and checks only the new files. The work under the DB mutex is O(live files) per catch-up after a change: in the measurements of the Test Plan, a catch-up after a one-file flush holds the DB mutex for about 24 ms with 10,000 SSTs and about 230 to 260 ms with 100,000 SSTs (p50), about 2.1 to 2.5 times the time of a file-mode catch-up of the same DB. A catch-up that finds a missing file repeats this work at each call until the file is back or a new commit arrives. Replaying only the changed rows (a delta of the rows) would avoid this, and is out of scope. - No crash test lane covers store-mode remote compaction or followers; only unit tests cover them. - A secondary or follower that stays open across a rollback done without the store keeps its old view and reports nothing, because the DB row keeps authority kStore and its commit sequence. `RollBackManifestStore()` says to stop every instance of the DB before the call. Changes visible to existing users: the new field `CompactionServiceOptionsOverride::manifest_store`, the new `ldb` flag `--manifest_store` and `LDBCommand::ARG_MANIFEST_STORE`, the updated comments of `LiveFileStorageInfo::replacement_contents`, `DB::GetLiveFiles()`, `DB::GetLiveFilesStorageInfo()`, `DestroyDB()`, `DBOptions::manifest_store`, `DBOptions::remote_compaction_manifest_floor` and the store mode overview in `include/rocksdb/manifest_store.h`, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, and `DestroyDB()` with a store in the options reads the DB row (see New behavior). How to read this diff: 1. Overview: read "Call order" and "Not supported in store mode" in `include/rocksdb/manifest_store.h`, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and the `StoreModeOptions()` table in `db/manifest_store_state.h`. 2. Copies of the DB: read the `VersionSet::CheckpointRowsRefs` comment in `db/version_set.h`, then `db/manifest_rows.cc`, then `GetLiveFilesStorageInfoImpl()` in `db/db_filesnapshot.cc` with `DBImpl::MetadataInStore()` in `db/db_impl/db_impl.h`. Finish with `utilities/checkpoint/checkpoint_impl.cc` and `GetCheckpointDBOptions()` in `utilities/db_split_merge.cc`. 3. `DestroyDB()`: read its comment in `include/rocksdb/db.h`, then the rules table and the helpers above `DestroyDB()` in `db/db_impl/db_impl.cc`. 4. Secondary and follower, the open: read the comment "Store mode in a secondary or follower" at `ReactiveVersionSet::ReadStoreForCatchUp()` in `db/version_set.h`. Then read `ManifestStoreRead` in `db/manifest_store_state.h`, and `ReadStore()`, `BuildStoreManifestBytes()`, `OpenStoreRead()`, `ApplyStoreRead()`, `Recover()` and `MissingFilesAtStoreOpen()` in `db/version_set.cc`. 5. Secondary and follower, the catch-up: read `ReadStoreForCatchUp()`, then `ReadAndApply()` and `ApplyStoreCatchUp()` in `db/version_set.cc`. Then read `ManifestTailer::VerifyFile()` and `VerifyBlobFile()` in `db/version_edit_handler.h`, and the callers in `db/db_impl/db_impl_secondary.cc` and `db/db_impl/db_impl_follower.cc`. 6. Remote compaction: read `applied_commit_sequence()` in `db/manifest_store_state.h`, then `db/compaction/compaction_job.{h,cc}` and `compaction_service_job.cc`, then the floor check in `DBImplSecondary::OpenAndCompact()` (`db/db_impl/db_impl_secondary.cc`) and `CompactionServiceOptionsOverride::manifest_store` in `include/rocksdb/options.h`. 7. `ldb`: read `include/rocksdb/utilities/ldb_cmd.h` and `tools/ldb_tool.cc`, then `tools/ldb_cmd.cc`, with `VersionSet::DumpManifestFromStore()` in `db/version_set.cc`. 8. Tests: in `db/db_manifest_store_test.cc`, the tests from `Checkpoint` to the end are new. Then `LdbCmdTest.ManifestStore` in `tools/ldb_cmd_test.cc` and `db/db_basic_test.cc`. Differential Revision: D133614698
✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit a59eba9 SummaryLarge, well-structured PR that extends store mode to checkpoints, backups, secondaries, followers, remote compaction, DestroyDB, and ldb. The design is thorough with explicit crash-safety analysis, DB-mutex cost tables, and known-limitation documentation. The diff is truncated so this review covers only the visible portions. High-severity findings (2):
Full review (click to expand)Findings🔴 HIGHH1. Missing src.mk updates for new source files --
|
| Context | Does code execute? | Assumptions hold? | Action needed? |
|---|---|---|---|
| WritePreparedTxnDB | YES (store mode is orthogonal) | YES (read_callback visibility is unaffected) | None |
| ReadOnly DB | YES (MetadataInStore checks read_only_) | YES | None |
| CompactionService | YES (min_store_commit_sequence added) | YES (forward-compatible serialization) | None |
| User-defined timestamps | YES (RowsToRewriteAfterOpen handles timestamp_size changes) | YES | None |
| Concurrent writers | N/A (store mode uses single-writer claim) | YES | None |
| FIFO / Universal compaction | YES (compaction style is orthogonal) | YES | None |
| BlobDB (direct write) | YES (track_min_file_number added) | Mostly -- see M2 | Verify at scale |
Positive Observations
- Thorough crash-safety analysis: The PR description includes step-by-step state tables for every multi-step operation (create, enter, destroy), with explicit analysis of what state each crash leaves and how recovery handles it.
- Feature-off cost discipline:
track_min_file_number_gates the blob tracking overhead;MetadataInStore()gates the checkpoint path; the compaction input field defaults to 0 for backward compatibility. - DB mutex cost table: The PR description includes a table of work added under the DB mutex for each path, with measurements (e.g., "24 ms with 10,000 SSTs").
- Well-structured for review: The "How to read this diff" section with 8 ordered reading paths helps reviewers navigate the 17K-line change.
- Conditional destroy with conflict detection: DestroyDB uses
ManifestStoreDestroyOptionswith expected commit sequence to detect concurrent modifications, returning Busy instead of corrupting.
ℹ️ 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
Summary:
Background: the parent diff, "Add store mode: keep the MANIFEST metadata of a DB in a ManifestStore", adds store mode: with
DBOptions::manifest_storeset, the rows in aManifestStorehold the metadata of a DB, and the MANIFEST file that CURRENT names is only a small stub. Paths that copy, follow or delete a DB through its MANIFEST file could not work with a stub, so the parent diff makes them return NotSupported. This diff makes them work on a DB in store mode, so that an application can keep using checkpoints, backups, secondary and follower instances, remote compaction,DestroyDB()andldbafter it moves a DB into the store.Terms: the parent diff defines store mode, the DB row, the authority (kFile, kStore, kShadow), the stub and done stub, the commit sequence, epochs and claims, consistent scans and the copy files (see
db/manifest_store_state.handinclude/rocksdb/manifest_store.h). This diff adds one term:ManifestStoreState::applied_commit_sequence()). The next commit sends this same value as its expected commit sequence. A scan at or above it includes every commit of the primary so far.Previous behavior: on a DB in store mode,
GetLiveFiles(),GetLiveFilesStorageInfo()(and so checkpoints, backups and the stacked BlobDB),SplitDB()andMergeDB()(which use a checkpoint),DB::OpenAsSecondary()andDB::OpenAsFollower()with a store,compaction_servicewith a store,DB::OpenAndCompact(), andDestroyDB()return NotSupported.ldbhas no way to get the store.New behavior:
Two parts carry most of the design: (1)
GetLiveFilesStorageInfo()builds a MANIFEST from memory; (2) a secondary or follower reads the store and replays the rows as a new MANIFEST. The rest is small:DestroyDB(), the remote compaction floor,ldb, and split/merge.GetLiveFilesStorageInfo()gives the MANIFEST entry with its content inLiveFileStorageInfo::replacement_contents: a MANIFEST that RocksDB builds from the in-memory state. A copy of the DB is a normal DB in file mode. The MANIFEST entry keeps the file name of the stub; the copy writesreplacement_contentsunder that name, where the new CURRENT expects it. The stub bytes and the MANIFEST file copies stay in the source. A checkpoint of some column families leaves the other column families out of the built MANIFEST and, when the DB tracks the OPTIONS file number in the MANIFEST, records the OPTIONS file that the checkpoint writes, so no MANIFEST append is needed.GetLiveFiles()still returns NotSupported, because it names files for the caller to copy and no MANIFEST file that CURRENT can name holds the metadata.SplitDB()andMergeDB()work on a source in store mode: they open their checkpoint, a DB in file mode, without the store of the source.DB::OpenAsSecondary()andDB::OpenAsFollower()accept a store object (usually one without an epoch).DBOptions::open_files_async, or the trusted recovery of a remote compaction worker that got a floor, the open does not check files, so it does not detect this, as in file mode. A worker without a floor checks files, andDB::OpenAndCompact()retries its TryAgain.db/version_set.h.compaction_serviceworks with a store. The worker gets the store from the new fieldCompactionServiceOptionsOverride::manifest_store, because the OPTIONS file never holds it, and opens the DB as a store-mode secondary. WhenDBOptions::remote_compaction_manifest_flooris true in store mode, the primary sends the stub number in the existing fieldmin_manifest_file_numberand its applied commit sequence in the new compaction input fieldmin_store_commit_sequence. A nonzero stub number makes the worker open withtrust_manifest_recovery(as for the MANIFEST floor in file mode) and turns on the floor check: the worker refuses a scan whose replayed commit sequence is belowmin_store_commit_sequence(Incomplete, so the job can run locally). With the option false, both fields are 0. A worker reads an input without the field as "no floor", and an older worker skips the field.DestroyDB():DBOptions::manifest_store, it lists the folder, callsManifestStore::Destroy(), and then deletes the files, including the stub and the copy files. A listing error (other than a missing folder) or an error while reading CURRENT or the stub (for example a timeout) is returned before the rows are removed or any file is deleted, so the call can be repeated. A missing or broken file-mode MANIFEST is not such an error, and the DB is deleted as a file-mode DB. Without a store it still returns NotSupported.DestroyDB()of such a copy with the store of the source removes the rows of the source DB. TheDestroyDB()andGetLiveFilesStorageInfo()comments say to remove such a copy without the store (for example withDestroyDir()).Destroy()it reads the DB row and refuses (InvalidArgument, nothing deleted) when the row has a db id other than the stub's, so a store object of another DB given by mistake cannot remove that DB's rows.Destroy()gets the commit sequence and the last commit id of the checked DB row (or commit sequence 0 when there was none) inManifestStoreDestroyOptions. When another writer changed the DB row after the check (for example the DB that a checkpoint was taken from enters store mode at the same time), the store removes nothing, andDestroyDB()returns Busy without deleting any file. It does not retry.ManifestStore::Destroy()comment states that it returns OK when there is no DB row, soDestroyDB()can run again after a crash between the two steps; the stub that such a crash leaves names a DB that the store no longer has, andDB::Open()refuses it.ldb: the new global flag--manifest_store=<store>creates the store withManifestStore::CreateFromString()and passes it to every DB open throughLDBCommand::OpenDB()and toDB::ListColumnFamilies()(remote_compaction_primaryandremote_compaction_workerbuild their own options and do not use it). An unknown store name fails before any DB access. With the flag,ldb manifest_dump(without--path) prints the MANIFEST records from a consistent scan of the store.ldb dump_live_filesmakes its own consistent scan for its MANIFEST section, and takes its SST and blob file lists from the open DB, so the two sections can show different points in time. Both commands fail when the DB row names the MANIFEST file as the authority (after a rollback).LoadLatestOptions()and the other functions that read OPTIONS files from the folder already return NotSupported (parent diff), because they read that number from the MANIFEST file, which is a stub. With--manifest_store,ldbthen loads the OPTIONS file whose number the DB row records, and keeps only the column families that a consistent scan lists as live. A live column family that the OPTIONS file lacks gives Corruption.Implementation (file by file)
db/db_filesnapshot.cc,db/manifest_rows.cc: inGetLiveFilesStorageInfoImpl(), the newVersionSet::GetManifestRowsWithoutFiles()copies the DB row, the WAL rows and the column family rows in the DB mutex section that lists the live files, and refs the current Version and the ColumnFamilyData of each column family. In the same section, the existing loop that lists the live files records the files marked for compaction. The references and marks are kept inVersionSet::CheckpointRowsRefs. After the unlock,VersionSet::AddManifestFileRows()adds the file rows from those Versions (with a newVersionEdit::AddExistingFile()overload indb/version_edit.{h,cc}that takes the recorded mark), andManifestRowsToRecords()andRecordsToManifestBytes()encode the rows.VersionSet::ReleaseCheckpointRowsRefs()unrefs the Versions and ColumnFamilyData in a second short DB mutex section whenGetLiveFilesStorageInfoImpl()returns. A live file pin that the caller asked for is separate and stays until the caller releases it. The newDBImpl::MetadataInStore()tells the copy paths that the MANIFEST file is a stub: a primary whose VersionSet commits to the store, or a read-only, secondary or follower instance with a store in its options.utilities/checkpoint/checkpoint_impl.cc: the checkpoint acceptsreplacement_contentsfor the MANIFEST, and the subset checkpoint skips the CF-drop append in store mode.db/version_set.{h,cc},db/db_impl/db_impl_secondary.cc,db/db_impl/db_impl_follower.cc:ReactiveVersionSet::OpenStoreRead()reads the store for the open. When a scanned file is missing,Recover()callsMissingFilesAtStoreOpen(), which reads the DB row and returns TryAgain after a newer commit (unless a scanned file exists but fails its check), else Corruption with the file numbers from the newManifestTailer::NewestStateMissingFileNumbers()andVersionBuilder::GetMissingFileNumbers().ApplyStoreRead()records the attempted commit sequence, and the catch-up callers free the scanned rows after they release the DB mutex.ApplyStoreCatchUp()skips a scan below the attempted commit sequence or at or below the installed one.ReadAndApply()records the commit sequence of a catch-up scan as installed only when the tailer installed the Versions of all column families (newManifestTailer::CanInstallVersions(), called byVersionEditHandlerPointInTime::CheckIterationResult(); it returns true outside a store-mode catch-up, so file mode does not change).ReadStoreForCatchUp()reads the store and builds the records without the DB mutex.ReadAndApply()callsApplyStoreCatchUp()with the DB mutex held, in place ofMaybeSwitchManifest(). The steps, locks and errors are in the comment "Store mode in a secondary or follower" atReadStoreForCatchUp(). The records reach the tailer throughNewStringSequentialFile(), whose file frees its bytes when a read reaches the end.VersionSet::DumpManifestFromStore()usesBuildStoreManifestBytes()and shares the print code withDumpManifest()(DumpManifestRecords()).db/version_edit_handler.{h,cc},db/version_builder.cc: the new virtual functionsVersionEditHandler::HeldFile()andHeldBlobFile()return null, except inManifestTailerduring a store-mode catch-up, where they return the metadata object of a held file in the current Version.VersionBuilderthen adds a reference to that object instead of making a new one. In file mode both functions return null, so file mode does not change.ManifestTailer::VerifyFile()and the newVerifyBlobFile()skip a held file. Such a file was checked when the instance added it (or is checked by the asynchronous file opening of the open, withDBOptions::open_files_async). During the open in store mode, the tailer records the files whose check returns Corruption, andMissingFilesAtStoreOpen()uses that set; the open frees it after use, and file mode and catch-ups record nothing. The comment "Held files in store mode" indb/version_edit_handler.hhas the details.db/manifest_store_state.{h,cc}: the applied commit sequence (applied_commit_sequence_) is astd::atomic, so that other threads can read it withManifestStoreState::applied_commit_sequence(). The new helperStoreModeOptions()tells the reader paths (read-only, secondary and follower instances, and the remote compaction worker) that the options give a store, so they read the metadata from the store.db/compaction/:CompactionJobcaptures the applied commit sequence, andCompactionServiceInputserializes it asmin_store_commit_sequence.db/db_impl/db_impl_secondary.cc: the worker copies the store from the override and checks the floor.db/db_impl/db_impl_open.cc:DBImpl::CheckManifestStoreOptions()accepts a store for every open function and withcompaction_service;best_efforts_recoveryandbest_efforts_blob_db_repairwith a store stay InvalidArgument.db/db_impl/db_impl.cc:DestroyDB()and its helpersDestroyManifestStoreRows(),ReadFileModeDbId()(which reads the IDENTITY file withReadDbIdFromIdentityFile()of the parent diff) andDestroyRolledBackRows(), with the rules table above them.tools/ldb_cmd.cc,include/rocksdb/utilities/ldb_cmd.h,tools/ldb_tool.cc: they addLDBCommand::ARG_MANIFEST_STOREand the protected memberLDBCommand::manifest_store_, load the committed OPTIONS file from the DB row, and dump the store.utilities/db_split_merge.cc: the options of the checkpoint DB have no store, no migration and no copy mode.Mutex: the new work under the DB mutex, by path. The work that grows with the number of live files is O(live files). The Test Plan has the measured hold time of a catch-up.
GetLiveFilesStorageInfo()in store mode (primary)ReadDbRow(), the scan (only when the commit sequence changed), building the records, and freeing the scanned rows after the replay; a separate mutex makes concurrent catch-ups call the store one at a timeSafety boundaries and unsupported cases:
GetLiveFiles(),RepairDB(), and the tools that read or rewrite the MANIFEST file offline (ldb reduce_levels,update_manifest,unsafe_remove_sst_file,file_checksum_dump,repair) return NotSupported in store mode.DestroyDB()with it returns NotSupported.DestroyDB()also returns the error of a stub that this binary cannot decode (for example a stub of a newer binary) and keeps the rows.GetLiveFilesStorageInfo()that ignoresreplacement_contentsfor the MANIFEST entry copies the stub. Opened without a store, such a copy fails with NotSupported. It must never be opened with a store object of the source DB: that open claims the rows of the source, and the source stops. TheGetLiveFilesStorageInfo()comment says so.manifest_store_migratereturns InvalidArgument (a rule of the parent diff), so a copy cannot take over the rows of the source.DestroyDB()of such a copy with the store of the source keeps the rows of the source, because they have authority kStore.ldbcommands that open the DB for writing (for examplecheckpointandbackup) claim the DB, which fences the running primary. These commands need such an object. Read-only commands never claim. The help text says so.CompactionServiceOptionsOverride::manifest_storefails on the stub with NotSupported.DestroyDB()).Known limitations:
RollBackManifestStore()says to stop every instance of the DB before the call.Changes visible to existing users: the new field
CompactionServiceOptionsOverride::manifest_store, the newldbflag--manifest_storeandLDBCommand::ARG_MANIFEST_STORE, the updated comments ofLiveFileStorageInfo::replacement_contents,DB::GetLiveFiles(),DB::GetLiveFilesStorageInfo(),DestroyDB(),DBOptions::manifest_store,DBOptions::remote_compaction_manifest_floorand the store mode overview ininclude/rocksdb/manifest_store.h, and the release note. For a DB in file mode, the serialized compaction input has one more field, with the value 0, andDestroyDB()with a store in the options reads the DB row (see New behavior).How to read this diff:
include/rocksdb/manifest_store.h, then the "Copies of the DB", "Remote compaction" and "DestroyDB()" paragraphs and theStoreModeOptions()table indb/manifest_store_state.h.VersionSet::CheckpointRowsRefscomment indb/version_set.h, thendb/manifest_rows.cc, thenGetLiveFilesStorageInfoImpl()indb/db_filesnapshot.ccwithDBImpl::MetadataInStore()indb/db_impl/db_impl.h. Finish withutilities/checkpoint/checkpoint_impl.ccandGetCheckpointDBOptions()inutilities/db_split_merge.cc.DestroyDB(): read its comment ininclude/rocksdb/db.h, then the rules table and the helpers aboveDestroyDB()indb/db_impl/db_impl.cc.ReactiveVersionSet::ReadStoreForCatchUp()indb/version_set.h. Then readManifestStoreReadindb/manifest_store_state.h, andReadStore(),BuildStoreManifestBytes(),OpenStoreRead(),ApplyStoreRead(),Recover()andMissingFilesAtStoreOpen()indb/version_set.cc.ReadStoreForCatchUp(), thenReadAndApply()andApplyStoreCatchUp()indb/version_set.cc. Then readManifestTailer::VerifyFile()andVerifyBlobFile()indb/version_edit_handler.h, and the callers indb/db_impl/db_impl_secondary.ccanddb/db_impl/db_impl_follower.cc.applied_commit_sequence()indb/manifest_store_state.h, thendb/compaction/compaction_job.{h,cc}andcompaction_service_job.cc, then the floor check inDBImplSecondary::OpenAndCompact()(db/db_impl/db_impl_secondary.cc) andCompactionServiceOptionsOverride::manifest_storeininclude/rocksdb/options.h.ldb: readinclude/rocksdb/utilities/ldb_cmd.handtools/ldb_tool.cc, thentools/ldb_cmd.cc, withVersionSet::DumpManifestFromStore()indb/version_set.cc.db/db_manifest_store_test.cc, the tests fromCheckpointto the end are new. ThenLdbCmdTest.ManifestStoreintools/ldb_cmd_test.ccanddb/db_basic_test.cc.Differential Revision: D133614698