Repository navigation
Limit prepared ingestion SST protection to reserved files - #15490
joshkang97 wants to merge 1 commit into
Conversation
|
@joshkang97 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D127694250. |
✅ clang-tidy: No findings on changed linesCompleted in 345.6s. |
Summary: Pull Request resolved: meta#15490 ## Summary Prepared external ingestions held a `pending_outputs_` watermark until commit or abort, preventing reclamation of unrelated SSTs created later and compacted away. Prepared ingestions now protect only their reserved SST numbers through `pending_ingestion_outputs_` (`first_file_number` -> `num_files`), copied into full-purge `sst_live` snapshots. This preserves staged inputs and generated tombstones while allowing unrelated obsolete SSTs to be deleted. Successful manifest completion releases reservations under the DB mutex after all Versions are installed, including grouped commits performed by another writer. Waiting for the ingestion caller to resume could otherwise let purge claim a compacted input and retain it through the stale reservation, leaving its grabbed marker behind. Failure and abort retain protection through cleanup. Public APIs and persisted formats are unchanged, existing background-output protection remains in place, and handles still retain other resources until consumed. ## Example Keep a prepared handle open for SST `100`, containing key `z`. Meanwhile, normal DB writes update another key, `a`. The SST numbers are illustrative. ```text Prepare ingestion: SST 100: key z (staged, awaiting commit) Unrelated DB activity: flush a=old --> SST 101 --+ +--> compaction --> SST 103 (live) flush a=new --> SST 102 --+ 101 and 102 become obsolete Files remaining after full purge, before commit/abort: SST State Before fix After fix 100 staged kept kept 101 obsolete kept deleted 102 obsolete kept deleted 103 live kept kept ``` `100` is not yet visible to reads or compaction. After compaction releases its input references, the old watermark still protects obsolete `101` and `102`. The new reservation protects only staged `100`; `103` remains because it is live. Differential Revision: D127694250
5aacc3a to
2a72f4f
Compare
Summary: X-link: meta#15490 ## Summary Prepared external ingestions held a `pending_outputs_` watermark until commit or abort, preventing reclamation of unrelated SSTs created later and compacted away. Prepared ingestions now protect only their reserved SST numbers through `pending_ingestion_outputs_` (`first_file_number` -> `num_files`), copied into full-purge `sst_live` snapshots. This preserves staged inputs and generated tombstones while allowing unrelated obsolete SSTs to be deleted. Successful manifest completion releases reservations under the DB mutex after all Versions are installed, including grouped commits performed by another writer. Waiting for the ingestion caller to resume could otherwise let purge claim a compacted input and retain it through the stale reservation, leaving its grabbed marker behind. Failure and abort retain protection through cleanup. Public APIs and persisted formats are unchanged, existing background-output protection remains in place, and handles still retain other resources until consumed. ## Example Keep a prepared handle open for SST `100`, containing key `z`. Meanwhile, normal DB writes update another key, `a`. The SST numbers are illustrative. ```text Prepare ingestion: SST 100: key z (staged, awaiting commit) Unrelated DB activity: flush a=old --> SST 101 --+ +--> compaction --> SST 103 (live) flush a=new --> SST 102 --+ 101 and 102 become obsolete Files remaining after full purge, before commit/abort: SST State Before fix After fix 100 staged kept kept 101 obsolete kept deleted 102 obsolete kept deleted 103 live kept kept ``` `100` is not yet visible to reads or compaction. After compaction releases its input references, the old watermark still protects obsolete `101` and `102`. The new reservation protects only staged `100`; `103` remains because it is live. Reviewed By: xingbowang Differential Revision: D127694250
2a72f4f to
fd77489
Compare
✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit fd77489 SummaryWell-designed change that replaces an overly-broad watermark-based file protection mechanism with targeted tracking of specific ingestion file ranges. The correctness reasoning is sound: the manifest write callback fires under mutex after all Versions are installed, the non-full-scan path is inherently safe (ingestion files cannot enter No high-severity findings. Full review (click to expand)Findings🔴 HIGHNone. 🟡 MEDIUMM1. Capture-by-reference
|
| Context | Code executes? | Assumptions hold? | Action needed? |
|---|---|---|---|
| WritePreparedTxnDB | Yes (ingestion goes through same path) | Yes | Safe |
| ReadOnly DB | No (ingestion not supported) | N/A | Safe |
| CompactionService | No (ingestion runs on primary) | N/A | Safe |
| User-defined timestamps | Yes | Yes (file numbering unaffected) | Safe |
| Column family drop | Yes (caught at commit time with error) | Yes | Safe |
| db_paths (multi-path) | Yes (ingestion always path_id=0, full scan covers all paths) | Yes | Safe |
| FIFO / Universal compaction | Yes | Yes (file numbering unaffected) | Safe |
Non-full-scan path safety: Files enter obsolete_files_ only when Version::Unref drops a file's refcount to zero (version_set.cc:1045-1057). Ingestion files are not in any Version until commit, so they cannot appear in obsolete_files_. The non-full-scan path only processes files from GetObsoleteFiles, so no protection is needed there. Verified.
Grouped commit callback ordering: finish_batch processes ALL writers in the batch sequentially (version_set.cc:5930-5951), calling each writer's callback. The callback on the last writer erases all handles' entries. This fires after all Versions are installed (line 6454+) and under mutex (line 6411). Even when another thread is the batch leader, the ingestion thread blocks on cv.Wait() until finish_batch completes. Verified safe.
Assumption stress test:
- Claim: "contiguous file number range."
FetchAddFileNumber(n)isnext_file_number_.fetch_add(n)(version_set.h:1565), atomic. Called under mutex. Returns start of contiguous range. Verified. - Claim: "no double-erase." On success: only manifest_wcb erases (old post-LogAndApply erase removed). On failure: only rollback erases (manifest_wcb checks
s.ok()).UnorderedMap::erasewith missing key is a no-op. Verified. - Claim: "crash recovery is safe."
pending_ingestion_outputs_is in-memory only. After crash, files exist on disk but are not in any Version. Next full-scan purge finds them not insst_live(no in-memory map) and deletes them. Same as old behavior. Verified.
Positive Observations
- The design correctly separates concerns: background jobs use the
pending_outputs_watermark (appropriate for monotonically increasing file numbers), while ingestion uses precise file-range tracking. - Using manifest write callbacks ensures the reservation is released atomically with Version installation, closing a subtle race window in grouped commits.
- Test coverage is thorough: the grouped commit test (
PreparedIngestionGroupedCommitDoesNotKeepObsoleteSsts) uses sync points to precisely control thread interleaving and verify the callback fires correctly even when another thread performs the manifest write. - The
PreparedIngestionProtectsGeneratedTombstonetest verifies that range tombstone files generated duringatomic_replace_rangeare also protected, covering theNumFilesToPrepareaccounting.
ℹ️ 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
|
This pull request has been merged in 800b574. |
Summary:
## Background
RocksDB deletes an SST file once it is obsolete, meaning no Version references it anymore, usually because a compaction replaced it. Files that a running flush or compaction is still writing are also in no Version, but they must not be deleted. To protect them, each flush or compaction records the next file number in `pending_outputs_` when it starts. The obsolete-file purge then skips every SST numbered at or above the smallest recorded number (`min_pending_output`, exposed as `rocksdb.min-obsolete-sst-number-to-keep`). The purge applies this cutoff to every SST: both files found by scanning the DB directories and files that `VersionSet` already knows are obsolete (`obsolete_files_`, filled when the last Version referencing a file is destroyed).
`53af5d877` ("Redesign pending_outputs_", 2014) introduced the cutoff, replacing tracking of each job's exact output file numbers. At first the cutoff was applied only in `PurgeObsoleteFiles()`. That leaked files: a file taken from `obsolete_files_` and then held back was neither deleted nor tracked until the next full directory scan. `863009b5a` ("Fix deleting obsolete files meta#2", 2015) fixed the leak by also applying the cutoff in `VersionSet::GetObsoleteFiles()`, so such files stay in `obsolete_files_` until the cutoff moves past them. A `FIXME` left in `PurgeObsoleteFiles()` asks whether these files should be held back at all. More recently, [meta#15490](meta#15490) stopped prepared external ingestions from holding a `pending_outputs_` entry. They now protect only their reserved file numbers, so a long-lived prepared ingestion no longer holds back unrelated obsolete SSTs.
## The problem
While a long-running job is in progress, obsolete SSTs pile up on disk. Every SST created after the job started and since compacted away is kept until the job finishes, even though none of them can be an unfinished output: each was part of an installed Version, so holding it back protects nothing. Usually the wait is short, but a remote compaction can wait in `CompactionService::Wait()` for hours or days. Under a steady write load, obsolete SSTs can then grow to many times the size of the live data and fill the disk; `rocksdb.obsolete-sst-files-size` shows the growth.
## Previous behavior
- `GetObsoleteFiles()` handed off only obsolete SSTs numbered below `min_pending_output`; the rest stayed in `obsolete_files_`.
- `PurgeObsoleteFiles()` kept every SST candidate numbered at or above `min_pending_output`, from either source.
## New behavior
The purge deletes an SST that `VersionSet` reports as obsolete, whatever jobs are still running, apart from a brief exception when event listeners are configured (below). `GetObsoleteFiles()` hands off all obsolete SSTs, and `PurgeObsoleteFiles()` applies the cutoff only to SST candidates that came from the directory scan. Both parts are needed: changing only `GetObsoleteFiles()` would bring back the 2015 leak.
Unchanged:
- Unfinished outputs are found only by the directory scan, so the cutoff still protects them.
- Inputs of a running compaction stay protected: the compaction holds a reference on its input Version, so they never reach `obsolete_files_`.
- Live files, including trivially moved ones, are still excluded by the live-file set and `only_delete_metadata`.
- Files quarantined after a failed MANIFEST write are still checked before anything else.
- Obsolete blob files still honor the cutoff. `VersionBuilder` can report a blob file obsolete without it having been part of an installed Version, so the argument above does not cover them.
## Keeping event listener outputs available
The cutoff also had a side effect that listeners can observe. A job removes its `pending_outputs_` entry only after its `OnFlushCompleted()` or `OnCompactionCompleted()` callbacks return, so RocksDB did not delete the files those callbacks report while the callbacks ran, even if another compaction made them obsolete in the meantime. `EventListener` did not document this, but a listener that opens, copies, or links a reported file might depend on it. Without the cutoff for known-obsolete files, such a listener could find the file already deleted.
To keep that behavior, this change keeps a narrower form of the cutoff for known-obsolete SSTs, in `DBImpl::listener_pending_outputs_`. While a job might still report its outputs to listeners, its `pending_outputs_` number is also registered there, and `GetObsoleteFiles()` leaves obsolete SSTs at or above the smallest registered number in `obsolete_files_` for a later purge. A compaction registers just before installing its outputs and unregisters after `OnCompactionCompleted()` returns, so a remote compaction holds nothing back while it waits. A flush registers for its whole duration, which also covers a flush that installs its outputs over several MANIFEST writes. Nothing is registered when no listeners are configured.
This change also documents the behavior in `listener.h`, as best effort rather than a guarantee: RocksDB actively avoids deleting a file before a callback that reports it returns. The documented exceptions predate this change: the inputs that `OnCompactionCompleted()` reports (including trivially moved files), and files reported to `OnExternalFileIngested()`, whose protection ends when the ingestion is committed, before the callback runs.
Registering a lower bound on file numbers, as `pending_outputs_` does, rather than the exact output file numbers is a deliberate compromise, because more precision has diminishing returns. With listeners configured, RocksDB therefore still keeps unrelated obsolete SSTs created after a job started while a flush runs or while a compaction's completion callbacks run. That retention lasts as long as a local flush or the callbacks, not as long as a compaction waits. Alternatives considered:
- Track the exact output file numbers. This alternative keeps only the reported files, but the numbers would have to be passed out of `MemTableList::TryInstallMemtableFlushResults()` and `CompactionJob::Install()` at each install site, roughly 2.5 to 3 times the code, only to delete some files a little sooner.
- Hold a reference on the current Version while listeners run. This alternative is simpler, but the reference is taken after the outputs are installed, so it misses a flush that installs its outputs over several MANIFEST writes if a compaction deletes an earlier output in between.
- Keep newly installed outputs from being picked by compactions until listeners have been notified. A slow listener would then block compaction of new L0 files.
## Consequences
- `rocksdb.min-obsolete-sst-number-to-keep` returns the same value as before, but now bounds only unrecognized files found by a directory scan, not known-obsolete SSTs (apart from the brief retention with listeners described above). Its documentation is updated. An application that read the property to decide which obsolete SSTs it could still copy or link out of band would be affected. Like meta#15490, this change adds no option to restore the previous behavior.
- Secondary instances, including remote compaction workers opened by `DB::OpenAndCompact()`, may find obsolete SSTs deleted sooner than before. They already handle this for files below the cutoff: they read the MANIFEST through `ManifestTailer`, which builds the most recent Version that has no missing files.
Bonus: `CLAUDE.md` gets guidance on keeping crash test checks for one feature cheap, so that they do not take time and operations away from finding other failures. The guidance comes from designing the `db_stress` check described in the test plan.
Reviewed By: jaykorean
Differential Revision: D130987455
Summary: Pull Request resolved: #15710 ## Background RocksDB deletes an SST file once it is obsolete, meaning no Version references it anymore, usually because a compaction replaced it. Files that a running flush or compaction is still writing are also in no Version, but they must not be deleted. To protect them, each flush or compaction records the next file number in `pending_outputs_` when it starts. The obsolete-file purge then skips every SST numbered at or above the smallest recorded number (`min_pending_output`, exposed as `rocksdb.min-obsolete-sst-number-to-keep`). The purge applies this cutoff to every SST: both files found by scanning the DB directories and files that `VersionSet` already knows are obsolete (`obsolete_files_`, filled when the last Version referencing a file is destroyed). `53af5d877` ("Redesign pending_outputs_", 2014) introduced the cutoff, replacing tracking of each job's exact output file numbers. At first the cutoff was applied only in `PurgeObsoleteFiles()`. That leaked files: a file taken from `obsolete_files_` and then held back was neither deleted nor tracked until the next full directory scan. `863009b5a` ("Fix deleting obsolete files #2", 2015) fixed the leak by also applying the cutoff in `VersionSet::GetObsoleteFiles()`, so such files stay in `obsolete_files_` until the cutoff moves past them. A `FIXME` left in `PurgeObsoleteFiles()` asks whether these files should be held back at all. More recently, [#15490](#15490) stopped prepared external ingestions from holding a `pending_outputs_` entry. They now protect only their reserved file numbers, so a long-lived prepared ingestion no longer holds back unrelated obsolete SSTs. ## The problem While a long-running job is in progress, obsolete SSTs pile up on disk. Every SST created after the job started and since compacted away is kept until the job finishes, even though none of them can be an unfinished output: each was part of an installed Version, so holding it back protects nothing. Usually the wait is short, but a remote compaction can wait in `CompactionService::Wait()` for hours or days. Under a steady write load, obsolete SSTs can then grow to many times the size of the live data and fill the disk; `rocksdb.obsolete-sst-files-size` shows the growth. ## Previous behavior - `GetObsoleteFiles()` handed off only obsolete SSTs numbered below `min_pending_output`; the rest stayed in `obsolete_files_`. - `PurgeObsoleteFiles()` kept every SST candidate numbered at or above `min_pending_output`, from either source. ## New behavior The purge deletes an SST that `VersionSet` reports as obsolete, whatever jobs are still running, apart from a brief exception when event listeners are configured (below). `GetObsoleteFiles()` hands off all obsolete SSTs, and `PurgeObsoleteFiles()` applies the cutoff only to SST candidates that came from the directory scan. Both parts are needed: changing only `GetObsoleteFiles()` would bring back the 2015 leak. Unchanged: - Unfinished outputs are found only by the directory scan, so the cutoff still protects them. - Inputs of a running compaction stay protected: the compaction holds a reference on its input Version, so they never reach `obsolete_files_`. - Live files, including trivially moved ones, are still excluded by the live-file set and `only_delete_metadata`. - Files quarantined after a failed MANIFEST write are still checked before anything else. - Obsolete blob files still honor the cutoff. `VersionBuilder` can report a blob file obsolete without it having been part of an installed Version, so the argument above does not cover them. ## Keeping event listener outputs available The cutoff also had a side effect that listeners can observe. A job removes its `pending_outputs_` entry only after its `OnFlushCompleted()` or `OnCompactionCompleted()` callbacks return, so RocksDB did not delete the files those callbacks report while the callbacks ran, even if another compaction made them obsolete in the meantime. `EventListener` did not document this, but a listener that opens, copies, or links a reported file might depend on it. Without the cutoff for known-obsolete files, such a listener could find the file already deleted. To keep that behavior, this change keeps a narrower form of the cutoff for known-obsolete SSTs, in `DBImpl::listener_pending_outputs_`. While a job might still report its outputs to listeners, its `pending_outputs_` number is also registered there, and `GetObsoleteFiles()` leaves obsolete SSTs at or above the smallest registered number in `obsolete_files_` for a later purge. A compaction registers just before installing its outputs and unregisters after `OnCompactionCompleted()` returns, so a remote compaction holds nothing back while it waits. A flush registers for its whole duration, which also covers a flush that installs its outputs over several MANIFEST writes. Nothing is registered when no listeners are configured. This change also documents the behavior in `listener.h`, as best effort rather than a guarantee: RocksDB actively avoids deleting a file before a callback that reports it returns. The documented exceptions predate this change: the inputs that `OnCompactionCompleted()` reports (including trivially moved files), and files reported to `OnExternalFileIngested()`, whose protection ends when the ingestion is committed, before the callback runs. Registering a lower bound on file numbers, as `pending_outputs_` does, rather than the exact output file numbers is a deliberate compromise, because more precision has diminishing returns. With listeners configured, RocksDB therefore still keeps unrelated obsolete SSTs created after a job started while a flush runs or while a compaction's completion callbacks run. That retention lasts as long as a local flush or the callbacks, not as long as a compaction waits. Alternatives considered: - Track the exact output file numbers. This alternative keeps only the reported files, but the numbers would have to be passed out of `MemTableList::TryInstallMemtableFlushResults()` and `CompactionJob::Install()` at each install site, roughly 2.5 to 3 times the code, only to delete some files a little sooner. - Hold a reference on the current Version while listeners run. This alternative is simpler, but the reference is taken after the outputs are installed, so it misses a flush that installs its outputs over several MANIFEST writes if a compaction deletes an earlier output in between. - Keep newly installed outputs from being picked by compactions until listeners have been notified. A slow listener would then block compaction of new L0 files. ## Consequences - `rocksdb.min-obsolete-sst-number-to-keep` returns the same value as before, but now bounds only unrecognized files found by a directory scan, not known-obsolete SSTs (apart from the brief retention with listeners described above). Its documentation is updated. An application that read the property to decide which obsolete SSTs it could still copy or link out of band would be affected. Like #15490, this change adds no option to restore the previous behavior. - Secondary instances, including remote compaction workers opened by `DB::OpenAndCompact()`, may find obsolete SSTs deleted sooner than before. They already handle this for files below the cutoff: they read the MANIFEST through `ManifestTailer`, which builds the most recent Version that has no missing files. Bonus: `CLAUDE.md` gets guidance on keeping crash test checks for one feature cheap, so that they do not take time and operations away from finding other failures. The guidance comes from designing the `db_stress` check described in the test plan. Reviewed By: jaykorean Differential Revision: D130987455 fbshipit-source-id: 1ec9c7127bec6017a6742b98bb53dba45139e87d
Summary:
X-link: #15490
Summary
Prepared external ingestions held a
pending_outputs_watermark until commit or abort, preventing reclamation of unrelated SSTs created later and compacted away. Prepared ingestions now protect only their reserved SST numbers throughpending_ingestion_outputs_(first_file_number->num_files), copied into full-purgesst_livesnapshots. This preserves staged inputs and generated tombstones while allowing unrelated obsolete SSTs to be deleted.Successful manifest completion releases reservations under the DB mutex after all Versions are installed, including grouped commits performed by another writer. Waiting for the ingestion caller to resume could otherwise let purge claim a compacted input and retain it through the stale reservation, leaving its grabbed marker behind. Failure and abort retain protection through cleanup. Public APIs and persisted formats are unchanged, existing background-output protection remains in place, and handles still retain other resources until consumed.
Example
Keep a prepared handle open for SST
100, containing keyz. Meanwhile, normal DB writes update another key,a. The SST numbers are illustrative.100is not yet visible to reads or compaction. After compaction releases its input references, the old watermark still protects obsolete101and102. The new reservation protects only staged100;103remains because it is live.Reviewed By: xingbowang
Differential Revision: D127694250