Repository navigation
Long-running compactions no longer delay deleting obsolete SSTs - #15710
pdillinger wants to merge 1 commit into
Conversation
|
@pdillinger has exported this pull request. If you are a Meta employee, you can view the originating Diff in D130987455. |
|
| Check | Count |
|---|---|
performance-inefficient-vector-operation |
1 |
| Total | 1 |
Details
db/listener_test.cc (1 warning(s))
db/listener_test.cc:2226:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 19a04b5 SummaryThis is a well-designed change that solves a real production problem (long-running remote compactions preventing deletion of unrelated obsolete SSTs). The core insight is sound: files in High-severity findings (0): No high-severity findings. Full review (click to expand)Findings🟡 MEDIUMM1. Stress test
|
| Context | Affected? | Safe? | Notes |
|---|---|---|---|
| WritePreparedTxnDB | YES | YES | Same flush/compaction paths |
| ReadOnly DB | NO | N/A | No background jobs |
| SecondaryInstance | Consumer | YES | ManifestTailer handles missing files |
| CompactionService | YES | YES | Core benefit of the change |
| CF drop during compaction | YES | YES | CF drop triggers FindObsoleteFiles |
| DB shutdown | YES | YES | Defer releases; shutdown drains jobs |
| CompactFiles() | YES | YES | Also purges obsolete files |
| FIFO compaction | YES | YES | Delete and temp-copy paths handled |
| Blob files | Unchanged | YES | Intentionally still use min_pending_output |
Positive Observations
- Sound core design: The separation of "unrecognized files from directory scan" vs "known-obsolete files from VersionSet" is clean and well-reasoned.
- Pragmatic listener compromise: Registration timing (flush: start-to-end; compaction: pre-install to post-callbacks) correctly balances correctness with the problem being solved.
- Comprehensive testing: Three new tests (remote compaction pinning, flush listener, compaction listener) plus stress test runtime verification.
- Good use of Defer: Ensures cleanup on all exit paths in both production code and tests.
- Correct blob file carve-out: Blob files are intentionally excluded because
VersionBuildercan report them obsolete without them having been in an installed Version. - Clear documentation: Updated
kMinObsoleteSstNumberToKeepdocs and thoroughlistener_pending_outputs_member comments.
ℹ️ 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
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
19a04b5 to
a4eec58
Compare
✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit a4eec58 SummaryWell-designed change that solves a real problem (obsolete SSTs piling up during long-running remote compactions) with a minimal, focused approach. The core safety argument -- that files in High-severity findings (0): No high-severity findings. Full review (click to expand)Findings🟡 MEDIUMM1.
|
| Context | Affected? | Analysis |
|---|---|---|
| Secondary instances | Yes | May find files deleted sooner. Already handle missing files via ManifestTailer. Safe. |
| ReadOnly DB | No | No compactions run. |
| Remote compaction workers | Indirect | Workers don't use pending_outputs_. Primary benefits from this change. |
| WritePreparedTxnDB | No | Same background compaction paths, no special interaction. |
| External file ingestion | No | Uses pending_ingestion_outputs_, unaffected. |
| Checkpoint / Backup | No | Neither depends on kMinObsoleteSstNumberToKeep. |
| DB::Close / shutdown | Safe | listener_pending_outputs_ entries released by Defer. NotifyOnCompactionCompleted skips callbacks during shutdown, Defer still runs. |
| Error recovery | Safe | Same FindObsoleteFiles/PurgeObsoleteFiles paths with correct logic. |
Assumption Stress Test
Claim: "Every SST in obsolete_files_ was part of an installed Version"
- Verified: Only insertion path is
~Version()(version_set.cc:1064) whenFileMetaData::refsdrops to 0. Failed compaction outputs are cleaned up via job context, notobsolete_files_.
Claim: "Inputs of a running compaction are protected by Version reference"
- Verified:
Compactionholdsinput_version_->Ref(). Input files don't enterobsolete_files_while compaction runs.
Claim: "Blob files need different treatment"
- Verified:
VersionBuildercan callAddObsoleteBlobFile()directly without the file having been in an installed Version. Correctly preserved.
Defer safety on all BackgroundCompaction return paths:
- Verified: The
Defer release_listener_pending_outputis defined early in the function (after the if-else branch determination). All paths -- no compaction picked, deletion, trivial move, forward to bottom, trivial copy, non-trivial, failure -- return through the same scope where the Defer runs.ReleaseListenerPendingOutputis safe withstd::nullopt(checkshas_value()first).
Positive Observations
- Clean separation of concerns:
listener_pending_outputs_is nicely separated frompending_outputs_with clear documentation. - Defense in depth: Multiple layers of protection preserved (pending_outputs for directory scans, listener_pending for callbacks, Version refs for inputs, live-file set for current files).
- Thorough testing: Three complementary strategies (deterministic unit tests, probabilistic stress test, existing tests updated).
- Well-documented behavioral change:
listener.h,db.h, and release note all clearly communicate the change. - Correct Defer usage: Handles all return paths including early returns where
listener_pending_outputstaysstd::nullopt. - Intentional compromise well-justified: Lower-bound approach vs exact tracking is well-reasoned with alternatives enumerated.
ℹ️ 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 a813464. |
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 asrocksdb.min-obsolete-sst-number-to-keep). The purge applies this cutoff to every SST: both files found by scanning the DB directories and files thatVersionSetalready 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 inPurgeObsoleteFiles(). That leaked files: a file taken fromobsolete_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 inVersionSet::GetObsoleteFiles(), so such files stay inobsolete_files_until the cutoff moves past them. AFIXMEleft inPurgeObsoleteFiles()asks whether these files should be held back at all. More recently, #15490 stopped prepared external ingestions from holding apending_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-sizeshows the growth.Previous behavior
GetObsoleteFiles()handed off only obsolete SSTs numbered belowmin_pending_output; the rest stayed inobsolete_files_.PurgeObsoleteFiles()kept every SST candidate numbered at or abovemin_pending_output, from either source.New behavior
The purge deletes an SST that
VersionSetreports as obsolete, whatever jobs are still running, apart from a brief exception when event listeners are configured (below).GetObsoleteFiles()hands off all obsolete SSTs, andPurgeObsoleteFiles()applies the cutoff only to SST candidates that came from the directory scan. Both parts are needed: changing onlyGetObsoleteFiles()would bring back the 2015 leak.Unchanged:
obsolete_files_.only_delete_metadata.VersionBuildercan 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 itsOnFlushCompleted()orOnCompactionCompleted()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.EventListenerdid 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, itspending_outputs_number is also registered there, andGetObsoleteFiles()leaves obsolete SSTs at or above the smallest registered number inobsolete_files_for a later purge. A compaction registers just before installing its outputs and unregisters afterOnCompactionCompleted()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 thatOnCompactionCompleted()reports (including trivially moved files), and files reported toOnExternalFileIngested(), 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:MemTableList::TryInstallMemtableFlushResults()andCompactionJob::Install()at each install site, roughly 2.5 to 3 times the code, only to delete some files a little sooner.Consequences
rocksdb.min-obsolete-sst-number-to-keepreturns 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 Limit prepared ingestion SST protection to reserved files #15490, this change adds no option to restore the previous behavior.DB::OpenAndCompact(), may find obsolete SSTs deleted sooner than before. They already handle this for files below the cutoff: they read the MANIFEST throughManifestTailer, which builds the most recent Version that has no missing files.Bonus:
CLAUDE.mdgets 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 thedb_stresscheck described in the test plan.Reviewed By: jaykorean
Differential Revision: D130987455