Skip to content

13/14: Handle lost relocation files and dropped origins (#15720) - #15720

Open
xingbowang wants to merge 13 commits into
meta:mainfrom
xingbowang:export-D132305446
Open

xingbowang wants to merge 13 commits into
meta:mainfrom
xingbowang:export-D132305446

Conversation

@xingbowang

@xingbowang xingbowang commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Background

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file: reads treat its values as deleted, and a compaction of an SST that references a dropped origin turns those references into deletions (10/14). Without this diff, two problems are left:

  • A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
  • skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file. The open fails instead of losing values that a relocation file on disk still holds, in the cases that the fallback checks cover (see "Fallback checks"). It also adds an open check for missing relocation files (see "Open check").

The option gate of diff 2 stays in this diff, so blob indirection is still usable only in tests here. [Blob GC] 14/14 removes the gate, in the same diff that adds the crash-test support for the option.

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:

  • The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
  • A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

How to read this diff

  1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
  2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
  3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), IsBlobReferenceLost(), IsBlobGenerationLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_), then the compaction iterator loss check in db/compaction/compaction_iterator.{h,cc} (CheckBlobValueLoss(), lost_blob_value_, blob_value_loss_possible_).
  4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
  5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
  6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
  7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
  8. Side changes and public comments: db/db_filesnapshot.cc (live-file lists skip lost files), Version::AppendBlobRelocationFileMetaData() and VersionSet::GetTotalBlobFileSize() in db/version_set.cc (they skip lost files too), BlobRelocationState::SetFile() and DeleteFile() in db/blob/blob_relocation_manifest.cc (the relocation byte totals leave out lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, the property in db/internal_stats.cc, and the comments of best_efforts_blob_db_repair and CompactRangeOptions::skip_missing_blob_files in include/rocksdb/options.h. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.

Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

Term Meaning
loss record MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted

Terms of this diff:

Term Meaning
repair open An open with best_efforts_blob_db_repair (base option)
dropped blob file A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted
lost reference An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost())
base gate Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file
loss gate Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file
fallback in time Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST

Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage; reads treated its values as deleted, and compactions repaired its references (10/14). VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo(), GetLiveFilesChecksumInfo(), GetColumnFamilyMetaData(), the rocksdb.total-blob-file-size property and the relocation byte totals (rocksdb.live-blob-file-size, rocksdb.blob-stats, EstimateLiveDataSize() and relocation-file-bytes) listed or counted lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values.

New behavior

Repair open

  • A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
  • A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
  • Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo(), GetLiveFilesChecksumInfo(), GetColumnFamilyMetaData() and GetAllColumnFamilyMetaData() leave out lost files, because they have no readable values (a corrupt file that a repair open marked lost can still be on disk until GC removes its record). The blob size statistics do not count them either: the relocation state's byte totals (BlobRelocationState::PhysicalFileBytes() and RecordBytes()) leave out lost files, so rocksdb.total-blob-file-size, rocksdb.live-blob-file-size, rocksdb.blob-stats (size and space amp), EstimateLiveDataSize() and relocation-file-bytes of rocksdb.indirect-blob-gc-stats count only the blob files on disk. The census leaves the garbage of a lost file out of the relocation garbage total, so the garbage stays below the total size. So SstFileManager tracking at open and ldb dump_live_files do not count or open a missing file. DB::VerifyFileChecksums() skips lost files too, because they have no bytes to check; it still checks every relocation file that is not lost.
  • The public comments of best_efforts_blob_db_repair and CompactRangeOptions::skip_missing_blob_files describe what this diff adds for column families with blob indirection: lost relocation files, the compactions that a loss starts (see "Compaction"), the two fallback checks, and that skip_missing_blob_files returns NotSupported there.

Reads

  • A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
  • Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
  • Get checks for loss after the range tombstone check, like the base dropped-file check. A key that a newer range tombstone covers is decided by the tombstone, so its value is not parsed and the read is not counted as a lost read.
  • A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
  • Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
  • The blob fetcher records, when it is made, whether its Version has lost files. DBIter and GetContext copy that bool when they are made, and MergeHelper::MergeUntil() reads it once per call. With no lost file, the read path pays one predictable branch for each entry and never reads the Version for the loss check. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
  • Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

Compaction

  • A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
  • The loss gate is column-family wide: while the input Version has any lost relocation file, every compaction of that column family runs locally (bypassing DBOptions::compaction_service), repairs the references it reads, and writes exact reference metadata at every output level, including L0. Nothing schedules the compactions that rewrite the remaining holders, so this state lasts until compactions have rewritten every SST that references a lost file. The public comment of best_efforts_blob_db_repair recommends CompactRange() of the column family with bottommost_level_compaction set to kForce after an open that marks relocation files lost. With the default setting (kIfHaveCompactionFilter) and no compaction filter, CompactRange() does not rewrite the bottommost level by itself, so SSTs there can keep their references to the lost file, and the loss mode can stay. Universal compaction always rewrites in CompactRange().
  • The reason for the L0 rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed. In normal operation a coarse L0 input never holds a routed number (a flush references only its own new blob files), so the rule matters only for SSTs whose blob indexes were written directly, for example with WriteBatchInternal::PutBlobIndex().
  • A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
  • The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) accepts a lost generation number (VersionStorageInfo::IsBlobGenerationLost()), because the repair iterator turns its references into deletions and the output never writes them. The same check already accepts a dropped origin without a route (10/14). The output checks do not accept a lost file. Remote output validation uses Version::ValidateBlobReferenceGeneration(), which returns NotFound for it. The install-time output check (CompactionJob::ValidateBlobRelocationOutputDependencies()) fails with Corruption when an output depends on a lost relocation file, also by the file's own number (a flattened reference), which its same-file rule would otherwise accept. The repair iterator removes such references first, so this check is only a safety net. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
  • CompactionIterator gets its own loss check: it reads HasBlobValueLoss() once (blob_value_loss_possible_, set in the constructor and in SetBlobFetcher()), and calls the out-of-line CheckBlobValueLoss() for each blob index or entity only when that bool is true; a lost value is treated as deleted but keeps its Put type (lost_blob_value_). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions. In a flush, its effect is that the compaction filter does not run on a lost blob index or on an entity whose blob columns are all lost, so the filter does not read the lost file for them and the flush does not fail. An entity with only some lost blob columns still reaches the filter, and a filter that reads its columns reads the lost one too. A flush meets a lost value only when a blob index or blob column was written directly into the memtable.
  • When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

Fallback checks

  • Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
  • Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
  • Scope: the two checks cover a missing SST file, a missing or corrupt relocation file, and an older MANIFEST file. They cannot cover lost MANIFEST bytes. If the synced bytes of an indirect blob GC edit are cut off, no part of recovery sees the edit, and the open treats the point before it as the newest state; it then deletes the relocation file as an unknown file. Base RocksDB has the same limit for any edit whose synced bytes are lost (for example, the outputs of a compaction whose input files were already deleted), so this case is out of scope.
  • Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family. It says to restore the file, or to open once with best_efforts_blob_db_repair, and that such an open reads the lost values as deleted and does not replay the WAL. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

Only relocation files get this check. Normal and origin blob files keep the behavior of base RocksDB, which does not check blob files at open: a missing one fails only the reads of its values until a repair open drops it. The check runs whether or not paranoid_checks is set, and it checks only that the file exists: a truncated relocation file fails the reads of its values, and a repair open marks it lost.

skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

Monitoring

  • BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
  • rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
  • An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (their values read as deleted): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
  • LogDroppedBlobFiles() runs at the end of VersionSet::TryRecover(), after the older-MANIFEST check. So an open that fails that check does not log files as lost or dropped. The WARN line for dropped blob files of base keeps its text.
  • Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

Implementation

The essential choices, and why they are enough:

  • Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Background".
  • One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, and the read paths copy that bool, so a DB without a loss pays one predictable branch per entry and no Version read.
  • Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
  • Accept a lost file only where it is repaired. The compaction input check accepts a lost generation number; the output checks still reject it.
  • Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

Also in this diff

  • The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
  • db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio. Until the option gate goes away in 14/14, an open with --enable_blob_indirection fails with NotSupported.
  • A release note (unreleased_history) describes the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory. The release note that announces the option and its monitoring comes with 14/14.
  • The comment of enable_blob_indirection in include/rocksdb/advanced_options.h names the new L0 rule for outputs while a relocation file is lost.

Changes visible to existing users

  • A DB that never uses blob indirection has no lost relocation file. Its reads pay one predictable branch per entry in DBIter::ParseKey() and per matched blob or entity entry in GetContext::SaveValue(), and MergeHelper::MergeUntil() reads the bool once per call. DBIter keeps two more std::string members (empty unless a file is lost).
  • Compaction and flush pay one predictable branch per blob index or entity (blob_value_loss_possible_, fixed for the job) and a few predictable tests of lost_blob_value_ per key. While a file is lost, a compaction checks each blob entry twice: once in the repair iterator and once in CompactionIterator.
  • With best_efforts_blob_db_repair, the WARN line for dropped blob files is logged at the end of VersionSet::TryRecover() instead of after each MANIFEST file that recovery reads. The text is the same, and an open that succeeds logs it once, as before.
  • skip_missing_blob_files returns NotSupported only for a column family with blob indirection. Plain column families keep the base behavior.

Safety, compatibility and limitations

  • Persisted data: this diff adds no MANIFEST tag. Diff 4 added the loss record (kBlobPhysicalFileLoss) as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence. In this diff, only a test can turn on blob indirection, so only tests write the loss record; production can write it from 14/14 on.
  • Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
  • No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
  • Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
  • A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
  • Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
  • One lost file puts the whole column family into loss mode (see "Compaction"). Possible follow-ups, not planned yet: mark the SSTs that reference a lost file for compaction, using the census, or a per-input loss gate.
  • When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
  • A lost file is removed only after compactions have rewritten all its holders. Automatic compactions may never rewrite some of them, so the user should run CompactRange() with bottommost_level_compaction set to kForce (see "Compaction").
  • The fallback checks do not cover lost synced MANIFEST bytes (see "Fallback checks").
  • The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
    • The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
    • The check against indirect blob GC edits fails for an origin that GC retired with no route.
    • Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
      A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here. The crash test does not reach loss repair: the crash test never deletes blob files, and skip_missing_blob_files is rejected on column families with blob indirection.

Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files".

Tracking issue: #15301


Differential Revision: D132305446

@meta-cla meta-cla Bot added the CLA Signed label Nov 18, 2026
@meta-codesync

meta-codesync Bot commented Nov 18, 2026

Copy link
Copy Markdown

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

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

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

Completed in 5067.0s.

Summary by check

Check Count
bugprone-argument-comment 45
cert-err58-cpp 13
clang-analyzer-core.NonNullParamChecker 2
clang-analyzer-cplusplus.NewDeleteLeaks 1
clang-analyzer-optin.core.EnumCastOutOfRange 1
clang-analyzer-optin.performance.Padding 1
clang-analyzer-security.ArrayBound 1
cppcoreguidelines-avoid-non-const-global-variables 2
cppcoreguidelines-missing-std-forward 2
cppcoreguidelines-pro-type-member-init 4
performance-inefficient-string-concatenation 1
performance-inefficient-vector-operation 14
performance-move-const-arg 2
performance-no-automatic-move 6
performance-unnecessary-value-param 2
Total 97

Details

db/blob/blob_file_builder.cc (2 warning(s))
db/blob/blob_file_builder.cc:60:61: warning: the parameter #7 is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
db/blob/blob_file_builder.cc:61:34: warning: the parameter #8 is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
db/blob/blob_file_cache.cc (1 warning(s))
db/blob/blob_file_cache.cc:109:14: warning: constness of 'validation' prevents automatic move [performance-no-automatic-move]
db/blob/blob_file_cache_test.cc (1 warning(s))
db/blob/blob_file_cache_test.cc:426:1: warning: Potential leak of memory pointed to by field '_M_head_impl' [clang-analyzer-cplusplus.NewDeleteLeaks]
db/blob/blob_file_reader.cc (1 warning(s))
db/blob/blob_file_reader.cc:1484:5: warning: uninitialized record type: 'lookup_key_bytes' [cppcoreguidelines-pro-type-member-init]
db/blob/blob_file_reader_test.cc (13 warning(s))
db/blob/blob_file_reader_test.cc:438:7: warning: argument name 'last_original_offset' in comment does not match parameter name 'value' [bugprone-argument-comment]
db/blob/blob_file_reader_test.cc:941:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:1125:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:1532:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:1555:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:1885:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:2084:9: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:5272:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:5351:5: warning: uninitialized record type: 'header' [cppcoreguidelines-pro-type-member-init]
db/blob/blob_file_reader_test.cc:5402:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:5405:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:5532:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_file_reader_test.cc:5535:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/blob/blob_garbage_meter_test.cc (3 warning(s))
db/blob/blob_garbage_meter_test.cc:160:45: warning: argument name 'generation' in comment does not match parameter name 'generation_file_number' [bugprone-argument-comment]
db/blob/blob_garbage_meter_test.cc:168:37: warning: argument name 'seq' in comment does not match parameter name 's' [bugprone-argument-comment]
db/blob/blob_garbage_meter_test.cc:238:37: warning: argument name 'seq' in comment does not match parameter name 's' [bugprone-argument-comment]
db/blob/blob_gen2_format.cc (1 warning(s))
db/blob/blob_gen2_format.cc:63:60: warning: argument name 'size' in comment does not match parameter name 'n' [bugprone-argument-comment]
db/blob/blob_reference_census.cc (3 warning(s))
db/blob/blob_reference_census.cc:1235:12: warning: constness of 'status' prevents automatic move [performance-no-automatic-move]
db/blob/blob_reference_census.cc:2689:9: warning: Forming reference to null pointer [clang-analyzer-core.NonNullParamChecker]
db/blob/blob_reference_census.cc:2732:9: warning: Forming reference to null pointer [clang-analyzer-core.NonNullParamChecker]
db/blob/blob_reference_metadata.cc (1 warning(s))
db/blob/blob_reference_metadata.cc:906:10: warning: constness of 'release_status' prevents automatic move [performance-no-automatic-move]
db/blob/blob_relocation_manifest.cc (1 warning(s))
db/blob/blob_relocation_manifest.cc:34:19: warning: variable 'blob_file_table_plain_scan' is non-const and globally accessible, consider making it const [cppcoreguidelines-avoid-non-const-global-variables]
db/blob/blob_source.cc (2 warning(s))
db/blob/blob_source.cc:647:12: warning: constness of 'status' prevents automatic move [performance-no-automatic-move]
db/blob/blob_source.cc:774:12: warning: constness of 'status' prevents automatic move [performance-no-automatic-move]
db/blob/blob_source_test.cc (1 warning(s))
db/blob/blob_source_test.cc:2411:7: warning: uninitialized record type: 'record_of' [cppcoreguidelines-pro-type-member-init]
db/column_family.cc (1 warning(s))
db/column_family.cc:1601:19: warning: variable 'allow_blob_indirection_for_test' is non-const and globally accessible, consider making it const [cppcoreguidelines-avoid-non-const-global-variables]
db/compaction/compaction_job.cc (1 warning(s))
db/compaction/compaction_job.cc:1707:12: warning: constness of 'input_check_status' prevents automatic move [performance-no-automatic-move]
db/db_impl/db_impl_compaction_flush.cc (1 warning(s))
db/db_impl/db_impl_compaction_flush.cc:712:15: warning: Excessive padding in 'class rocksdb::DBImpl::IndirectBlobGCJob' (44 padding bytes, where 4 is optimal). Optimal fields order: db_, cfd, candidate_physical_file_numbers, made_progress, sfm_reserved_bytes, log_buffer, column_family, stale_input_is_retryable, blob_reference_census, input_version, input_version_number, input_storage, table_cache, blob_file_cache, gc_job_token, selected_reader_bytes, mismatched_input, group_read_bytes, plan_end, aggregate_input_bytes, candidate_local_failure_input, candidate_local_failure_reason, edit, published_output_count, published_relocated_count, published_relocated_value_bytes, read_input_count, published_input_count, start_micros, input_bytes_read, bytes_written, census, sfm_background_error, status, gc_block_cache, memory_tracker, inputs, suppressed_files, suppression_reasons, eligible_inputs, generation_checks, plans, group_reads, capacity_deferred_files, bins, outputs, readers, output_directory, write_options, manifest_write_options, release_selected_reader_charge, release_group_read_charge, transient_suppressions, oversized_suppressions, routed_generations_by_input, corrupt_inputs, candidate_stamp, read_options, gc_read_options, blob_gc_file_options, source_table_options, mutable_cf_options, job_id, empty_files_only, allow_value_relocation, deferred_input, census_mismatch, sst_open_fails_job, invariant_check_failed, installed, internal_error, output_needed, delete_renamed_outputs, consider reordering the fields or adding explicit padding members [clang-analyzer-optin.performance.Padding]
db/db_options_test.cc (5 warning(s))
db/db_options_test.cc:2305:5: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/db_options_test.cc:2483:27: warning: initialization of 'kTypeInfo' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/db_options_test.cc:2540:25: warning: initialization of 'kTypeInfo' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/db_options_test.cc:2591:10: warning: Out of bound access to memory around 'changed_rounds' [clang-analyzer-security.ArrayBound]
db/db_options_test.cc:2629:24: warning: initialization of 'kTypeInfo' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc (10 warning(s))
db/internal_stats.cc:344:26: warning: initialization of 'blob_relocation_lost_files' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:346:26: warning: initialization of 'indirect_blob_gc_idle_micros_with_candidates' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:348:26: warning: initialization of 'indirect_blob_gc_stats' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:349:26: warning: initialization of 'blob_reference_census_unready_micros' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:351:26: warning: initialization of 'blob_indirection_format_version_name' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:483:35: warning: initialization of 'kBlobRelocationLostFiles' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:485:35: warning: initialization of 'kIndirectBlobGcIdleMicrosWithCandidates' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:487:35: warning: initialization of 'kIndirectBlobGcStats' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:489:35: warning: initialization of 'kBlobReferenceCensusUnreadyMicros' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/internal_stats.cc:491:35: warning: initialization of 'kBlobIndirectionFormatVersion' with static storage duration may throw an exception that cannot be caught [cert-err58-cpp]
db/memtable_list.cc (1 warning(s))
db/memtable_list.cc:1169:25: warning: argument name 'column_family_options' in comment does not match parameter name 'new_cf_options' [bugprone-argument-comment]
db/repair_test.cc (1 warning(s))
db/repair_test.cc:94:44: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]
db/version_builder.cc (1 warning(s))
db/version_builder.cc:2896:29: warning: forwarding reference parameter 'fn' is never forwarded inside the function body [cppcoreguidelines-missing-std-forward]
db/version_builder_test.cc (32 warning(s))
db/version_builder_test.cc:158:9: warning: passing result of std::move() as a const reference argument; no move will actually happen [performance-move-const-arg]
db/version_builder_test.cc:1345:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1345:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1362:49: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1669:27: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1670:27: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1711:37: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1712:37: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1843:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1843:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1895:14: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1895:42: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1921:14: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1921:42: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1979:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1979:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1996:9: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1996:37: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:1997:36: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2009:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2009:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2024:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2024:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2044:38: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2100:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2100:35: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2670:27: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2671:27: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2681:29: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:2682:29: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_builder_test.cc:4108:9: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]
db/version_builder_test.cc:4302:34: warning: argument name 'seq' in comment does not match parameter name 's' [bugprone-argument-comment]
db/version_edit_test.cc (7 warning(s))
db/version_edit_test.cc:96:7: warning: passing result of std::move() as a const reference argument; no move will actually happen [performance-move-const-arg]
db/version_edit_test.cc:491:7: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_edit_test.cc:492:34: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_edit_test.cc:562:23: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_edit_test.cc:563:23: warning: argument name 'physical_file_number' in comment does not match parameter name 'target_file_number' [bugprone-argument-comment]
db/version_edit_test.cc:566:31: warning: argument name 'source_file_number' in comment does not match parameter name 'old_file_number' [bugprone-argument-comment]
db/version_edit_test.cc:1058:45: warning: argument name 'generation' in comment does not match parameter name 'generation_file_number' [bugprone-argument-comment]
db/wide/db_wide_basic_test.cc (1 warning(s))
db/wide/db_wide_basic_test.cc:3517:7: warning: The value '8' provided to the cast expression is not in the valid range of values for 'CompressionType' [clang-analyzer-optin.core.EnumCastOutOfRange]
db/wide/wide_column_serialization.cc (1 warning(s))
db/wide/wide_column_serialization.cc:363:55: warning: forwarding reference parameter 'visit' is never forwarded inside the function body [cppcoreguidelines-missing-std-forward]
table/block_based/block_based_table_reader.cc (4 warning(s))
table/block_based/block_based_table_reader.cc:1663:21: warning: argument name 'need_upper_bound_check' in comment does not match parameter name 'disable_prefix_seek' [bugprone-argument-comment]
table/block_based/block_based_table_reader.cc:1673:3: warning: uninitialized record type: 'key_block' [cppcoreguidelines-pro-type-member-init]
table/block_based/block_based_table_reader.cc:2890:35: warning: argument name 'aligned_buf' in comment does not match parameter name 'direct_io_buffer_context' [bugprone-argument-comment]
table/block_based/block_based_table_reader.cc:5344:20: warning: argument name 'need_upper_bound_check' in comment does not match parameter name 'disable_prefix_seek' [bugprone-argument-comment]
tools/block_cache_analyzer/block_cache_trace_analyzer_test.cc (1 warning(s))
tools/block_cache_analyzer/block_cache_trace_analyzer_test.cc:883:7: warning: 'push_back' is called inside a loop; consider pre-allocating the container capacity before the loop [performance-inefficient-vector-operation]

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 18, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values.

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate

At this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (the option gate: diff 2 adds it, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-14, except that diffs 10-14 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files <== this diff |
| 14 | RepairDB rebuilds relocation state; option gate removed |
| 15 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 18, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values.

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate

At this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (the option gate: diff 2 adds it, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-14, except that diffs 10-14 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files <== this diff |
| 14 | RepairDB rebuilds relocation state; option gate removed |
| 15 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 18, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values.

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate

At this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (the option gate: diff 2 adds it, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-14, except that diffs 10-14 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files <== this diff |
| 14 | RepairDB rebuilds relocation state; option gate removed |
| 15 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
@meta-codesync meta-codesync Bot changed the title 13/15: Handle lost relocation files and dropped origins 13/14: Handle lost relocation files and dropped origins Nov 19, 2026
@xingbowang
xingbowang force-pushed the export-D132305446 branch 3 times, most recently from 2d89c68 to 5e321a1 Compare November 19, 2026 18:13
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins 13/14: Handle lost relocation files and dropped origins (#15720) Nov 19, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, three db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst and --indirect_blob_gc_read_coalesce_bytes.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, three db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst and --indirect_blob_gc_read_coalesce_bytes.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins (#15720) 13/14: Handle lost relocation files and dropped origins Nov 20, 2026
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins 13/14: Handle lost relocation files and dropped origins (#15720) Nov 20, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, three db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst and --indirect_blob_gc_read_coalesce_bytes.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, three db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst and --indirect_blob_gc_read_coalesce_bytes.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins (#15720) 13/14: Handle lost relocation files and dropped origins Nov 20, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, four db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, four db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count, and ldb manifest_dump lists every lost file.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## Parts of this diff

1. Repair open (db/version_builder.cc, db/blob/blob_relocation_manifest.h): best_efforts_blob_db_repair marks a missing or corrupt relocation file lost.
2. Read path (db/blob/blob_fetcher.{h,cc}, db/version_set.{h,cc}, table/get_context.cc, db/db_iter.{h,cc}, db/merge_helper.cc): a lost value reads as a point deletion, and a wide-column entity loses only its lost blob columns.
3. Compaction (db/compaction/compaction.{h,cc}, db/compaction/compaction_job.cc, db/blob/missing_blob_repair_iterator.h): a compaction turns references to lost and dropped files into deletions or partial entities.
4. Fallback checks (db/version_builder.h, db/version_edit_handler.{h,cc}, db/version_set.cc): a repair open fails instead of falling back to a point that would drop values that a relocation file on disk still holds.
5. Open check (db/db_impl/db_impl_open.cc, db/db_impl/db_impl_files.cc): every normal open checks that each relocation file that is not marked lost exists.
6. skip_missing_blob_files guard (db/db_impl/db_impl_compaction_flush.cc): CompactRange with skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references. A first-time reader can skip this part; the rest of the diff does not depend on it.
7. Option gate removal, the public RepairDB comment, four db_bench flags and the release notes (db/column_family.{h,cc}, db/db_test_util.cc, include/rocksdb/advanced_options.h, include/rocksdb/db.h, tools/db_bench_tool.cc, unreleased_history/). Safe to skip on a first read.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open).
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files) and CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| unflattened reference | Index with generation number == origin (value not relocated, or not flattened yet) |
| flattened reference | Index with generation number != origin: compaction rewrote the generation number to the relocation file that holds the value |
| route | Old file number -> the relocation file that now holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| indirect origin | Normal blob file written with enable_blob_indirection on; it is the origin of unflattened references |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. An SST that has it is an exact SST |
| coarse SST | An SST without exact reference metadata. It records one frontier file number and pins every indirect-origin blob file at or above it. Frontier 0 means no coarse frontier |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file. An SST that the census counts for a file is a holder of that file |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version |
| format fence | A MANIFEST record that marks a column family (per-CF fence) or the whole DB (DB-global fence) as possibly holding blob indirection data. It never clears. See "MANIFEST records" in db/blob/blob_relocation_manifest.h |
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. A lost file stays in the Version, but its values read as deleted. Code comments also call it an accepted loss |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. Point reads and iterators count. An iterator can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC and TableReaderCaller::kBlobRelocationFileRead.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator limitation above is known and not fixed here.

## Stack context (same in diffs 2-13, except that diffs 10-13 add the diff 10 route rule to the install line; "<== this diff" marks this diff's part):

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P (a relocation input that gets an output keeps a route
    |      for all its generation numbers), re-point the routes into the
    |      inputs to P, and remove each input (blob file retirement for a
    |      blob file, relocation file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files; option gate removed <== this diff |
| 14 | db_stress and crash test support |

Tracking issue: meta#15301

Differential Revision: D132305446
@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Claude Code Review - OBSOLETE

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

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit fe5ed4d


Summary

This is diff 13/14 of a large blob indirection stack. The visible portion of the diff (truncated at ~40% of 77K lines) shows well-structured changes across cache reservation, blob file building, blob file caching, and blob fetcher subsystems. The code quality is high with thorough documentation and test coverage. The design follows RocksDB conventions and handles edge cases carefully.

High-severity findings (0):

No high-severity findings.

Full review (click to expand)

Findings

🔴 HIGH

No high-severity findings identified in the visible portion of the diff.

🟡 MEDIUM

M1. CacheEntryRole public API change — include/rocksdb/cache.h (enum), cache/cache_entry_roles.cc (strings)
  • Issue: Three new CacheEntryRole enum values (kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus, kIndirectBlobGcWorkingMemory) are inserted before kMisc. Since kNumCacheEntryRoles = static_cast<uint32_t>(CacheEntryRole::kMisc) + 1, the numeric value of kMisc changes, and kNumCacheEntryRoles increases from 15 to 18. This is a public API behavioral change affecting downstream code that hardcodes or persists CacheEntryRole numeric values, sizes arrays based on kNumCacheEntryRoles, or iterates over the enum.
  • Root cause: The enum comment says "Do not add to this enum after kMisc" and the string arrays must match. The new roles are correctly placed before kMisc.
  • Suggested fix: No code fix needed, but release notes should mention the new cache entry roles.
M2. BlobFileBuilder constructor parameter added without default — db/blob/blob_file_builder.h
  • Issue: BlobSource* blob_source added as required parameter to both constructors, breaking all callers. Existing callers at db/builder.cc:236 and db/compaction/compaction_job.cc:1831 don't pass it in the base code. Caller updates must be in the truncated portion of the diff.
  • Suggested fix: Verify ALL callers updated. The non-defaulted approach follows CLAUDE.md's "avoid new defaulted parameters" rule.
M3. CacheReservationHandle::Resize updates size before UpdateCacheReservation succeeds — cache/cache_reservation_manager.cc
  • Issue: Resize() sets incremental_memory_used_ = memory_used before UpdateCacheReservation(). On failure, the handle's internal size is already changed. This is consistent with MakeCacheReservation() behavior and documented/tested (FailedResizeRemainsLocallyOwned).
  • Suggested fix: None needed. Consistent design.
M4. BlobFileCache failed relocation open cache uses NowMicros — db/blob/blob_file_cache.h:~line kFailedRelocationOpenMicros
  • Issue: Expiry check uses NowMicros() which may not be monotonic on all platforms (unlike NowNanos()). A wall clock step could shorten the 1-second TTL. Unlikely to cause practical issues.
  • Suggested fix: Consider NowNanos() / 1000 for monotonicity, or document the limitation.

🟢 LOW / NIT

L1. StableBlobContents::CreateFromSaved returns invalid object, not error Status — db/blob/blob_contents.h
  • Issue: CreateFromSaved returns a unique_ptr with valid_ = false on failure. The FullTypedCacheHelperFns::Create callback returns Status::OK() and sets *out_obj even for invalid data. Readers must check validity. Per the comment, "readers erase it." Verify all readers check.
L2. BlobFileAddition duplicate kIndirectOrigin rejection — db/blob/blob_file_addition.cc:108
  • Issue: Correctly rejects duplicate kIndirectOrigin custom field tags with has_indirect_origin guard. Good defensive coding.
L3. Separate mutex stripes for relocation files — db/blob/blob_file_cache.h
  • Issue: 32 relocation stripes vs 128 blob file stripes. Well-documented rationale: relocation opens can hold the mutex long (reading all location blocks), and Evict() runs under DB mutex and must not wait for such opens. Good design.

Cross-Component Analysis

Context Affected? Safe? Notes
WritePreparedTxnDB Yes Yes Loss check is per-Version
ReadOnly DB Yes Yes Open check runs
User-defined timestamps Yes Yes Uses kTypeDeletionWithTimestamp
Tailing iterator Yes No Known: keeps fetcher for freed Version
skip_missing_blob_files Yes Yes Guarded for indirection CFs
FIFO compaction No N/A Rejected by enable_blob_indirection validation

Positive Observations

  1. Thorough documentation: Exceptionally detailed PR description and inline comments explaining design rationale.
  2. Performance-aware design: has_lost_blob_relocation_files_ cached at construction avoids per-key Version reads when no files are lost. Separate mutex stripes prevent cross-contention.
  3. Good test coverage: Tests cover resize semantics, cache quantum sharing, failed resize, stable identity index, CRC computation, and failed open caching.
  4. Forward compatibility: kIndirectOrigin custom field tag correctly placed in forward-compatible range with duplicate detection.
  5. Build system consistency: New source files added to both BUCK and CMakeLists.txt.

ℹ️ About this response

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

Limitations:

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

Commands:

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

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 20, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 21, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude Code Review - OBSOLETE

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

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit f233a08


Summary

This is diff 13/14 of the blob indirection stack -- a massive change (190 files, ~78K insertions) that handles lost relocation files, dropped origins, removes the option gate, and adds db_bench flags. The diff is truncated so this review covers only the visible portions. The design is thorough and well-documented, with careful attention to data integrity and compatibility.

High-severity findings (0):
No high-severity findings in the visible portions of the diff.

Full review (click to expand)

Findings

🟡 MEDIUM

M1. CacheReservationHandle::Resize overflow check updates size before reservation -- cache/cache_reservation_manager.cc:~45
  • Issue: Resize() sets incremental_memory_used_ = memory_used before calling UpdateCacheReservation(). On failure, GetTotalMemoryUsed() returns the inflated value. The comment documents this as intentional (matching MakeCacheReservation semantics), and the test FailedResizeRemainsLocallyOwned validates it. However, the overflow guard returns MemoryLimit and keeps the OLD size, while a failed UpdateCacheReservation keeps the NEW size. This asymmetry between overflow and cache-full failures may confuse callers.
  • Root cause: The overflow path is a special case that returns before modifying incremental_memory_used_, while the cache-full path is after the assignment.
  • Suggested fix: Document the asymmetry explicitly in the comment, or unify the two failure modes.
M2. BlobFileCache::GetBlobFileReaderImpl validate-on-hit releases without erasing -- db/blob/blob_file_cache.cc:~175
  • Issue: When a cached reader fails validation (e.g., metadata mismatch between a normal blob file and a relocation file at the same file number), the cache entry is released but not erased. The next caller will find the same entry again and fail again. This is intentional if file number collisions are impossible (global file number allocator), but after a repair open or fallback, file number reuse is theoretically possible.
  • Root cause: RocksDB uses a global file number allocator, so collisions between file types should not occur in correct operation.
  • Suggested fix: Consider erasing the entry on validation failure (like RefreshBlobFileReader does) so a subsequent open can succeed. If this is intentionally not done to surface a Corruption, document why.
M3. failed_relocation_opens_ not bounded -- db/blob/blob_file_cache.h:~217
  • Issue: The failed_relocation_opens_ map has no size bound. With many lost relocation files, each producing a remembered Corruption, the map grows without limit. Entries expire after 1 second, but only on the next access to that specific file number.
  • Root cause: No periodic cleanup or size cap. ForgetFailedRelocationOpen() from the Version deleter is the expected cleanup path.
  • Suggested fix: Document that ForgetFailedRelocationOpen() is the lifecycle-based cleanup, or add a size cap.
M4. StableBlobContents::CreateFromSaved returns invalid object instead of error Status -- db/blob/blob_contents.cc:~103
  • Issue: On validation failure, CreateFromSaved returns a StableBlobContents with valid_ = false. The FullTypedCacheHelperFns::Create callback returns OK and caches it. This may cache an invalid entry that every reader then erases -- wasteful under concurrent access to a corrupted secondary cache entry.
  • Root cause: Intentional design: the cache layer does not fail on promotion.
  • Suggested fix: Consider returning non-OK from Create when the entry is invalid. Low impact (rare path).

🟢 LOW / NIT

L1. BlobFileBuilder removes db_id_ and db_session_id_ members -- db/blob/blob_file_builder.h:~116
  • Issue: Clean refactor. Cache prepopulation now goes through BlobSource::PrepopulateFlushBlob. Constructor parameters become unnamed for API compat.
  • Suggested fix: None.
L2. BlobFileAddition 6-param constructor correctly avoids defaulted parameters -- db/blob/blob_file_addition.h:~35
  • Issue: Follows CLAUDE.md guidance. 5-param delegates to 6-param with is_indirect_origin=false.
  • Suggested fix: None.
L3. Cache entry role strings added before "Misc" -- cache/cache_entry_roles.cc:~29
  • Issue: Three new roles correctly ordered. Verify enum definition has matching values before kMisc (not visible in truncated diff).
  • Suggested fix: Verify.
L4. BlobFileCache constructor chaining allocates 32 extra mutex stripes for base path -- db/blob/blob_file_cache.cc:~28
  • Issue: ~2KB per BlobFileCache even without relocation. Acceptable, documented.
  • Suggested fix: None.
L5. Evict() contract: only for normal blob files -- db/blob/blob_file_cache.cc:~290
  • Issue: Debug assert verifies. Relocation files evicted via TableCache::Evict(). Good contract boundary.
  • Suggested fix: None.

Cross-Component Analysis

Context Affected? Notes
WritePreparedTxnDB Likely yes Loss acts as same-sequence deletion, should interact correctly with snapshot visibility.
ReadOnly DB Yes Open check runs. Missing file fails with NotFound.
User-defined timestamps Yes Uses kTypeDeletionWithTimestamp.
Remote compaction Yes Loss gate forces local. Conservative and correct.
Tailing iterator Yes, known limitation IsBlobValueLost() may read freed Version. Same problem exists in base blob fetches.

Positive Observations

  • Thorough PR description with reading guide and term glossary.
  • Feature-off cost is zero (one bool test per key, no Version read).
  • Consistent repair semantics through shared MissingBlobRepairIterator path.
  • Fallback safety checks prevent data loss on repair open.
  • CRC computed once, derived three ways -- efficient and correct.
  • Separated stripe mutexes prevent DB-mutex deadlock via Evict().
  • Failed open cache absorbs bursts to bad relocation files.

ℹ️ About this response

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

Limitations:

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

Commands:

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

xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins 13/14: Handle lost relocation files and dropped origins (#15720) Nov 23, 2026
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
xingbowang added a commit to xingbowang/rocksdb that referenced this pull request Nov 23, 2026
Summary:
Pull Request resolved: meta#15720

## Why the change is required

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file, and reads treat its values as deleted. Without this diff, three problems are left:

- A compaction of an SST that holds an indirect reference to a dropped origin fails with Corruption (CompactionJob::ValidateBlobRelocationInputGenerations()).
- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file, and no value whose data is still on disk is lost. It also adds an open check for missing relocation files (see "Open check"). This is the last diff that adds feature behavior, so it also removes the option gate that diff 2 added (see "Option gate removal").

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), VersionStorageInfo::IsBlobReferenceLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes: db/db_filesnapshot.cc (live-file lists skip lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, and the property in db/internal_stats.cc. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.
9. Last, the option gate removal: ColumnFamilyData::ValidateOptions() in db/column_family.cc, then the comments in include/rocksdb/advanced_options.h and include/rocksdb/db.h. It depends on nothing else in this diff.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage, and reads treated its values as deleted. But a compaction of an exact SST that holds an indirect reference to a dropped origin failed with Corruption, because CompactionJob::ValidateBlobRelocationInputGenerations() found the generation number unreadable. VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() listed lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values. ColumnFamilyData::ValidateOptions rejected enable_blob_indirection outside tests (the option gate of diff 2).

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo() and GetLiveFilesChecksumInfo() skip lost files, because they have no bytes to copy. DB::VerifyFileChecksums() skips them too, because they have no bytes to check; it still checks every relocation file that is not lost.
- VersionBuilder rejects a loss record that names no live relocation file of the edit's column family ("Blob relocation loss names no live target").

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. With no lost file, the loss check for each key never reads the Version. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- With either gate, the compaction runs locally. With the loss gate, it also writes exact reference metadata at every output level, including L0. Without the loss gate, an L0 output is exact only when the compaction is bottommost or an L0 input is already exact (diff 7). The reason for the loss rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed.
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- A lost generation number is legal (Version::ValidateBlobReferenceGeneration() returns OK), so the compaction does not fail. The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) also accepts a dropped origin without a route, because the repair iterator turns its references into deletions and the output never writes it. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator has its own loss check (diff 10). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions.
- Holders are repaired only when a compaction rewrites them. Nothing schedules a compaction for them.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead, and it never loses a value whose data is still on disk. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family, and says to restore the file or to open with best_efforts_blob_db_repair. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (reads of their values return NotFound): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

### Option gate removal

- This diff removes the option gate that diff 2 added, and its test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. ColumnFamilyData::ValidateOptions no longer rejects enable_blob_indirection, so the option can be used in production from this diff. The other option checks stay: enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h no longer says that option validation rejects the option.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Why the change is required".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, so a DB without a loss pays no per-key Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

These belong here because this diff makes the option usable outside tests:
- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio.
- Release notes (unreleased_history) describe the feature and its options, its monitoring, that RepairDB returns NotSupported for a DB with blob indirection data, and the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory.
- Tests: db/db_test_util.cc no longer sets the gate allowance, and the gate test in db/blob/db_blob_index_test.cc is removed. Tests that called the gate hook drop the call.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. It is the first diff where a production open writes the loss record (kBlobPhysicalFileLoss). Diff 4 added that tag as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence.
- Production use: with the gate removed, a column family can activate blob indirection outside tests. Once it does, releases that do not know the format cannot open the DB (format fence, diff 4). The release note says so.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. With disable_auto_compactions, that needs a manual compaction.
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files; option gate removed".

Tracking issue: meta#15301

Differential Revision: D132305446
@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit bb97e0d


Summary

This is a large (190 files, 78K+ lines) diff that completes the blob indirection feature stack by handling lost relocation files, adding an open check, fallback safety checks, skip_missing_blob_files guards, the option gate removal, db_bench integration, and monitoring. The design is thorough and well-documented. The loss lifecycle (mark → read-as-deletion → repair-compaction → census-removal) is carefully integrated across all read paths (Get, iterator, merge, compaction). The PR description is exceptionally detailed and serves as the primary architectural reference.

High-severity findings (1):

  • [db/blob/blob_fetcher.h:166-174] Tailing iterator use-after-free: has_lost_blob_relocation_files_ is cached at construction, but IsBlobValueLost() reads the Version, which a flush may have freed. Documented as a known limitation identical to base blob fetches, but the new loss path increases exposure since it fires on every entry (not just cache misses).
Full review (click to expand)

Findings

🔴 HIGH

H1. Tailing iterator use-after-free on lost-value reads — db/blob/blob_fetcher.h:166-174
  • Issue: VersionBlobFetcherBase caches has_lost_blob_relocation_files_ at construction, so HasBlobValueLoss() never reads the freed Version. However, when this bool is true, IsBlobValueLost() delegates to version_->IsBlobValueLost(), which reads storage_info_. A tailing iterator keeps its fetcher after dropping its Version reference, so a flush can free the Version during a scan. If the Version had lost relocation files, every BlobIndex/entity the tailing iterator encounters calls IsBlobValueLost() on the freed Version.
  • Root cause: The base blob fetch path has the same lifetime problem (fetching from a freed Version), but it is exercised only on cache misses. The loss check is exercised on every entry when HasBlobValueLoss() is true, making the window much larger.
  • Suggested fix: The PR documents this as a known limitation. A proper fix would pin the Version (or a copy of the loss state) in the fetcher. This is out of scope for this diff but should be prioritized given the increased exposure.

🟡 MEDIUM

M1. PermitUncheckedError on failed relocation open status — db/blob/blob_file_cache.cc:155
  • Issue: The failed.status.PermitUncheckedError() on the cached failed-open Status means the error can expire without ever being returned to a caller. This is a deviation from the project's preference to avoid new PermitUncheckedError uses.
  • Suggested fix: Consider moving the PermitUncheckedError to the expiry/erase path rather than the insertion path, so at least the initial error is always checked.
M2. CheckRelocationFilesExist releases DB mutex during directory listing — db/db_impl/db_impl_open.cc:493
  • Issue: The function releases mutex_ to call env_->GetChildren(), then re-acquires and continues iterating GetColumnFamilySet(). The comment correctly states "Startup has not exposed any CF", but there is no assertion or static guarantee that this function is only called during startup.
  • Suggested fix: Add a startup-phase assertion or document this restriction in the declaration.
M3. BlobFileBuilder silently discards db_id/db_session_id — db/blob/blob_file_builder.cc:62-63
  • Issue: Constructor parameters renamed to unnamed (std::string /*db_id*/). Callers pay for constructing/moving std::string objects that are immediately discarded.
  • Suggested fix: Acceptable as transitional if these parameters will be removed.
M4. CompactionIterator::CheckBlobValueLoss ROCKSDB_COLD annotation — db/compaction/compaction_iterator.cc
  • Issue: The ROCKSDB_COLD annotation assumes the function fires rarely. In a flush of a memtable with many lost references and no repair iterator (BuildTable), it fires for every entry. The PR documents this case but the annotation may mislead the compiler.
  • Suggested fix: Document that the COLD annotation applies to CompactionJob runs, not BuildTable runs.
M5. Potential entity allocation on hot path — db/version_set.cc:3129
  • Issue: Version::IsBlobValueLost calls RemoveBlobColumns() for every wide-column entity when HasLostBlobRelocationFiles() is true. Verify that the lambda-based check has an early exit when no column is lost.
  • Suggested fix: Verify RemoveBlobColumns fast path; if it has one, this is a non-issue.

🟢 LOW / NIT

L1. Java ticker mapping unavailable for BLOB_DB_LOST_BLOB_READ_COUNT
  • Issue: All 256 byte values of org.rocksdb.TickerType are used. The PR documents this.
  • Suggested fix: Documented; no action needed.
L2. StableBlobContents::CreateFromSaved returns validity via bool, not Status
  • Issue: Inconsistent with CreateWithVerifiedValue. Intentional for cache promotion API constraints.
  • Suggested fix: No action needed; documented.

Cross-Component Analysis

Context Executes? Assumptions hold? Action
WritePreparedTxnDB YES YES - loss check before visibility Safe
ReadOnly DB YES YES Safe
Secondary instance YES YES Safe
CompactionService Local only YES - conservative Safe
User-defined timestamps YES YES - kTypeDeletionWithTimestamp Safe
Tailing iterator YES KNOWN BUG (H1) Documented
MemPurge N/A N/A Safe
Legacy BlobDB Never lost YES Safe
FIFO compaction Blocked YES Safe
Old snapshots YES YES - same seqno deletion Safe

Assumption stress-tests:

  • "A Version never changes its loss state" — Correct. BlobRelocationState is set during SaveTo() in VersionBuilder; the Version is immutable thereafter.
  • "No real range tombstone from loss" — Correct. Lost keys call FlushPendingTombstoneRun (forward) or set range_tomb_end_key_ as exclusive end (reverse), preventing false tombstones.
  • "Feature-off cost is zero" — Correct. Only cost is the bool test in HasBlobValueLoss(), which is false when no relocation state exists.

DB Mutex analysis:

  • CheckRelocationFilesExist(): releases mutex for GetChildren, safe during startup.
  • CheckSkipMissingBlobFilesSupported(): under mutex, no I/O.
  • No new work under DB mutex in steady-state for the loss feature.

Positive Observations

  1. Excellent documentation: PR description with "How to read this diff" guide, term definitions, and detailed behavioral specifications. blob_relocation_manifest.h provides comprehensive architectural overview.
  2. Feature-off zero cost: Only a single bool check per blob entry (HasBlobValueLoss()), cached at fetcher construction.
  3. Consistent loss semantics: All read paths (Get, iterator, merge, compaction) use the same IsBlobValueLost() → deletion pattern.
  4. Defensive fallback checks: CheckRepairFallbackAgainstGc() prevents data loss from repair-open fallback past GC edits.
  5. Range tombstone correctness: Lost keys correctly end tombstone runs in both directions.
  6. Conservative remote compaction: Loss repair runs locally, avoiding protocol complexity.

ℹ️ 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

@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins (#15720) 13/14: Handle lost relocation files and dropped origins Nov 24, 2026
@xingbowang
xingbowang force-pushed the export-D132305446 branch 2 times, most recently from 03616c0 to f9138a4 Compare November 25, 2026 02:30
@meta-codesync meta-codesync Bot changed the title 13/14: Handle lost relocation files and dropped origins 13/14: Handle lost relocation files and dropped origins (#15720) Nov 25, 2026
…a#15323)

Summary:
Pull Request resolved: meta#15323

Background:
A Version is the in-memory list of the SST files and blob files of one column family (CF). VersionSet::LogAndApply builds each new Version with a VersionBuilder and installs it while it holds the DB mutex. Each VersionBuilder starts from a base Version: the current Version of its CF when the builder was made. In this diff, "finalizing the blob metadata" of a new Version means two things: adding the blob files to the new Version, and then checking the consistency of the whole new Version. When force_consistency_checks is on (the default) or in debug builds, this check walks every SST. Work under the DB mutex delays unrelated DB operations, and this delay grows with the number of files. Later diffs in the indirect blob GC stack add more blob state to each Version in the same finalization step.

Terms used in this diff:
- ColumnFamilyData (CFD): the in-memory object of one CF. It is reference counted, and a dropped CF is freed when its last reference is released.
- SuperVersion: the reference-counted set of memtables and the current Version that readers use. Each SuperVersion holds one CFD reference.
- MANIFEST writer queue: LogAndApply puts one writer (a ManifestWriter) per CF into this queue. The writer at the head of the queue processes a batch of queued writers. The thread that owns that writer is the leader; the thread that called LogAndApply for a writer is its caller.
- Writer callback: a function that a LogAndApply caller passes per writer (the `manifest_wcbs` argument, stored as ManifestWriter::manifest_write_callback). Flush uses it to remove the flushed memtables.
- No-MANIFEST LogAndApply call: a call that passes dummy edits (VersionEdit::MarkNoManifestWriteDummy). It installs new Versions but writes no MANIFEST record. Only SetOptions uses it. In ProcessManifestWrites, such a batch has skip_manifest_write set.
- Dummy flag: the mark set by VersionEdit::MarkNoManifestWriteDummy() on a dummy edit. A test can clear it on the SetOptions edits through the sync point DBImpl::SetOptions:dummy_edit, so that SetOptions runs through the MANIFEST path.
- pre_cb: a callback that LogAndApply runs under the DB mutex when the caller's first writer reaches the head of the MANIFEST writer queue.
- Options map: the option names and values that one SetOptions call gets for one column family handle.
- Phasing anchor (compaction_phase_anchor_time): the time from which periodic catch-up compactions are spread out. SetOptions moves it to the current time when an options map sets periodic_compaction_seconds, even to its current value, and the LogAndApply step of the call succeeds. Like the new options, the moved anchor stays in effect even if a later step (the OPTIONS file write or the seqno-to-time worker update) fails and the call returns an error. It does not move if the call returns early because no option changes. See VersionSet::PrepareCompactionPhaseReanchor() in version_set.h.

Why the change is required:
- Blob metadata finalization must run without the DB mutex before later diffs add work to it. This diff moves finalization, and the consistency check of the new Version that follows it, out of the mutex. It changes no format.
- SetOptions must change too. Before this diff, SetOptions installs the new options in pre_cb. It relies on LogAndApply keeping the DB mutex held until the new Version is installed. With this diff, the no-MANIFEST path of LogAndApply also releases the mutex during blob finalization. SetOptions builds its new Versions through the same ProcessManifestWrites code, so they need the same unlocked step (the consistency check that walks every SST, and in later diffs the derived blob state). Holding the mutex only for SetOptions would keep that cost under the mutex, once for every CF that SetOptions touches. If SetOptions still installed the options in pre_cb, a reader could see the new options with the old Version. So with this diff, SetOptions only prepares the options in pre_cb, and LogAndApply publishes them together with the new Versions. The phasing anchor follows the same rule, so it moves in two steps (prepare, then publish with the new Versions).
- With this diff, SetOptions makes one LogAndApply call for all its CFs, so that the options and the Versions are published together. Because there is one call, the result is all-or-nothing: either every CF changes or none does. In one call, all writers of one CF share one new Version, built with the options of the first writer. So when two handles point to the same CF, SetOptions merges their options maps into one writer. Otherwise the second map would be lost.
- Writer callbacks must run in the same DB mutex hold as the install, and at the end of the batch. Later diffs need this.
  - Existing window in base RocksDB: atomic flush removed the flushed memtables only after LogAndApply returned. Another thread can lead the batch and install the new Versions of this flush. Until the flush thread wakes up, takes the DB mutex and removes the memtables, other code under the DB mutex sees both the new SST files and the flushed memtables. This diff runs every callback in the mutex hold of the install, and atomic flush uses a callback too. This closes the window.
  - End of the batch: as in base RocksDB, the callbacks run when the writers of the batch are marked done, with no DB mutex release in between. A Flush(wait=true) caller returns as soon as its memtables are removed. When the flush thread leads its batch, it installs its new SuperVersion right after LogAndApply() returns, without releasing the DB mutex. If more flushes finished during the MANIFEST write, MemTableList::TryInstallMemtableFlushResults() first commits them in another LogAndApply() round, which can release the DB mutex. A flush writer that another leader takes into its batch installs its SuperVersion after it takes the DB mutex again. For the SuperVersion install, base RocksDB works the same way in both cases. The atomic flush memtable removal does not: when another thread leads the batch, that thread runs the atomic flush callback, so the memtables are removed in the leader's thread. So the atomic flush job reserves its pending flush-completion notifications before the install. Otherwise the leader could release the DB mutex after the removal and before the flush thread takes it back, and a Flush(wait=true, listener_wait=true) caller could return before OnFlushCompleted runs.

How to read this diff:
1. Read the summary sections Why and "New behavior: building a Version".
2. Read db/version_builder.h (SaveTableFilesTo, SaveBlobFilesAndCheckTo) and their bodies in db/version_builder.cc. They depend on nothing new. Then read base_checked_ and VersionBuilder::Apply in db/version_builder.cc (the base Version check). You can skip this last part on a first read; it does not depend on the other steps.
3. Read ProcessManifestWrites in db/version_set.cc: the finalize_blob_files lambda, the two unlock paths (no-MANIFEST and MANIFEST), the comment and debug checks after mu->Lock() in the MANIFEST path, and the blob_finalization_failed branch. This is where the second step of the save runs without the mutex. Only SetOptions uses the no-MANIFEST path. Releasing the mutex there is safe only because SetOptions publishes its options at install time (steps 5 to 7).
4. In the same function, read publish_batch_callbacks and finish_batch. Then read InstallMemtableAtomicFlushResults in db/memtable_list.cc. This step does not depend on steps 5 to 7.
5. Read the pieces that SetOptions needs: PrepareMutableCFOptions and PublishMutableCFOptions in db/column_family.h, ParamsForCfAtAnchor in db/periodic_compaction_phaser.h, and MutableCFOptionsPublication, the phasing anchor comment above PrepareCompactionPhaseReanchor, and the LogAndApply comment in db/version_set.h.
6. Read how these pieces go through LogAndApply in db/version_set.cc: the new ManifestWriter fields, how the new Version is built, the skip_manifest_write grouping, and the install block that publishes the options and the anchor.
7. Read DBImpl::SetOptions in db/db_impl/db_impl.cc. The comment at its top lists its steps. It groups the maps by CF, builds one dummy edit per CF, defines pre_cb (LogAndApply runs it under the DB mutex), makes one LogAndApply call, installs the new SuperVersions, and writes one OPTIONS file.
8. Optional: read "Also in this diff" and its code (finish_batch and the null CFD check in db/version_set.cc). They do not depend on the steps above.

Previous behavior:
- LogAndApply called VersionBuilder::SaveTo under the DB mutex. SaveTo added the SST files, blob files and compact cursors to the new Version, and then checked its consistency.
- VersionBuilder::Apply checked the consistency of the base Version on every edit.
- SetOptions made one no-MANIFEST LogAndApply call per CF. Each call installed the options of its CF in pre_cb. When a map set periodic_compaction_seconds, SetOptions moved the phasing anchor to the current time before its first LogAndApply call (VersionSet::ReanchorCompactionPhase), so the anchor moved even when the call failed later. If a later CF failed, the earlier CFs kept their new options, and the next SetOptions call finished the update.
- Each writer callback ran when its writer was taken off the queue at the end of the batch. Atomic flush updated its memtable lists after LogAndApply returned.

New behavior: building a Version
1. Under the DB mutex, VersionBuilder::SaveTableFilesTo adds the SST files and compact cursors to each new Version.
2. LogAndApply releases the DB mutex. VersionBuilder::SaveBlobFilesAndCheckTo adds the blob files. Then it builds the list of dropped blob files (VersionStorageInfo::GetDroppedBlobFiles()). A dropped blob file is a missing blob file that an open with best_efforts_blob_db_repair recorded. Then it checks the consistency of the complete new Version (SST and blob state).
3. LogAndApply takes the DB mutex again and installs the new Versions.

In the no-MANIFEST path (used by SetOptions), Version::PrepareAppend (which calls VersionStorageInfo::PrepareForVersionAppend) also runs in step 2, without the mutex. The MANIFEST path already ran it without the mutex.

If finalization fails, no MANIFEST record has been written. LogAndApply returns the error, deletes the unpublished Versions and keeps the current MANIFEST writer, the same as for a SaveTableFilesTo failure. It does not log "Error in committing version edit to MANIFEST" and does not force a new MANIFEST file. It also keeps an earlier MANIFEST I/O error and its quarantined files, because it did no MANIFEST I/O: a failed finalization does not reset io_status() and does not clear the error handler's quarantine.

New behavior: consistency check of the builder's base Version
VersionBuilder::Apply checks the consistency of the base Version only until the first check passes, so at most once per builder when the base Version is consistent. This is safe because the base Version never changes during the builder's life. It applies to all DBs and every builder user: LogAndApply, recovery and point-in-time recovery. Point-in-time recovery can undo the last edit with RollbackLastApply, but this does not change the base Version. With force_consistency_checks (true by default), a builder that applies many edits does not walk every SST of the base Version for each edit. The first Apply of each builder still walks every SST of its base Version. LogAndApply makes new builders for each batch, so under the DB mutex this saves walks only when one batch has more than one edit for the same CF. Recovery applies many edits to one builder, so it saves more. A failed check is not remembered, so the next Apply reports it again.

New behavior: SetOptions
The steps are listed in one place: the comment at the top of DBImpl::SetOptions (db/db_impl/db_impl.cc). The contract:
- The call is all-or-nothing. If preparation fails for any CF, no CF's options change and no OPTIONS file is written. A dropped CF fails the call before any options map is parsed. One exception: a key that sets a field inside a Customizable option, such as "table_factory.filter_policy.bloom_before_level" for a Ribbon filter policy, or a field of a custom prefix extractor or compression manager, can change the live object in place. The same holds for a mutable field of a custom object in an option that SetOptions cannot replace, such as merge_operator ("merge_operator.<field>" or "merge_operator={<field>=<value>}"), and for a field of a custom object that a whole table factory value sets, such as "block_based_table_factory={filter_policy.<id>.<field>=<value>}": the new factory is a clone that shares that object with the old one. Such a change takes effect when it is parsed, for every CF that shares the object, and a failed call does not undo it. So when a failed call has parsed a map with any key for a Customizable option, mutable or immutable, whole key or field (OptionsMapSetsCustomizableOption() in options/cf_options.h), it marks the OPTIONS file stale, and the next SetOptions or SetDBOptions call writes the file. Some counted keys change no live object (for example "table_factory=BlockBasedTable"). Such a key still has a cost after a failed call: the next SetOptions call that changes no option does not return early. It builds new Versions and SuperVersions for its CFs and writes an OPTIONS file. This happens once for each failed call. A failed call with only other options leaves the OPTIONS file up to date.
- Apart from options changed in place (the exception above), readers never see a mix of old and new options and Versions. LogAndApply publishes the options, the phasing anchor and the new Versions in one DB mutex hold, and SetOptions installs the new SuperVersions before it releases the mutex.
- One call writes one OPTIONS file. A failed OPTIONS file write sets options_file_stale_, so the next call writes the file again.
- Options maps given through different handles of the same CF go into one writer and are applied in map iteration order.
- The batch of one SetOptions call holds only the writers of that call (see step 2 in the MutableCFOptionsPublication comment in version_set.h).

Test-only MANIFEST path: a test can clear the dummy flag of the SetOptions edits (see Terms), so that SetOptions writes a real MANIFEST record. The options are then published only after that write succeeds. Grouping could then mix SetOptions writers with the writers of other callers. So a writer with prepared options is never grouped with another caller's writers, before or after: once the batch holds all writers of the leader's caller, it stops if the leader has prepared options, or before a next writer that has prepared options.

New behavior: writer callbacks
All writer callbacks of a batch run once, under the DB mutex, at the end of the batch, right before the writers are marked done. On success this is in the mutex hold of the install. The full contract (failure, early return, no user code or I/O) is in the comment of VersionSet::LogAndApply in version_set.h. Atomic flush passes one callback, on its first writer, that updates the memtable lists of the whole group. So the new Versions and the removal of their flushed memtables happen in one critical section. If LogAndApply returns before the batch starts (every CF of the group was dropped while its writers waited), no callback runs, and atomic flush updates the memtable lists itself after LogAndApply returns.

Implementation:
- VersionBuilder::SaveTo is split into SaveTableFilesTo (under the mutex) and SaveBlobFilesAndCheckTo (without the mutex). SaveTo still calls both. The unlocked step is safe for two reasons. First, ProcessManifestWrites keeps the builder guards (BaseReferencedVersionBuilder) alive across the unlocked part, so each builder keeps its base Version referenced. Second, the batch stays at the head of the MANIFEST writer queue, so no other thread installs a Version for these CFs in the meantime.
- ColumnFamilyData::SetOptions is replaced by two steps: PrepareMutableCFOptions parses and validates options without publishing them, and PublishMutableCFOptions publishes them.
- LogAndApply gets one new trailing parameter, a MutableCFOptionsPublication pointer (null by default). It holds the per-CF prepared options and the phasing anchor time. When it is set, the CFs must be distinct (checked in debug builds). A new Version constructor overload takes the PeriodicCompactionPhaseParams as an explicit std::optional argument, so a new Version can use the new anchor before it is committed. The constructor with the base signature uses the current parameters of the VersionSet. VersionSet::ReanchorCompactionPhase is replaced by PrepareCompactionPhaseReanchor (read the clock) and CommitCompactionPhaseReanchor (commit under the DB mutex).

Also in this diff:
These items are small and independent of the core. They are here because they touch the same LogAndApply code, or because later diffs depend on them.
- finish_batch signals every writer of the batch. Only the first writer of each caller has a thread that waits on it, so the other signals do nothing. Before this diff, finish_batch searched the leader's own writers for each writer of the batch, so it could skip the signal for them. This search takes time quadratic in the number of writers of a large multi-CF call, and with this diff a SetOptions call puts all its CFs in one batch. Signaling every writer removes the search.
- A writer with a null CFD in a batch that is not a CF add or drop returns Corruption. Before this diff, the code asserted, and release builds dereferenced the null pointer. The check replaces the assert in code that this diff rewrites. A version_set_test case covers it.
- Tests only, no code change: an iterator, a GetEntityLazy result and a pinned GetMergeOperands result keep a dropped CF alive only through the CFD reference of their SuperVersion, as before. Lazy blob reads in later diffs depend on this, so this diff adds tests for it. A tailing iterator depends on the base fix "Fix use-after-free in ForwardIterator::RebuildIterators on a dropped column family", which is already in the base of this stack.

Safety, compatibility and limitations:
- No persisted format changes: the MANIFEST records and the OPTIONS file format are the same. No public option changes.
- No option gates this change. The unlocked finalization and the base Version check apply to every DB.
- Behavior change: a SetOptions call over several CFs is all-or-nothing, also when one of the CFs is dropped. In base RocksDB the call also failed for a dropped CF or invalid options, but the CFs handled before the failing one kept their new options. EnableAutoCompaction() with several handles calls SetOptions, so it follows the same rule. A release note (unreleased_history/behavior_changes/setoptions_multi_cf_all_or_nothing.md) and the SetOptions comment in include/rocksdb/db.h describe this, including the exception for fields inside Customizable options that change a live object in place. The phasing anchor does not move when the LogAndApply step fails.
- Group commit of several writers for the same CF is unchanged.
- SaveTableFilesTo still runs under the mutex, and its cost is linear in the number of SST files. So building a Version under the mutex is not constant time.

Performance:
A db_bench readwhilewriting benchmark (release build) compares this diff with its parent commit (the baseline). The runs were measured on an earlier build of this diff, on an earlier master, so they are not from the current commits. The workloads write no blob files, so the gain most likely comes from the consistency checks (see the last bullet).
- Setup: 16-byte keys, 100-byte values, no compression, WAL off, 4 MB write buffers, 256 KB target file size, 16 background jobs, 4 subcompactions, no blob files. Each DB is first filled with fillrandom. Then readwhilewriting runs for 90 s with 8 threads.
- W1: 1 CF, 50M keys, about 20K SSTs (19.3K at start, 25K at end).
- W2: 4 CFs with atomic flush, 50M keys, about 16K SSTs at start.
- W3: 400K keys, about 110 SSTs at start, as a control.
- Method: 3 runs per binary on one shared host; the numbers are medians.
- An install is one MANIFEST batch (one ProcessManifestWrites call) that installs flush or compaction results. Its hold time is the time it holds the DB mutex. Total hold is the sum of all hold times, divided by the run time in seconds.
- The hold time comes from a local timer patch, not part of this diff, applied to both binaries. It measures the DB mutex hold of each ProcessManifestWrites call (one batch) and pauses at each unlock. db_bench was also patched locally in both binaries, to set atomic_flush and to spread the writes over all CFs.
- The DB mutex wait is the DB_MUTEX_WAIT_MICROS ticker, as a total over the whole run. On the earlier base where these runs were measured, the ticker counted nanoseconds (see perf_step_timer.h), so the values were converted from nanoseconds to seconds. On current master, the base of this diff, the ticker counts microseconds.

Results (base -> this diff):
- W1: hold per install p50 6.67 -> 3.13 ms, p99 13.5 -> 5.85 ms; total hold 92.4 -> 45.1 ms per s; DB mutex wait 207.9 -> 166.4 s; reads/s 84.9K -> 90.6K; writes/s 187K -> 193K; read p99.9 1778 -> 1724 us; write p99 2.40 -> 2.51 us; process CPU 905 -> 929 s.
- W2: hold per install p50 1.60 -> 1.03 ms, p99 8.49 -> 5.33 ms; total hold 133.8 -> 91.2 ms per s; DB mutex wait 306.7 -> 270.9 s; reads/s 103.7K -> 108.5K; writes/s 544K -> 560K; read p99.9 3236 -> 2455 us; write p99 2.67 -> 2.73 us; process CPU 1591 -> 1623 s.
- W3: hold per install p50 0.046 -> 0.041 ms, p99 0.146 -> 0.148 ms; total hold 1.5 -> 1.4 ms per s; DB mutex wait 2.6 -> 2.7 s; reads/s 929K -> 939K; writes/s 552K -> 547K; read p99.9 31.6 -> 31.5 us; write p99 2.29 -> 2.42 us; process CPU 956 -> 951 s.

What the results show:
- With about 20K to 25K SSTs (W1) and frequent flush and compaction installs, the DB mutex hold time of one install drops by about half. The total DB mutex wait drops by 20%, and reads per second rise by 6.7%.
- With 4 CFs and atomic flush (W2), the hold time drops by about a third and the read p99.9 latency drops by 24%.
- The small DB (W3) shows no meaningful change: apart from the small drop of the hold p50, the metrics are within noise.
- Costs: in W1 and W2 the process CPU time rises by 2.7% and 2.0%, and the write p99 latency rises by 4.8% and 2.3% (5.7% in W3). In W1 and W2 the runs of this diff also did more reads and writes.
- The hold time that remains includes two walks over every SST under the mutex: SaveTableFilesTo, and the base Version check in the first Apply of each builder. The benchmark did not measure how the remaining hold time splits between them.
- Most of the saving likely comes from the check of the new Version, which this diff moves out of the DB mutex. The once-per-builder base Version check saves less under the mutex, because each batch makes new builders (see "New behavior: consistency check of the builder's base Version"). We estimate, without a measurement, that saving the blob file metadata itself costs little, because it mostly copies shared pointers for the blob files. The benchmark did not measure these parts separately.

Validation and known limitations:
- Unit tests cover SetOptions (all-or-nothing, two handles of the same CF, one OPTIONS file, no mixed view, phase anchor), unlocked blob finalization and its failure, the base Version consistency check, atomic flush when every column family is dropped while it waits, and reads that outlive a CF drop. See the Test Plan.
- The new callback order is covered only through the atomic flush tests; see "Not covered" in the Test Plan.

Tracking issue: meta#15301

Differential Revision: D123408321
Summary:
Pull Request resolved: meta#15540

Background:
The goal of this stack is indirect blob GC, a blob GC that does not depend on SSTs: it removes garbage from blob files without rewriting any SST. Such a GC needs two things that RocksDB does not have:
- A value identity that does not change when the value moves to another file.
- A checked list of the blob references that each SST keeps. The list must include older internal versions of a key that the SST still keeps (for example for snapshots), and the blob columns of wide-column entities.
This diff adds both. Later diffs build the census (an in-memory reverse index from generation number to the SSTs that use it) and GC on top of this list.

This diff in one paragraph:
With the new column family option enable_blob_indirection on, the blob file writer gives each new value an indirect BlobIndex (type 3, kIndirectBlob). It stores the value's stable identity (origin file, original offset) and its CRCs (an uncompressed value stores only the CRC of the uncompressed value; a compressed value also stores the CRC of its stored bytes). Each blob file that it writes gets a version 2 header, which records the file's own number. Only blob indirection writes version 2. Also with the option on, the block-based table builder collects every blob reference that the SST keeps. It writes them as "exact reference metadata": data blocks, one reference index block, and a 72-byte descriptor table property. In this diff only the table builder writes this metadata, and only tests read it. A temporary option gate (see "option gate" under Terms) keeps the option off outside tests on DB::Open, CreateColumnFamily and SetOptions. "Safety boundaries" lists two paths that it does not cover. With the option on, the collector checks each wide-column entity with blob columns in full before it records the entity's blob indexes. With the option off, wide-column entities take the same path as in base.

How to read this diff:
1. Overview: read "Background" and "This diff in one paragraph" above, and "Terms used in this diff" right below. Then read the top comment of db/blob/blob_reference_metadata.h (terms, layout diagrams, run and entry layout, index layout).
2. Indirect BlobIndex (core; db/blob/blob_index.h) and canonical varints (util/coding.h GetCanonicalVarint32/64): read the overview comment and the kIndirectBlob / kIndirectFlattenedBlob code. Every later part uses these fields: origin, original offset, generation number, logical CRC and stored CRC. The new formats read varints only in the canonical form.
3. Blob file writer (core; db/blob/blob_file_builder.cc, blob_log_format.{h,cc}, blob_log_writer.cc, blob_file_reader.cc): see how a new value gets a type-3 index and how its CRC is computed once. Then read the version 2 header format at the top of blob_log_format.h, BlobLogHeader::DecodeFrom(), BlobFileBuilder::OpenBlobFileIfNeeded() and the file number check in BlobFileReader::ReadHeader().
4. Format types and decoders (core): the structs in db/blob/blob_reference_metadata.h, then in the .cc the constants, GapBase, DecodeEntryBody, DecodeRunEntriesAt, DecodeBlobReferenceIndex and BlobReferenceGroupDecoder. They use only BlobIndex and the canonical varints. Learn the on-disk format here, before you read the writer.
5. Collector and its cache charge (core): first read the new CacheEntryRole kBlobReferenceMetadataBuildingBuffer (include/rocksdb/cache.h) and CacheReservationHandle::Resize (cache/cache_reservation_manager.h). Then read BlobReferenceMetadataCollector in this order: the class comment, Add, AppendSorted, BuildAndWriteDataBlocks, EncodeIndex, FinishOnce. Then read the unsorted fallback (AppendUnsorted, SortUnsortedGroup, SortAndEncodeGroup).
6. Wide-column walk (db/wide/wide_column_serialization.cc, ForEachBlobIndex and WalkV2Columns; see "Also in this diff"; you can skip it on a first read): it gives every blob index of an entity to a callback after it checks the whole entity. Only the table builder's collector path (AddBlobReferences()) uses it. All other readers keep the base walk, ForEachBlobFileNumber.
7. Option (you can skip it on a first read; tests need it to turn the feature on): enable_blob_indirection (include/rocksdb/advanced_options.h, options/cf_options.cc), and the option checks and gate in db/column_family.cc (ValidateOptions, TEST_SetAllowBlobIndirection), db/db_impl/db_impl_open.cc and db_impl_secondary.cc (the FIFO check for opens that skip ValidateOptions).
8. Table integration (core): table/block_based/block_based_table_factory.cc (the shared reservation manager), then block_based_table_builder.cc (Rep constructor, AddImpl, WriteBlobReferenceMetadata, EstimatedTailSize). See where the collector is created, fed (AddImpl(), which both Add() and TryAdd() call) and finished. block_based_table_reader.cc maps the new block name to a block type.

Terms used in this diff:

Stack terms:

| Term | Meaning |
|---|---|
| origin | Blob file where the value was first written |
| original offset | Value offset in the origin file |
| stable identity | (origin, original offset). Never changes, even when the value moves |
| generation number | The file number that a reference uses to find its value. A new value has generation number == origin. When indirect blob GC moves the value, the reference keeps its generation number, and a route sends the read to the relocation file |
| indirect BlobIndex | A kIndirectBlob (type 3) or kIndirectFlattenedBlob (type 4) index. It stores the stable identity, so the value can move without an SST rewrite |
| unflattened reference | Index with generation number == origin: the value was not moved, or it was moved but no compaction has rewritten its reference yet (see "flatten" in "Stack context: terms for later diffs") |
| flattened reference | Index with generation number != origin (type 4). Only flatten (diff 10) writes it; this diff defines the encoding |
| route | Maps an old file number (a file that GC has removed from the Version) to the relocation file that holds its live values. One hop: a target is never itself routed. Stored in the MANIFEST (diff 4) |
| relocation file | Block-based table keyed by (origin, original offset) that holds copied values. Each value is the stored bytes plus a 5-byte trailer (kSimpleGen2BlobTrailerSize) |
| logical CRC | CRC32C of the uncompressed value (BlobIndex::stable_checksum()) |
| stored CRC | CRC32C of the stored bytes plus the compression byte |
| physical file | A file that holds value bytes: a normal blob file or a relocation file. A generation number can name a physical file, or it can be only the key of a route |
| exact reference metadata | Per-SST sorted list of every blob reference the SST keeps, written when the SST is built. References with the same encoding class, generation number and origin form a group. The list is stored as data blocks, with an index of the groups. An SST that has it is an exact SST |
| blob file header version 2 | BlobLogHeader with version kVersion2 (2), written for every blob file when enable_blob_indirection is on. It stores the file's own number, and its flags byte is 0. The file has no TTL |
| option gate | Until diff 14, ColumnFamilyData::ValidateOptions returns NotSupported for enable_blob_indirection on a read-write open, CreateColumnFamily and SetOptions, unless a test calls ColumnFamilyData::TEST_SetAllowBlobIndirection(true). It keeps the option off on these paths while the stack is not complete. DB::OpenAndCompact() and RepairDB do not go through it (see "Safety boundaries") |

Terms of this diff (all defined at the top of db/blob/blob_reference_metadata.h):

| Term | Meaning |
|---|---|
| encoding class (class) | kDirect (a legacy kBlob or kBlobTTL index), unflattened, or flattened |
| reference group (group) | All references of one SST with the same (encoding class, generation number, origin) |
| group key | The (encoding class, generation number, origin) of a reference group. The index lists groups by it |
| run | The part of one group inside one data block |
| record bytes | The bytes the value's record takes in the file named by its generation number |
| gap | How far a record is from where it would be if the records were back to back. A gap of 0 means back to back |
| descriptor | The 72-byte table property that points to the reference index block and holds the totals, the CF ID, the SST file number and the relocation-state fingerprint |
| relocation-state fingerprint | 128-bit hash of the routes and relocation files of the Version that an SST was built from (fields route_snapshot_fingerprint_*). Written as 0 in this diff |
| legacy | Written the way RocksDB writes it without blob indirection |

Previous behavior:
- A BlobIndex named only a physical blob file and an offset. A value could not move to another file without rewriting every SST that referenced it.
- An SST had no metadata that listed its blob references. The only way to find them was to scan its user keys.
- Every blob file had a version 1 header. The header did not say which file number the file has, or whether indirect BlobIndexes reference its values.

New behavior:

Option and option gate:
- This diff adds a new column family option, `enable_blob_indirection`. It is off by default, and SetOptions can change it.
- The option gate (see Terms) keeps the option off outside tests until the stack is complete. ColumnFamilyData::ValidateOptions rejects the option with NotSupported on a read-write open, CreateColumnFamily and SetOptions. Read-only opens (DBImplReadOnly and CompactedDBImpl) and secondary opens (including DB::OpenAndCompact) do not run ValidateOptions; they check only the FIFO rule (see "Notable implementation details"). Only tests can turn the option on, through the internal ColumnFamilyData::TEST_SetAllowBlobIndirection(). DBTestBase sets it.
- When the option is on, ValidateOptions also requires enable_blob_files, the block-based table format, no blob direct write, and a compaction style other than FIFO.

Blob file writer (option on):
- The blob file writer encodes each new value with a stable identity (origin file, original offset) and two checksums:
  - the logical CRC: the CRC32C of the uncompressed value.
  - the stored CRC: the CRC32C of the exact stored (maybe compressed) bytes, extended with the compression byte.
- For an uncompressed value the stored CRC is not written, because the reader can compute it from the logical CRC.
- The checksums have no version field of their own. The BlobIndex type byte gives the format version: the two new types, 3 (kIndirectBlob) and 4 (kIndirectFlattenedBlob, see "Notable implementation details"), are BlobIndex::kIndirectBlobFormatVersion (1). A later format uses new type values.
- The read path does not check these checksums yet. The check starts in diff 3.

Blob file header version 2 (option on):
- Background: a blob file starts with a 30-byte header (BlobLogHeader::kSize) and ends with a 32-byte footer (BlobLogFooter::kSize). A new format capability gets a new format version, so the blob file writer of this diff writes version 2 (kVersion2) exactly when enable_blob_indirection is on. All other blob files keep version 1.
- Version 2 is like version 1, but the file has no TTL, and the header reuses the two expiration-range fields: the first one holds the file's own number (not 0), and the second one holds 0. The flags byte is 0. The footer is the same as in version 1.
- Why: only blob indirection writes version 2, so the version alone tells tools and the RepairDB guard (diff 4) that the file belongs to blob indirection, without the MANIFEST. The file number also catches a blob file that was copied or renamed to another number.
- BlobLogHeader::DecodeFrom() accepts versions 1 and 2. It returns Corruption for any other version and, in version 2, for a nonzero flags byte, file number 0 or a nonzero second field. Version 1 decoding is the same as in base.
- BlobFileReader returns Corruption ("Blob file number mismatch") when a version 2 header names another file number than the file it opens.

Exact reference metadata (option on):
1. What: a sorted list of every blob reference that the SST keeps, in plain blob values and in the blob columns of wide-column entities.
2. Where: data blocks (target 16 KB each before compression; small blocks waste less I/O, because indirect blob GC reads a whole block to get a few groups) and one reference index block, written after the SST data blocks and before the SST tail, plus a 72-byte descriptor table property.
3. Who reads it: only tests in this diff. The census and indirect blob GC read it in later diffs, and remote compaction checks its SST identity fields (diff 11).
4. Details: the top comment of db/blob/blob_reference_metadata.h has the full format with diagrams, the record-bytes rules and the gap rule.
- Not collected: SstFileWriter output (it has no DB file number) and any output whose CF is unknown (it has no CF ID). The descriptor needs both values, so these outputs stay in the legacy form.

Checks on the metadata:
- A repeated or overlapping reference in one group fails the SST build with Corruption. Readers check every count, order, size and total against the index and the descriptor, so corrupt metadata returns Corruption. The writer never makes a data block larger than kTargetDataBlockSize (16 KB), and readers accept up to kMaxDataBlockSize (64 KB). Details: "Readers" and "Integrity" at the top of db/blob/blob_reference_metadata.h, and BlobReferenceGroupDecoder.

Collection and memory:
- Each reference is encoded when it is added, in the on-disk entry encoding, into its group's chain of 512-byte chunks. Only a group that takes the unsorted fallback is encoded a second time, in Finish(). Inside a group, references normally arrive in rising offset order, so no reference is sorted; at the end only the groups are sorted. A group that gets a lower offset takes the unsorted fallback. The BlobReferenceMetadataCollector class comment explains the chunks, the chunk size and the fallback.
- The collector keeps every reference of the SST in memory until the SST is finished, and charges this memory to the block cache under a new CacheEntryRole, kBlobReferenceMetadataBuildingBuffer. "Memory usage" and "Memory charge" in the BlobReferenceMetadataCollector class comment explain the parts of this memory and the charge rule. The measured amounts are under "Performance".
- There is no fixed limit on references. The collector fails with MemoryLimit above 2^20 groups or 2^20 data blocks in one SST; these are persisted format limits. It also fails with MemoryLimit when the reference index block could be larger than 64 MB (kMaxTopLevelMetadataBlockSize), which can happen from about 945K groups (64 MB / kMaxIndexEntrySize, 71 bytes per group), or from fewer groups when the SST also has many data blocks.
- There is no charge when the table has no block cache or when charging for this role is disabled. Each block-based table factory holds one cache reservation manager for this role, shared by its builders and the SST summaries. If the charge fails because the block cache is full (strict_capacity_limit), the memory stays uncharged and the SST build goes on, as for readahead buffers; the next charge update tries again. So a full cache does not fail a flush or compaction. The builder writes a WARN line to the info log for each SST that had a failed charge. The manager is shared, so a failed charge means that the shared block cache was full, not that this SST is large. The uncharged memory is at most the reference buffers of the SSTs that are being built and, when the caller keeps it, the BlobReferenceSstSummary of each finished SST (the table builder in this diff keeps none). Each SST's buffers and summary grow with its number of blob references. The buffers and their charge are released when the SST is finished or abandoned.

<details>
<summary><b>Notable implementation details:</b> encodings, collector, table builder, tools</summary>

- BlobIndex adds two indirect encodings. The legacy encodings do not change.
  - Type 3, kIndirectBlob (unflattened, generation number == origin), stores the origin, the original offset, the stored size, the compression type, the logical CRC and, for compressed values, the stored CRC. It does not store the generation number. This saves the size of one varint file number per reference (about 3 to 4 bytes for typical file numbers; an estimate, not measured).
  - Type 4, kIndirectFlattenedBlob (flattened), stores the generation number first, then the same fields. Its generation number must be above the origin. The decoder rejects type 4 with generation number <= origin, so each reference has one encoding.
  - stored_checksum() computes the stored CRC of an uncompressed value when a caller asks for it: the logical CRC extended with the compression byte. A decode does not compute it, because most decodes (for example in compaction) never read it.
- The new files blob_reference_metadata.{h,cc} define the exact reference metadata. The files also contain:
  - BlobReferenceMetadataCollector, the collector described above. It takes the SST identity (CF ID, SST file number and the relocation-state fingerprint) as one BlobReferenceSstIdentity, set by field name.
  - The index codec and the descriptor table property.
  - BlobReferenceGroupDecoder, the only decoder of reference runs. It reads a group one data block at a time and holds every corruption check of a group walk. DecodeRun() is its only public decode call. Readers that visit one group (found by its group key in the index) use it, and so do readers that visit every block in order.
- Callers in this diff: only the table builder runs the collector. The decoders (DecodeBlobReferenceIndex, BlobReferenceGroupDecoder, ForEachBlobReference*) are used only by tests. kMaxDecodedBlobReferenceBytes is used only in compile-time checks of the count limits. The census (diff 5) and indirect blob GC (diffs 8 and 9) are their first production users. The census is also the first user of BlobReferenceSstSummary (see the last bullet of "Notable implementation details").
- Descriptor: the CF ID and the SST file number are the SST identity fields. They say which column family and SST the list belongs to. The decoder rejects a descriptor whose identity fields are not set (unknown CF ID or SST file number 0; BlobReferenceMetadataDescriptor::HasSstIdentity()) with Corruption ("Incomplete blob reference descriptor"). The unknown CF ID is TablePropertiesCollectorFactory::Context::kUnknownColumnFamily, the value that the table builder gets for an unknown column family. Both identity fields are required: the collector fails Add() and Finish() with InvalidArgument when either one is not set, so it never writes a descriptor that the decoder rejects. The descriptor also has a 128-bit relocation-state fingerprint (the route_snapshot_fingerprint fields). Remote compaction uses it in diff 11 to check that an SST built elsewhere used the same routes as the job that asked for it. In this diff the table builder always writes 0, and DecodeFrom() does not check it. The field is in the format from this diff on, so the descriptor keeps one format version (1) through the stack. While the option gate is on, only tests and the two paths listed under "Safety boundaries" can write this format.
- The collector validates each BlobIndex once, when it is added. Its Finish() writes the data blocks and then the reference index block through one block writer, and fills the descriptor, including the index handle. Destroying the collector frees its memory and then its charge, also when the build is abandoned.
- BlockBasedTableBuilder creates the collector with the CF ID and SST file number from TableBuilderOptions. It passes the size of each entry's user key to the collector, so the collector can compute the exact size of each blob record. It adds the collector's EstimatedEncodedSize() to its tail size estimate: the blocks are written before the tail, but output file size planning uses this estimate. The reference blocks are written with BlockType::kUserDefinedIndex, which keeps their contents as opaque bytes. BlockBasedTable::BlockTypeMaybeCompressed() treats that type as never compressed, so a reader must not read a reference data block through the table's normal block read path (RetrieveBlock()), which would return a compressed block without decompressing it. The readers in later diffs read these blocks with BlockFetcher and maybe_compressed set. Readers read them without the block cache, so prepopulate_block_cache does not warm them into the block cache (WriteMaybeCompressedBlock() with warm_cache false).
- To save CPU, compaction decodes each kTypeBlobIndex output value once, in CompactionOutputs::AddToOutput(). It passes the decode to TableBuilder::TryAdd() in the new field TableBuilderAddContext::decoded_blob_index, and to new overloads of BlobGarbageMeter::ProcessOutFlow() and FileMetaData::UpdateBoundaries(). BlockBasedTableBuilder decodes a kTypeBlobIndex value once for both the referenced_blob_bytes count and the collector, and uses the caller's decode when it has one. If the decode fails, no decode is passed, and each reader decodes the value itself and returns its usual error. This applies with the option on or off. The SST bytes are the same as when each reader decodes the value itself.
- To keep the cost low with the option off, the new work stays off the base paths. CompactionOutputs::AddToOutput() builds the shared decode only for kTypeBlobIndex keys. The table builder feeds the collector in an out-of-line helper, BlockBasedTableBuilder::AddBlobReferences(), which AddImpl() calls only when the SST collects references and the entry is a kTypeBlobIndex or kTypeWideColumnEntity entry. That helper also decodes again a blob index that did not decode, only to report its error. For a wide-column entity, the helper also counts the referenced_blob_bytes property, so the builder walks the entity once. BlobIndex::DecodeFrom() decodes the base kinds in the main function and the indirect kinds in an out-of-line DecodeIndirectFrom(). For legacy indexes it returns the same status codes as in base; two messages differ (see "Changes visible to existing users"). A new general macro, ROCKSDB_NOINLINE in port/likely.h, keeps these helpers out of line: noinline on GCC and Clang, __declspec(noinline) on MSVC, and empty elsewhere.
- The collector converts each BlobIndex into a reference without deriving the stored CRC of an uncompressed value (ConvertBlobIndex() in db/blob/blob_reference_metadata.cc). The collector does not write that CRC, because a reader derives it again from the logical CRC. Deriving it would cost CPU for every reference of every output SST. BlobReference::FromBlobIndex() still derives it.
- With the option on, the blob file builder computes the CRC32C of each stored value once. The blob log record CRC combines it with the key CRC (crc32c::Crc32cCombine). The stored CRC extends it with the compression byte. For an uncompressed value it is also the logical CRC. The bytes written do not change.
- Read-only opens (DBImplReadOnly, CompactedDBImpl) and secondary opens skip ValidateOptions, so they check the compaction style against the option once per column family: in DBImpl::Recover() for read-only opens, and at the start of OpenAsSecondaryImpl() for secondary opens. DB::OpenAndCompact opens through OpenAsSecondaryImpl(), so it gets the same check.
- util/coding.h adds GetCanonicalVarint32/64. They reject overlong varint encodings, and a last byte with bits above the 32-bit or 64-bit range, which GetVarint32/64 drop. The new formats use them, so each value has one encoding.
- BlobReferenceSstSummary is the in-memory list of an SST's groups and totals that Finish() can return. It has no caller yet: the table builder passes a null summary output. It is checked and does not change after Finish(), so the finished builder, the SST metadata and the census (its first user, in diff 5) can share it. It is in this diff because Finish() hands the group buffer and its cache charge over to the summary. Adding the summary later would mean rewriting the charge code of Finish() in diff 5, so the charge code is written and tested once, here.
- sst_dump prints a "Blob reference metadata" section after the raw user collected properties of an SST that has exact metadata: the reference count, the stored value bytes, the column family ID, the SST file number when built and the index block handle. An SST without the descriptor prints nothing more.
- blob_dump prints the file number of a version 2 blob file header instead of its expiration range, because a version 2 header has no expiration range and keeps the file number in that field.

</details>

Also in this diff:
Wide-column walk for the collector (option on only). The collector needs the blob indexes of each wide-column entity, and it must not record part of a malformed entity in the reference metadata.
- Previous behavior: code that needs only the blob indexes of an entity uses WideColumnSerialization::ForEachBlobFileNumber. It skips the column names, decodes each blob index, and can call the callback before it finds a later error.
- New behavior: with the option on, BlockBasedTableBuilder::AddBlobReferences() uses the new WideColumnSerialization::ForEachBlobIndex. For an entity with blob columns, it checks the whole framing (section sizes, name order, exact input size), then decodes and validates (BlobIndex::Validate()) every blob index before any callback runs. So a malformed entity fails the build before the collector records any of its references. The same walk also counts the referenced_blob_bytes property, so the builder walks each entity once.
- Unchanged: UpdateBoundaries, BlobGarbageMeter, the compaction iterator, WideColumnSerialization::RemoveBlobColumns, and the referenced_blob_bytes count of an SST without a collector keep using ForEachBlobFileNumber, with the option on or off. With the option off, they and the table builder do the same work as in base and fail on the same input.
- Implementation: ForEachBlobIndex shares one V2 column walker (WalkV2Columns) with Deserialize(), so the two parse the V2 format the same way, in one pass. The walker visits a column only after it has checked that the input holds one type byte per column. Deserialize() reserves its outputs on the first visit, so a column count larger than the input is rejected before any memory is allocated for it. A smaller bogus count reserves memory bounded by the input size, as in base.

Changes visible to existing users:
These changes apply with enable_blob_indirection off, which is its default.
- BlobIndex::DecodeFrom() returns the same status codes as in base for legacy indexes. Two messages differ: a missing or extra compression byte reports "Corrupted blob compression" instead of "Corrupted blob offset", and an unknown type byte of 128 or more is printed as an unsigned number instead of a negative one. Type bytes 3 and 4 decode as the new types.
- The in-memory BlobIndex grows from 64 to 72 bytes on 64-bit builds, for the origin file number and the two CRCs. Reads pay for it with the option off too: MultiGet keeps one BlobIndex per key in its blob read context, DBIter keeps one per lazy blob column, and WideColumnSerialization::Deserialize() returns one per blob column.
- Public API: the new option `enable_blob_indirection` and its C API functions `rocksdb_options_set_enable_blob_indirection` and `rocksdb_options_get_enable_blob_indirection`. For an older release that loads the OPTIONS file, see the downgrade list under "Safety boundaries".
- CacheEntryRole: the new value kBlobReferenceMetadataBuildingBuffer is inserted before kMisc, so the numeric values of kMisc and kNumCacheEntryRoles grow by one.

Safety boundaries and unsupported cases:
- With the option off, new blob values and SSTs are written in the legacy form. Legacy blob indexes stay readable.
- Exact reference metadata has one format (version 1) with a fixed 72-byte descriptor. The decoders reject any other version as Corruption.
- The metadata blocks are protected by the table's block checksum only. With checksum = kNoChecksum, corrupt metadata is detected only when it breaks the format or order checks.
- DB::VerifyChecksum() and `sst_dump --command=verify` check the reference index block, because the meta-index lists it, but not the reference data blocks, which only the reference index points to. In this diff, corruption in a reference data block is found only when a reader decodes that block.
- The index decoder checks each decoded count against the remaining input size before it reserves memory. So a small corrupt index cannot make it allocate a large vector.
- Inlined-TTL and same-file blob indexes are not collected and cannot be relocated. Encoding, count and checksum errors return an error; a bad reference is never skipped.
- Option gate (see Terms): on DB::Open, CreateColumnFamily and SetOptions, only tests can turn the option on. Two paths that write SSTs do not run ValidateOptions(), so they can write the new formats outside tests:
  - DB::OpenAndCompact(), which a remote compaction worker calls, applies the column family options that the primary sends in CompactionServiceOptionsOverride::options_map, and opens through OpenAsSecondaryImpl(). If that map turns enable_blob_indirection on, the worker writes type-3 indexes, version 2 blob files and exact metadata into its output. Diff 11 makes the primary decline such an output for a job that did not ask for the feature, and run the job locally.
  - RepairDB builds tables from WAL files with the caller's options. It passes no blob file additions, so it writes no blob files and no type-3 indexes, but it can write exact metadata. Diff 4 makes RepairDB build its tables with the option off.
- The gate checks only the option value, never persisted state. Diff 14 removes it, once data written with the option stays readable through the end of the stack and the safety checks for turning the option on are in place.
- Downgrading the binary after data was written with the option on is not supported. Diff 4 adds a required MANIFEST record, so that an older release fails to open such a DB. In this diff alone, an older release behaves as follows for each new persisted item:
  - BlobIndex types 3 and 4: an older release returns Corruption ("Unknown blob index type") when it decodes such a value. Legacy indexes decode the same as in base.
  - Blob file header version 2: an older release rejects the file ("Unknown header version") when it opens it. Version 1 headers decode the same as in base.
  - Exact reference metadata (the reference blocks, their meta-index entry and the descriptor table property): an older release finds meta blocks by name, so normal reads do not touch them. Its DB::VerifyChecksum does not know the new meta-index name (a debug build asserts on an unknown name in BlockBasedTable::GetBlockTypeForMetaBlockByName()). An SST without the descriptor is read as before.
  - OPTIONS file entry enable_blob_indirection: as for any new option, an older release that loads this OPTIONS file needs ignore_unknown_options.

Performance:
Collector: the first three measurements below were made on an earlier build of this diff, with a release build. The memory and chunk-size numbers come partly from real DB runs (flush and CompactRange); the output-size number comes from a local harness that drives BlobReferenceMetadataCollector only (not a checked-in test).
- Collector memory (host not recorded; 16-byte keys, 1 KB values, 62K to 1M references per SST in 1 to 16 groups): the buffers used about 8.3 to 9 bytes per reference for uncompressed values and 12.8 to 13.5 bytes for compressed values, including the chunk headers. With 1000 groups in a 62K-reference SST, they used about 14 bytes per uncompressed reference.
- Chunk size, from the same measurement: for an SST with 1M references, the chunk size changed memory by less than 5% between 256 and 4096 bytes. For an SST with 62K references in 1000 groups, the partly filled chunks dominated: about 14 bytes per reference at 512 bytes, 22 at 1024 and 72 at 4096. 256 bytes used 3-4% more memory than 512 and made Finish() up to 1.6 times slower with 100 or more groups.
- Collector output size: one SST with 2M references in 200 groups that arrive interleaved writes 1449 data blocks (23.54 MB).
- Reference index block size, measured in census db_bench runs on an earlier build of the stack (source report and host not recorded; 16-byte keys, 200-byte values, 1 MB blob files, no compression, fillrandom and then a full compaction): about 1.7 KB per SST with 32 MB write buffers and a target file size of 8 MB or 2 MB, and about 10 KB per SST with 1 MB write buffers and a target of 2 MB or 200 KB. The size is the bytes read for the index blocks divided by the number of SSTs.

Benchmark, feature off, whole stack (db_bench, release builds). Baseline: the master commit under the stack at that time. Tested: an earlier build of the whole stack with enable_blob_indirection=false. Both builds are older than this commit.
- Workload: 5M keys of 16 bytes and 4 KB values, all in blob files (min_blob_size 512, 256 MB blob files, no blob compression, LZ4 for SSTs, compaction-time blob GC on with age cutoff 0.25), 64 MB write buffers and target file size, 16 background jobs, direct I/O, 4 GB block cache. Steps on one DB, each in its own process: fillrandom (1 thread) and an overwrite step with 2.5M writes (1 thread), each followed by waitforcompaction; readrandom (32 threads); multireadrandom (32 threads, 32 keys per batch); seekrandom (16 threads, 10 Next calls per seek); readwhilewriting (32 reader threads and one writer at full speed, 300 s).
- Method: 6 rounds. Each round runs four configurations on fresh DBs in a rotating order: base, the stack with the feature off, and two feature-on setups described in [Blob GC] 9/14. The host is a shared virtual machine with 192 vCPUs (AMD EPYC Genoa); each run is pinned to 32 of them, on btrfs with compress-force=zstd:3. A step starts only when the 1-minute load is below 20. Write amplification is the bytes that the process wrote to disk (/proc/<pid>/io) minus the WAL bytes, divided by the user bytes written. The results are medians of the 6 runs, with min-max in parentheses.
- Result: every measure overlaps base. Write amplification for fill + overwrite is 1.74 in both, and the DB at the end is 43.2 GB (38.6-44.5) against 43.9 GB (38.4-44.5). fillrandom is 0.8% slower and overwrite 0.6% slower. multireadrandom is 2.6% slower, seekrandom is 1.5% slower, and readwhilewriting reads are 0.6% faster.
- readrandom is 4.2% slower: 1,301,840 ops/sec (1,268,143-1,360,749) against 1,358,930 (1,242,903-1,411,848). The ranges overlap, but the stack is lower in 5 of the 6 rounds, so a small read cost of up to about 4% is not ruled out.
- Feature on: the same runs also measured the stack with the feature on. See "Performance" in [Blob GC] 9/14.

Feature-off cost of compaction CPU (db_bench, release builds, enable_blob_indirection off). This workload measures compaction CPU, which the benchmark above does not measure.
- Workload: 5M keys, 4 KB values in blob files, blob GC off. fillrandom, then a full compaction (the db_bench compact step). The measure is the user + system CPU of the process that runs the compact step; it also opens the DB and prints the stats.
- Setup: one shared AMD EPYC Genoa host with 192 CPUs, each run pinned to 32 CPUs. Base: the master commit under the stack at that time. Tested: an earlier build of the whole stack, on that master.
- Stack tip against base, 10 interleaved rounds: median 1.21 s (1.19 to 1.29) against 1.19 s (1.16 to 1.29), about 2% over base, and the ranges overlap. Median cycles are 1.5% higher. The stack tip runs 4% fewer instructions than base but has 14% more L1 i-cache misses, so the remaining small cost likely comes from code size in the hot loop.

Validation and known limitations:
- All numbers in "Performance" were measured on earlier builds (of this diff or of the stack), not on this commit.
- Unit tests cover the BlobIndex encodings and their rejection of bad input, the metadata layout and every corruption check, the collector (sorted path, unsorted fallback, memory charge), the flush integration, the option checks and option gate, the wide-column walks, and canonical varints. See the Test Plan.
- The collection buffer is not spilled to disk. One SST with very many blob references needs a matching amount of charged memory: the per-reference amount given under "Performance" (Collector memory), plus up to one partly used 512-byte chunk per group. While a fallback group is sorted, it also needs 16 bytes of sort key per reference and a second copy of its entries. For a test group of 200K references with every other one out of order, the test comment estimates about 44 bytes per reference, and the test checks that the peak charge is at most 56 bytes per reference.
- Flush still writes a single output file. Until diff 7, one compaction output collects every reference it gets, charged to the block cache. Diff 7 cuts compaction outputs (including L0) at a reference cap and keeps each user key's history in one output. With the option gate, a large output is reachable only through the test hook.

## Stack context

The later diffs of this stack point to this section. In the stack map, "<== this diff" marks this diff's row.

Goal: remove garbage from blob files without rewriting any SST. A value gets a stable identity when it is first written. Indirect blob GC copies the live values of whole files into a relocation file and installs routes in the MANIFEST. Readers follow the routes. SSTs are not changed.

How a read finds a value (P is the relocation file that holds the value now):

```
  SST entry
    indirect BlobIndex { generation number, origin, original offset, size, CRCs }
            |
            v
  Version file table: generation number -> live file, or route old file -> P
            |                                 |
       live file                          route found
            |                                 |
            v                                 v
  blob file: read at original offset   relocation file P (always one hop):
  relocation file: look up key         look up key (origin, original offset)
  (origin, original offset)
```

Lifecycle of one value (in this example, F is the blob file where the value is first written, and P is the relocation file that GC writes):

```
  write    new value goes to blob file F; index: origin = F, generation number = F
    |
  census   per generation number: the SSTs and references that use it;
    |      per physical file: live bytes, ranked by garbage ratio
  GC job   copy the live values of whole input files (stored bytes, checked
    |      with the stored CRC) into relocation file P, keyed by
    |      (origin, original offset)
  install  one MANIFEST edit: add P, route each input generation number still
    |      in use to P, re-point the routes into the inputs to P, and remove
    |      each input (blob file retirement for a blob file, relocation
    |      file deletion for a relocation file)
  flatten  compaction sets generation number = P in the SSTs it rewrites
    |
  route    route retirement: route deletion records remove the routes that
  delete   no SST uses
```

Stack map:

| Diff | Adds |
|---|---|
| 1 | Finalize blob metadata outside the DB mutex (prep) |
| 2 | Indirect BlobIndex (kIndirectBlob) and exact SST reference metadata <== this diff |
| 3 | Relocation file format and stable read path |
| 4 | MANIFEST routes and relocation state in the Version |
| 5 | Exact reverse reference census |
| 6 | MANIFEST apply outside the DB mutex, with a precondition re-check |
| 7 | Coarse flush metadata, per-SST reference cap, epoch runs |
| 8 | Indirect blob GC building blocks |
| 9 | Indirect blob GC job |
| 10 | Flatten generation numbers; route retirement |
| 11 | Remote compaction validation |
| 12 | Dynamic options and operations |
| 13 | Lost relocation files and dropped origins |
| 14 | db_stress and crash test support; option gate removed |

Stack context: terms for later diffs:

| Term | Meaning |
|---|---|
| Version file table | The table in a Version that maps a generation number to a live file or to a route (diff 4) |
| census | Background count, per generation number, of the SSTs and references that use it, plus live bytes per physical file (diff 5) |
| indirect origin | Normal blob file written with the option on; it is the origin of unflattened references |
| flatten | Compaction rewrites the generation number to the relocation file that holds the value, so old routes can go. Only flatten makes generation number != origin (diff 10) |
| blob file retirement | MANIFEST record (kBlobFileRetirement) that removes a collected blob file from the Version (diff 4) |
| route deletion | MANIFEST record that removes a route that no SST uses. Route retirement is the background job that writes these records (diff 10) |

Tracking issue: meta#15301

Differential Revision: D124652097
Summary:
Pull Request resolved: meta#15541

## Background

The terms are defined in "Terms used in this diff" below and in [Blob GC] 2/14. An indirect BlobIndex (added in diff 2) must find its value after indirect blob GC moves the value. This must work without rewriting SSTs and without making the cached value invalid. This needs two things, and this diff adds both:
1. A file format that holds moved values and finds them by stable identity (origin, original offset): the relocation file.
2. A read path and a blob cache key that do not depend on the physical file.

Nothing in the DB writes relocation files yet. Routes (MANIFEST records that send reads of an old file number to a relocation file) come in diff 4, and the indirect blob GC job (diff 9) first creates relocation files. No DB read reaches a relocation file yet (see "What is live in this diff"). This diff adds the relocation file builder and reader. Diff 8 sets the checksum type that relocation files use (kCRC32c, unless the table options turn checksums off) and the compression of their location blocks (the data blocks that hold location entries), before indirect blob GC (diff 9) writes the first one.

## How a read goes through this diff

A read goes through the new pieces in this order:

```
  Version (picks the physical file)
    -> BlobSource: stable blob cache, then the file
      -> BlobFileCache -> BlobFileReader
           blob log file: read the record at the original offset
           relocation file: BlobRelocationFileReader
             -> BlockBasedTable::MultiGetRawEntries (find the location entry)
             -> BlockBasedTable::MultiGetSameFileBlob (read the record)
```

## How to read this diff

1. Read "Terms used in this diff" below (and the stack terms in [Blob GC] 2/14). Then read the overview comment at the top of db/blob/blob_relocation_file.h. Together they explain the base terms, the file layout, the key and location-entry encoding, and the directory.
2. Read the record format changes in db/blob/blob_gen2_format.h: the size limit kMaxSimpleGen2BlobPayloadSize, compressed records and the batch read changes. Then read the format code in db/blob/blob_relocation_file.{h,cc}: the directory, the directory builder, the key, and the group encode and decode. The format code uses only the record format from this step.
3. Read the writer: the relocation methods and NewBlobRelocationTableBuilder in table/block_based/block_based_table_builder.{h,cc}. It uses only the code from step 2.
4. Read the table-level read helpers in table/block_based/block_based_table_reader.{h,cc}: MultiGetRawEntries (the batched lookup of location entries), RetrieveDataBlocks, and the no-BlobSource branch of MultiGetSameFileBlob (the record read). Also read the new fields in db/blob/same_file_blob_reader.h. Read PinDataBlocks and MultiGetRawEntriesPinned last. They belong to the pin_blob_relocation_location_blocks option, and you can skip them on a first read.
5. Read BlobRelocationFileReader in db/blob/blob_file_reader.{h,cc}: the class comment ("How a read works"), Open, CheckEntry and MultiGetBlob. Also read BlobPhysicalFile and RelocationBlobReadRequest in db/blob/blob_read_request.h. This step combines steps 2 and 4.
6. Read BlobFileCache::GetRelocationFileReader and failed_relocation_opens_ in db/blob/blob_file_cache.{h,cc}. Also read GetBlockBasedTableWriterOptions in table/adaptive/adaptive_table_factory.{h,cc}, which gives the cache the table options of the column family.
7. Read the stable cache on its own. It does not depend on steps 2 to 6 for normal blob files: StableBlobFingerprint (db/blob/blob_index.h), StableBlobContents (db/blob/blob_contents.{h,cc}), StableBlobCacheKeyBuilder and ChooseStableKeyDomain (db/blob/blob_source.{h,cc}), and the "Stable blob cache" comment at stable_blob_cache_ in db/blob/blob_source.h.
8. Read BlobSource::GetIndirectBlobFromCache, GetIndirectBlob, MultiGetIndirectBlobFromOneFile and FinishIndirectBlobRead (db/blob/blob_source.cc). Finish with the callers: db/version_set.cc (stable cache first; normal files only in this diff) and flush prepopulation in db/blob/blob_file_builder.{h,cc}. Check the legacy-change table last; you can skip it on a first read.

## Terms used in this diff

Stack terms (origin, original offset, stable identity, generation number, indirect BlobIndex, route, relocation file, physical file, logical CRC, stored CRC, option gate): see "Terms used in this diff" in [Blob GC] 2/14. This diff uses them with the same meaning.

Terms of this diff:

| Term | Meaning |
|---|---|
| stable | Always means "does not change when indirect blob GC moves the value": the stable identity, the stable cache key, the stable blob cache. The code name stable_checksum is the logical CRC |
| record | One stored value in a relocation file, in the SimpleGen2Blob record format (db/blob/blob_gen2_format.h): stored bytes, then a compression byte (1 byte) and a 4-byte checksum of the table's checksum type. Normal SSTs use the same format for embedded (same-file) blobs, so "embedded blob", "same-file blob" and "SimpleGen2 record" name the same record format |
| record bytes | Stored value size + kSimpleGen2BlobTrailerSize, summed over records |
| location entry | One data block entry of a relocation file. It locates a group of up to 32 values of one origin |
| origin partition | All values in one relocation file that share one origin file |
| served file | An old file number that may be routed to this relocation file. GC writes its input files and the file numbers already routed to them |
| directory | A table property of the relocation file: a header (counts, totals, directory digest, header CRC), then one entry per origin partition, then the served files |
| directory digest | CRC32C of the directory header counts and totals and the directory body. It is the file's identity, and diff 4 stores it in the MANIFEST |
| open tail | The end of the table that a reader loads at open: index, properties, metaindex and footer |
| fingerprint | StableBlobFingerprint: the fixed fields of an indirect BlobIndex (stored size, compression, logical CRC, stored CRC) |
| stable cache key | A blob cache key built from db_id, the session id and (origin, original offset). It does not use the generation number or the physical file, so it stays the same when the value moves |

## Previous behavior

- A blob read used a physical file number and an offset.
- The blob cache key was built from the physical file, so a moved value would get a new key and lose its cached copy.
- There was no relocation file format.

## New behavior

### Relocation file

The format is described once, in the overview at the top of db/blob/blob_relocation_file.h: the 8-byte prefix, the records, the location entries (groups of kBlobRelocationGroupSize (32) values, and why 32), the directory and its digest, the table options, and the num_entries check. The contract:
- A lookup of (origin, original offset) finds the first entry at or after that key, checks its origin, decodes the group and finds the exact offset. An offset that is not there gives Corruption ("entry is missing").
- Every origin and every served file has a smaller file number than the relocation file. Open checks this, the order and totals of the directory, that the directory fits in the open tail, and that the records fit before the tail.
- GetBlobRelocationFileMetadata returns the encoded directory and the size of the open tail. Diff 4 stores the tail size and the directory digest in the MANIFEST.

### Relocation reads

- BlobRelocationFileReader supports every read mode: single reads, batched reads, range reads of uncompressed values (also used by lazy reads) and whole reads of compressed values. BlobFileReader owns it, so the file cache keeps one entry type. Its class comment ("How a read works") gives the steps.
- BlockBasedTable::MultiGetRawEntries looks up the location entries of one batch (at most MultiGetContext::MAX_BATCH_SIZE (32) keys; a larger batch gets InvalidArgument for every key) together. It looks up all their data blocks in the block cache first. It reads one missing block through the normal block read path, and two or more missing blocks with one batched read (RetrieveMultipleBlocks). Then it finds each key in its block with SeekForGet. Sorted keys that fall in one location entry share one decode of it. A single Get takes the same path. It does not create a table iterator; it uses only an index iterator and a data block iterator on the stack.
- With kBlockCacheTier, a key whose block is not in the cache returns Incomplete. A bad block fails only the keys in that block.
- When a batch needs only one file read (one record, exact duplicates of one record, or overlapping ranges of one value), the reader uses a plain positional read (RandomAccessFileReader::Read). Otherwise it uses one MultiRead. Both paths do the same checks.
- Exact duplicates in a batch are read once. Each of them still counts as a read with its own bytes, as include/rocksdb/statistics.h says for requests that share a file read. Indirect reads of blob log files also read an exact duplicate once, in PlanReadBatches() (db/blob/blob_source.cc), where a duplicate must also have the same user key; ReadInPlannedBatches() counts the copy in BLOB_DB_BLOB_FILE_BYTES_READ, blob_read_count and blob_read_byte, because the reader never sees it.
- Checksums: the table under "Reads" in db/blob/blob_relocation_file.h says which checksums each read kind checks. Relocation files use format_version 6 or higher, so a record copied to another offset fails its checksum.
- Failed opens: BlobFileCache remembers some failed relocation opens for kFailedRelocationOpenMicros (1 second), so reads routed to a bad file do not reopen it each time. The comment at failed_relocation_opens_ in db/blob/blob_file_cache.h lists the remembered errors and gives the reasons.
- Table options: a relocation reader gets its table options from the column family options at open time: MakeBlobRelocationTableOptions() of the current block_based_table_factory. So a SetOptions() change of the table options applies to relocation files opened after it, the same as for pin_blob_relocation_location_blocks, the compression manager and block protection. A reader that is already open keeps the options it was opened with.

### Pinned location blocks (option)

- pin_blob_relocation_location_blocks is a new mutable column family option (default false), with a C API setter and getter. With it on, a relocation file reader reads all of its location blocks at open and keeps them until it is closed. With a block cache, the blocks are held through their cache handles, so they are charged and not evicted. A lookup then does a binary search over the last key of each block and a seek in the block, with no index lookup, no block cache lookup and no I/O. A change applies to relocation files opened after it.
- If the blocks cannot be kept (the block cache cannot charge them, or a block read fails), the open still succeeds: the reader logs a warning and does normal lookups. With strict_capacity_limit, the kept blocks hold block cache capacity that eviction cannot free. The option comment in include/rocksdb/advanced_options.h has the details. The tolerated pin failure is marked with `IGNORE_STATUS_IF_ERROR()`, as other best-effort reads at table open are, so the stress test does not expect the read to fail.

### Stable blob cache

The overview is the "Stable blob cache" comment at stable_blob_cache_ in db/blob/blob_source.h. The contract:
- Key: a standard 16-byte cache key built from db_id, the session and (origin, original offset). It stores a domain value (1, 2 or 3) in the top two bits of the origin. No real file number sets these bits: BlobIndex::DecodeFrom() rejects an indirect index with a file number above BlobIndex::kMaxFileNumber (2^62 - 1, equal to kFileNumberMask). So the key never equals another kind of cache key; ChooseStableKeyDomain() in db/blob/blob_source.cc has the proof.
- Entry: StableBlobContents holds the value and its fingerprint (stored size, compression, logical CRC, stored CRC). A header with its own CRC is written only when the entry moves to a secondary cache, and the header CRC and the value CRC are checked when the entry is loaded back. An entry that fails these checks is a cache miss, the same as a damaged block: the secondary cache drops it, and the read goes to the blob file. The secondary cache admission policy is the same as in base RocksDB.
- Cache first: Version::GetBlob, GetBlobRange and both MultiGet paths look up an indirect value in the stable cache before they read any blob file. A hit returns at once, and MultiGet groups only the misses by file. The cached value is not checked against the BlobIndex. This is safe: the key includes db_id and the session, so entries from before a reopen never match, and a blob file never changes after it is written and the DB never reuses a file number, so (origin, original offset) names the same bytes for the life of the DB. The key does not name the column family or the Version, so each hit checks that the blob file of the BlobIndex is in the Version (Version::CheckStableCacheHitHasFile(): one binary search in the Version's blob file list, no I/O). A hit for a file that is not in the Version returns the same Corruption as a cache miss for that file. Without this check, a corrupt BlobIndex that names another column family's blob file would read that column family's value while it is cached.
- Insert: a value that will be cached ends up in a buffer from the cache's allocator, and the entry adopts that buffer without another copy. A relocation record is read directly into that buffer. A normal blob file value is read into a local buffer and copied (or decompressed) into it once, as in base. The insert adds an entry only when the primary cache has none for the key, so concurrent readers of one value keep using the first entry.
- Flush: with enable_blob_indirection on, flush passes each value's fingerprint to BlobSource::PrepopulateFlushBlob. This fills the cache under the stable key, with the CRCs that BlobFileBuilder already computed for the BlobIndex.

### Retry of normal blob file reads

A single indirect read from a normal blob file retries a Corruption once with a newly opened reader, for a whole value and for an uncompressed range. A batched read retries only whole values; a batched range read returns the Corruption. Base MultiGetBlobFromOneFile retries whole values in the same way, and base MultiGetBlobRangeFromOneFile does not retry. Relocation reads are not retried; their failed opens are remembered instead.

### What is live in this diff

No DB read reaches a relocation file yet: BlobPhysicalFile::is_relocation is false on every DB read path. With the test hook (see "option gate"), DB reads use the indirect read path for normal blob files, and flush fills the stable blob cache. Tests drive the relocation file reader directly. The legacy read-path changes below apply to all users.

### Monitoring

- BLOB_RELOCATION_FILE_OPEN_FAILURES (ticker) counts relocation file reader opens that fail, for example because the file is missing, corrupt or cannot be read. Opens of normal blob files still count only in NO_FILE_ERRORS.
- BLOB_RELOCATION_FAILED_OPEN_CACHE_HITS (ticker) counts reads that get the remembered failure of an earlier open, without opening the file again. BlobFileCache remembers a failed open for kFailedRelocationOpenMicros (1 second) when the error comes from the file itself (Corruption, NotFound or PathNotFound).
- TableReaderCaller::kBlobRelocationFileRead marks the block reads of a relocation file (index and location blocks, in lookups and in the location block pin) in block cache traces. Record reads do not use the block cache, so they are not in a block cache trace. Relocation readers get the DB's block cache tracer, the same one that SST readers get, so a block cache trace includes these reads: one record for each block cache hit and each block read. BlockCacheTraceHelper::IsUserAccess() returns false for this caller, because one caller value covers all relocation reads: user reads and background reads both use it. The block cache trace analyzer prints the caller as "BlobRelocationFileRead".
- Location block lookups go through the normal block cache lookup and block read. So they count in the same block cache tickers (BLOCK_CACHE_DATA_*, BLOCK_CACHE_INDEX_*) and block read perf counters as SST blocks. Only a block cache trace tells them apart, by the caller kBlobRelocationFileRead.
- The Corruption message "Stable blob checksum mismatch" names the generation and origin file numbers and the original offset of the reference.
- Feature off: both tickers change only when a relocation file is opened, and only relocation file reads use the new caller. A DB without relocation files never updates them.

## Changes visible to legacy blob users (option off)

These changes are in code that the relocation reader and the stable read path share with the legacy blob read path (BlobSource, BlobFileCache, the SimpleGen2 record readers and BlockBasedTable). The relocation reader needs each of them, so they are in this diff and not in a separate one. They also apply with the option off.

| # | Change | Impact |
|---|---|---|
| 1 | Flush prepopulation of legacy blobs goes through BlobSource. BlobSource charges its blob cache to the block cache when charging is enabled | Affects users with prepopulate_blob_cache=kFlushOnly and blob cache charging enabled (CacheEntryRole::kBlobCache charged). In base RocksDB these entries were not charged |
| 2 | BlobFileCache returns Incomplete for kBlockCacheTier reads before it opens a reader | Callers already handled this case the same way |
| 3 | Legacy decompression returns Corruption for unsupported compression types and for sizes above about 4 GiB, before it allocates memory | Safer on bad input |
| 4 | SimpleGen2 readers accept compressed records in whole reads. A range read of a compressed record returns Corruption, as in base | Base writers never compress, so existing data is not affected |
| 5 | Batched MultiGetSameFileBlob works without a BlobSource | No behavior change for existing callers |
| 6 | An embedded-blob range read on a table reader with no BlobSource works. In this diff the only such reader is the relocation file reader; sst_dump and SstFileReader do no range or lazy blob reads. In base RocksDB this read returned Corruption, because reaching that path was taken as a sign of a corrupt index | Dropping the guard is safe: ValidateEmbeddedBlobIndex still checks that the index is a same-file index, that the file has embedded blobs and that the record is inside the file |
| 7 | A batched embedded-blob read that needs one file read (one record, exact duplicates of one record, or overlapping ranges of one value) uses a plain positional read instead of a MultiRead with one request | Same results and the same blob read statistics. A custom FileSystem sees a Read instead of a one-request MultiRead, and the MULTIGET_IO_BATCH_SIZE histogram gets no sample for it |
| 8 | BlockBasedTable::RetrieveMultipleBlocks also accepts no MultiGetRange. Then it reads synchronously and no GetContext gets statistics. This lets the relocation lookup share it | Normal MultiGet passes its range as before, so its behavior does not change |

## Implementation

- db/blob/blob_relocation_file.{h,cc} (new): the format code. The directory format version is 1 (BlobRelocationDirectory::kFormatVersion). The directory has no fixed count limit. Two checks bound its size instead: the decoder requires the size to equal the header plus the stated entries and served files, and ValidateForFileSize requires the encoded directory and the record bytes to each fit in the file.
- BlockBasedTableBuilder: non-virtual relocation methods (start, add served file, add record, get metadata); the base TableBuilder is unchanged. NewBlobRelocationTableBuilder creates and starts a relocation builder. It takes the file identity and size target in one struct (BlobRelocationTableFileInfo), so values of the same type (db_id and db_session_id, file_number and target_file_size) cannot be swapped by mistake. MakeBlobRelocationTableOptions forces the table options, with a comment for each.
- BlockBasedTable: MultiGetRawEntries, RetrieveDataBlocks (shared by the lookup and the pin), PinDataBlocks and MultiGetRawEntriesPinned. Embedded blob reads create their decompressor once per table reader. After a relocation reader checks the directory, it drops its copy of the directory property from its table properties. Debug builds assert that no read has started at that point (Rep::read_started), because the drop replaces the properties that readers share.
- BlobRelocationFileReader keeps only the directory totals and digest, not the decoded directory, because the location entry check proves that a value is in the file. BlobPhysicalFile describes one resolved physical file (open info, size, relocation flag, tail size and directory digest). BlobFileCache owns the session id. It builds the relocation table factory at the first relocation open, from the column family's current table factory, and builds it again when SetOptions() changes that factory. A relocation reader does not keep the factory: its table reader keeps its own copy of the table options. The signatures for normal files keep their base shape.
- BlobSource builds StableBlobCacheKeyBuilder on first use, because db_id is set during recovery, after the column family is created. Its MultiGet classifies the requests in one pass and reads them in sorted batches that do not overlap, with fixed-size buffers (at most 32 requests).
- BlobFileBuilder takes an optional BlobSource: flush passes one, compaction passes none.
- db_bench gets a --pin_blob_relocation_location_blocks flag.
- Memory with the feature off: every column family has a BlobFileCache and a BlobSource. Their 32 relocation stripe mutexes and 128 stable cache admission stripe mutexes are built on first use, and so is the relocation table factory. A column family that never reads or caches an indirect value does not allocate them.

<details>
<summary>**Implementation details:** stripe mutexes, block cache trace plumbing, request structs</summary>

- Relocation stripes: BlobFileCache opens relocation files under their own kNumberOfRelocationMutexStripes (32) stripe mutexes, so that BlobFileCache::Evict() of a normal blob file, which runs under the DB mutex, never waits for a long relocation open. The comment at relocation_mutex_ in db/blob/blob_file_cache.h gives the reasons.
- Stable cache insert: PutStableBlobIntoCache() locks one of kNumberOfAdmissionMutexStripes (128) admission mutexes, picked by a hash of the key, looks up the primary cache again and inserts only on a miss.
- Block cache traces: ColumnFamilyData passes the DB's BlockCacheTracer to BlobFileCache, as the required last parameter of the constructor that opens relocation files. The base constructor opens no relocation file, so it takes no tracer. BlobFileCache passes the tracer to BlobRelocationFileReader::Open, which puts it in the TableReaderOptions of the table reader. With tracing off, the cost is the same is_tracing_enabled() check that SST readers do. BlockBasedTable::RetrieveDataBlocks (the raw lookup and the pin) writes a trace record for each block cache hit and each block of a batched read; a single missing block goes through RetrieveBlock, which writes its own record.
- Request structs: most fields that this diff adds to read requests are grouped in one caller-owned struct per layer, behind one pointer (SimpleGen2ReadExtras, SameFileBlobStandaloneRead, and the output pointer of RelocationBlobReadRequest). The one exception is the optional output pointer BlobReadRequest::value_crc32c (with defaulted value_crc32c parameters on BlobFileReader::GetBlob() and VerifyBlob()). All new fields have defaults, so base call sites do not change.

</details>

## Safety boundaries and unsupported cases

- Public API: new tickers BLOB_RELOCATION_FILE_OPEN_FAILURES and BLOB_RELOCATION_FAILED_OPEN_CACHE_HITS, added just before TICKER_ENUM_MAX, so its value changes. New TableReaderCaller::kBlobRelocationFileRead (15), so kMaxBlockCacheLookupCaller changes. The new tickers have no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- Compatibility of new persisted data:
  - Relocation files are a new file kind, with a directory table property of format version 1 (BlobRelocationDirectory::kFormatVersion). Readers reject any other directory version. No DB code writes relocation files in this diff. Diff 4 records them only in required MANIFEST records, so an older release fails to open such a DB before it can try to read one.
  - OPTIONS file entry pin_blob_relocation_location_blocks: as for any new option, an older release that loads this OPTIONS file needs ignore_unknown_options.
  - Stable blob cache entries are not durable data. Their keys include db_id and the session id, so an entry from before a reopen never matches.
- CRC32C is for integrity, not for authentication.
- A whole-value read of a relocation file checks the record checksum only when verify_checksums is set (BlobVerifyPolicy::kVerifyIfNoAmplification), the same rule as for normal blob files. It checks the logical CRC when verify_checksums is set or when the value goes into the stable blob cache.
- Range reads follow the base rule. A range read that covers the whole value is a whole read: the public lazy API turns it into a whole read (kWholeBlobLength), and a whole read checks the CRC as the verify policy says. A range read of a strict part of an uncompressed value reads only the range bytes and checks no CRC, unless force_verify is set (then the lazy API reads and checks the whole value). So the application owns the integrity of the data it reads by range. Callers send the internal range functions only strict parts, and these functions do not turn a range into a whole read, the same as the base functions for separate blob files. This holds for relocation files and for embedded blobs. See the checksum table under "Reads" in db/blob/blob_relocation_file.h.
- A range read of a compressed value is not supported, as in base: the internal range functions return Corruption ("Cannot range-read a compressed blob"), because a byte range of a compressed record cannot be decompressed alone. Callers read the whole value and slice it, as the public lazy API already does for a compressed reference. This compression check comes first in every range path, before the cache lookup and before the kBlockCacheTier check. So a compressed range also returns Corruption on a stable blob cache hit and for a kBlockCacheTier read.
- Relocation files do not index user keys. This diff adds no separate blob map files.
- Option gate (see Terms): behavior with the option on can be reached only through the test hook. Diff 14 removes the gate.

## Performance

This diff cannot be benchmarked alone, because no DB code writes relocation files yet. The read numbers below were measured on an earlier build of the whole stack (its tip, which includes the indirect blob GC job of diff 9). They measure the format and read path added here.

Benchmark, feature off: see "Performance" in [Blob GC] 2/14. It covers the whole stack, including the legacy read-path changes of this diff.

Read benchmark (db_bench, release build): 1M keys of 16 bytes, 2 KB values, about 41% live, one indirect blob GC pass that relocated 401.5K values into 16 relocation files. The baseline is a build with one location entry per value, on the same data. Warm reads use an 8 GB block cache after a warm-up; cold reads use a 16 MB or 4 MB block cache with direct reads. Each read point runs for 20 s. This benchmark has no comparison with reads of unmoved values from a normal blob file.

Location size and read speed. The baseline is a build with one location entry per value, on the same data. Throughput is in operations per second, with 8 threads, the median of 3 runs, for both the baseline and this format.

| Case | Baseline | This format | Change | Notes |
|---|---|---|---|---|
| Location bytes per relocated value, uncompressed | 24.6 B | 4.32 B | -82% | This diff writes uncompressed location blocks, so this is also the size on disk |
| Location bytes per relocated value on disk, LZ4 | 11.9 B | 2.36 B | -80% | From diff 8, location blocks use the column family's compression |
| Index size of one relocation file | 4.2 KB | 0.80 KB | -81% | |
| Get, warm 8 GB block cache | 2.07M | 1.99M | -4% | Baseline measured on another day with another build |
| MultiGet of 32 random keys, warm 8 GB block cache | 2.63M | 2.53M | -4% | Same as above |
| Get, cold 16 MB block cache, direct reads | 258K | 1.58M (range 1.53M to 1.59M) | about 6.1x | The location blocks (about 1.7 MB) mostly fit in the cache next to the SST blocks. The baseline was not rerun, so this ratio compares two days and two builds |

pin_blob_relocation_location_blocks. The baseline is the same build with the option off. 8 threads, median of 3 runs.

| Case | Change with the option on |
|---|---|
| Get, warm block cache | +9.3% |
| MultiGet of 32 random keys, warm block cache | +10.0% |
| Get, cold 16 MB block cache | +19.9% (almost no block cache misses left) |
| Get, cold 4 MB block cache | -6.2% (the kept blocks, about 1.7 MB, take cache space from SST blocks) |
| Get, warm block cache, 1 thread | +9.3%, but noisy: the option-off and option-on ranges overlap, and the option-off runs moved 5.6% between two sessions |

Open cost of pin_blob_relocation_location_blocks, on another earlier build of the stack. One relocation file was written like one file of the read data: 26,099 values of 2 KB from 2 origins, about 41% live, LZ4 location blocks. Each run timed 300 calls of BlobRelocationFileReader::Open(), with a new block cache for each open; the table gives the median of 3 runs. The extra bytes are the LZ4 location blocks.

| Read mode | Bytes read per open, option off | Option on | Time per open, option off | Option on |
|---|---|---|---|---|
| Direct reads | 3.5 KB | 64.9 KB | 118.5 us | 312.5 us |
| Page cache | not reported | not reported | 18.9 us | 93.9 us |

All numbers come from one shared host with 192 cores (each step pinned to 32 cores).

## Validation and known limitations

- Unit tests cover the file format, the read paths, the stable cache and the legacy changes. See the Test Plan.
- The read numbers in "Performance" were measured on an earlier build of the whole stack, not on this commit.
- The relocation block size (4 KB) is an estimate. No diff in this stack tunes it.

## Stack context

See [Blob GC] 2/14, section "Stack context", for the goal, the read and lifecycle diagrams, the stack map and the terms for later diffs. This diff's row of the stack map: 3, Relocation file format and stable read path.

Tracking issue: meta#15301

Differential Revision: D124682381
…5542)

Summary:
Pull Request resolved: meta#15542

## Background

Indirect blob GC (this stack) moves the live values of a blob file into a relocation file (a file that holds values GC copied, diff 3). It never rewrites the SSTs that point to them. An SST reference finds its value by a generation number: a file number that does not change when the value moves. So every reader needs a durable map from the generation number to the file that holds the bytes now. A route is one entry of this map: it sends reads of a removed file number to the relocation file that holds its values now. Files on disk cannot give this map: a relocation file on disk may be half written, not installed yet, or already replaced. So the map must be committed in the MANIFEST, in the same edit as the file it points to, and each Version must own routes and relocation files the same way it owns SST and blob files. File numbers come from one DB-wide counter, so each file number names one file: one file kind (SST, blob file or relocation file) in one column family. "File protection" below lists the checks that keep a wrong MANIFEST record from deleting or misreading a file. "Terms used in this diff" below defines all terms.

Nothing in this diff creates routes or relocation files. The indirect blob GC job (diff 9) is the first writer. This diff is the durable model that GC installs into.

## Terms used in this diff

Stack terms from earlier diffs (origin, original offset, stable identity, generation number, indirect BlobIndex, unflattened and flattened reference, relocation file, indirect origin, exact reference metadata, option gate): see "Terms used in this diff" and "Stack context: terms for later diffs" in [Blob GC] 2/14, and the relocation file terms in [Blob GC] 3/14. This diff uses them with the same meaning. The rows below are new, have a meaning that this diff extends, or are repeated because this diff depends on them:

| Term | Meaning |
|---|---|
| live file | A blob file or relocation file that GC has not removed |
| old file | A file number whose file GC has removed. The number stays only as the key of a route, because SSTs may still store it as their generation number |
| route | Maps an old file number to the relocation file that now holds its live values (the target). One hop: a target is never itself routed. This diff stores routes in the MANIFEST, and the Version owns them |
| physical file | A blob file on disk that holds values: a normal blob file or a relocation file, as in [Blob GC] 2/14. SSTs are not called physical files. A generation number is not always a physical file: after GC removes a blob file, its number can stay only as the key of a route |

Terms of this diff:

| Term | Meaning |
|---|---|
| target | The live relocation file that a route points to. It holds all live values of the old file |
| format fence | A sticky, required MANIFEST record that says a column family (per-CF fence) or the DB (DB-global fence) may hold feature data. A binary without the feature fails to open the DB |
| fenced column family | A column family whose per-CF fence is set. Only a fenced column family has a file table. Other column families are legacy column families |
| feature data | Persisted state that only blob indirection writes: a format fence, a relocation file, a route, a blob file retirement or accepted-loss record, an indirect-origin blob file, or an SST with exact reference metadata |
| activation | The first edit in the DB that sets a per-CF fence. From then on the VersionSet keeps the DB-global fence |
| file table | BlobFileTable: per-Version table from a file number to a live blob file, a live relocation file or a route |
| relocation state | BlobRelocationState: the live relocation files, the routes and the file table of one Version. Versions share it copy-on-write |
| blob file retirement | A record (kBlobFileRetirement, one file number) that removes a collected indirect-origin blob file from the Version |
| route deletion | A record that removes the route of an old file that no SST uses any more |
| accepted loss | A record (kBlobPhysicalFileLoss, one file number) that declares a relocation file lost. It never names a normal or indirect-origin blob file; base RocksDB records a missing one as dropped (kDroppedBlobFile) when a DB is opened with best_efforts_blob_db_repair. This diff decodes it, and VersionBuilder rejects it |

## How a read goes through this diff

A read goes through the new pieces in this order:

```
  Version::GetBlob / MultiGetBlob
    -> stable blob cache (diff 3): a hit checks the file table (no I/O) and returns
    -> Version::ResolveBlobPhysicalFile: look up the generation number in the
       file table (BlobFileTable)
         live blob file or live relocation file: read it (one lookup)
         route: look up its target, a live relocation file (two lookups)
    -> BlobSource reads the physical file (diff 3)
```

## How to read this diff

1. Read "Terms used in this diff" above (core steps are 1 to 6). Then read the top comment of db/blob/blob_relocation_manifest.h ("Background", "Terms", "Lifecycle of one value", "MANIFEST records"). Its example, blob file 12 and relocation file 20, shows the whole idea.
2. Records. In db/blob/blob_relocation_manifest.h, read BlobRelocationFileAddition, BlobRelocationFileMetaData, BlobRelocationRoute and BlobRelocationRouteDeletion. Then read the new tags and setters in db/version_edit.h, and the indirect-origin flag in db/blob/blob_file_addition.h and db/blob/blob_file_meta.h. These depend only on the relocation file format from diff 3.
3. File table. Read BlobFileTable in db/blob/blob_relocation_manifest.h (the comment first, then the .cc). It is a copy-on-write map from a file number to a tagged value that points to the metadata of step 2.
4. Version state and reads. Read BlobRelocationState (same files). Then read the relocation API of VersionStorageInfo in db/version_set.h, and Version::ResolveBlobPhysicalFile and GetBlob in db/version_set.cc. Now you know how a read finds a value.
5. Edit checks. In db/version_builder.cc, read the comment "How a relocation change reaches the new Version" above blob_relocation_file_changes_. Then read Apply() (blob file retirements first), ApplyBlobFileRetirement, ApplyBlobRelocationState and SaveBlobFilesAndCheckTo.
6. Fences and MANIFEST writes. Read VersionEdit::MaybeSetBlobIndirectionFormatFence and its callers (flush_job.cc, compaction_job.cc, db_impl_open.cc). Then read WriteCurrentStateToManifest and the fence part of ProcessManifestWrites in db/version_set.cc, and the replay of the new records in db/version_edit_handler.cc. The "no re-add" rule is explained once, at VersionSet::RejectReaddedBlobRelocationState in db/version_set.h.
7. Other supporting work (you can skip it on a first read). Read "Freeing relocation state" at VersionSet::FreeBlobRelocationState in db/version_set.h, then ~Version and db/job_context.h; catch_up_mutex_ in db/db_impl/db_impl_secondary.h; the RepairDB guard in db/repair.cc; the live-file lists in db/db_filesnapshot.cc; and the purge rule for relocation files (ShouldKeepFooterlessBlobFile() in db/db_impl/db_impl_files.cc).

## Previous behavior

- The MANIFEST tracked SST files and normal blob files only.
- A kIndirectBlob reference (diff 2) was read from the blob file named by its generation number. Diff 3 added a relocation file reader, but no Version could send a read to a relocation file.
- No MANIFEST record marked a DB or column family as using the new formats, so an older binary could open such a DB and misread it.

## New behavior

The top comment of db/blob/blob_relocation_manifest.h describes the records, the route rules and the lifecycle of one value, and the BlobFileTable class comment gives the table layout. This section states the contract.

### MANIFEST records

- A relocation file addition keeps only small fields: size, checksum method and value, tail size, total entries, total record bytes and the 4-byte directory digest (the file's identity, checked at open). The deletion is a separate record. The file stays on disk while any Version uses it, like a blob file.
- There is one route per old file number. Route and relocation file numbers are at most kFileNumberMask (2^62 - 1), the same limit as SST and blob files.
- The relocation records carry no format version or column family of their own. The fence gives the version, and the edit names the column family.
- All new tags are required tags, so an older binary fails to open the DB instead of misreading it.

### Route rules (one hop)

Route rules: see "MANIFEST records" in db/blob/blob_relocation_manifest.h. This diff does not check that a target holds a given origin. Indirect blob GC proves it at install, and the reader checks the key on every read.

### Reads

Version::GetBlob, GetBlobRange and both MultiGet paths first look up an indirect value in the stable blob cache (diff 3). A hit opens no file. It checks the generation number in the file table with Version::CheckStableCacheHitHasFile(), which does the same lookup as a miss (one lookup, or two for a route), so a hit fails with the same Corruption as a miss when the BlobIndex names no physical file of this Version. On a miss, Version::ResolveBlobPhysicalFile looks up the generation number in the file table. A live blob file (unmoved value) or a live relocation file (flattened reference) takes one lookup. A route takes two lookups, and its target is always a live relocation file. The relocation reader checks the key (origin, original offset). The read path copies no shared_ptr.

### File table

- Each Version of a fenced column family has one file table with every live blob file, live relocation file and route. Legacy column families have none.
- The table is sharded and copy-on-write. An unchanged Version shares the whole state. An edit copies the top array and rebuilds only the shards it changes; a route change also rebuilds the shard of its target, which holds the route count.
- The table memory is charged to the file metadata cache reservation, best effort: a failed charge never fails an edit. An entry takes 16 bytes with 32-bit keys, or about 18 bytes with the shard headers, padding and top array (computed from the struct sizes, not measured; a unit test checks 12 to 32 bytes per entry for 10,000 entries).
- Relocation files are also kept in a sorted vector for iteration. A debug build checks after each Version build that the table and the vectors agree. Versions and MANIFEST snapshots keep no deletion history.

### Edit checks

Every edit is checked against the final state of its own column family. A bad edit fails with Corruption (an accepted-loss record and a fence on a FIFO column family fail with NotSupported) and has no partial effect (see the ApplyBlobRelocationState comment). These are rejected: duplicate or conflicting records; a set and a delete of the same key; a file number used by another file kind in the same column family; deleting a relocation file that is not live there, or that a route still targets; deleting a route that does not exist there, unless an earlier edit of the same builder deleted it; a route from a live file; a route to anything but a live relocation file.

Two more rules:
- The "no re-add" rule: adding back a relocation file, route or blob file that an earlier edit of the same MANIFEST deleted (or removed by blob file retirement) is rejected at replay and when LogAndApply writes, because file numbers are never reused. So is adding a relocation file or blob file whose number is a route that an earlier edit deleted, because that number belongs to an old file (a blob file or relocation file that GC removed). A new MANIFEST starts without deletion history. With reuse_manifest_on_open, the deletions replayed from the reused MANIFEST seed the write-time check. The comment at VersionSet::RejectReaddedBlobRelocationState names the three places that check it.
- A repeated relocation file addition (MANIFEST replay or catch-up) must equal the file that the builder already has. Apply() compares the small records and returns Corruption on a mismatch.

### Fences

- Both fences are sticky (never cleared, also after the option is turned off) and are required tags.
- Every edit that adds an SST built with enable_blob_indirection on sets the per-CF fence. Flush, compaction and the WAL-recovery flush all use one helper for this, VersionEdit::MaybeSetBlobIndirectionFormatFence. Because of the option gate, only tests reach this.
- A MANIFEST snapshot writes the DB-global fence first, and the per-CF fence only for column families that have their own. The DB-global fence exists because a per-CF fence goes away with its column family. After the last fenced column family is dropped and a new MANIFEST is written, the DB-global fence still marks the DB as one that has used the format: an older binary still fails to open it, RepairDB still refuses it, and LogAndApply still runs the "no re-add" check. At that point the only feature data left on disk is relocation files that no Version lists and that wait for the obsolete file purge.
- FIFO compaction is rejected for a column family whose own fence is set, also after the option is turned off and after MANIFEST rotation.
- A fenced column family needs a Block-Based Table writer and a compaction style other than FIFO, also with the option off. Its later flush and compaction outputs must store blob reference metadata, which only the Block-Based Table writes, and its relocation files must stay readable. SetOptions() (ColumnFamilyData::PrepareMutableCFOptions()) returns NotSupported for new options that break this. A read-write DB open (ColumnFamilyData::ValidateBlobIndirectionOptionsAfterRecovery()) checks the compaction style when the option is on or the column family is fenced. For a fenced column family it also returns NotSupported when blob direct write is on or the table factory is not Block-Based.

### Blob file retirement

- A blob file retirement record removes a live indirect-origin blob file that indirect blob GC has collected. The indirect blob GC job (diff 9) is its first writer. A file that still has live values also gets its route in the same edit; an empty file leaves without a route.
- VersionBuilder applies blob file retirement records before the relocation records, so the rule "the old file of a route is not a live file" still holds.
- SSTs can keep references under the number of a blob file removed by blob file retirement. Compaction writes no BlobFileMetaData garbage record for a routed generation number or for a live relocation file. VersionBuilder ignores a garbage record for a routed generation number (it can come from a compaction picked before the blob file retirement). The census of diff 5 tracks these values instead.
- These fail with Corruption: a route from a live blob file without its blob file retirement record; a blob file retirement record for a file that is not a live indirect-origin blob file; a new blob file or relocation file that reuses a route key, also when the same edit or an earlier edit of the batch deletes that route; and a route deletion that names no route.

### Accepted loss

The accepted-loss record is decoded here. VersionBuilder fails on it with NotSupported instead of skipping it. Diff 5 applies it. No code in this diff writes it. Its first producer is best-efforts recovery in diff 13, through the MANIFEST snapshot.

### File protection

File numbers come from one DB-wide counter, so two column families do not get the same file number. Nothing checks this across column families. Three kinds of checks keep a wrong MANIFEST record from deleting or misreading a file:
- Per column family: VersionBuilder checks each relocation, route and retirement record against the state of the edit's own column family (see "Edit checks" above).
- Purge: the obsolete file purge is DB-wide. A .blob file stays while any column family's Version lists it as a blob file or a relocation file (Version::RemoveLiveFiles() and, for a full scan, Version::AddLiveFiles()).
- Read: a reader checks the column family ID in the blob file header, or in the table properties of a relocation file, when it opens the file. Each read in a relocation file also checks the value's key (origin, original offset), so a wrong route cannot return another value.
"File protection" in db/blob/blob_relocation_manifest.h lists every check.

### Freeing builder state inside a batch

LogAndApply destroys the version builders of a batch, with their staged relocation file and route changes, under the DB mutex, and does not release the mutex for them. The staged changes hold one map entry per relocation file record and per route record in the edits of the batch, so freeing them costs less than applying those edits and does not grow with the file table. The writer callbacks then run in the same mutex hold as the install of the new Versions, as in diff 1. This matters for a flush: if another thread could take the mutex between the install and the callbacks, it would see the new L0 file while the flushed memtables are still in the immutable list. A memtable switch in that state would build a SuperVersion that reads the flushed data twice, so a merge operand would be applied twice. When a batch fails, LogAndApply deletes its new Versions under the mutex. A new Version that is the only owner of its relocation state hands its file table to the deferred free (row "Freeing Version state" in "Changes visible to existing users").

### Other changes

- BlobFileAddition gets an indirect-origin flag, so a Version knows which normal blob files are indirect origins. It is a new custom field, written only when set. It adds about 8 bytes per blob file in memory (an estimate, with padding).
- Checkpoints and backups copy relocation files: live-file lists, checksum lists and GetLiveFilesStorageInfo include them. rocksdb.total-blob-file-size counts them too, because it reports the disk space of every blob file that some Version keeps alive. The other blob statistics (GetBlobStats(), so rocksdb.live-blob-file-size, rocksdb.live-blob-file-garbage-size and rocksdb.blob-stats; rocksdb.num-blob-files; GetColumnFamilyMetaData() and GetApproximateSizes()) count only normal blob files in this diff.

### Monitoring

- BLOB_DB_INDIRECT_READ_ROUTED (ticker) counts reads that miss the blob cache and find their file through a route in Version::ResolveBlobPhysicalFile(): the reference names an old file whose live values moved to a relocation file. A blob cache hit does not count: it checks the generation number in the file table, but it reads no file. A route whose target is missing fails with Corruption and does not count.
- rocksdb.blob-indirection-format-version (DB::Properties::kBlobIndirectionFormatVersion, an int property per column family) returns the per-CF format fence of the current Version. 0 means that the column family has no format fence yet: no SST built with enable_blob_indirection on was installed.
- The Corruption messages of ResolveBlobPhysicalFile() name the generation number and the origin of the reference, and the route target when the target is missing.
- ldb manifest_dump prints one line for each column family that has the per-CF format fence, relocation files or routes: "--- blob indirection --- format version: V, relocation files: F (B bytes, N values), routes: R". When the DB-global fence is set, it also prints "db blob indirection format version V". A DB without blob indirection prints nothing more.
- Feature off: the ticker changes only on the route branch, and only a fenced column family has routes. The property reads one field of the current Version when it is called.

## Changes visible to existing users (feature off)

These changes also reach DBs that never turn the option on, because the shared code must handle relocation state: freeing a large file table and the relocation file checks at catch-up run without the DB mutex, RepairDB must look for feature data in every DB before it writes a new MANIFEST, and LogAndApply and Version build must tell a legacy edit from a relocation edit.

| Change | Effect |
|---|---|
| Freeing Version state | A fenced Version holds a file table that can be large. Its memory is freed without the DB mutex ("Freeing relocation state" at VersionSet::FreeBlobRelocationState). Versions, builders and FileMetaData reference counts still change only under the DB mutex. A legacy Version or builder has no relocation state, so nothing changes for it |
| Secondary and follower catch-up | Record decoding, the relocation file checks (I/O) and blob metadata finalization run without the DB mutex. catch_up_mutex_ serializes them: a concurrent caller waits and then catches up. Builder apply, SST file saves and Version deletion stay under the mutex. In a legacy DB, record decoding and blob metadata finalization also run without the DB mutex |
| RepairDB | First reads all MANIFESTs once, the descriptor property of every SST and the header of every blob file, to look for feature data (see "Safety boundaries"). The SST read can open a table one more time: the repair table cache holds only 10 tables, so in a DB with more SSTs the later scan opens the table again |
| LogAndApply | One O(1) check per edit (VersionEdit::SetsBlobIndirectionState). The legacy path does no other new work under the DB mutex |
| Version build | The relocation state is one null shared pointer. The legacy validation does not scan blob files |

## Implementation

MANIFEST records, edit checks and fences: see "New behavior". The choices that are not stated there, and why they are enough:
- Copy-on-write, sharded file table (BlobFileTable inside BlobRelocationState): an unchanged Version shares the whole state, and an edit rebuilds only the shards it changes. So an edit that does not touch relocation state copies no table data, and a legacy CF holds only one null shared pointer.
- Route resolution in Version::ResolveBlobPhysicalFile: one table lookup for a live file and two for a route, because a route is one hop. SyncBlobFileTable keeps the table's blob file entries in step with the saved blob files.
- Work that can be large runs without the DB mutex: freeing relocation state (VersionSet::FreeBlobRelocationState) and the ManifestTailer steps (through the RunWithoutDbMutex helper). catch_up_mutex_ in secondary and follower DBs serializes catch-up, so that releasing the DB mutex does not let two catch-ups run at once.
- Point-in-time MANIFEST replay (best-efforts recovery and secondary catch-up) opens and checks each relocation file that it replays (VersionEditHandlerPointInTime::VerifyBlobRelocationFile, through BlobRelocationFileAddition::ToPhysicalFile()), unless trust_manifest_recovery is set. So such an open does I/O for each relocation file.
- Small items: relocation files in the live-file lists of checkpoints and backups (db/db_filesnapshot.cc), the purge rule for relocation files (db/db_impl/db_impl_files.cc), and the RepairDB guard (db/repair.cc). "Safety boundaries" below explains the purge rule and the guard.

## Safety boundaries and unsupported cases

- Public API: new ticker BLOB_DB_INDIRECT_READ_ROUTED, added just before TICKER_ENUM_MAX, and new property rocksdb.blob-indirection-format-version. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- Normal recovery fails closed when a required record names a file that is not valid. A bad edit is never partly applied.
- Best-efforts recovery in a fenced column family (without best_efforts_blob_db_repair) accepts a MANIFEST point only when no relocation file is missing, any missing SSTs are an L0 suffix (as in base), and no missing blob file is one that the save rule would keep in that point's Version (VersionBuilder::Rep::SaveRuleKeepsBlobFile(), which follows the keep rules of SaveBlobFilesTo()). The save rule does not keep a blob file that a blob file retirement record removed, or a normal blob file that no SST links and whose bytes are all garbage, or a normal blob file below the smallest oldest_blob_file_number of the saved SSTs; a dropped-file record from a best_efforts_blob_db_repair open also accepts a missing file. The base check treats a missing blob file as not needed when it is below the smallest blob file that some SST of the point links (GetMinOldestBlobFileNumber()), or when no SST or only missing L0 files link it. This does not hold with the fence: an indirect reference can name a blob file that is not the oldest blob file of its SST, indirect blob GC deletes its inputs without rewriting the SSTs that reference them, and an SST's oldest blob file can be a retired origin (VersionBuilder::Rep::MissesNeededBlobFile()). The same blob file check runs in secondary catch-up, which accepts no missing SST. Recovery falls back to the newest point that misses no needed blob file (the empty column family if the file is in the starting snapshot of the MANIFEST). Consequence: in a fenced column family, plain best-efforts recovery can fall back further than base would, because it cannot use the base relaxation for a missing blob file linked only to a missing L0 suffix. In the worst case it reaches an empty DB, which is consistent. It never accepts a point whose SSTs reference a missing file, and a healthy DB keeps its newest point. To keep more data, open with best_efforts_blob_db_repair, which records missing files as dropped. A column family without the fence keeps the base rule.
- Downgrade to a binary without the feature is not supported once a fence is written. The fence is a required tag, so the older binary fails to open.
- Compatibility of persisted data: a MANIFEST written without these records is read the same as before. The new records are required tags, so an older release fails to open a MANIFEST that has them. The indirect-origin field of BlobFileAddition is an ignorable custom field, written only when set. An older release could skip it, but it never applies such an addition, because the per-CF fence is a required tag in the same edit.
- RepairDB guard. RepairDB does not support a DB that uses blob indirection: it writes a new MANIFEST from the files it finds, so it would lose the relocation files and routes that the old MANIFEST records. Before any archive or NewDB step, RepairDB looks for feature data: in any MANIFEST, a fence, a relocation or route record, a blob file retirement or accepted-loss record, or an indirect-origin blob file addition; in any SST, a decodable exact reference metadata descriptor; in any blob file, a version 2 header (diff 2). Only blob indirection writes a version 2 header, and RepairDB can read it without the MANIFEST, which is often damaged when RepairDB runs. If it finds any feature data, it returns NotSupported ("RepairDB does not support a DB that uses blob indirection") and leaves all inputs untouched. Otherwise legacy repair runs as in base, and its WAL-converted output keeps enable_blob_indirection off. Later diffs add evidence for the data they add.
- Nothing in this diff writes routes, relocation files or loss records. Diff 9 (the indirect blob GC job), diff 10 (flatten, route retirement) and later diffs do.
- The deleter of a relocation file does not evict its cached reader. The deleter can run under the DB mutex: this happens when the last Version or LogAndApply version builder that owns the file is destroyed. ManifestTailer frees relocation state without the DB mutex. An eviction would take the stripe mutex of the file in the blob file cache, which a relocation file open can hold while it reads its location blocks (pin_blob_relocation_location_blocks). The deleter only drops the remembered failed open of the file. PurgeObsoleteFiles() deletes the file and evicts the reader with TableCache::Evict(), outside the DB mutex (the blob file cache shares its Cache with the table cache). A relocation file has no blob log footer, so the purge recognizes it by its prefix (kBlobRelocationFilePrefix) instead of keeping it as a footerless blob file that blob direct write may still be writing. The purge (ShouldKeepFooterlessBlobFile()) reads the blob log footer first, so a blob file with a valid footer costs no extra read. Only a file without a valid footer gets the prefix read. A relocation file smaller than a blob log header plus footer (BlobLogHeader::kSize + BlobLogFooter::kSize, 62 bytes) has no room for a footer, but its prefix is still read, and the purge deletes it.
- Option gate (see Terms): behavior with the option on is reachable only through the test hook. Diff 14 removes the gate.

## Validation and known limitations

- Unit tests cover the record codecs, edit checks and atomic apply, the file table against a std::map model (both key scans, both key widths), blob file retirement, replay and MANIFEST snapshots, checkpoints, freeing state without the DB mutex, the RepairDB guard and secondary catch-up. See the Test Plan.
- Known limitations:
  - RepairDB does not support a DB with blob indirection data. It returns NotSupported (see "Safety boundaries").
  - The RepairDB search for feature data is best effort. It skips a MANIFEST, record, SST or blob file that it cannot read. So a DB whose feature data is all unreadable still gets legacy repair.
  - Only tests can turn the option on until diff 14.

## Stack context

See [Blob GC] 2/14, section "Stack context", for the goal, the read and lifecycle diagrams, the stack map and the terms for later diffs. This diff's row of the stack map: 4, MANIFEST routes and relocation state in the Version.

Tracking issue: meta#15301

Differential Revision: D124740371
Summary:
Pull Request resolved: https://github.com/meta/rocksdb/pull/15543

## Why the change is required

Indirect blob GC (this stack) moves the live values of a blob file into a relocation file and never rewrites the SSTs that reference them. An SST reference finds its value by its generation number: a file number that stays the same when the value moves. Before GC drops a value, it must prove that no SST still uses it. Routes (old file number -> relocation file, diff 4) point forward, so they cannot tell which SSTs use a generation number. GC needs the reverse view: for each generation number, the SSTs that use it and the bytes they keep. This diff adds that view, the census. "Terms used in this diff" below defines the terms of this diff and names the lower diffs that define the others.

The census must not slow down the MANIFEST write queue. A full scan of the SSTs, or a copy of a DB-sized reverse index for each new Version, at the head of the queue would delay every Version install. So a background job builds the census, and each install hands it only a small prepared change.

Nothing in this diff uses the census to collect files. The indirect blob GC job (diff 9) is the first user.

## Stack context

This diff is part 5 of the indirect blob GC stack. "[Blob GC] 2/14", section "Stack context", gives the goal of the stack, how a read finds a value, the lifecycle of a value and the stack map. The row of this diff in the stack map is "5: Exact reverse reference census".

## Terms used in this diff

Terms from lower diffs, used here without change: origin, original offset, stable identity, generation number, unflattened and flattened reference, exact reference metadata, group (reference group), descriptor, option gate (diff 2); relocation file (diff 3); indirect origin (diff 2, "Stack context: terms for later diffs"); route, format fence, fenced column family (fenced CF), relocation state, blob file retirement, accepted loss (diff 4). A later diff adds route retirement (diff 10): the background job that removes the routes that no SST uses; see "[Blob GC] 2/14", "Stack context: terms for later diffs".

Terms of this diff (the top comment of db/blob/blob_reference_census.h defines them in more detail):

| Term | Meaning |
|---|---|
| SST summary | BlobReferenceSstSummary (a type from diff 2): the totals of every indirect group of one SST, in memory. The table builder makes it for a new SST, or a reader decodes it from the reference index of an existing SST. It is never written to the MANIFEST |
| census | Background, in-memory count, per generation number, of the SSTs that reference it, plus live bytes per physical file. One per column family that needs it |
| exact SST | An SST with exact reference metadata (a nonempty descriptor). The census counts only exact SSTs, and only their two indirect classes |
| coarse SST | An SST built without exact reference metadata. It records one file number, its frontier, and GC must treat every indirect-origin file at or above the frontier as used (see "Coarse SST" in db/blob/blob_reference_metadata.h). No code in this diff writes a coarse SST |
| physical file | The physical files (diff 2) that the census tracks: indirect-origin blob files and relocation files, which hold value bytes and can be GC candidates |
| holder | An exact SST that has at least one counted group with a given generation number |
| slot | A small dense number that the census gives each exact SST, so that holder sets stay small |
| delta | The census change of one Version install: SSTs added and removed (with their summaries) and relocation state changes |
| change log | One ordered queue of deltas. The census reads it through one cursor, the build cursor, during the build and after it |
| census job | The background job on the LOW pool that builds the census and applies deltas |
| worker | The code that applies deltas and changes the census contents. The census job runs it, and so does a flush or compaction thread right after its install. Only one thread runs it at a time |
| ready (census publication) | The census has applied every delta up to the current Version and stores its ranked GC candidates in that Version |
| install reservation | While a Version install of the column family is being prepared (BeginInstallPreparation()), the census does not become ready, because that Version is about to be replaced |

## Previous behavior

- There was no reverse census, so nothing could find the SSTs that use a generation number.
- The MANIFEST did not record an SST's reference descriptor.
- Diff 4 decoded the accepted-loss record but failed replay on it.
- A blob file left the Version when no SST linked it and its approximate garbage count reached its total. This also applied to indirect origins.
- Blob files below the oldest linked blob file (the smallest oldest_blob_file_number over the saved SSTs) were dropped from the Version. This also applied to indirect origins.

## New behavior

### Census job

- Each fenced CF has one census. One background job on the LOW pool serves the census of every fenced CF in turn. The job builds no census for a CF without the per-CF fence.
- Once the DB has the DB-global format fence, a column family with enable_blob_indirection also gets the census object at its next install, before its own per-CF fence is set (ColumnFamilyData::blob_reference_census()), so that its installs can be reserved. The job builds that census only after the per-CF fence is set. Until then, the column family reports census-state none and an unready time of 0, and DumpStats does not warn about it, because its census does not wait for any build.
- Open schedules the census of each CF that already has the fence. A CF that gets the fence after open (at its first flush with the option on) has its census scheduled when that Version's SuperVersion is installed.
- Apply after an install: the census job shares the LOW pool with compactions, so with few background threads a delta could wait a long time. So at the end of each background flush and compaction, the thread releases the DB mutex and runs the worker for each column family with a census that the job flushed or compacted (also when the job failed). A column family dropped before the job ends is not visited. So the work is O(the job's column families), and a DB without blob indirection has nothing to visit. A column family in the retry list is visited too, so its deltas do not wait for the periodic task. For each column family, the thread applies the queued deltas in order, up to and including the delta of the Version that was current at the end of its job. The job records that Version number under the DB mutex at the end of the job, at or after its install. A later install that happened while the job had the DB mutex released after its install (for example while it notified its event listeners) can still be applied here. The deltas of installs after the job recorded the number are left to the census job, so a flush thread in the HIGH pool does not keep applying the deltas that other jobs install while it applies. If the thread applied at least one delta and no delta is left, it then tries to publish. When deltas are left, the census becomes ready a little later, when the census job applies them.
- This step does not wait: if another thread runs the worker of a column family, it skips that column family. It also skips a column family whose build has not started, has not finished its scan of the SSTs, or has a stored failure.
- This step never fails the flush or the compaction. When it cannot go on, it leaves the rest to the census job. A delta that gets TryAgain (a registered indirect blob GC job has not yet copied its snapshot) is not changed and stays at the front of the queue. On a change log overflow, the thread stops, and the census job restarts the build, or fails it after a second overflow; if a delta failed at the same time, the thread drops the queued deltas. Any other failure may have changed the census part way, so that delta is never applied again: the thread stores the failure and logs it once, later applies after an install skip the column family, and the census job fails the build with that error and builds again. A failed FinalizeWorkerBuild() after the deltas is handled the same way. FinalizeWorkerBuild() builds the holder sets one generation number at a time and may stop part way, so a later call returns the same Corruption again and never builds the rest from a partial state. A census job run that fails stores its failure the same way before it releases the worker run lock (BlobReferenceCensus::worker_run_mutex(), which the thread that runs the census worker holds), so no apply after an install runs between the failure and the end of the build. The census job also handles a publish that fails or must wait.
- Before this step and before it frees the deferred census cleanup, the flush or compaction thread wakes the waiters of bg_cv_ and atomic_flush_install_cv_. It does so whenever it will release the DB mutex here, also for a job without a census whose deferred cleanup is not empty. Both steps leave unchanged what the waiters wait for.
- Installs on other threads (for example a user CompactFiles()) do not run this step. The census job, or the next flush or compaction of the same column family, applies their deltas. They do free the deferred census cleanup after their SuperVersion install (see "Freeing census state without the DB mutex").
- After a failure, the census retries through a periodic task (PeriodicTaskType::kBlobReferenceCensus, period 1 second). The task is registered when the first census build starts. The retry delay doubles after each failure: 1 s, 2 s, and so on up to 32 s. One second matches the shortest retry delays: the first retry after a failed build, and the first retry of a candidate that failed for a transient reason. While an indirect blob GC snapshot is pending, the census asks for a retry after 1 ms; because the task runs once per second, this retry really waits until the next tick, up to 1 s.
- Retry policy: the census retries every failed build without limit, also for errors that may not go away (for example Corruption or a missing SST). It never sets a background error. Only indirect blob GC needs the census; reads and writes do not. A background error would stop all writes of the DB for an index that only GC uses, so a failed census only delays GC. Every failed build logs a line with its status (except after a second change log overflow, which logs a fixed WARN line). A build that a rebuild install canceled (status Aborted) restarts at once and logs at INFO: a rebuild install comes from DeleteFile(), DeleteFilesInRange() or a compaction that could not read an input summary, it can happen many times during one large build, and it needs no action. A Corruption logs at ERROR. Every other failure, including a restart after a change log overflow, logs at WARN. The signals of a census that keeps failing are census-state=failed and census-consecutive-failures in rocksdb.indirect-blob-gc-stats, and the DumpStats WARN after 10 minutes. There is no failure ticker: it would be one more value in the public Tickers enum that nobody has asked for, and the signals above already show a census that keeps failing. It can be added in a follow-up. The same policy is in the comment "Errors and rebuild" in db/blob/blob_reference_census.h.
- When no column family is on the retry list, which is the usual case, the periodic task returns before it takes the DB mutex. The size of the retry list is an atomic that changes only under the DB mutex. A column family that joins the list after this check waits for the next tick.

### Holder sets

- For each generation number, the census keeps the set of SSTs that hold it, plus its reference count and byte totals.
- The groups of one SST are summed per generation number. An SST that holds a generation number for several origins is one holder of it.
- SST numbers map to slots. A new SST gets the lowest free slot.
- Each holder set is a delta-varint list or a bitmap, whichever is smaller. Let U be one past the highest slot in use. A list becomes a bitmap when it is larger than U/8 bytes. A stored bitmap ends at the highest slot of its own set, so it takes at most about U/8 bytes. A bitmap becomes a list when the list would be smaller than U/16 bytes. The gap between the two points keeps a set from switching back and forth.
- A bitmap is updated in place: bits are set and cleared. It is encoded again only when it may cross the switch point.
- A list is encoded again at its exact size, so no capacity slack is charged. A list that switches to a bitmap frees its buffer.
- The census keeps no per-SST summary after it adds a file.

### Where SST summaries come from

- Versions do not keep SST summaries. A summary is set only on new files in an edit, and Versions drop it.
- A compaction reads the reference index of each input SST when its job starts. The read uses fill_cache off and the job's rate limiter priority, and its memory is charged to kBlobReferenceCensus. The compaction passes these summaries with its edit, so the census can remove the inputs.
- Every compaction does this read, also a full compaction, so every compaction install updates the census with a delta.
- If the read fails, the compaction still runs, and the census is rebuilt after the install.

### Paths that remove an SST

An install marks the census for rebuild when it removes an exact SST without its summary. The census stops being ready, and the build runs again at once, without backoff. The summaries of the SSTs that the install adds are kept as seeds, so the rebuild does not read those SSTs.

| Path | Census handling |
|---|---|
| Compaction (CompactionJob) | Supplies the summaries of the removed SSTs |
| Full compaction (every base SST removed) | Like any compaction: supplies the summaries of the removed SSTs (delta) |
| DeleteFile, DeleteFilesInRange(s) | Rebuild |
| Ingestion with a replace range | Rebuild (ingestion into a fenced CF is rejected until diff 12) |
| FIFO deletion | Not reachable: blob indirection rejects FIFO compaction |
| Trivial move, ReFitLevel, PromoteL0, experimental metadata update | The same file number is removed and added; the census skips it |
| FIFO temperature change (copies a file to a new file number) | Not reachable: a fenced CF rejects FIFO compaction |
| RepairDB | Rejected with NotSupported for a DB that uses blob indirection (the RepairDB guard of diff 4) |
| Best-efforts recovery | New DB open; the census is built as at open |

### Change log and self-check

- The build cursor can have at most kMaxLogMemory (256 MB) of queued delta weight. A delta's weight (QueueWeight()) counts all memory that the delta keeps in the change log, including the SST summaries that have their own cache charge. The change log charges only the rest (ChargeBytes()), so no summary is charged twice. Outside a build, an installing thread usually applies each delta at once. During the scan of a build, installing threads skip the column family, so deltas wait in the log between build slices. 256 MB is an estimate, not a measurement, of a size that only a long build of a very large DB under heavy write load should reach.
- The limit is checked before each append, so the cursor holds at most the limit plus one delta. If the cursor is already at the limit, the build restarts at once. The restarted build, and every later build until one publishes, has a larger limit, kMaxRestartLogMemory (1 GB, 4 x kMaxLogMemory, an estimate, not tuned). The factor 4 leaves room for one slow full rebuild under write load.
- If a build also overflows the larger limit, it fails and retries after the normal backoff (1 s, doubled after each failure, at most 32 s). The census job logs a WARN line and counts it in a new ticker, BLOB_DB_CENSUS_RESTART_OVERFLOW_COUNT. So overflows never restart builds in a loop without a delay, and the change log memory stays bounded. Indirect blob GC waits while the census is not ready, so no value is lost. An overflow that the publish step finds (after the last catch-up of the build) is handled the same way as one that a build slice finds.
- Debug builds compare the ready census with a fresh build from the same Version. They do this after 1 in 16 publications of the census job, chosen with util/random.h. They also add up the live bytes of the generation numbers on each physical file again, and compare the sums with the candidate heap. A publish by the apply after an install is not checked.

### GC candidates

- A ready census stores ranked indirect blob GC candidates in the Version and schedules compaction picking. No picker uses them until diff 9.
- One GC job selects at most kBlobGcMaxSelectedFiles (8) files.
- A GC job checks that the census is ready for its Version, and copies the holders of only the generation numbers of the selected files, without the DB mutex. So GC never copies or scans the whole census under the DB mutex.

### Cache charging

- Census memory is charged to a new CacheEntryRole, kBlobReferenceCensus. This covers the reverse index, its build state, the change log and the queued deltas. The change log charge leaves out the summaries that already have their own cache charge: the table builder charges the summary of a new SST (kBlobReferenceMetadataBuildingBuffer), and the compaction's input read charges the summary of a removed SST (kBlobReferenceCensus).
- A change log entry that holds a newer relocation state is charged only for that state's relocation file metadata. The state's file table is already charged to the file metadata reservation (diff 4). Each shard of the table is charged once, until its last holder frees it, so it is not charged again for each entry.
- The role follows cache_usage_options.options_overrides, with the same default as the other charged roles. It has its own line in the block cache entry stats.
- With charging for kBlobReferenceCensus disabled, the census itself, its build state and its change log are not charged. The SST summaries that a census build or a compaction reads are then charged to kBlobReferenceMetadataBuildingBuffer, unless that role is disabled too. The comment of kBlobReferenceCensus in include/rocksdb/table.h says so.
- A failed block cache charge never fails a flush, a compaction, a census build or an install, and never sets a background error. When a charge of the census worker state, its build state, an SST summary or a change log entry fails because the block cache is full (strict_capacity_limit), that memory stays uncharged and the work goes on (AllowUnchargedWhenCacheIsFull()). The census still becomes ready, and installs still update it by delta. The change log stays bounded by kMaxLogMemory (256 MB), or by kMaxRestartLogMemory (1 GB) after an overflow restart; the summaries that installs add count in that limit. The worker state and build state are not bounded by a fixed limit: they grow with the SSTs and blob files of the column family, as when census charging is disabled. A census build holds one summary that it reads at a time. A compaction holds the summaries of its input SSTs until it ends, so that memory grows with the compaction input. Reporting: ReadBlobReferenceSstSummary() takes an explicit counter for uncharged reads. The census build passes the census counter, and the census job logs one WARN line per build that had any uncharged census charge or summary read; census-uncharged-builds in rocksdb.indirect-blob-gc-stats counts these builds. census-uncharged-charges counts the census charge attempts and the summary reads of a census build that failed because the cache was full and went on uncharged, also those of installs and applies after the census is ready, which log nothing. It counts attempts, not bytes, so it does not show how far the census is above the cache limit. A later charge that succeeds can charge that memory again. A compaction does not count its uncharged input summary reads there; it logs one WARN line for all of them. Other callers (the debug self-check) pass no counter and log one WARN line per uncharged read. The copies that indirect blob GC takes keep a strict charge, because GC is optional work that skips or defers its inputs when it cannot charge them. The debug self-check uses the same kind of copy, so with a full cache it skips its comparison.

### Monitoring

- rocksdb.indirect-blob-gc-stats (DB::Properties::kIndirectBlobGcStats) is a map property per column family. DB::GetProperty() also returns it as text, one "key=value" line per key in key order, because GetProperty() needs a string form of every property (db_stress reads every property with it). A call runs under the DB mutex, as other map properties do. It reads the current Version and relaxed atomics of the census, and takes only two short census locks: the log mutex (in IsReady()) and worker_state_mutex_ (in StayingMemoryBytes()). It never takes the worker mutex, so it does not wait for a running census build. Every *-micros key is a duration, not a timestamp. The comment of DB::Properties::kIndirectBlobGcStats (include/rocksdb/db.h) lists every key. Some details are not in that comment. census-state is building while the census is unready and no build has failed, also before its first build starts, and failed when its last build failed. tracked-files, the garbage-bytes-*, coarse-pinned-* and relocation-garbage-bytes keys show the totals of the last census publish. Also, a new census is unready from the moment it is created (ColumnFamilyData::GetOrCreateBlobReferenceCensus() calls NoteUnready()), so a census whose first build never starts, for example while background work is paused, shows its unready time and not 0. A column family without its per-CF fence is the exception: it shows census-state none and 0 (see "Census job"). When an install gives the column family its fence, the unready time starts again at that install (VersionSet::ProcessManifestWrites()), so the time before the fence is not counted. census-consecutive-failures is capped at 6, because from the sixth failure on the retry delay stays at its maximum. BlobGcCandidateHeap keeps the garbage and tracked-file totals up to date as the heap changes, and a publish copies them.
- rocksdb.blob-reference-census-unready-micros (DB::Properties::kBlobReferenceCensusUnreadyMicros, an int property) returns the same value as census-unready-micros. One helper, InternalStats::BlobReferenceCensusUnreadyMicros(), computes both.
- VersionEdit::DebugString() and DebugJSON() print the kind of blob reference metadata of each added SST: "exact (N references, B stored value bytes)", "coarse (frontier F)" or "legacy". An SST without such metadata prints nothing more. ldb manifest_dump also prints one line per column family with blob indirection: "--- blob reference metadata --- exact SSTs: E, coarse SSTs: C (lowest frontier F), legacy SSTs: L".
- LOG lines:
  - When a build publishes for the first time, the thread that publishes it logs INFO "Blob reference census is ready at Version N after M ms". This is the census job, or a flush or compaction thread whose apply after an install finishes the build.
  - DBImpl::DumpStats() logs a WARN for each column family whose census has been unready for more than 10 minutes (kCensusUnreadyWarnMicros, a fixed choice), with the state and the number of failed builds in a row (capped at 6). The check runs in the stats dump, not in the census job, so it also fires when that job is stuck or paused. It runs once per stats dump (every stats_dump_period_sec seconds), so with stats dumps off there is no such WARN.
- rocksdb.blob-stats prints "Number of blob files: N (+M relocation files)" when the column family has M > 0 relocation files. Without relocation files the text is the same as in base RocksDB. The DumpStats line "Blob file count: ..." does not change.
- A new Version starts with the relocation garbage of the Version it is built from, and the census publish then sets the exact value for it. So rocksdb.live-blob-file-garbage-size, the garbage and space amplification lines of rocksdb.blob-stats and rocksdb.estimate-live-data-size do not drop to 0 (or jump up) after each install while the census catches up. The value read never exceeds the record bytes of the current relocation files. The docs of these properties and of rocksdb.num-blob-files in include/rocksdb/db.h say how they count relocation files: num-blob-files counts only normal blob files, and the size and garbage properties include relocation files.
- PauseBackgroundWork() also waits for a scheduled census job, because the job is background work that changes the current Version (it stores the GC candidates) and schedules compactions, and the job does not start again while background work is paused. ContinueBackgroundWork() checks every column family again and schedules the job for those that need a census run.
- DB::Resume() and automatic recovery wait for background work too, but for at most the running census run, not for the whole build. While a recovery waits, the census job does not start again; the recovery starts it again after its wait. So the background error does not stay set while a large census builds.
- Feature off: a column family without blob indirection has no census. The map then shows census-state none and zeros, and the DumpStats check skips the column family.

## Supporting changes (also in this diff)

The census needs each of these changes. Each part says why.

### SST metadata in the MANIFEST

Why: after a reopen, the census must know which SSTs are exact, so the MANIFEST stores the descriptor of each SST.

- Flush and compaction outputs record their SST descriptor in the MANIFEST. builder.cc and compaction_outputs.cc call ExtractBlobReferenceDescriptorFromTableProperties for this.
- Trivial move, ReFitLevel, PromoteL0 and the experimental metadata update keep the blob reference metadata of the moved SST (VersionEdit::AddExistingFile).
- The RepairDB guard of diff 4 also treats a new SST record as feature evidence when its descriptor decodes or when it has a coarse frontier (CheckBlobIndirectionRepairAdmission() in db/repair.cc).
- A fenced CF rejects a newly added SST that has no exact blob metadata (test VersionBuilderTest.FormatFenceRequiresExactSstMetadata). The one exception is a level move of an SST that has no exact metadata and no coarse frontier in its current place either. So a move cannot drop the exact metadata of an SST, and it cannot turn a coarse SST into a legacy SST, which would stop pinning the indirect origins that the SST may still reference. So in this diff, a flush with the option off on a fenced CF fails closed. Because of the option gate, only the test hook can reach this.

### Blob file lifetime

Why: indirect blob GC needs an indirect origin to stay in the Version while SSTs still use its generation number.

- In a fenced CF, a blob file below the oldest linked blob file (the smallest oldest_blob_file_number over the saved SSTs) is dropped only when it is a normal blob file. An indirect origin below it stays in the Version until its blob file retirement record (diff 4) removes it.
- Behavior change from base: a normal blob file leaves the Version as soon as no SST links it and its approximate garbage count reaches its total. An indirect origin stays even then, because SSTs can still use its generation number while compaction counts its values as garbage. It leaves only through its blob file retirement record. In this diff only tests write that record, so such a file stays in the Version and on disk. Later diffs in this stack add the indirect blob GC job that writes this record, also when the blob options are off or automatic compactions are disabled.
- Best-efforts recovery in a fenced column family follows the same rule: a missing indirect origin without a blob file retirement record is a needed file (SaveRuleKeepsBlobFile()).
- With best_efforts_blob_db_repair, base RocksDB records a missing blob file as dropped (kDroppedBlobFile) only when an SST may still use it: the file has linked SSTs, or some of its values do not count as garbage. A missing indirect origin that has no blob file retirement record is always recorded as dropped, even when all its values count as garbage. The reason is that its garbage count never decides whether it stays in the Version (see the bullet above). SaveDroppedBlobFilesTo() does not keep a dropped file whose number is smaller than the oldest blob file that any SST references. When no SST references a blob file, it keeps no dropped file at all.
- An SST links only its oldest blob file. When that file is an indirect origin that blob file retirement removed, the oldest linked blob file still comes from the SSTs, so the newer normal blob files that the SST references keep their place in the Version.
- Legacy forced blob GC marks nothing in two cases: while the oldest blob file is an indirect origin and the option is on, or while the oldest blob file has no linked SSTs. When the option is off, legacy forced blob GC still forces an oldest blob file that SSTs still link.

### Accepted loss

Why: GC must not pick a lost relocation file that still has live bytes, so the Version marks the file lost.

- VersionBuilder applies the accepted-loss record, both at replay and at install. It marks a relocation file lost in the Version: BlobRelocationFileMetaData::CreateMarkedLost and IsMarkedLost, BlobRelocationState::HasLostFiles, and the lost bit of the file table entry. The census keeps a lost file that still has live bytes out of the candidate heap.
- VersionBuilder checks, at replay and at install, that the record names a live relocation file of its own column family ("Blob relocation loss names no live target").
- A lost relocation file loses its own values and the values of every old file routed to it.
- A read through a lost relocation file (directly or through a route to it) returns NotFound.

### Version release

Why: the census job pins a Version, and it must free the relocation state of that Version without the DB mutex.

- Background work that pins a Version (for example the census job) releases it with Version::UnrefAndFreeBlobRelocationState. The Version is destroyed under the DB mutex like every Version. Only its relocation state is freed outside the mutex, and only when the Version was its last owner.
- LogAndApply never releases the DB mutex to free census state. "Step 4 of the census install" in VersionSet::ProcessManifestWrites() cancels the unused reservations under the mutex. It then moves the census installs, the old census state and the census state of a dropped column family to the deferred census cleanup, a list in VersionSet. Each entry holds a reference to its column family, because census state can hold relocation file metadata, whose deleter uses the column family, and the build context of a build that waits between slices, whose Version takes the DB mutex when it is released. So the writer callbacks run in the same mutex hold as the install of the new Versions, and a flush can never be seen half finished (a new L0 file while its memtable is still in the immutable list).
- VersionSet::ReleaseDeferredPublicationCleanup() frees the list without the DB mutex and then drops the column family references. Flush and compaction jobs call it after they install their SuperVersions. So do the census job when it starts, the user-thread installs CompactFiles(), DeleteFilesInRanges(), ReFitLevel() (CompactRange() with change_level) and PromoteL0(), and also SetOptions(), DropColumnFamily() and DB close. A SuperVersion install whose census is behind schedules the census job, so an entry from another caller usually waits only until the census job runs. When a LogAndApply caller is not one of these callers, its entry waits for the next of these calls. Examples are IncreaseFullHistoryTsLow(), CreateColumnFamilyWithImport(), ResumeImpl(), ReserveFileNumbersBeforeIngestion() and UpdateManifestForFilesState(). They change no SST, or run without a built census, so their entries are small. While background work is paused, such an entry can wait until background work continues or the DB closes, and its memory stays charged to the block cache meanwhile. An entry keeps no change log entry and no delta alive: once the change log owns the log entry, Install() resets the prepared install's pointers to the log entry and to the delta (the log entry owns the delta). ~VersionSet() frees what is left while the column families still exist; it asserts that no entry holds a census build context, because freeing one takes the DB mutex.
- SetOptions on a fenced CF frees the deferred census cleanup right after it installs its SuperVersions (VersionSet::ReleaseDeferredPublicationCleanup()).

### Groundwork

These parts have no production user in this diff. Only tests call them.

| Part | What it is | First user |
|---|---|---|
| Metadata-only commit (BeginMetadataCommit() / EndMetadataCommit()) | A MANIFEST commit that changes relocation state (routes, relocation files) but adds no SST. At most one runs per census at a time. An indirect blob GC job cannot register (BeginGcJob()) while one is in progress (TryAgain), or while its result is unknown (Busy) | Diff 9 |
| GC job registration (BeginGcJob(), IsGcJobActive(), EndGcJob()) and the selected copy (BlobReferenceCensusState, SnapshotSelected()) | At most one GC job is registered per census. From BeginGcJob() until SnapshotSelected() has copied the selected generation numbers, the worker applies no delta, so the copy shows the census at the job's input Version. The job reads no later delta, and an install that invalidates the census does not end the registration. The debug self-check already uses the selected copy | Diff 9 |
| Candidate publication | The ranked candidates stored in the Version | Diff 9 |
| Indirect blob GC accessors (SuppressBlobFileForIndirectBlobGC and the others in VersionStorageInfo) | Pick and skip candidate files of a Version | Diff 9 |
| Relocation state fingerprint | 128 bits that depend only on the relocation files, the routes and the format version, not on the order of the changes. It is the sum of one digest per relocation file and per route, so each change updates it in O(1) | Diff 7 (stored in compaction outputs) and diff 11 (remote compaction check) |
| Coarse SST (kOldestCoarseIndirectOriginFileNumber, on-disk tag 84; VersionStorageInfo::OldestCoarseIndirectOriginFileNumber(), the coarse pin in the candidate heap) | An SST without exact metadata that records only a frontier. The MANIFEST, VersionBuilder and the census already accept and honor a frontier; no code in this diff writes one | Diff 7 (coarse flush SSTs) |

## Implementation

- Install path: the comment at BlobReferenceCensusInstallBatch in db/version_set.h lists the steps: reserve under the DB mutex, prepare without it, install under it after the MANIFEST write, and move the garbage to the deferred census cleanup, which ReleaseDeferredPublicationCleanup() frees without the DB mutex. Table builders hand off checked summaries, so a successful install links the prepared handles and does not open the tables again. BuildBlobReferenceCensusDelta() runs after Version::PrepareAppend(), which computes the new Version's coarse frontier, so the delta carries the frontier of the same Version as its SST changes.
- MANIFEST: the NewFile record gets three new custom fields, all not safe to ignore. On disk their tags are 82, 83 and 84 (kCustomTagNonSafeIgnoreMask (64) plus 18, 19 and 20). They do not clash with the safe-to-ignore tags 18 (kDbOwnershipStartTime) and 19 (kDataFileProvenance), because the mask bit is part of the tag.
  - kBlobReferenceDescriptor (tag 82).
  - kBlobReferenceLegacyMetadata (tag 83, the legacy marker). It marks an SST in a fenced column family that has no descriptor and no coarse frontier. VersionBuilder sets it in memory, a MANIFEST snapshot writes it, and an edit that copies the file metadata, such as a trivial move, carries it.
  - kOldestCoarseIndirectOriginFileNumber (tag 84, the coarse frontier).
- Build: the build runs in slices from a pinned Version, and each slice returns the LOW thread. At reopen the census reads only each SST's reference index, which holds the totals of every group. It reads no reference data block, and the index decoder checks that the totals add up to the descriptor. The reads keep the caller's I/O activity, rate limiter priority and deadlines, but always skip the block cache fill and always check checksums. During a build the worker collects the changes of each generation number and builds each set once at the end. "Scheduling" at the top of db/blob/blob_reference_census.h lists the states of the census job.
- Column family lifetime: the census holds a reference to the ColumnFamilyData of a column family (cfd->Ref()) in two places. ScheduleBlobReferenceCensus() takes one for each column family that it queues; the column family keeps it while it waits in the run queue or the retry list, and the census job releases it when the column family leaves both. Each build takes one more when it starts, for its starting Version, and the deleter of that Version releases it. So a dropped column family stays alive until the census is done with it. The new DBImpl::ReleaseColumnFamilyDataRef releases such a reference. It takes the DB mutex, so its callers (the census job, the cleanup of the run queue and the retry list at close, and the deleter of the starting Version) call it without the mutex.
- Table readers for reference reads: the census build and the compaction job-start read get the SST's reader through TableCache::GetBlobReferenceReader(). It first looks for the reader in the table cache without I/O (the pinned reader of the SST, or a cache lookup). That reader already read the table tail, so the census reads only the reference index. On a miss it opens an ephemeral reader that is not inserted into the table cache, so a census build never evicts the reader of another SST. Both kinds read the reference blocks with fill_cache=false, checksum checks and no persistent cache. Their other metadata blocks (index and the rest) use the persistent cache, as base readers do. Only the blob reference blocks skip it. An ephemeral reader reads no filter block, and its open does not insert metadata blocks into the shared block cache. Indirect blob GC (diff 9) gets its readers the same way.
- Worker: the worker applies each delta in one merge pass per touched generation number. Removals free their slots before additions take the lowest free slots. Each build has a token (an id). A canceled build context no longer matches the token; it is detached and destroyed without the DB mutex and the census log mutex.
- Memory: change log and snapshot memory is bounded and charged. The group buffer of a summary is charged before it grows. The selected copy (BlobReferenceCensusState) is charged at its real size.

## How to read this diff

1. Big picture. Read "Why the change is required" and "Terms used in this diff". Then read the top comment of db/blob/blob_reference_census.h (Background, Terms, Ownership, Data flow of one install, Scheduling, Apply after an install, Build, Per generation number, Readers, Threads and locks, Why this design, Census memory charge, Errors and rebuild, Self-check). It names every census part and the order in which they run.
2. Input type. Read BlobReferenceSstSummary in db/blob/blob_reference_metadata.h (diff 2). Every census change is a list of these summaries. Also read the "Coarse SST" section in the same file.
3. Holder sets and candidate heap. Read BlobCensusSlotTable and BlobCensusSlotSet in blob_reference_census.h. Then read BlobCensusSlotSet::Update(), UpdateBitmap() and Encode() in blob_reference_census.cc. They depend on no other new part, and they hold most of the census memory. Next read BlobGcPhysicalFileSummary and BlobGcCandidateHeap (header and .cc). The census uses this heap to rank physical files by garbage ratio.
4. Deltas and the change log. Read BlobReferenceCensusDelta, BlobReferenceChangeLogEntry and ChangeLogCursor in the header. Then read Install(), AppendChange(), TakeBuildDeltas() and AcknowledgeBuildDeltas() in the .cc. This is how each Version install reaches the census.
5. Worker. Read WorkerState::ApplyFiles() and WorkerState::Finalize(), then BlobReferenceCensus::ApplyWorkerDelta(), in blob_reference_census.cc. They apply summaries and deltas to the holder sets and to the heap.
6. Producers. Read where summaries and deltas come from: TableBuilder::GetBlobReferenceSstSummary (table/table_builder.h), TableCache::ReadBlobReferenceSstSummary and the reader it gets from TableCache::GetBlobReferenceReader (db/table_cache.h), CompactionJob::ReadInputBlobReferenceSummaries (db/compaction/compaction_job.cc), and the install path at BlobReferenceCensusInstallBatch in db/version_set.h (its comment lists the steps).
7. Drivers. Read the census job in db/db_impl/db_impl_open.cc: DBImpl::ScheduleBlobReferenceCensus, BuildBlobReferenceCensus, BGWorkBlobReferenceCensus and PublishBlobReferenceCensusWorker. Then read the apply after an install in the same file: ApplyBlobReferenceCensusAfterInstall and ApplyBlobReferenceCensusDeltas. BackgroundCallFlush and BackgroundCallCompaction (db/db_impl/db_impl_compaction_flush.cc) call them at their end. Last, read the debug check CheckBlobReferenceCensus (it uses BlobReferenceCensusState, the selected copy).
8. Supporting changes (see "Supporting changes" above; you can skip them on a first read). Read the three new NewFile custom fields (kBlobReferenceDescriptor, kBlobReferenceLegacyMetadata and kOldestCoarseIndirectOriginFileNumber; on-disk tags 82 to 84) in db/version_edit.h, accepted loss (db/blob/blob_relocation_manifest.h, db/version_builder.cc), the blob file lifetime rules (db/version_builder.cc) and Version::UnrefAndFreeBlobRelocationState (db/version_set.h). Last, the groundwork listed under "Groundwork" in "Supporting changes".

## Performance

Build and setup: these numbers were measured on an earlier build of this stack: release builds of all diffs of the stack as of 2026-11-20, measured on 2026-11-21, not on this commit. So they include later diffs: for example, flush outputs carry only a coarse classification (diff 7), and the census does not count them. db_bench does not report these numbers, so the runs used two benchmark-only patches that are not part of the stack: LOG lines with thread CPU timers around the census calls, and a timer around each apply call after an install. Host: a shared virtual machine with 192 vCPUs (AMD EPYC Genoa). Each step was pinned to 32 vCPUs and started at a 1-minute load below 20, with stress tests paused.

Baseline: base RocksDB has no census, so there is no like-for-like baseline. The tables give the absolute cost of the census: memory, build time, bytes read, and the CPU added to installs and compactions.

Census build, full compaction and overwrite. Setup: 16-byte keys and 200-byte values, all values in 1 MB blob files, no compression, enable_blob_indirection on, a 1 GB block cache, one subcompaction. Each case runs fillrandom and a full compaction, then 3 warm and 3 cold reopens, then one more full compaction in one job, then an overwrite of 10% of the keys with automatic compactions. Each reopen waits until the census is ready. Each case ran in 6 passes on fresh DBs (pass N uses seed N). The tables give the median of the 6 passes; the build rows use the median of 3 reopens within a pass. The census build, memory and full compaction rows agree within about 10% between passes. The one exception is the cold build of case A (1.5 to 2.1 ms), a very small value.

| Case | Keys | Target file size | Write buffer | SSTs |
|---|---|---|---|---|
| A | 4M | 8 MB | 32 MB | 11 |
| B | 16M | 2 MB | 32 MB | 163 |
| C | 4M | 2 MB | 1 MB | 41 |
| D | 4.6M | 200 KB | 1 MB | 471 |

Census build at open. "Warm" has the DB files in the page cache, and "cold" drops them before the open (POSIX_FADV_DONTNEED). The DB uses max_open_files=-1, so the open loads every table reader before the census builds. Census memory is measured at the close of a warm reopen; bytes read are the IOSTATS bytes of the first warm build:

| Measure | A | B | C | D |
|---|---|---|---|---|
| Census memory at rest (charged) | 334 KB | 1.34 MB | 351 KB | 485 KB |
| Build CPU time, warm | 1.1 ms | 13.2 ms | 20.0 ms | 261 ms |
| Build wall time, warm | 1.1 ms | 13.3 ms | 20.1 ms | 263 ms |
| Build CPU time, cold | 1.2 ms | 13.6 ms | 21.1 ms | 271 ms |
| Build wall time, cold | 1.9 ms | 16.9 ms | 26.1 ms | 329 ms |
| Bytes read (reference index blocks only) | 18.1 KB | 277 KB | 396 KB | 4.52 MB |

Full compaction in one job that rewrites every SST. Every compaction reads the reference index of its inputs at job start (CompactionJob::ReadInputBlobReferenceSummaries) and holds their summaries during the job. Then the job's change is applied to the census:

| Measure | A | B | C | D |
|---|---|---|---|---|
| Read at job start (inputs, bytes, time) | 11 SSTs, 18.1 KB, 0.10 ms | 163 SSTs, 277 KB, 1.8 ms | 41 SSTs, 396 KB, 2.3 ms | 471 SSTs, 4.52 MB, 29.8 ms |
| Input summaries held during the job (charged) | 59 KB | 1.07 MB | 1.81 MB | 23.5 MB |
| Largest census apply CPU in the step (the job's change in case D) | 0.7 ms | 5.8 ms | 3.0 ms | 28.7 ms |
| Peak census memory | 433 KB | 3.12 MB | 3.36 MB | 39.6 MB |

The census applies a change under its own worker locks, not under the DB mutex, so installs and reads do not wait for the apply. Only the publish after an apply takes the DB mutex, for a short time. The apply cost grows with the reference groups in the change: about 29 ms for the about 1 million groups of case D's full compaction. The census job or the flush or compaction thread that installed the change runs the apply (see "Apply after an install" in "Census job").

Overwrite of 10% of the keys with automatic compactions. "Prepare" is the install work done without the DB mutex; "under the DB mutex" is the rest of the install. The apply row counts the applies of the census job and of the flush and compaction threads. Peak census memory includes the summaries that compactions hold at job start and the summaries of their outputs. The install time under the DB mutex is a few us and varies by up to 65% between passes:

| Measure | A | B | C | D |
|---|---|---|---|---|
| Installs | 3 | 14 | 127 | 144 |
| Install prepare CPU, avg / max | 16 / 20 us | 25 / 70 us | 11 / 256 us | 13 / 426 us |
| Install CPU under the DB mutex, avg / max | 5.7 / 8.0 us | 4.8 / 8.2 us | 2.6 / 8.8 us | 2.6 / 9.8 us |
| Census apply CPU per change, avg / max | 26 / 26 us | 53 / 258 us | 52 us / 3.0 ms | 404 us / 29.2 ms |
| Compaction-start reads (inputs, bytes, time) | none | 10 SSTs, 2.7 KB, 0.1 ms in 2 jobs | 82 SSTs, 791 KB, 3.8 ms in 19 jobs | 942 SSTs, 9.04 MB, 53.5 ms in 21 jobs |
| Peak census memory | 345 KB | 1.47 MB | 3.55 MB | 39.8 MB |

The largest delta in these runs is the full compaction of case D: 471 removed and 471 added SSTs, with about 1.02 million reference groups. Its summaries take about 47 MB by estimate (twice the 23.5 MB of input summaries above), below the 256 MB change log limit (BlobReferenceCensus::kMaxLogMemory). No change log overflow happened in these runs; with the 256 MB limit, this is a weak check.

The census does not keep each SST's summary in the Version. That design would hold the summaries in the census and in every live Version, so it would multiply the summary memory.

Apply after an install (4M fillrandom and 4M overwrite, 16-byte keys, 2 KB values, no compression, 64 MB blob files, blob indirection and indirect blob GC on; 6 runs per setting, max_background_jobs 2 and 8 in turn). The time is the whole call, including waits for the DB mutex. With max_background_jobs=2, the flush and compaction threads applied almost every census delta right after their install (for example, 263 of 282 in the fill and all 321 in the overwrite of one run). With max_background_jobs=8, the census job applied most deltas itself (the installing threads applied 8 to 22 per process), so most calls found nothing to apply or could not take the worker run lock (another thread was running the census worker), and returned in about 1-2 us at P50. The runs had no build without the apply after an install, so they do not show its throughput cost.

| Added time on the installing thread, one call (jobs = max_background_jobs) | P50 | P99 | Max |
|---|---|---|---|
| Flush that applied 1-2 deltas and published (jobs=2) | 17 us | 28 us | 305 us |
| Compaction that applied 1-2 deltas and published (jobs=2) | 79 us | 383 us | 452 us |
| Compaction that applied a delta (jobs=8) | 19 us | 116 us | 120 us |
| Compaction that could not take the worker run lock (jobs=8) | 1 us | 14 us | 36 us |
| Flush with nothing to apply (jobs=8) | 2 us | 3 us | 37 us |

## Safety, compatibility, and limitations

- The census is derived state that only indirect blob GC uses. It is not persisted, and it is rebuilt after reopen.
- A census that is not ready, or that failed, pauses GC and route retirement. It does not affect ordinary reads or writes.
- A coarse frontier conservatively keeps every indirect origin at or above it in use.
- DeleteFile, DeleteFilesInRange(s) and ingestion with a replace range rebuild the whole census. GC and route retirement pause until the rebuild is ready.
- A new exact SST that comes without its prepared summary is a bug, and debug builds assert. In release builds the commit still goes ahead: the census is rebuilt from disk, GC waits for the rebuild, and an ERROR is logged.
- These still fail the commit: a duplicate SST addition in one commit, and a new SST in a fenced CF that has no exact metadata (no descriptor, no legacy marker and no coarse frontier).
- So a flush in a fenced CF with enable_blob_indirection off fails, because its SST has no exact metadata. Diff 7 adds coarse flush SSTs. Only the test hook can create this state (the option gate of diff 2).
- With the option off, forced blob GC stays paused for a CF while its oldest blob file has no linked SSTs, and so do the files behind it. This happens for an indirect origin that no SST references any more (it waits for a blob file retirement record), or for a normal blob file or indirect origin newer than an indirect origin that blob file retirement removed.
- Persisted data: the NewFile record gets three custom fields (kBlobReferenceDescriptor, kBlobReferenceLegacyMetadata and kOldestCoarseIndirectOriginFileNumber, tags 82 to 84; see "Implementation"). A DB that never used blob indirection writes none of these fields. Older data: an SST record without them decodes as before. In a fenced CF, VersionBuilder marks such an SST as legacy in memory, and a MANIFEST snapshot writes the legacy marker, so replay accepts an SST that was added before the fence. A DB that a build of diff 4 alone fenced cannot be opened, because that build added SSTs without a descriptor after the fence; diff 4 is never released alone, so only test DBs can be in this state. Older readers: all three tags are not safe to ignore, so an older RocksDB version fails to open a MANIFEST that has one, with Corruption ("new-file4 custom field not supported"). The census itself is not persisted.
- Remote compaction of a fenced CF is a known gap in this diff: a remote output has a descriptor but no summary, so debug builds assert at the install (version_set.cc, BuildBlobReferenceCensusDelta()), and release builds rebuild the census after each such compaction. A later diff of this stack reads the summary of each remote output on the primary. Until then, the option gate keeps this to tests.
- A read-only open with best_efforts_recovery of a fenced DB fails with NotFound ("Current MANIFEST requires a missing relocation file") when the final MANIFEST state needs a relocation file that is missing. A read-write open falls back to an older complete Version and writes a new MANIFEST, so later opens see the same state. A read-only open cannot write the MANIFEST, and its fallback would show old values of keys that later edits overwrote, so it fails instead. This needs a DB that used blob indirection.

## Changes visible to existing users

These changes affect a DB that never enables blob indirection:
- Memory: FileMetaData has four new fields (the descriptor, the legacy marker, the coarse frontier and the summary pointer). The legacy marker sits next to the other bool fields, so it takes no padding. sizeof(FileMetaData) grows from 456 to 512 bytes (g++ 11, x86_64), so every SST of every DB uses 56 more bytes in memory. For example, a DB with 100,000 SSTs uses about 5.6 MB more. The fields are empty for such a DB, and nothing is written to disk. A follow-up moves the summary to the VersionEdit and the descriptor, legacy marker and coarse frontier behind one pointer that only fenced column families set.
- Public API: CacheEntryRole::kBlobReferenceCensus is inserted before kMisc. This changes the numeric values of kMisc and kNumCacheEntryRoles.
- Public API: rocksdb.block-cache-entry-stats has new keys for the new role (count.blob-reference-census, bytes.blob-reference-census and percent.blob-reference-census). They are 0 for such a DB.
- Public API: a new ticker, BLOB_DB_CENSUS_RESTART_OVERFLOW_COUNT ("rocksdb.blobdb.census.restart.overflow.count"), is added after BLOB_DB_DROPPED_BLOB_READ_COUNT, before the tickers of diffs 3 and 4. So the values of those tickers and of TICKER_ENUM_MAX change. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- Public API: new properties rocksdb.indirect-blob-gc-stats (including census-uncharged-builds and census-uncharged-charges) and rocksdb.blob-reference-census-unready-micros. A column family without blob indirection reports census-state none and zeros.

For a DB that enables blob indirection: the census and the SST reference summaries are charged to the block cache, but a failed charge never fails a flush, compaction or census job. With strict_capacity_limit and a full cache, the census goes on uncharged, so census memory can go above the block cache limit, also a strict one. The copies that indirect blob GC takes keep a strict charge: with a full cache, GC skips or defers its inputs. The change log stays bounded by kMaxLogMemory (256 MB), or 1 GB after an overflow restart. The rest of the census grows with the number of SSTs and blob files, like base per-file metadata. The census-uncharged-builds and census-uncharged-charges keys of rocksdb.indirect-blob-gc-stats show when this happens.

## Validation and known limitations

Validation: unit tests cover the census worker, the slot sets, every SST removal path, the Version changes, retry, cache charging and SetOptions (see the Test Plan). Removal-path tests check after each step that the census equals a fresh build from the current Version. db_bench runs measured build time, memory and install CPU on an earlier build of the stack (see "Performance"). The per-diff test runs used make debug builds without sanitizers (see the Test Plan). This matters here because the census runs on several threads (census job, flush and compaction threads) and frees state without the DB mutex; no sanitizer result is claimed for these paths. There is no crash test at this diff; db_stress support comes in diff 14.

Known limitations:
- The initial build has no bound that is independent of the DB size.
- Census memory is one record per generation number that some SST references, plus one entry per (generation number, SST) pair in the holder sets. The number of origins per generation number does not add to it.
- Each compaction of a fenced CF, also a full compaction, reads the reference index of its inputs at job start and holds the input summaries during the job. They are charged to the block cache when it has room (see "Cache charging"). "Performance" shows the cost.
- Under very heavy write load during a long build, a build can overflow the restart limit too. Then the census stays not ready and retries after the backoff, and indirect blob GC pauses until a build publishes. The ticker BLOB_DB_CENSUS_RESTART_OVERFLOW_COUNT shows this case.
- The apply after an install runs before the flush or compaction counts as finished, so its background slot stays busy for that time. It applies only the deltas up to the job's own Version, but the job's own delta can be large: a very large compaction delta can take tens of ms (estimate from the full compaction apply cost in "Performance").
- Deltas from installs on user threads (for example a user CompactFiles()) wait for the census job or for the next flush or compaction of the same column family.
- A census build keeps its starting Version until its last slice ends. A slice reads at most 16 SSTs and then waits for its next turn in the LOW pool, so a build of a large column family can take many turns. During that time, SSTs that compactions replace, and the blob files that those compactions drop, stay on disk, and every rebuild (for example after DeleteFilesInRange() or an overflow restart) keeps a new Version. A follow-up keeps only the starting file list and pins the current Version within each slice.

Tracking issue: https://github.com/facebook/rocksdb/issues/15301

Differential Revision: D124759451
…meta#15719)

Summary:
Pull Request resolved: meta#15719

## Why the change is required

Indirect blob GC (diff 9) installs its result with one LogAndApply() call. Its edit can hold one route change per old file number (a file that GC removed; see diff 4), so applying it with VersionBuilder::Apply() can take a long time. Base RocksDB applies every edit with the DB mutex held, so a large edit would block every thread that needs the DB mutex. The GC edit is valid only while the GC input is unchanged, so the caller passes a precondition (pre_cb) that LogAndApply() checks before the edit is committed. This diff adds two things to VersionSet: a call that applies its edit without the DB mutex when the caller asks for it, and a rule that keeps a call with a precondition out of other callers' batches, so its precondition always runs. It does not depend on any GC code.

## Stack context

This diff is part 6 of the indirect blob GC stack. "[Blob GC] 2/14", section "Stack context", gives the goal of the stack, how a read finds a value, the lifecycle of a value and the stack map. The row of this diff in the stack map is "6: MANIFEST apply outside the DB mutex, with a precondition". The code of this diff uses no blob indirection type. The Safety section names later users; for their terms see "[Blob GC] 2/14": flattened reference in "Terms used in this diff", and route retirement in "Stack context: terms for later diffs".

## Terms used in this diff

| Term | Meaning |
|---|---|
| MANIFEST writer queue | VersionSet::manifest_writers_. Each LogAndApply() call adds one writer per column family. Only the writer at the head of the queue (the queue head) writes to the MANIFEST |
| group commit | The queue head (the leader) takes later writers of the queue into its batch and writes their edits in the same MANIFEST write. The later writers then return without reaching the queue head |
| precondition (pre_cb) | A callback that a LogAndApply() caller passes. It checks that the caller's edit is still valid. It runs once, under the DB mutex, at the queue head. If it fails, the call fails and installs nothing |
| precondition writer | The first writer of a LogAndApply() call that passes pre_cb. Its ManifestWriter::requires_precondition is set. Only the first writer gets it, because only the first writer of a call waits for the queue head |
| batch barrier | A writer that ends grouping: no batch holds both a precondition writer and the writers of another caller |
| unlocked apply | VersionBuilder::Apply() of one edit while the DB mutex is released (VersionSet::LogAndApplyHelper()). Only a VersionSet::LogAndApplyWithUnlockedApply() call gets it |

## Previous behavior

LogAndApply() ran pre_cb once, under the DB mutex, when the caller's first writer reached the queue head. If an earlier leader took the writer into its group commit, the writer never reached the queue head, so its pre_cb never ran. Every edit was applied with VersionBuilder::Apply() under the DB mutex. In base RocksDB only SetOptions() passes pre_cb, and its dummy edit is never grouped, so base never skips a pre_cb.

## New behavior

- A precondition writer is a batch barrier. An earlier leader stops its group before such a writer (rule 5). So the writer always reaches the queue head, and its pre_cb runs there against every Version committed before it. When the writer leads, the batch holds only the writers of its own caller (rule 4). Rule 4 gives the caller two properties. First, the Version that the call installs holds only the caller's own edits. Indirect blob GC (diff 9) relies on this when it applies its job-start suppressions to the new current Version. Second, another caller's edit cannot fail the batch, and a failure of the batch cannot fail another caller. Route retirement (diff 10) relies on this, because it treats a Corruption from VersionBuilder as a failed check of its own protocol. The precondition itself does not need rule 4: edits apply in queue order, so a later edit cannot change the state that the precondition checked.
- pre_cb runs once per call, at the queue head. The batch can release the DB mutex later (to apply an edit, finalize blob files or write the MANIFEST), and pre_cb does not run again. So pre_cb may depend only on state that changes through LogAndApply() (for example, which Version is current, the files it lists, and column family drops), which stays frozen while the call is at the queue head, or on state that the caller owns. Per-file state that changes under the DB mutex outside LogAndApply(), such as FileMetaData::being_compacted, is not frozen. A caller whose pre_cb reads other state must explain at the call site why a later change cannot make its edit unsafe. The pre_cb paragraph of VersionSet::LogAndApply() in db/version_set.h states this contract.
- The new VersionSet::LogAndApplyWithUnlockedApply() takes one column family, one edit and a pre_cb. When the call leads a batch that writes a MANIFEST record, its edit is applied without the DB mutex. Every other call, including a LogAndApply() call with a pre_cb, applies its edits under the DB mutex, as in base.
- A dummy edit (SetOptions()) writes no MANIFEST record and is applied under the DB mutex, as in base.

## Implementation

The essential choices, and why they are enough:

- Only the first writer of a call gets requires_precondition and apply_unlocked (set in LogAndApplyImpl()). The writers of one call are queued together, and only the first one waits for the queue head, so one flag per call is enough.
- ProcessManifestWrites() has two new stop rules in the list at "Loop increment/conditions". Rule 4 ends a batch led by a precondition writer after that caller's writers, which keeps the caller's Version and its result separate from other callers (see "New behavior"). Rule 5 stops before the next precondition writer, which makes sure that pre_cb runs at the queue head.
- The unlocked apply happens only for the leader's own edit (last_writer == &first_writer), only when the leader has apply_unlocked, and only in a batch that writes a MANIFEST record. It is safe without the DB mutex for three reasons, listed in the comment of LogAndApplyHelper(): the edit and the builder belong to this writer, and the builder holds a reference to its base Version; the writer stays at the queue head, so no other Version is installed and no other MANIFEST edit is applied; and ProcessManifestWrites() already ran the re-add check (RejectReaddedBlobRelocationState()) under the DB mutex.
- The unlocked apply is a separate entry point, not a parameter of LogAndApply(), so no existing caller can get it by accident. A call that only needs a precondition keeps the DB mutex for its small edit.
- ProcessManifestWrites() walks the queue by index instead of by iterator. Other callers can add writers while the DB mutex is released, and std::deque::push_back invalidates iterators. Indexes stay valid, because no writer leaves the queue during the batch.
- The sync point "VersionSet::LogAndApplyHelper:ApplyUnlocked" marks the unlocked apply for tests.

## How to read this diff

1. This summary: "Terms used in this diff" and "New behavior".
2. db/version_set.h: the pre_cb paragraph in the comment of VersionSet::LogAndApply() (the run-once contract), and the comment of VersionSet::LogAndApplyWithUnlockedApply().
3. db/version_set.cc: ManifestWriter::requires_precondition and ManifestWriter::apply_unlocked, and where LogAndApplyImpl() sets them. The single pre_cb run is also in LogAndApplyImpl(), at the queue head.
4. db/version_set.cc: VersionSet::LogAndApplyHelper(). This is the unlocked apply: unlock, VersionBuilder::Apply(), lock. Its comment says why the apply is safe without the DB mutex.
5. db/version_set.cc: VersionSet::ProcessManifestWrites(). Read the comment on the index walk, the call to LogAndApplyHelper(), and the list of stop rules at "Loop increment/conditions". Rules 4 and 5 are new.
6. db/version_set_test.cc and db/db_options_test.cc: the tests listed in the Test Plan.

## Safety, compatibility, and limitations

- Outside tests, no caller in this diff applies an edit without the DB mutex, and base RocksDB passes pre_cb only from SetOptions(), whose dummy edit is applied under the DB mutex and is never grouped. So this diff changes no behavior for existing users. The first caller of LogAndApplyWithUnlockedApply() is indirect blob GC (diff 9).
- No public API, no persisted format and no option changes. LogAndApply() and LogAndApplyWithUnlockedApply() are internal.
- Cost: a precondition writer never joins an earlier leader's batch, and as leader it takes no writers of later callers. So a caller with a precondition gets no group commit with other callers. In this stack, indirect blob GC installs (diff 9), route retirement (diff 10) and compaction installs whose output has a flattened reference or depends on a blob file of the input Version (diff 10) pass a precondition. So in a column family with blob indirection, most compaction installs (an estimate) get no group commit with other callers.
- Measured cost: benchmark C1 in the diff 10 summary measured this on an earlier build of the stack (2026-11-16), not on this commit. It compared the stack tip with the same build plus a benchmark-only change that lets compaction installs join group commit, on the B2 workload (5M keys, 4 KB values in blob files, fillrandom and three rounds of overwrites, 3 runs each, one shared host). It found no measurable difference in overwrite throughput, P99 write latency, write stall time or MANIFEST syncs (1,108 against 1,110). Every difference was inside the run-to-run spread, which was about 20% for throughput on the shared host. So the benchmark shows only that the cost is below that noise level. The tradeoff is small there because MANIFEST writes are rare in that workload (about 10 per second), so a compaction install seldom has another writer to group with. A workload with many more MANIFEST writers was not measured.
- Cost of the apply that this diff moves out of the DB mutex (rough numbers): a temporary timing test, not in this diff, applied one edit with one relocation file and a given number of route records (1,000, 10,000 and 100,000 below) to a VersionBuilder. It ran on a make debug build (DEBUG_LEVEL=1, -O2 with assertions, gcc) on a shared AMD EPYC host under heavy load (load average 119-141), 3 runs of 5 tries each, so the numbers are noisy, and a release build was not measured. VersionBuilder::Apply() took about 0.3-0.7 us per route: about 0.25-0.5 ms for 1,000 routes, 4-7 ms for 10,000 routes and 65-100 ms for 100,000 routes. Destroying the builder, which stays under the DB mutex, added about 3-5% of that. The re-add check and RecordBlobRelocationDeletions() were not timed. Each route is one old file number. Indirect blob GC (diff 9) takes at most 8 inputs per job, so we estimate that a typical GC install has far fewer than 1,000 routes. Only a GC input that is a relocation file that already serves many old file numbers gives more.
- What the unlocked apply does not change: other MANIFEST writers still wait in the writer queue behind the call for the whole apply, as they do for the MANIFEST write. Examples are flush installs and synced writes that track WALs in the MANIFEST. Only threads that need the DB mutex but not the queue (for example compaction picking and background job scheduling) are helped.
- Limitation: pre_cb does not run again after the DB mutex is released later in the batch. A caller must not depend on state that can change in that window in a way that makes its edit unsafe (see the contract above).

## Validation and known limitations

New unit tests in version_set_test cover the unlocked apply, the single pre_cb run, the batch barrier, and a writer queued during the unlocked apply, both when the leader's apply passes and when it fails. A test in db_options_test covers the single pre_cb run of SetOptions() on its test-only MANIFEST path. This diff has no end-to-end benchmark, because no caller uses the unlocked apply yet; it has only the rough timing of Apply() above. The per-diff test runs used make debug builds without sanitizers, so no sanitizer result is claimed for the unlocked apply.

Tracking issue: meta#15301

Differential Revision: D132305444
…och runs together and count each run as one L0 sorted run (meta#15718)

Summary:
Pull Request resolved: meta#15718

## Why the change is required

Exact reference metadata (diff 2) lists every blob reference of an SST. The census (diff 5) reads it, and indirect blob GC (diffs 8 and 9) will read it. While an SST is built, the table builder keeps these references in memory until the SST is finished. This diff fixes two costs of that, and two problems that the second fix creates (an ordering problem and a counting problem):

1. Flush output does not need exact metadata. A later compaction rewrites it with exact metadata: a compaction into L1 or deeper, a bottommost compaction, or an L0 compaction with an exact input. So flush writes only a small table property, the coarse classification. It holds one file number (the frontier), so the flush needs no reference memory.
2. A compaction output with many references needs much memory. So compaction starts a new output when the output already holds blob_indirection_max_references_per_sst references (the reference cap). This bounds the memory of one output being built.
3. The cap can cut one compaction to L0 into several exact L0 files with one epoch number (an epoch run). A compaction output gets the smallest epoch number of its inputs. So if a later compaction to L0 takes a newer file and only part of a run, its output can overlap a file of the run that it left behind, with the same epoch. L0 orders overlapping files by epoch, so the two files have no order, and the Version consistency check (on by default) rejects them. So every picker takes all files of an epoch run. The comment of VersionStorageInfo::ExpandExactL0Inputs() has a worked example.
4. If each file of an epoch run counted as one L0 sorted run, the L0 count after such a compaction would be at least the number of files that the cap cut its output into (about the reference count divided by the cap). Universal compaction with num_levels = 1 would then compact the same run again and again, the leveled size-based intra-L0 pick would repeat, and writes could slow down or stop for good. So an exact epoch run counts as one sorted run. This is correct because the files of the run share one epoch and their key ranges do not overlap, so each key is in at most one of them, the same as in a single file.

Intended users: the census and indirect blob GC read the exact metadata. This diff adds no GC code.

## Stack context

This diff is part 7 of the indirect blob GC stack. "[Blob GC] 2/14", section "Stack context", gives the goal of the stack, how a read finds a value, the lifecycle of a value and the stack map. The row of this diff in the stack map is "7: Coarse flush metadata, per-SST reference cap, epoch runs".

## Terms used in this diff

Terms from lower diffs, used here without change: origin, generation number, legacy, exact reference metadata (diff 2); route (diff 2); indirect origin, format fence (diff 4); census, exact SST, coarse SST (diff 5).

| Term | Meaning |
|---|---|
| frontier | The oldest indirect origin that a coarse SST references. Frontier 0 means no indirect reference |
| pin | A coarse SST pins every indirect-origin blob file at or above its frontier: the census and GC must treat that file as used. This is not the base RocksDB meaning (a Version or block that stays alive) |
| coarse classification | The table property kBlobReferenceClassificationPropertyName that a coarse SST stores: format version 1, the frontier and a CRC32C (16 bytes) |
| reference cap | The column family option blob_indirection_max_references_per_sst. A compaction output that already holds this many exact references takes no new user key. The code calls it the blob reference limit (max_blob_references, BlobReferenceLimitReached(), kBlobReferenceLimit, closed_by_blob_reference_limit) |
| user key history | All versions of one user key that a compaction keeps, including deletions and inline values |
| epoch number | The L0 order number of a file (base RocksDB). Newer L0 files have larger numbers |
| epoch run | The exact L0 files that one compaction to L0 wrote. They share one epoch number |
| exact epoch run | Adjacent L0 files with one known epoch number, at least one of them exact. This is how the code finds an epoch run |
| sorted run | Base RocksDB term: files whose key ranges do not overlap. Each L0 file is one sorted run, except that an exact epoch run counts as one sorted run for compaction triggers and write stalls (see "Epoch runs"). Reads do not treat an exact epoch run as one: Get(), MultiGet() and iterators still check, open and seek each file of the run on its own (see "Validation and known limitations") |

## Previous behavior

When enable_blob_indirection was on, every flush and compaction output got exact reference metadata, except SstFileWriter output and outputs whose column family was unknown. No SST stored a coarse classification, although the file metadata and the census could already hold a coarse frontier (diff 5). A compaction output had no limit on its number of references. Each compaction to L0 wrote one file, so no epoch number had more than one file.

## New behavior

### Which SSTs get exact metadata

When enable_blob_indirection is on, or the CF has the format fence (the option was on before):

- A compaction output gets exact metadata when its level is L1 or deeper, when the compaction is bottommost (at any level, including L0), or when an L0 input already has exact metadata (Compaction::CollectExactBlobReferences()). Bottommost is Compaction::bottommost_level(): no file in a deeper level overlaps the key range of the compaction; for an output to L0, the compaction includes the oldest L0 file and every deeper level is empty.
- Other compaction outputs at L0 get only the coarse classification. A flush and an L0 compaction that is not bottommost stay coarse to save collector memory. A flush also writes exactly one file (BuildTable()), so it could not apply the reference cap that bounds the memory of one exact output. An output never loses exact metadata that an input has, because a coarse output would pin files again that the census already tracks exactly.
- Flush output and WAL recovery flush output get only the coarse classification.
- SstFileWriter output gets neither and stays legacy. It can hold only same-file (embedded) blob references (SstFileWriter::OpenWithEmbeddedBlobs), never a reference to a blob file, so it has nothing to list.
- The table builder does not check the column family. It follows TableBuilderOptions::collect_blob_reference_metadata, whose default is false. Only compaction sets it to true (from Compaction::CollectExactBlobReferences()), so a new caller that does not set it writes no exact metadata. Flush, WAL recovery flush, SstFileWriter and SstFileDumper (sst_dump, which builds tables only to measure their sizes and then throws them away) set it to false.

When the option is off and the CF has no fence, an SST gets neither, as in base RocksDB.

### Coarse classification

- The table builder keeps no reference list for a coarse SST. It keeps only the oldest indirect origin that it sees. A coarse SST must not hold a reference with generation number != origin: the builder returns Corruption ("Coarse SST cannot contain a flattened blob reference (generation number != origin)") for one. A flushed SST cannot hold one, because a flush writes only references to its own new blob files.
- A classification with frontier 0 means the SST has no indirect reference (only legacy references, or none). Such an SST is stored as a legacy SST (blob_reference_legacy_metadata), so recovery accepts it without exact metadata, and it pins nothing.
- An SST with both an exact-metadata descriptor and a classification is Corruption.
- The Version keeps the lowest frontier of its SSTs (diff 5). The census keeps each indirect-origin blob file at or above it out of its GC candidate heap. So a coarse SST stops GC of those files until a compaction rewrites it with exact metadata.

### Coarse L0 files and L0 moves

- A coarse L0 file with a frontier other than 0 is never trivially moved out of L0 (Compaction::MustRewriteCoarseL0File()). A move would keep its pin until some later compaction rewrites it, which can take a long time. The level picker's L0 trivial move stops before such a file; the files picked before it still move. experimental::PromoteL0 returns NotSupported for such a file. An SST whose classification has frontier 0 is stored as a legacy SST and can move.
- Cost: for sequential inserts, each coarse L0 file is written once more at L0 to L1. The extra writes are about (SST bytes per entry / value size). See "Performance" for the measured case and the estimates. Random-key workloads already rewrite at L0 to L1.
- With num_levels = 1 there is no L1. Flushed data gets exact metadata when a bottommost compaction rewrites it, for example a universal compaction that includes the oldest sorted run. Until then, indirect blob GC cannot collect indirect-origin blob files at or above the coarse frontier.

### Reference cap

- The table builder keeps the references of an SST in memory until the SST is finished. They use about 8 to 14 bytes per reference (estimates). A compressed value is at the high end, because its entry also stores the CRC of its stored bytes. So the default cap of 1M references (1048576) bounds the memory of one output being built to about 8 to 14 MB. With small keys, a full output at the default cap is well below the default target_file_size_base (64 MB); see "Performance". Larger keys or no compression make outputs larger.
- It is a soft limit. Compaction starts a new output only before a new user key, so a user key history is never split. An output may pass the cap by one key's history. The check runs only when the output's builder collects references (CompactionOutputs::builder_collects_blob_references_, set in NewBuilder()), and then costs one virtual call (TableBuilder::BlobReferenceLimitReached()) per row.
- The option is mutable through SetOptions(). Its range is [4096, 2^28]. The lower bound is a fixed choice, not measured. The upper bound keeps one SST's metadata within the format limit of 2^20 data blocks of about 16 KB. A value outside the range fails option validation with InvalidArgument.
- Flush output has no exact metadata, so the cap applies to compaction outputs only.
- Monitoring: the ticker COMPACTION_OUTPUT_BLOB_REFERENCE_LIMIT_CUTS counts outputs that the cap closed. The histogram COMPACTION_OUTPUT_BLOB_REFERENCES records the reference count of each exact compaction output. The INFO log names the cut reason BlobReferenceLimit. The table_file_creation event of an exact compaction output has "blob_references", and "close_reason": "blob_reference_limit" when the cap closed it.

### Epoch runs

- Every picker takes all files of an epoch run that has an exact file (VersionStorageInfo::ExpandExactL0Inputs()). This covers the level picker, the universal picker, CompactRange and CompactFiles.
- In a column family with the format fence, an exact epoch run counts as one L0 sorted run (VersionStorageInfo::NumL0SortedRuns(), or L0SortedRunEnd() for a walk over the files). The count is used by:
  - the L0 compaction score, for leveled and universal compaction;
  - l0_delay_trigger_count(), which drives the write slowdown, the write stop and the compaction speedup;
  - FlushJobInfo::triggered_writes_slowdown and triggered_writes_stop (DBImpl::NotifyOnFlushBegin() and NotifyOnFlushCompleted()). They compare the same count with level0_slowdown_writes_trigger and level0_stop_writes_trigger, so an exact epoch run counts once in these flags too, as in the L0 part of the write stall;
  - both leveled intra-L0 triggers (PickIntraL0Compaction() and PickSizeBasedIntraL0Compaction()). The cost-based pick of PickIntraL0Compaction(), used when L0 to Lbase is blocked, also needs at least kMinFilesForIntraL0Compaction (4) sorted runs among the whole runs it would take, so one exact epoch run is never picked alone and rewritten into itself;
  - the L0 trigger of EstimateCompactionBytesNeeded(), which gives rocksdb.estimate-pending-compaction-bytes and drives the soft and hard pending compaction bytes stalls;
  - universal UniversalCompactionBuilder::CalculateSortedRuns(): one SortedRun per run, whose size is the sum of its files. Every universal pick of that sorted run takes all its files.
  - the universal check that never compacts one L0 sorted run alone into L0 (UniversalCompactionBuilder::BuildCompactionToNextLevel()). It counts sorted runs with CountL0SortedRuns(), not files. So with num_levels = 1, a read-triggered or delete-triggered pick that holds only one exact epoch run, for example when the whole DB is one run after a full compaction and reads are hot on one run file, picks nothing. Otherwise the run would be rewritten into itself, and with the reference cap cutting the output again, steady reads could make the same rewrite again and again.
- The size-ratio, size-amplification and periodic universal picks check their L0 sorted runs with CheckExactL0RunRange(). If the pick would hold only part of an exact epoch run, if a file of an exact run is being compacted, or if a picked file has epoch number 0 and an L0 file with that epoch is exact, the pick stops and logs a WARN line, also in release builds.
- rocksdb.num-files-at-level0 and NumLevelFiles(0) stay file counts. Without the format fence, every L0 sorted run count equals the L0 file count, as in base RocksDB.
- With universal compaction and num_levels = 1, a delete-triggered compaction takes the first sorted run that has a marked file, and the older sorted runs, until a sorted run that is being compacted or has a marked standalone range deletion. Each sorted run is a whole epoch run, so the pick never starts or stops inside one. As in base RocksDB, it does not start at the last sorted run, which can be a whole exact epoch run. The pick fails when a picked file has an unknown epoch number (0) and an L0 file with that epoch is exact.
- A file of the run can widen the key range of the pick. So when the run expansion adds a file, the L0 overlap search runs again on the wider range, until the set stops changing. The loop compares the files of the set, not only its size: an input set that holds a file newer than the starting file can lose that file and gain another one in the same round, and the key range of the gained file must still be searched. No caller passes such a set today; GetOverlappingL0Files() asserts this in debug builds. Without the format fence there are no epoch runs, so the expansion does one search and returns before it builds any file list. When the expansion adds no file (always the case without the format fence), GetOverlappingL0Files() searches once, as in base RocksDB, and ExpandInputsToCleanCut() does not search at all. The result is in the Version's epoch order (newest first), also when the inputs were found out of order.
- The Version consistency check covers a whole epoch run. The base check compares only L0 files that are next to each other, and the files of one epoch are in largest-seqno order, not key order. So in a column family with the format fence, the check also sorts the files of each epoch that has more than one L0 file by smallest key and compares each file with the next one in key order (VersionBuilder CheckL0EpochRunsDoNotOverlap()). When the consistency checks run (always in debug builds; in release builds with force_consistency_checks, which is on by default), two overlapping files of one epoch make the install fail with Corruption ("L0 files of same epoch number but overlapping range"). Pickers take whole runs, so this check is a safety net. The cost is one pass over L0 per check, plus a sort of the files of each epoch that has more than one file (about R log R key compares for a run of R files), at each Version build. Without the fence it does not run and costs nothing.
- CompactFiles() can be given only some files of a run. A run file that the caller did not name can widen the key range of the L0 inputs, and the files of L1 up to the output level that overlap the wider range must be inputs too. Otherwise the output, which holds the newer L0 data, goes below an older L1 file. So CompactFiles() repeats the run expansion and the input sanitizing step (SanitizeCompactionInputFilesForAllLevels(), which adds L0 files next to the named ones and the overlapping files down to the output level) until the input set stops changing.
- The L0 trivial move drops a run that it could take only in part.
- If a needed file of the run is already being compacted, the pick fails. CompactFiles then returns Aborted. A DB that never used enable_blob_indirection is not affected.

### Point lookups in an epoch run

Problem: the cap can cut an output inside a range tombstone. Then both files of the run keep the whole tombstone, and the left file's largest key is the exclusive end <cut key, kMaxSequenceNumber, kTypeRangeDeletion>. A point lookup reads a file's range tombstones untruncated. L0 orders the files of one epoch by largest sequence number, and Version::Get() can ask a file about a key that the file does not hold. FilePicker keeps the left file for a lookup at the cut key, because its key range filter compares user keys. With at most 3 files, all in L0, FilePicker does not filter by key range at all. So without a check, the tombstone of the file that does not hold the key could hide a live, newer value in the other file, and Get() would return NotFound. MultiGet() does not depend on the check: Version::MultiGet() does not end a key's search at a covering tombstone (it skips the key only for the rest of the current file), so it finds the newer value in the other file.

Fix (TableCache::RangeTombstonesMayCoverUserKey()): for an L0 file, a range tombstone counts for a lookup key only when the key is inside the file's key range, and not at an exclusive tombstone end. Get() and MultiGet() run the check only for an L0 file that has range tombstones in a Version with the format fence (Version passes check_l0_range to TableCache::Get(), TableCache::MultiGet() and TableCache::MultiGetFilter(); the last one is used by the async MultiGet() path), and it costs up to two user key compares per such file. Only a fenced Version can hold a cut L0 epoch run, because the reference cap applies only with the fence. Base L0 files are never cut and their key range includes their tombstones, so without the fence the base tombstone rules hold, and Get() and MultiGet() skip the check with no per-key work. The check also runs in MultiGet(), so the covering tombstone sequence number is correct for both. L1 and deeper need no check, because FindFile() compares internal keys.

### Monitoring

- COMPACTION_COARSE_L0_TRIVIAL_MOVE_BLOCKED (ticker) counts leveled L0 trivial move picks that stopped at a coarse L0 file. The files picked before it still move. The coarse file waits for a normal compaction, which rewrites it with exact metadata. The pick stops before it checks whether the coarse file could move at all (key range and overlap with Lbase), so the count includes files that could not have moved anyway, and the same file counts again at each pick while it is the oldest L0 file not yet picked.
- New keys of rocksdb.indirect-blob-gc-stats: coarse-sst-count (the number of SSTs with a nonzero coarse frontier) and lowest-coarse-frontier (the lowest frontier of the Version, 0 when there is no coarse SST).
- sst_dump also prints the coarse classification of an SST ("coarse classification: frontier F", or "no indirect references (legacy SST)" when the frontier is 0) in its "Blob reference metadata" section.
- Feature off: only a column family with blob indirection has coarse files, so the ticker does not change and both keys are 0.

## Implementation

- TableBuilderOptions gets collect_blob_reference_metadata (default false) and track_blob_reference_classification. Flush, WAL recovery flush and compaction set both. They set track_blob_reference_classification when the column family uses blob indirection now or has used it: UsesBlobIndirection() in db/version_set.h checks the option and the format fence. Compaction sets collect_blob_reference_metadata from Compaction::CollectExactBlobReferences(); SstFileWriter and SstFileDumper set it to false. The block-based table builder follows these fields instead of deciding by itself, so one place (the caller, which knows the level and the inputs) decides what metadata an SST gets.
- A compaction output stores the relocation-state fingerprint (a 128-bit hash of the relocation files and routes; diffs 2 and 5) of the compaction's input Version in the existing field of its exact-metadata descriptor (diff 2). Other builders store 0. The fingerprint is not checked when the descriptor is decoded, and no code at this diff reads it. Diff 11 (remote compaction validation) compares it with the input Version of the job.
- CompactionOutputs::UpdateTableProperties() returns a Status, because reading the classification back can fail. If it fails during a remote compaction install, the install returns kFailure and removes the files it installed. If it fails while a resumed compaction restores its earlier outputs, the resume fails.
- RepairDB returns NotSupported, with inputs untouched, when an SST has a valid classification, also with frontier 0. Such an SST shows that the DB used enable_blob_indirection, which RepairDB does not support (the RepairDB guard of diff 4).
- The L0 sorted run count: CalculateBaseBytes() (run for each new Version) counts the L0 sorted runs in one pass over the L0 files, and stores the result for NumL0SortedRuns() and l0_delay_trigger_count(). EstimateCompactionBytesNeeded() counts again with CountL0SortedRuns(). ComputeCompactionScore() and CalculateSortedRuns() walk the L0 files run by run with L0SortedRunEnd(). Without the format fence, these functions take the base path: each L0 file is one sorted run.
- FlushJob has a test hook for its TableBuilderOptions (sync point FlushJob::WriteLevel0Table:TableBuilderOptions), so tests can make a flush write exact metadata.

## How to read this diff

1. Read "Terms used in this diff" above. Then read the top overview of db/blob/blob_reference_metadata.h (the list of which SSTs get exact metadata, and the paragraph "Reference cap and epoch runs"), and its sections "Coarse SST" and "Coarse classification property".
2. The builder: in table/table_builder.h, read the TableBuilderOptions fields collect_blob_reference_metadata and track_blob_reference_classification, and TableBuilder::BlobReferenceLimitReached(). Then read table/block_based/block_based_table_builder.cc: BlockBasedTableBuilder::AddBlobReferences() computes the frontier (AddImpl() calls it only when the SST collects references or tracks the classification), WriteBlobReferenceMetadata() writes the property, and BlobReferenceLimitReached() checks the cap. EncodeBlobReferenceClassification() and DecodeBlobReferenceClassification() are in db/blob/blob_reference_metadata.cc.
3. The callers that set the two fields: FlushJob::WriteLevel0Table() in db/flush_job.cc, DBImpl::WriteLevel0TableForRecovery() in db/db_impl/db_impl_open.cc, and CompactionJob::OpenCompactionOutputFile() in db/compaction/compaction_job.cc with Compaction::CollectExactBlobReferences() in db/compaction/compaction.cc. Then read how the property gets into the file metadata: ExtractBlobReferenceClassificationFromTableProperties() in db/builder.cc, its callers in db/compaction/compaction_outputs.cc, and the blob_reference_legacy_metadata comment in db/version_edit.h.
4. L0 moves: Compaction::MustRewriteCoarseL0File() and IsTrivialMove() in db/compaction/compaction.cc, LevelCompactionBuilder::TryPickL0TrivialMove() in db/compaction/compaction_picker_level.cc, and DBImpl::PromoteL0() in db/db_impl/db_impl_experimental.cc.
5. The reference cap (safe to skip on a first read): the option comment in include/rocksdb/advanced_options.h, the range check in ColumnFamilyData::ValidateOptions() (db/column_family.cc), and CompactionOutputs::AddToOutput() and NoteBlobReferenceLimitCut() in db/compaction/compaction_outputs.cc. Then the statistics and the event log fields in CompactionJob::FinishCompactionOutputFile() and db/event_helpers.cc.
6. Epoch runs (safe to skip on a first read): VersionStorageInfo::ExpandExactL0Inputs() in db/version_set.h (its comment has a worked example of why a pick takes the whole run) and db/version_set.cc. Then its callers: CompactionPicker::ExpandL0ToWholeRuns() (used by ExpandInputsToCleanCut() and GetOverlappingL0Files()) and GetCompactionInputsFromFileNumbers() in db/compaction/compaction_picker.cc, SetupOtherL0FilesIfNeeded() and TryPickL0TrivialMove() in db/compaction/compaction_picker_level.cc, and PickDeleteTriggeredCompaction() in db/compaction/compaction_picker_universal.cc. Then the safety net: CheckL0EpochRunsDoNotOverlap() in db/version_builder.cc. Then the sorted run count: L0SortedRunEnd(), CountL0SortedRuns() and NumL0SortedRuns() in db/version_set.h, their callers CalculateBaseBytes(), ComputeCompactionScore() and EstimateCompactionBytesNeeded() in db/version_set.cc, PickIntraL0Compaction() and PickSizeBasedIntraL0Compaction() in db/compaction/compaction_picker_level.cc, and UniversalCompactionBuilder::CalculateSortedRuns(), AppendL0RunFiles() and CheckExactL0RunRange() in db/compaction/compaction_picker_universal.cc. Then TableCache::RangeTombstonesMayCoverUserKey() in db/table_cache.h and its callers in db/table_cache.cc and db/table_cache_sync_and_async.h.
7. Last, skim the small changes: the classification check in db/repair.cc, the UpdateTableProperties() status in db/compaction/compaction_service_job.cc, table/sst_file_writer.cc, the coarse-sst-count and lowest-coarse-frontier keys in db/internal_stats.cc, and the coarse classification line in tools/sst_dump_tool.cc.

## Also in this diff

- port/likely.h gets a second general macro, ROCKSDB_COLD, next to ROCKSDB_NOINLINE of diff 2. It marks a function that runs rarely even with its feature on: cold and noinline on GCC and Clang (the compiler places it away from the hot code), __declspec(noinline) on MSVC, and empty elsewhere. NoteBlobReferenceLimitCut() uses it, so the per-key code of AddToOutput() stays small.
- An existing version_set_test case also checks that the rejected edit leaves no relocation file metadata for the colliding file number.
- Two db_secondary_test cases test the best-efforts blob file check of diff 4 in secondary catch-up. They are here because building their state needs a flush with enable_blob_indirection off in a fenced column family, which diffs 5 and 6 reject and this diff allows.

## Performance

These numbers were measured on earlier builds of this stack, not on this commit. Each item names its build.

- Reference cap (db_bench, an earlier release build of this stack, as of 2026-11-20; 6 interleaved rounds; a shared virtual machine with 192 vCPUs, each step pinned to 32 of them; btrfs): fillrandom of 8.2M keys with 512-byte blob values (about 4.3 GB of user data), target_file_size_base 256 MB, blob GC off, then a full manual compaction, with leveled and with universal compaction. The default cap (1,048,576 references) was compared with a cap of 16,777,216, which never ends an output. Result (medians): a full compaction writes 5 SSTs of about 25 MB instead of 1 SST of about 124 MB, with the same total SST bytes and compaction write bytes. Fill throughput, fill CPU and full compaction time and CPU show no clear difference. The largest output holds 1,048,576 references against about 5.18M, so the estimated collector peak per output (8 to 14 bytes per reference, a design estimate) is about 8-15 MB against 41-73 MB. The compaction process peak RSS was 86-87 MB against 111-123 MB. Tradeoff: a lower cap makes more, smaller files.
- Output size at the default cap (profile run, one run per configuration, build of 2026-11-16; reruns up to 2026-11-18 wrote the same SST bytes; one shared host with 192 cores, each step pinned to 32 cores): 5M keys of 16 bytes, 4 KB values, LZ4, blob GC off. The SSTs used about 22 bytes per blob reference on average, including the reference metadata. Full outputs of 1,048,576 references were 24.3 to 24.9 MB, below the default target_file_size_base (64 MB). So the cap, not the target size, ended these outputs. The cap changes the number of files, not the total bytes.
- Coarse L0 rewrite (db_bench, the same earlier release build of this stack as in the first item; 6 interleaved rounds; same host): a sequential fill (fillseq) of 5M keys with 16-byte keys and 4 KB values. The baseline is a bench-only build of the same stack build in which flush writes exact metadata, so flushed L0 files can be trivially moved (it made 78 trivial move events and no compaction writes). The stack wrote 205.5 MB of compaction output, which raises (flush + compaction write bytes) / user bytes from 1.0087 to 1.0184 (+0.96%). Throughput showed no measurable difference. That is about 41 bytes per SST entry (41 / 4096 is about 1%). From that figure, the extra writes are about 16% at 256-byte values and about 64% at 64-byte values (estimates, not measured).

## Safety, compatibility, and limitations

- The option gate: at this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (diff 2 adds the gate, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.
- Changes visible to existing users: the sorted run counting applies only to column families with the format fence; without it, each L0 file stays one sorted run. CountL0SortedRuns() then returns the number of files, so the universal one-sorted-run check above behaves as in base RocksDB. The L0 range tombstone check of point lookups runs only in a column family with the format fence, so a column family that never used the option does no extra work in point lookups.
- Persisted data:
  - New table property kBlobReferenceClassificationPropertyName (16 bytes: format version 1, frontier, CRC32C). An SST without it (all older SSTs) has no classification, as before. Older RocksDB versions ignore the property. A wrong size, version or CRC, or a frontier above the file number mask, is Corruption.
  - This diff is the first writer of the coarse frontier (kOldestCoarseIndirectOriginFileNumber, on-disk tag 84, defined in diff 5) and writes the legacy marker (kBlobReferenceLegacyMetadata, on-disk tag 83) for a classification with frontier 0. Both tags are not safe to ignore, so older RocksDB versions fail to open such a MANIFEST ("new-file4 custom field not supported"). Only a column family that uses or has used blob indirection writes them.
  - The new option blob_indirection_max_references_per_sst is written to the OPTIONS file. An older RocksDB version that loads that file treats it like any unknown option: the load fails unless ignore_unknown_options is set.
- Public API:
  - New column family option blob_indirection_max_references_per_sst (experimental, mutable, valid range [4096, 268435456], default 1048576), with its C API getter and setter.
  - experimental::PromoteL0 returns NotSupported for a coarse L0 file with a frontier other than 0.
  - New tickers COMPACTION_OUTPUT_BLOB_REFERENCE_LIMIT_CUTS and COMPACTION_COARSE_L0_TRIVIAL_MOVE_BLOCKED, and histogram COMPACTION_OUTPUT_BLOB_REFERENCES. The tickers are added among the tickers of this stack (COMPACTION_COARSE_L0_TRIVIAL_MOVE_BLOCKED just before TICKER_ENUM_MAX), and the histogram just before HISTOGRAM_ENUM_MAX, so the values of the entries after them change. The Java API maps the histogram (HistogramType and portal.h). The new tickers have no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- Internal API: TableBuilder::BlobReferenceLimitReached() and the two TableBuilderOptions fields.
- Under universal compaction, a coarse flushed run pins every indirect-origin blob file at or above its frontier until a compaction rewrites it with exact metadata (into L1 or deeper, in a bottommost compaction, or in an L0 compaction with an exact input).
- Known gap, fixed in diff 12: turning the option on while an older flush or compaction (picked with the option off, in a column family without the format fence) is still running can fail its install with Corruption ("An SST added after the format fence has no exact blob reference metadata"). It becomes a background error, with no data loss. In diffs 7 to 11 it is reachable only through the test hook.
- Deferred to diff 12: base RocksDB import (CreateColumnFamilyWithImport) rejects an SST whose metadata names a blob file (oldest_blob_file_number). This diff adds no check of the SST itself: ingestion of an SST with indirect references, and import of one whose metadata names no blob file, are not rejected in this diff.

## Validation and known limitations

Unit tests cover which SSTs get exact or coarse metadata, the coarse L0 move rules, the reference cap (including user key histories, timestamps, wide-column entities and per-key placement), the option range, the epoch run rules of every picker, the consistency check of an epoch run, the sorted run count of an epoch run (compaction triggers and write stalls), and point lookups across a range tombstone that the cap cut. Limits of the validation:
- All benchmark numbers come from earlier builds of the stack (see "Performance"). The extra writes of coarse L0 files were measured only for 4 KB values; the numbers for smaller values are estimates. A follow-up measures coarse flush with small values, and whether coarse flush stays is decided before diff 14 lifts the option gate. Once a DB can write coarse SSTs, later releases must keep reading them (the NewFile custom tag kOldestCoarseIndirectOriginFileNumber, kCustomTagNonSafeIgnoreMask | 20, and the table property kBlobReferenceClassificationPropertyName) and keep the census pin, even if coarse flush is removed.
- The per-diff test runs used make debug builds on Linux x86_64 without sanitizers (see the Test Plan); no sanitizer result is claimed. There is no crash test at this diff; db_stress support comes in diff 14.
- The local make builds have no coroutines, so in them the async MultiGet() case of L0RangeTombstoneCheckRunsOnlyWithFormatFence runs the sync path. The internal buck build compiles RocksDB with coroutines (-DUSE_COROUTINES). A reviewer's buck dev build showed that the test fails when both MultiGetFilter() call sites pass check_l0_range without the fence condition. We did not rerun that build.
- Read cost in a fenced column family: a point lookup (Get() or MultiGet()) does up to two user key compares per key for each L0 file that has range tombstones (TableCache::RangeTombstonesMayCoverUserKey()). Without the format fence the check does not run. Telling cut files from other L0 files would need a new per-file MANIFEST field, so every L0 file of a fenced column family gets the check.
- Read cost of an L0 epoch run (known limitation, not measured): reads treat each file of a run as its own L0 file. Get() and MultiGet() compare the key range of each run file, and an iterator seeks every run file. When L0 is the only level with files and has at most 3 files, the reads skip the key range compare and probe the filter of each file instead. With metadata pinning (pin_l0_filter_and_index_blocks_in_cache), run files up to 1.5 times write_buffer_size are pinned like flushed files; at the default cap they are about 25 MB. The number of run files is about the reference count divided by the cap. It matters most for universal compaction with num_levels = 1, where all data stays in L0: after a full compaction of 1 TB of 4 KB values, an estimated 256 run files at the default cap (about 1,000 files for 1 KB values). In leveled compaction, runs come only from intra-L0 picks and CompactFiles() to L0, and they last until the next L0 to Lbase compaction. With universal compaction and num_levels > 1, a run stays in L0 only when the output level is L0. A read benchmark, and reading a run as one sorted run (a binary search in the file pickers and one level iterator per run), are follow-ups, to be done before diff 14 lifts the option gate.

Tracking issue: meta#15301

Differential Revision: D132305445
Summary:
Pull Request resolved: meta#15544

## Background

Indirect blob GC (diff 9) copies the live values of blob files that hold a lot of garbage into new relocation files, and rewrites no SST. Before it copies anything, it must know the exact live references of each input file, keep its memory bounded, decide which inputs share an output, and copy the stored bytes without decompressing them. This diff adds those parts as building blocks that work without the DB, with unit tests only. Their only intended user is the GC job of diff 9. Splitting them out lets a reviewer check each block on its own before the job that combines them.

## Previous behavior

Up to diff 7, a table reader could read only the reference index of an SST (TableReader::ReadBlobReferenceGroups(), which the census uses), not the references themselves. No code read the stored (maybe compressed) bytes of a value out of a file, and nothing planned GC outputs. Location blocks of relocation files were written with kNoCompression, and relocation files used the checksum type of the table options.

## New behavior

No DB code calls the new blocks yet. Each block gives its caller this contract:
- Batch reference reader: one call reads the references of many groups from one SST, decodes the SST's reference index once, and reads each needed data block once. Each request appends to a vector or to a sink, with a room check before the read and an error per request.
- Live set: holds the exact live references of one GC input, checks each reference, merges copies of one stable identity and builds one origin run per origin.
- Memory budget: many users share one 64 MB budget that is charged to the block cache.
- Packing plan: puts whole inputs into outputs, the same way each time.
- Stored-byte reads and writes: read the exact stored bytes of a value, check them with the stored CRC, and never decompress. Neighbor values can share one read, and a large value is streamed in chunks. A relocation record can be written from a checked stream.

## Implementation

### Batch reference reader

- TableReader::ReadBlobReferences() reads adjacent data blocks together, in MultiRead batches of at most kBlobReferenceReadBatchBytes (256 KB, an estimate that holds many blocks per read but keeps the buffer small).
- A request names one group, or (whole_generation) every group of one generation number. Requests must be sorted and unique, and a batch must not mix whole-generation and single-group requests; otherwise the call returns InvalidArgument.
- Before the read, each group is checked against the room left in its output, minus the references of earlier requests with the same output. A group that does not fit gets Aborted and appends nothing.
- Per-request errors are NotFound (no such group), Aborted (no room) and Corruption (a corrupt block, or totals that do not match the index). The other requests continue. A failed request drops only the references it appended, so references from earlier requests or earlier calls stay.
- Each read sets the found totals of every request to 0 first, so a request that is read again (for example for the next SST) never keeps the totals of an earlier read.
- Status checks: after a successful call, the caller must read every request status. When the whole call fails (for example a read error that is not corruption), the call marks every request status, and every read request status of its MultiRead, as checked, so a caller that stops at the call error does not leave unchecked statuses.
- after_index_read reports the real memory of the decoded reference index, before any data block is read, so a caller can charge it. The size grows with the number of groups, so a fixed estimate can be too small.

### Live set, memory budget and packing plan

- BlobRelocationLiveSet checks each appended reference: its generation number must be one of the input's, and its encoding class must match it (unflattened if and only if generation number == origin). It already accepts flattened references (generation number != origin), which only diff 10 writes, so that a relocation input can be collected again after flatten. It keeps each reference as a BlobRelocationLiveValue of at most 40 bytes.
- Record bytes: a value of a relocation input is in the relocation file, where its record is the stored value plus the 5-byte trailer. An unflattened reference to a relocation input reaches it through a route and carries the record size of the old normal blob file (record header and user key). The live set gives such a reference the trailer size when the input has more than one generation number, which only a relocation input has. So live_record_bytes() is the size of the live values in the input file.
- Finalize() sorts by stable identity and merges copies of one identity, which can come from several SSTs or several generation numbers. Copies must agree on size, compression and both CRCs; otherwise it returns Corruption.
- Reserve() charges the exact capacity first, so the owner pays for the memory before the batch reader fills it.
- BlobRelocationMemoryTracker bounds the memory of all its users together to 64 MB (kMaxBytes, an estimate) and charges it to the block cache. A request over the budget returns MemoryLimit. A live set charges 40 bytes per reference, counted before copies merge, so one input with more than about 1.68 million references (64 MB / 40 bytes) never fits. The tracker is not thread-safe; its users run on one thread.
- PlanBlobRelocationPacking() uses first fit decreasing by estimated size. An input is never split. An input larger than the target gets an output of its own. As a defensive check, two inputs that hold the same origin never share an output, because an output holds one entry per stable identity (origin, original offset). More outputs than the limit returns MemoryLimit.

### Stored-byte reads and writes

- A request with a null payload is only checked, not returned.
- ReadCoalescedRanges() merges neighbor ranges into one read when the gap between them is at most coalesce_bytes, and keeps each read under a size limit. Ranges past the buffer limit get Incomplete, and the caller reads them in a later call. The first read is always issued, so a call always makes progress. A range out of order or overlapping an earlier one is a caller error and gets InvalidArgument.
- Normal blob files: BlobFileReader::MultiGetStoredBlobsForRelocation() takes requests sorted by offset. StreamStoredBlobForRelocation() streams one value in chunks of kBlobRelocationStreamChunkSize (256 KB), so memory does not depend on the value size. 256 KB is a choice, not a measurement: diff 9 streams only values that are too large for one batch read, so a streamed value takes a few chunk reads instead of many small ones. These reads count BLOB_DB_BLOB_FILE_BYTES_READ and blob_read_byte, merged gaps included. blob_read_count counts file reads, so a merged read of several values counts once, and a stream counts once. The blob_read_time of a stream also includes the time spent in its consumer, because reads and consumer calls take turns.
- Relocation files: BlobRelocationFileReader::MultiGetStoredBlobs() looks values up by stable identity. It also checks the record checksum in the trailer, unless the file uses kNoChecksum. When the location entries put the records of two different values in overlapping bytes, the entries are corrupt, so the later value gets Corruption before any read (an overlap that reached ReadCoalescedRanges() would get InvalidArgument, which means a caller error). A request with origin 0 gets InvalidArgument. A request that would bring the call's total stored bytes past max_stored_value_size gets MemoryLimit. StreamStoredBlob() streams one value. These reads update no blob read ticker or perf counter. If the relocation table is not open, every request gets Corruption.
- WriteSimpleGen2BlobRecordStream() and the streaming BlockBasedTableBuilder::AddBlobRelocation() write a record from a checked source without holding the whole payload. The source has already computed the CRC32C of the stored bytes, so the writer only adds the file's checksum context. A source that fails, or that delivers the wrong number of bytes, fails the write, and the caller must not publish the partial file.
- Both AddBlobRelocation() overloads run the same checks (CheckBlobRelocationValue()): the stored size is 1 byte to kMaxSimpleGen2BlobPayloadSize, the compression type is supported, and the origin is older than the file. An origin that is not older also fails the builder, because the reader would reject the finished file.

### Cache role

- New CacheEntryRole::kIndirectBlobGcWorkingMemory holds the working memory of indirect blob GC. BlockBasedTableOptions accepts a cache_usage_options.options_overrides entry for it, which diff 9 reads. It has its own line in the block cache entry stats.

## Also in this diff

These change relocation file code from diff 3. They belong here because the GC job of diff 9 is the only writer of relocation files, and the streaming write above needs the checksum rule.
- Location block compression: the data blocks that hold location entries use the column family's bottommost_compression if it is set, else its compression. A relocation file holds long-lived data, like bottommost data (a design choice). Values are written outside the blocks, already in stored form, and are never recompressed.
- No parallel compression: it writes data blocks to the file from other threads, while the builder writes the records from the calling thread.
- No dictionary: dictionary sampling holds the data blocks in memory until the sampling ends, and location blocks are small, so a dictionary is not worth that memory (a design choice). The builder sets max_dict_bytes and zstd_max_train_bytes to 0. It also sets the new internal field TableBuilderOptions::ignore_data_block_dictionary, so the block-based table builder ignores the data-block dictionary guidance of the compressor (sampling or a pre-defined dictionary) and never buffers data blocks. Such a manager works for normal SSTs, so it must not make the relocation file (and with it the GC job of diff 9) fail. A compressor that brings its own dictionary can still use it, and the file then has its dictionary block; reads handle it as for any SST. No other builder sets the field. StartBlobRelocationFile() returns InvalidArgument if the builder buffers data blocks anyway.
- Checksum type: relocation files use kCRC32c for block and record checksums, unless the table options set kNoChecksum. A record trailer can then reuse the stored CRC32C of the value, so streaming a value needs no second checksum pass.
- Lookup caller: the lookup iterator of a relocation file (BlobRelocationFileReader::NewLookupIterator()) uses TableReaderCaller::kBlobRelocationFileRead (diff 3). So block cache traces mark these location lookups like the other relocation file reads. A relocation file has the embedded blob stats property, so BlockBasedTable::NewIterator() would wrap its iterator with the embedded-blob resolving iterator, which can rewrite a kTypeBlobIndex entry to kTypeValue. NewIterator() skips that wrapper for the caller kBlobRelocationFileRead, so FindBlobIndex() checks the raw location entries, including their type.

## Safety, compatibility and limitations

- Option gate: at this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (diff 2 adds the gate, diff 14 removes it). The building blocks and the relocation file rules are reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection. Only the new cache role (see Public API) is visible in production.
- Persisted data: relocation files written by this diff can have compressed location blocks and always use kCRC32c or kNoChecksum. The read path of diff 3 reads both the old and the new form with no change, because a block-based table reader takes the compression type from each block and the checksum type from the footer. No RocksDB release writes or reads relocation files; diff 4 says what an older binary does with a DB that has feature data (it fails to open).
- Public API: CacheEntryRole::kIndirectBlobGcWorkingMemory is inserted before kMisc. This changes the numeric values of kMisc and kNumCacheEntryRoles.

## Validation and known limitations

Unit tests cover the batch reader (block reads, room checks, errors including a whole-call read error, found totals, whole-generation reads into a live set, index size report), the live set (checks, merges, origin runs, record bytes of a relocation input, exact reservation), the shared memory budget, the packing plan, stored reads of both file kinds, streaming writes and streamed reads of both file kinds, coalesced reads, and compressed location blocks. See the Test Plan.

Known limitations:
- The tests call each block directly. The job that combines them, and its end-to-end tests, come in diff 9.
- This diff has no db_stress coverage; diff 14 adds it.
- One GC input with more than about 1.68 million references never fits the 64 MB budget (see "Live set, memory budget and packing plan"). Diff 9 decides what the job does with such an input.

## How to read this diff

1. Overview: read "Terms used in this diff" below, then the overview at the top of db/blob/blob_relocation_gc.h. It lists the five parts and the order in which a GC job (diff 9) calls them.
2. Batch reference reader: in table/table_reader.h read BlobReferenceSink, BlobReferenceGroupRead, kBlobReferenceReadBatchBytes and the ReadBlobReferences() comment. Then read ReadBlobReferences(), ReadIndexedBlobReferenceGroups() and ReadBlobReferenceDataBlocks() in table/block_based/block_based_table_reader.cc. The table reader part depends only on the exact reference metadata of diff 2.
3. Memory budget and live set: read BlobRelocationMemoryTracker, BlobRelocationLiveValue, BlobRelocationOriginRun and BlobRelocationLiveSet in db/blob/blob_relocation_gc.{h,cc}, and CacheEntryRole::kIndirectBlobGcWorkingMemory in include/rocksdb/cache.h. A live set is a BlobReferenceSink from step 2.
4. Packing plan: read BlobRelocationPackingItem, BlobRelocationPackingBin and PlanBlobRelocationPacking() in db/blob/blob_relocation_gc.{h,cc}. It does not depend on step 3.
5. Coalesced reads: read CoalescedReadBuffers and ReadCoalescedRanges() in db/blob/blob_gen2_format.{h,cc}.
6. Stored reads: for normal blob files, read MultiGetStoredBlobsForRelocation() and StreamStoredBlobForRelocation() in db/blob/blob_file_reader.{h,cc}, and StreamAndVerifyBlobStoredPayload() in db/blob/blob_gen2_format.h. For relocation files, read BlobRelocationFileReader::MultiGetStoredBlobs() and StreamStoredBlob() in the same files, the read table at the top of db/blob/blob_relocation_file.h, and BlockBasedTable::MultiGetStoredSameFileBlob() and StreamStoredSameFileBlob() in table/block_based/block_based_table_reader.{h,cc} (their request type, StoredSameFileBlobReadRequest, is in db/blob/same_file_blob_reader.h).
7. Streaming writes: read WriteSimpleGen2BlobRecordStream() in db/blob/blob_gen2_format.h and the streaming AddBlobRelocation() in table/block_based/block_based_table_builder.{h,cc}.
8. Last (safe to skim): the "Also in this diff" rules, in the NewBlobRelocationTableBuilder() comment in table/block_based/block_based_table_builder.h and MakeBlobRelocationTableOptions() in db/blob/blob_relocation_file.cc. BUCK, CMakeLists.txt and src.mk add db/blob/blob_relocation_gc.cc.

## Terms used in this diff

The stack terms (origin, original offset, stable identity, generation number, unflattened and flattened reference, route, relocation file, logical CRC, physical file, exact reference metadata, census) are defined in [Blob GC] 2/14. The file table that maps a generation number to a live file or to a route is in [Blob GC] 4/14.

The overview at the top of db/blob/blob_relocation_gc.h defines the terms of this diff: input, generation numbers of an input, output, live set, record bytes, stored CRC, sink, location block and coalesced read. The comment of BlobRelocationOriginRun in the same file defines origin run.

## Stack context

The goal, the read and lifecycle diagrams, the stack map and the terms for later diffs are in [Blob GC] 2/14, section Stack context. This diff is row 8 of the stack map: indirect blob GC building blocks. Diff 9 adds the job that uses them.

Tracking issue: meta#15301

Differential Revision: D124782167
Summary:
Pull Request resolved: https://github.com/meta/rocksdb/pull/15545

## Background

A blob file can hold mostly garbage while the SSTs that reference it are cold. Compaction-time blob GC (enable_blob_garbage_collection) reclaims a blob file only when compaction rewrites the SSTs that reference it. So the garbage stays on disk until those SSTs are compacted, and when they are, compaction copies the live values again. This diff adds the indirect blob GC job. It collects whole files of one column family, normal blob files or relocation files, into new relocation files, installs the result with one MANIFEST edit, and rewrites no SST. A relocation file also gets garbage when SSTs drop its values, so GC collects relocation files too. The job combines the building blocks of diff 8.

## Previous behavior

Up to diff 8, nothing collected a blob file outside compaction. The census ranked candidates, and the building blocks of diff 8 had only test callers. Compaction-time blob GC rewrote the values of the oldest blob files (below blob_garbage_collection_age_cutoff) together with the SSTs that reference them. A garbage-heavy blob file whose SSTs were not compacted stayed on disk.

## New behavior

In short:
1. GC runs on a LOW-pool compaction worker, only when that worker finds no LSM compaction to run.
2. One job collects up to 8 input files of one column family into up to 8 relocation files, and installs them with one MANIFEST edit.
3. GC copies only the exact live set, and only for inputs whose exact garbage ratio is at least indirect_blob_gc_garbage_ratio (a new column family option, default 0.5).
4. A census mismatch triggers one census rebuild. A repeat mismatch of the same file suppresses that file.
5. Corrupt blob data follows paranoid_checks, as in compaction. In both settings, a corrupt or unsupported input is suppressed alone, and the other inputs stay candidates. If such an input is found in the copy phase, the job also ends without installing any output. With paranoid_checks true (the default), corrupt blob data also makes the job fail with Corruption and set a background error. An SST that GC cannot open (for example, one with a bad footer) also follows paranoid_checks: with true the job fails with Corruption and sets a background error; with false GC skips the blob files that the SST references. Corrupt exact reference metadata (a bad reference block in an SST that opens, or two live values that overlap in their origin file) never fails the job, with both values of paranoid_checks. A value read that the blob reader rejects with InvalidArgument is a GC internal error, not corrupt data: GC skips that input, counts a failed job and sets no background error. Output, I/O and MANIFEST errors are background errors.
6. New tickers, a histogram, DB properties and LOG lines report what GC does (see "Monitoring" in the details below).

The overview at the top of db/blob/blob_relocation_gc.h describes the job steps and the suppression rules. The implementation details below add the numbers and the cases that the code comments do not hold.

## Changes visible to existing users

These changes apply to DBs that never enable blob indirection:
- Obsolete-file purge keeps a temp file whose number is protected by pending outputs (number >= min_pending_output). The rule applies to every temp file in every DB. Base RocksDB deletes such a temp file unless it is live, the pending MANIFEST or an options file. So a full purge does not delete the temp output of a running job.
- Every Statistics object has the new tickers and the new histogram INDIRECT_BLOB_GC_JOB_MICROS (see "Safety, compatibility and limitations"). They stay 0 unless a GC job runs. The new values are appended before TICKER_ENUM_MAX and HISTOGRAM_ENUM_MAX, so code that walks all tickers or histograms sees more entries.
- Every OPTIONS file holds the two new keys indirect_blob_gc_garbage_ratio and indirect_blob_gc_read_coalesce_bytes. An older RocksDB that loads such an OPTIONS file (for example with LoadLatestOptions()) fails on the unknown keys, unless the caller sets ignore_unknown_options. DB::Open does not read the OPTIONS file.
- The property rocksdb.indirect-blob-gc-idle-micros-with-candidates exists for every column family and reports 0 without a census.
- BlobFileCreationReason has the new value kIndirectBlobGC. Only GC sends it.

Nothing else is visible. The WARN line text "Indirect blob GC error" appears only for GC jobs. The GC scheduling check, the idle time and the DumpStats check run only for a column family with a census. The byte-based SstFileManager check shares its body with the existing compaction check, which keeps its behavior.

## Safety, compatibility and limitations

- Option gate: at this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (diff 2 adds the gate, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.
- Persisted data:
  - OPTIONS file: see "Changes visible to existing users". An OPTIONS file without the new keys loads with the defaults (0.5 and 16384).
  - MANIFEST: the install writes the records of diff 4 (relocation files, routes, route deletions, blob file retirement). Diff 4 states their compatibility: they are required tags, so an older binary fails to open the DB instead of misreading it.
- Public API: new tickers INDIRECT_BLOB_GC_JOBS_STARTED, _INSTALLED, _STALE, _NOTHING_INSTALLED and _FAILED, INDIRECT_BLOB_GC_CORRUPT_INPUTS, INDIRECT_BLOB_GC_OVERSIZED_INPUTS, INDIRECT_BLOB_GC_CENSUS_MISMATCHES, INDIRECT_BLOB_GC_KEYS_RELOCATED, INDIRECT_BLOB_GC_BYTES_RELOCATED, INDIRECT_BLOB_GC_BYTES_READ and INDIRECT_BLOB_GC_BYTES_RECLAIMED; new histogram INDIRECT_BLOB_GC_JOB_MICROS; new property rocksdb.indirect-blob-gc-idle-micros-with-candidates; new BlobFileCreationReason::kIndirectBlobGC. The Java API maps the histogram (HistogramType and portal.h). The new tickers have no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- Public API: the new column family options indirect_blob_gc_garbage_ratio (mutable through SetOptions, default 0.5) and indirect_blob_gc_read_coalesce_bytes (mutable through SetOptions, default 16384), with their C API getters and setters (the C API files are generated), and the new keys corrupt-input-files and corrupt-input-file-list of rocksdb.indirect-blob-gc-stats. A new garbage ratio applies from the next census publish: SetOptions() installs a new SuperVersion, and InstallSuperVersionAndScheduleWork() queues the census job.
- Completeness of the live set: GC compares the SSTs and totals that it reads with the census snapshot. The check covers only the SSTs that the census lists for an input. It cannot find an SST that holds a generation number of an input but that the census does not list. So completeness rests on the census build (diff 5), and on ingestion and import of SSTs with kIndirectBlob references being rejected (diff 12 rejects them; this diff does not).
- Candidates: a blob file referenced only by legacy BlobIndex entries is not an indirect origin, so it is not a candidate. A normal blob file at or above the coarse frontier is not a candidate. A relocation file is suppressed while one of its routed generation numbers is at or above the coarse frontier. In normal operation a coarse SST does not reference a routed generation number, but GC keeps this pin so that it never collects a file that a coarse SST may still read.
- Census estimates may understate garbage; only the exact live set allows deletion. Transient failures have retry delays, so a bad candidate cannot block other candidates for ever.
- With a separate remote compaction pool, indirect blob GC runs as local work in the LOW pool and counts toward max_compactions.
- Direct GC reads fall back to buffered reads only when the direct open fails. A file system that accepts O_DIRECT at open but fails some direct reads makes those GC jobs fail.
- GC reads of relocation-file inputs do not update BLOB_DB_BLOB_FILE_BYTES_READ or blob_read_byte. INDIRECT_BLOB_GC_BYTES_READ counts them.
- Not supported: indirect blob GC does not pack across column families, place values by user key, apply a temperature policy, or run remotely.

## Performance

### Benchmark B2: indirect blob GC against compaction-time blob GC

The workload is a garbage-heavy overwrite load (db_bench, release builds). Abase is RocksDB without the stack (compaction-time blob GC). B is the full stack with enable_blob_indirection=true and the default indirect blob GC options. Atip is the full stack with enable_blob_indirection=false. The stack build is older than this commit. Each value is the median of 6 runs, with the min-max range in parentheses. The baseline for "B against Abase" is Abase.

| Measure | Unit | Abase | B | B against Abase |
|---|---|---|---|---|
| Bytes written to disk per user byte, without the WAL | ratio | 1.74 (1.59-1.83) | 1.25 (1.25-1.26) | 28% fewer, ranges do not overlap |
| Wall time of the write steps (fillrandom and the three overwrite rounds, each with its waitforcompaction) | s | 148 (128-163) | 120 (118-122) | 19% less, ranges do not overlap |
| DB size at the end of the run | GB, range of 6 runs | 15.7-19.8 (two groups) | 17.4-18.3 | about the same; the comparison is weak |
| Blob files after the overwrites | count | 165 | 223 | 35% more |

- multireadrandom is about 11% faster with B (the ranges do not overlap; the reason was not investigated). readrandom shows no measurable difference.
- Feature off: Atip shows no measurable difference from Abase in any of these measures; the ranges overlap.

### Benchmark M: read/write matrix

The runs are the same as the feature-off benchmark in [Blob GC] 2/14 ("Performance"). BASE is base RocksDB with compaction-time blob GC. ON is the stack with enable_blob_indirection=true and blob GC on, so indirect blob GC runs. ONNOGC is the same stack build with enable_blob_indirection=true and blob GC off. Each value is the median of 6 runs, with the min-max range in parentheses. The baseline for "ON against BASE" is BASE. A "-" means that the value was not reported.

| Measure | Unit | BASE | ON | ON against BASE | ONNOGC |
|---|---|---|---|---|---|
| Write amplification without the WAL, fill + overwrite | ratio | 1.74 (1.72-1.74) | 1.35 (1.34-1.36) | 22% lower | 1.09 |
| Bytes relocated by GC, fill + overwrite | GB | 21.4 (compaction-time blob GC) | 8.3 (indirect blob GC) | - | - |
| Write amplification without the WAL, readwhilewriting | ratio | 1.52 (1.52-1.53) | 1.67 (1.66-1.67) | 10% higher | 1.10 |
| Bytes relocated by GC, readwhilewriting | GB | 60 | 72 | - | - |
| DB size at the end | GB | 43.9 (38.4-44.5) | 34.8 (34.5-35.0) | 21% smaller | 134.7 (3.1 times BASE) |
| fillrandom throughput | ops/sec | - | - | 3.6% faster | - |
| fillrandom P99 latency | - | - | - | 11.8% lower | - |
| Write stall time in readwhilewriting | - | - | - | 7.8% shorter | - |
| seekrandom throughput | ops/sec | 238,944 (228,450-246,041) | 209,579 (199,543-213,480) | 12.3% slower | 2.7% slower than BASE (ranges overlap because of one BASE run) |
| seekrandom P99 latency | - | - | - | - | 9.6% higher than BASE, no overlap |
| readwhilewriting read P99 latency | us | 225.6 (205.3-231.3) | 248.6 (246.3-251.9) | 10.2% higher | 25% lower than BASE |

- The ON against BASE ranges in the table do not overlap. overwrite, readrandom, multireadrandom and readwhilewriting read ops/sec show no clear change (the ranges overlap).
- The relocated bytes explain about the whole write amplification gap in fill + overwrite. In readwhilewriting, indirect blob GC relocates more bytes, and the DB ends smaller.
- Without GC (ONNOGC), nothing rewrites blob values, so write amplification is low, but the space keeps growing in this workload.
- Costs and their likely causes: part of the seekrandom cost does not come from relocated values, because ONNOGC is also slower; the cause was not profiled. The higher readwhilewriting read P99 with ON likely comes from the background GC work, because ONNOGC is lower than BASE; this was not profiled.
- Not measured: other value sizes, other age cutoffs, a rate-limited writer in readwhilewriting, and CPU profiles.

<details>
<summary>**Benchmark details:** builds, workloads and method of B2 and M</summary>

Benchmark B2:
- Configurations: Abase is base. B uses indirect_blob_gc_read_coalesce_bytes 16384 and indirect_blob_gc_garbage_ratio 0.5. Atip is the stack with enable_blob_indirection=false.
- Workload: 5M keys of 16 bytes, 4 KB values in blob files (min_blob_size 512, 256 MB blob files, no blob compression, lz4 for SSTs), compaction-time blob GC on with age cutoff 0.25, 16 background jobs, direct I/O. fillrandom, then three rounds of 2.5M overwrites of the same keys, each followed by waitforcompaction, then readrandom and multireadrandom with 32 threads.
- Method: six interleaved rounds, each with a fresh DB per configuration, on a shared virtual machine with 192 vCPUs (each step pinned to 32 of them), on btrfs with compress-force=zstd:3. A step starts only when the 1-minute load is below 20. One Atip run was stopped during a load spike and run again on a quiet host. Bytes written come from the process I/O counters (/proc/<pid>/io) minus the WAL bytes, because the flush and compaction tickers do not count the relocation files that GC writes.

Benchmark M:
- Builds: BASE is base RocksDB. ON and ONNOGC use an earlier build of the full stack. Both builds are older than this commit.
- Workload, steps, host and method are the same as in [Blob GC] 2/14 (6 rotating rounds). In short: 5M keys of 16 bytes and 4 KB values, all in blob files, GC age cutoff 0.25. fillrandom, an overwrite step with 2.5M writes, readrandom, multireadrandom and seekrandom, then readwhilewriting for 300 s with 32 readers and one writer at full speed. That writer writes about 31 to 33 million keys (medians) over the 5M-key space, so the last step is a heavy, steady overwrite load with write stalls in every configuration.

</details>

## Validation and known limitations

Unit tests cover relocation of the exact live set, packing and reclaim of relocation files, removal of files with no live value, the census totals check and its rebuild, per-file mismatch suppression, memory and disk space limits, error locality, SSTs that cannot be opened, failed invariant checks, the install precondition and its retries, changes during the copy, MANIFEST failures with an unknown result, temp-file and orphan cleanup, the separate remote compaction pool, the cache role, mmap reads, coarse pins, the RepairDB guard and the monitoring signals. See the Test Plan.

Known limitations:
- This diff has no db_stress coverage; diff 14 adds it.
- The memory degrade is partial in one case: when the SST reader charge fails in the read phase, every planned input of the job gets a transient suppression and is retried after the delay, also an input whose SSTs were already all read.
- While the block cache stays full, indirect GC is suppressed (a logged, counted transient suppression that is retried), so empty relocation files are not removed until the cache has room. GC keeps its strict charge because its working memory can reach the 64 MB budget, and running it uncharged would break the cache limit that the user set.
- The census build (diff 5) handles an SST that cannot be opened in its own way: it fails the build and retries after a backoff, with no background error. This diff does not change the census build, so the census build and the GC job follow different rules for such an SST.
- One GC job holds at most about 1.6 million live values: the 64 MB job memory budget minus the 2.5 MB I/O workspace charge, the 576 KB fixed SST reader charge and an estimate of the planned read list, at 40 bytes per live value. A file with more live values never fits, so GC skips it. The skip ends when the file's live count drops to the limit that GC stored for the file when it skipped it, when the file's total bytes change, when the census is rebuilt, or (for a relocation file) when the coarse frontier rises. For example, at 50% garbage a 256 MB blob file reaches the limit when its records are smaller than about 84 bytes, and a 1 GB blob file when they are smaller than about 336 bytes (computed from the limit, not measured). The limit leaves out the decoded reference index of the SST reader, because GC knows its size only after it reads the index. So a file just under the limit whose SST has a very large reference index can still fail the reader charge; it then gets a transient suppression and is retried after 1 to 32 s. Only compaction-time blob GC reclaims such a file: when compaction rewrites its SSTs and the file is within blob_garbage_collection_age_cutoff. The limit is not exact, because GC estimates the read list at twice the number of holders (one for each generation number of the file and each SST that holds it), which is an upper bound. So GC can skip a file that would just fit, by up to about 1.8 live values per holder (one 72-byte read list entry at 40 bytes per value). For the same reason, a relocation file that GC wrote can be too large for a later job. The job that wrote it held all its live sets next to its actual read list, but a later job judges the file against twice the file's own holder count, and compactions can raise that count. Each new holder lowers the limit of the file by about 3.6 live values (two 72-byte entries), so a relocation file near the limit can later be skipped as too large.
- A GC internal error (a rejected value read, which only a GC bug causes) gives the input a normal suppression, and that suppression ends at the file's next live-bytes change. So a deterministic GC bug repeats about once per compaction that touches the file. Each time, GC writes an ERROR line and counts INDIRECT_BLOB_GC_JOBS_FAILED, but it never sets a background error. A failed GC invariant check works the same way, except that the job ends as stale, so it is not counted in INDIRECT_BLOB_GC_JOBS_FAILED.
- A rebuild install that cancels a ready census (for example, after DeleteFilesInRange()) resets the census mismatch state (the remembered files and the mismatch rebuild counts): the first publish of the new build forgets the remembered files and sets the counts back to 0. This matters only when a census mismatch persists, so a metadata bug must exist first. Each such install can then cost one more round of mismatch rebuilds.
- Untested paths and the test environment: see the Test Plan.

<details>
<summary>**Implementation details:** scheduling, plan and read, decide and pack, copy, install, errors, working memory, cleanup</summary>

### Scheduling (step 1)

- A LOW-pool worker that has no pre-picked compaction and found no LSM compaction takes up to 8 candidates (kIndirectBlobGCMaxInputs, a fixed limit, not tuned; it matches the 8 candidates that the census publishes) in the Version's rank order. LSM compaction always has priority. The census heap ranks normal blob files and relocation files together.
- GC needs auto compaction on, enable_blob_files, enable_blob_garbage_collection, enable_blob_indirection, and a census that is ready for the current Version. ColumnFamilyData::NeedsCompaction() also returns true when these hold and the Version has a published candidate, so GC is scheduled even when no LSM compaction is needed.
- Only one GC job runs per column family at a time (indirect_blob_gc_cfs_in_progress_), because a job removes whole relocation files and re-points the routes into them.
- With a separate remote compaction pool, the worker that picks GC is a remote coordinator. GC then runs as local work through RunLocalCompaction(): it waits for a local compaction credit, is counted in bg_compaction_scheduled_, and runs in the LOW pool. The DB mutex is released during the wait. If SetOptions() turns blob GC off in that window (enable_blob_files, enable_blob_garbage_collection or enable_blob_indirection), the job ends before it registers with the census, with no suppression. So when GC is turned on again, a later job can collect the inputs.
- A stale job ends with TryAgain. BackgroundCompaction() turns it into Busy and enqueues the column family again. Busy is not a background error: BackgroundCallCompaction() waits only 10 ms (to prevent a hot loop) instead of the 1 s wait after an error. CompactionTooLarge and an aborted job also enqueue it again.

### Plan, read and check (steps 2 to 4)

- GC takes a reference to the input Version, registers the job with the census (BeginGcJob()), and takes the census snapshot of the inputs' generation numbers. It finds the generation numbers of each input with one scan of the input Version's routes, without the DB mutex.
- GC reserves each live set from the census reference counts before any read. All live sets and the GC buffers share one 64 MB memory budget (BlobRelocationMemoryTracker, diff 8). When the budget is used by earlier inputs, the input that does not fit and all later inputs are deferred. When no earlier input holds a reservation, GC suppresses only the input that does not fit and still plans the next ones. A deferral for memory writes an INFO line that names the first deferred input ("Indirect blob GC defers blob file #N ..."). Before it reserves an input's live set, GC checks that the live set can fit at all, even as the only live set of a job. The limit is the budget minus the charges that a job holds next to the live set: the 2.5 MB I/O workspace, the 576 KB fixed SST reader charge, and an estimate of the planned read list (144 bytes for each generation number of the input and each SST that holds it, at least 1,152 bytes; one entry is 72 bytes, and the list grows by doubling, so the estimate is twice the entries). At 40 bytes per live value, the limit is about 1.6 million values. An input above the limit gets a normal suppression at once, because a retry cannot fit it either. Any other input that does not fit gets a transient suppression (for example, when the block cache charge fails). GC suppresses an input above the limit as soon as it finds it. So a job that ends before it decides its inputs (for example, a job that only suppresses a file with a remembered census mismatch) also suppresses that input, in the census and in the current Version, and the next job does not plan it again before the census publishes. A stale job does not suppress it in the Version, and the census rebuild that follows a first mismatch report starts with no suppressions. A normal suppression for this reason counts in the new ticker INDIRECT_BLOB_GC_OVERSIZED_INPUTS and writes a WARN line. A change of the file's live bytes ends this suppression only when the file then has no more live values than a job can hold (BlobGcCandidateHeap::SuppressOversized()). So GC does not retry a file after each compaction of its SSTs.
- GC reads each needed SST once, with the reader from TableCache::GetBlobReferenceReader() (diff 5): the table cache reader, or an ephemeral reader on a miss. The reader is charged 64 KB + 2 x kBlobReferenceReadBatchBytes (256 KB each) = 576 KB (an estimate, also charged for a table cache reader, to keep it simple), plus the real size of the decoded reference index. One batch reads, per SST, every generation number of the inputs that the SST holds.
- GC compares the SSTs and totals that it found with the census snapshot (see "Completeness of the live set" above for what the check covers). On a mismatch it calls BlobReferenceCensus::ReportMismatch(). The census remembers the reported files (at most 1024, a choice: about 32 KB of memory, an estimate). The first report of a file makes the census stop being ready, requests a rebuild, and the job ends as stale. A report of a remembered file means that a rebuild did not clear its mismatch. GC then logs one ERROR line, suppresses only that file (normal suppression), and decides no input in that job, so it never relocates by a census entry that is known to be wrong. A rebuild that another file requests ends the suppression, but the file stays remembered, so its next report suppresses it again without one more rebuild. When a job's check finds no mismatch, GC calls ClearMismatch(file_number) for each checked input, and the census forgets those files only. The census forgets all remembered files at the first publish of a build that no report requested. A mismatch rebuild that restarts before it publishes (after a change log overflow, a rebuild install or another failure) is still a mismatch rebuild, so the restarted build keeps the remembered files and the counts. After a report, the census worker of the same build cannot publish again (kStale) until the census job fails that build (TakeMismatchReport()) and starts a new one. BeginBuild() also takes in a report that arrives between TakeMismatchReport() and the build start, because the new build reads the current Version, which is the rebuild that the report asks for.
- Rebuild backoff: the census job restarts a rebuild that a mismatch report requested at once, unless it is the third or a later one in a row. Then the rebuild waits, and the census job writes one ERROR line. Only a build that failed because of a mismatch report waits. A restart for another reason (for example a rebuild install from DeleteFilesInRange()) starts at once and writes no mismatch ERROR line. The wait doubles once per real wait, from 1 s up to 32 s. The census counts these waits on their own, so the order of GC reports and census builds does not change the waits. The counts go back to 0 when a GC check finds no mismatch, unless the remembered set is full, and at the publish of a build that no report requested. So when more files keep mismatching than the set can hold, the backoff limits the rebuilds.

### Decide and pack (steps 5 and 6)

- Garbage ratio: exact garbage = record bytes of the input - live record bytes. Each input must have exact garbage of at least indirect_blob_gc_garbage_ratio times its record bytes, on its own. The option is a double, default 0.5, valid range (0, 1]; other values fail with InvalidArgument. At 0, GC would pick files with no garbage and could not make its outputs smaller than its inputs. A low value frees space sooner but copies more: at value r, GC copies up to (1 - r) / r live bytes for each garbage byte it frees, so 1 byte at 0.5 and 3 bytes at 0.25 (computed from the definition, not measured). blob_garbage_collection_age_cutoff and blob_garbage_collection_force_threshold do not apply to indirect blob GC.
- Selection and the job use the same rule with the options of one Version. The census selection returns the 8 files with the highest estimated garbage ratio, with no ratio limit. When the census publishes, PublishBlobReferenceCensusWorker() cuts them at the ratio under the DB mutex (BlobGcCandidateHeap::CutSelection()), with the options of cfd->current(). The publish succeeds only when the census matches cfd->current(), and a job runs only when the census is ready at its input Version. The job check uses the options of that input Version. So the census never offers a file that the job rejects only because of a different ratio value.
- An input with no live value gets only its removal: no output and no source read.
- Packing uses PlanBlobRelocationPacking() (diff 8). The estimated output size of an input is its live record bytes + 64 KB + 48 bytes per live value (estimates on the safe side); it is 0 for an input with no live value. The target output size is 90% of min(blob_file_size, kIndirectBlobGCMaxOutputBytes (1 GB)); 1 GB and 90% are fixed choices, and the 90% leaves room for error in the estimate. When the inputs need more than 8 outputs (kIndirectBlobGCMaxOutputs), GC defers the input with the largest estimated output size and plans again.
- Space: GC reserves the estimated size of all outputs, capped at the total input size, through a new byte-based SstFileManagerImpl::EnoughRoomForCompaction(estimated_output_size, output_path, bg_error), and releases it after the job. If the check fails, GC defers the input with the largest estimated output size and checks again.
- GC never defers an input with no live value for outputs or space. Such an input needs no output and no space, and removing it frees space. When every input with a live value is deferred, the job still removes the inputs with no live value. The job returns CompactionTooLarge only when one input is left and it has a live value; the deferred inputs then get a transient suppression.

### Copy (step 7)

- GC copies the stored bytes and the compression type unchanged, keyed by (origin, original offset), and checks every copy with its stored CRC. GC never decompresses.
- Small values are read in batches of up to 1 MB (kIndirectBlobGCReadBatchBytes, an estimate), with 512 bytes of fixed per-value memory (an estimate), so a batch has at most 2048 values. Larger values are streamed in 256 KB chunks (kBlobRelocationStreamChunkSize; diff 8 explains the choice).
- Read coalescing: two neighbor values share one read when the gap between them is at most indirect_blob_gc_read_coalesce_bytes (new mutable option, default 16384, the read unit of remote file systems; blob values are large, so a gap of this size holds only a few dead values). 0 reads each value on its own. One read stays at most 1 MB.
- Readers: GC opens every input with its own reader, outside the blob file cache. Normal inputs use OpenBlobFileReaderUncached(), and relocation inputs use the new BlobFileCache::OpenRelocationFileReaderUncached(). GC opens relocation inputs without pinned location blocks (pin_blob_relocation_location_blocks), because GC is about to reclaim the file, and a pin would read every location block at IO_LOW and keep them charged until the purge. Because the reader is not cached, a user read never reuses GC's unpinned reader.
- Direct reads: GC input is cold data. Buffered io_uring reads of coalesced ranges can read more device bytes than needed, because readahead also reads the gaps (not measured for this diff). So GC opens normal blob file inputs for direct reads when mmap reads are off, and falls back to the configured open if that fails. Relocation-file inputs use buffered reads. User reads keep their buffered, cached readers.
- The GC I/O workspace (the buffers that read and stream the input values) is charged 2 x 1 MB + 2 x 256 KB before the live sets are known.
- Data reads and writes use Env::IO_LOW and do not fill the block cache. The MANIFEST write is not rate limited, so edits queued behind it do not wait for low-priority I/O.
- GC writes each output as a temp file, syncs it, and renames it to its blob file name before the install. If all outputs together are not smaller than all inputs together, GC drops every output before the rename and suppresses all its eligible inputs.

### Install (step 8)

- One MANIFEST edit adds every output, routes each live generation number of an input to the input's output, re-points the routes into a relocation input to the output, deletes the routes that no SST uses, writes the blob file retirement of each normal input and deletes each relocation input. Each output lists the old file numbers that it serves (its relocation directory, diff 3).
- At the queue head, the precondition checks that the column family is alive and the job is still registered (IsGcJobActive()), that each input is unchanged, and that no coarse SST pins an input. A relocation input must have the same number of routes into it: only GC changes routes, and only one GC job runs per column family, so an equal count means the same routes.
- Coarse pin: a normal input is pinned when its file number is at or above the coarse frontier. A relocation input is pinned when one of its routed generation numbers is at or above the coarse frontier; its own file number does not count. GC checks this at selection (and suppresses a pinned input) and again at the queue head. A pin can appear during the job. In this example, the file numbers are examples only: a flush takes its blob file number 25 before GC selects normal input 28, and installs its coarse SST with frontier 25 after. The job is then a normal stale job (TryAgain), not an invariant failure.
- Install protocol: the edit comes from the census snapshot, and the job does not follow the Version changes after it. This is enough because no SST added after the snapshot can hold a generation number of an input that the snapshot does not count: a compaction keeps or drops the references of its input SSTs, and a flush references only the new blob files that it writes. Ingestion and import are assumed to add no SST with kIndirectBlob references (diff 12 rejects them). So the snapshot can only count a holder too many, and the edit then keeps a route that no SST needs. Flushes and compactions do not wait for the GC job or its commit.
- The install uses VersionSet::LogAndApplyWithUnlockedApply() (diff 6): its edit is applied without the DB mutex, and its precondition runs once, under the DB mutex, at the MANIFEST queue head. The precondition starts the metadata commit (BeginMetadataCommit()). Until the MANIFEST write ends, no other GC job or metadata-only commit can start. When the write result is unknown, BeginGcJob() returns Busy until recovery: a GC attempt then ends with no error and no install, and after Resume() GC runs again by itself.
- If another Version was installed during the job, GC does not apply its job-start suppressions to the current Version, and enqueues the column family again.
- When the coarse frontier rises, the census heap retries the suppressed relocation files above the old frontier, because their routed generation numbers may no longer be pinned.

### Errors and suppression

The "Suppression" and "Corruption" paragraphs of the overview explain why GC suppresses an input, the two places where GC records it, and the two kinds. BlobGcCandidateHeap::Suppress() says how long a normal suppression lasts. The "Suppressed inputs" part of the IndirectBlobGCJob class comment lists every reason with its kind, and says when GC also suppresses the input in the current Version.

- Corrupt blob data (a bad record CRC or record format, or a corrupt header or footer when GC opens a normal blob file or a relocation file) follows paranoid_checks. With paranoid_checks true (the default), the job fails with Corruption, installs nothing, and the caller sets a background error with reason kCompaction. With paranoid_checks false, the corruption is candidate-local: GC leaves that input and its routes unchanged, suppresses it, and other background work continues. In both cases GC writes an ERROR line and counts INDIRECT_BLOB_GC_CORRUPT_INPUTS.
- An SST that GC cannot open (Corruption from TableCache::GetBlobReferenceReader(), for example a bad footer, meta-index block or properties block) damages user data, so it follows paranoid_checks like compaction. With true, the job fails with Corruption ("Indirect blob GC cannot open SST #N", where N is the SST file number), and the caller sets a background error with reason kCompaction. With false, GC skips the blob files that the SST references (normal suppression, reason "an SST that references it cannot be opened"). Those blob files are not corrupt, so they are not counted in INDIRECT_BLOB_GC_CORRUPT_INPUTS or listed in corrupt-input-file-list. In both cases an ERROR line names the SST.
- Corrupt exact reference metadata (a bad reference block in an SST that opens, or two live values of one origin that overlap), and a census mismatch that stays after a census rebuild, never set a background error, with both values of paranoid_checks, because the user data is not damaged. GC suppresses the input, writes an ERROR line and counts INDIRECT_BLOB_GC_CORRUPT_INPUTS. GC finds an overlap from the references alone, when it decides the input (CheckIndirectBlobGCLiveValuesDoNotOverlap()), before it reads any stored bytes. So an overlap follows the rule of a bad reference block, not the rule of corrupt blob data.
- A value read that the blob reader rejects with InvalidArgument is a GC internal error. GC rejects overlapping live values before it reads (see the bullet above), so only a GC programming check returns InvalidArgument here (for example, a normal read on a relocation file, or missing read buffers); a correct build never fails these checks. It is not corrupt data, so it does not count in INDIRECT_BLOB_GC_CORRUPT_INPUTS and does not follow paranoid_checks. In the batch and in the streaming read path, GC writes an ERROR line ("Indirect blob GC internal error on input #<file number>" with the status), gives the input a normal suppression, ends the job without installing any output, and counts the job in INDIRECT_BLOB_GC_JOBS_FAILED and BLOB_DB_GC_FAILURES. The job returns OK, so it sets no background error and writes go on. This is safe because GC publishes nothing from a failed job, so no data changes. When one read batch has both a Corruption and an InvalidArgument, the Corruption wins, so it still follows paranoid_checks.
- A failed invariant check names a state that normal operation never reaches. GC logs an ERROR line, gives every eligible input of the job a normal suppression in the census, and ends the job as a stale job. When the current Version is still the input Version, GC also suppresses the inputs in that Version, because the stale job is retried at once and the census publishes its new candidate list later. The suppression lasts until the file changes, the census is rebuilt or (for a relocation file) the coarse frontier rises, so a retry picks other candidates instead of failing the same check again. It counts only as a stale job (INDIRECT_BLOB_GC_JOBS_STALE) plus the ERROR line; it is not a background error, because the job installs nothing and the user data is not damaged. Debug builds assert, unless a test injected the failure.
- Output corruption, I/O errors and MANIFEST errors use the normal background-error handling. When one read batch has both a candidate-local error and another error, the other error wins.
- A stale job installs nothing; a later job tries again. At shutdown the job returns ShutdownInProgress. Cache pressure on the census snapshot gives the job's inputs a transient suppression. None of these is a background error.
- If the MANIFEST write fails, the outputs are quarantined, not deleted, and the inputs stay. This is also the state after a crash between the rename and the install.
- An output that fails before its rename never had its final name, and the SstFileManager never tracks it. Listeners see a failed creation (BlobFileCompletionCallback::OnBlobFileAbandoned()) and no deletion event. An output whose rename was tried and reported failure also gets OnBlobFileAbandoned(). The rename may still have created the final name, so GC deletes that name as a temporary file, with no blob file deletion event. A renamed output that GC deletes later (when the job does not install) sends the blob file deletion event.

### Working memory

The live sets, the census snapshot, the SST readers and the GC buffers are charged to CacheEntryRole::kIndirectBlobGcWorkingMemory (diff 8) in the job's block cache. The role follows cache_usage_options.options_overrides and is charged by default (kFallback counts as enabled). Setting it to kDisabled turns the charge off. The per-route bookkeeping of a job is not charged: the generation numbers routed to each relocation input, the source list of the census snapshot, the per-generation checks and the route records of the edit. It grows with the number of routes into the job's relocation inputs, which the Version already holds in memory, at tens of bytes per route (an estimate).

### Orphan outputs and RepairDB

- An orphan output is a file with the relocation file prefix that no Version owns. Purge deletes it (the purge rule of diff 4 recognizes it by its prefix).
- The RepairDB guard (diff 4) also rejects a DB with a validated relocation file: a <number>.blob file that starts with the relocation prefix and whose table properties hold a relocation directory that decodes and is valid for the file size. It needs no MANIFEST to find one. A file with the prefix but without a valid directory is not evidence. Files that cannot be read are skipped.

</details>

<details>
<summary>**Monitoring details:** tickers, histogram, properties and LOG lines</summary>

- Job outcome. Each job that begins (registers with the census) counts in INDIRECT_BLOB_GC_JOBS_STARTED. At its end, it counts in one of these tickers:
  - INDIRECT_BLOB_GC_JOBS_INSTALLED: the job installed its result;
  - INDIRECT_BLOB_GC_JOBS_STALE: an input changed, and a later job retries;
  - INDIRECT_BLOB_GC_JOBS_NOTHING_INSTALLED: no error and nothing installed, for example because every input was skipped, the job was deferred, the DB shut down or the column family was dropped;
  - INDIRECT_BLOB_GC_JOBS_FAILED: an error, or a GC internal error (a rejected value read; that job returns OK and sets no background error). Such a job also counts in the base ticker BLOB_DB_GC_FAILURES.
- Work. INDIRECT_BLOB_GC_KEYS_RELOCATED and INDIRECT_BLOB_GC_BYTES_RELOCATED (stored bytes) count the values that installed jobs moved into relocation files. The base tickers BLOB_DB_GC_NUM_KEYS_RELOCATED and BLOB_DB_GC_BYTES_RELOCATED count them too, as totals of both GCs. INDIRECT_BLOB_GC_BYTES_READ counts the bytes of the values that jobs read from their input files, normal and relocation files (stored bytes, plus the record trailer for a relocation file). Coalesced gaps and metadata reads are not counted. INDIRECT_BLOB_GC_BYTES_RECLAIMED counts, for installed jobs, the size of the removed input files minus the size of the new relocation files. The base tickers BLOB_DB_GC_NUM_FILES and BLOB_DB_GC_NUM_NEW_FILES count the removed input files and the new relocation files.
- Problems. INDIRECT_BLOB_GC_CORRUPT_INPUTS counts the inputs in which a job found corruption (a blob record, the header or footer of a blob or relocation file, exact reference metadata (also two live values that overlap in their origin file), invalid input metadata, or a census mismatch that stays after a census rebuild). An SST that cannot be opened does not count here, because its blob files are not corrupt. The ticker counts once per job, so the same file can count again after it comes back as a candidate. The keys corrupt-input-files (the number of files that GC currently skips for one of these reasons) and corrupt-input-file-list (at most 8 file numbers, lowest first, comma separated; partial when the count is above 8) of rocksdb.indirect-blob-gc-stats give the current set. A file stays in the set until it changes, the census is rebuilt, or the coarse frontier rises (relocation files only; the heap then retries every suppressed relocation file above the old frontier). INDIRECT_BLOB_GC_CENSUS_MISMATCHES counts the times a job found SSTs that do not match the census. INDIRECT_BLOB_GC_OVERSIZED_INPUTS counts the inputs whose exact live set cannot fit in the job memory budget even as the only live set of the job; each one also gets a WARN line, and the file is skipped until it has few enough live values to fit, the census is rebuilt or (for a relocation file) the coarse frontier rises.
- INDIRECT_BLOB_GC_JOB_MICROS (histogram) records the time of each job, from its start to its end.
- Idle time. Each column family keeps the time since which it has had GC candidates and no job began (ColumnFamilyData::NoteIndirectBlobGcCandidates()). The idle time shows whether GC falls behind, so it counts only while the latest options let a GC job run: enable_blob_files, enable_blob_garbage_collection and enable_blob_indirection on, and disable_auto_compactions off (ColumnFamilyData::IndirectBlobGcOptionsAllowJob()).
  - Under these options, a census publish with candidates while no GC job is registered (BlobReferenceCensus::HasGcJob()), or the end of a job that leaves candidates, starts it.
  - A job start, a publish without candidates, or a publish while the options do not let a job run clears it. A SetOptions() call after which the options do not let a job run also clears it. When the options turn GC on, the census publish of the new Version starts it.
  - So the idle time stays 0 while a job runs and while the options keep GC off. rocksdb.indirect-blob-gc-idle-micros-with-candidates (an int property) and the map key idle-micros-with-candidates report this duration through one helper. A long idle time with candidates means that GC is starved, for example by LSM compactions.
- LOG lines:
  - An ERROR for each corrupt input, with what the job found, also when other inputs of the job install. The file is skipped until it changes, the census is rebuilt or (for a relocation file) the coarse frontier rises.
  - An ERROR for an SST that cannot be opened, and an ERROR for a failed invariant check (see "Errors and suppression").
  - An INFO line with the skip reason of each skipped input, in two cases: the job installs (a corrupt input then gets only the ERROR line above), or the job ends with an OK status after it accepted no input. A job that fails, ends stale or is interrupted writes no reason lines; its corrupt inputs still get the ERROR line above.
  - One INFO line at the end of each job: "N candidates, R inputs read, M installed, S skipped, ...", then outputs, values relocated, bytes read and written, and the status. R counts the inputs that the job accepted: the inputs it read and packed, plus inputs with no live value that it only removes. M counts the inputs that the installed edit removed, so it is 0 unless the job installed.
  - An ERROR line when the census rebuilds for mismatch reports more than twice in a row and the next rebuild waits. The line names the wait in seconds and how many such waits came in a row.
  - An INFO line for each memory deferral of inputs to a later job.
  - The WARN line of a GC job error starts with "Indirect blob GC error" instead of "Compaction error".
  - DBImpl::DumpStats() logs a WARN for each column family whose idle time is longer than one stats dump period (stats_dump_period_sec). With stats dumps off, there is no such WARN.
- Listeners see the relocation files that GC writes with BlobFileCreationReason::kIndirectBlobGC.
- Feature off: only a GC job updates these tickers and the histogram, and GC runs only in a column family with a census. Without a census the idle time stays 0, and the DumpStats check skips the column family.

</details>

<details>
<summary>**Notable implementation details:** changes to base and shared code</summary>

Each of these pieces is needed by the GC job:
- Obsolete-file purge (db/db_impl/db_impl_files.cc) keeps a temp file whose number is protected by pending outputs, so a full purge during GC does not delete the temp output (see "Changes visible to existing users").
- SstFileManagerImpl (file/sst_file_manager_impl.{h,cc}) gets the byte-based EnoughRoomForCompaction() and OnCompactionCompletion(uint64_t) for GC, which has no CompactionInputFiles. Both EnoughRoomForCompaction() overloads share one body, EnoughRoomForCompactionLocked(), so the existing compaction check keeps its behavior.
- BlobFileCache (db/blob/blob_file_cache.{h,cc}) gets prefer_direct_reads for the direct reads of normal blob file inputs, and OpenRelocationFileReaderUncached(), which opens a relocation file reader without inserting it into the cache. GetRelocationFileReader() and the new function share one open body.
- BlobFileCompletionCallback::OnBlobFileAbandoned() (db/blob/blob_file_completion_callback.h) reports a failed creation for an output that did not complete its rename.
- ColumnFamilyData::IndirectBlobGcOptionsAllowJob() (db/column_family.h) holds the option checks for the idle time. DBImpl::SetOptions() clears the idle time when the new options do not let a GC job run.
- The WARN line of a background error from a GC job says "Indirect blob GC error" instead of "Compaction error". The docs of the base tickers BLOB_DB_GC_NUM_KEYS_RELOCATED, BLOB_DB_GC_BYTES_RELOCATED, BLOB_DB_GC_NUM_FILES and BLOB_DB_GC_NUM_NEW_FILES name indirect blob GC.
- db/table_cache.h makes DBImpl a friend, to get per-job SST readers outside the DB mutex. db/db_impl/db_impl_debug.cc adds TEST_RunIndirectBlobGCBatch() and test hooks for the job.
- db/blob/blob_relocation_gc.{h,cc} gets one overview for the job and the building blocks of diff 8 (terms, job shape, job steps, parts, suppression, corruption), and comments that name the job as the user of the building blocks.

</details>

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read the overview at the top of db/blob/blob_relocation_gc.h: background, terms, job shape, the invariant, job steps, the five parts (all from diff 8; three of them are in this file), suppression and corruption.
2. Census hooks: in db/blob/blob_reference_census.h read the census mismatch state table, ReportMismatch(), ClearMismatch() and TakeMismatchReport(), and the SnapshotSelected() charge comment. Then read the TakeMismatchReport() call in db/db_impl/db_impl_open.cc, the frontier retry in BlobGcCandidateHeap::SetCoarseIndirectOriginFrontier() (db/blob/blob_reference_census.cc), BlobGcCandidateHeap::CutSelection() and its call in PublishBlobReferenceCensusWorker() (db/db_impl/db_impl_open.cc), and GetCorruptFileReport(). They depend only on the census of diff 5.
3. Small support pieces (safe to skim): the byte-based EnoughRoomForCompaction() and OnCompactionCompletion(uint64_t) in file/sst_file_manager_impl.h, prefer_direct_reads and OpenRelocationFileReaderUncached() in db/blob/blob_file_cache.h, OnBlobFileAbandoned() in db/blob/blob_file_completion_callback.h, IndirectBlobGcOptionsAllowJob() and the idle time comment in db/column_family.h, and the options indirect_blob_gc_garbage_ratio and indirect_blob_gc_read_coalesce_bytes in include/rocksdb/advanced_options.h (with options/, db/c.cc, include/rocksdb/c.h and the generated c_api_gen/ files).
4. The entry: read the RunIndirectBlobGCBatch() comment in db/db_impl/db_impl.h (DB mutex, out parameters and return codes).
5. The job, part 1 (plan, read, decide): in db/db_impl/db_impl_compaction_flush.cc read the DBImpl::IndirectBlobGCJob class comment (job status, input outcomes, memory charges) and Run(). Then read Start(), SelectInputs(), PlanLiveSetReads(), ReadLiveSets() and DecideInputs().
6. The job, part 2 (pack, copy, install): read PackOutputs(), OpenInputReaders(), WriteOutputs() (with its error priority rule), then Install() with its "Install protocol" comment, the two functions that Install() calls (BuildEdit() builds the MANIFEST edit, and ValidatePhysicalInputs() is the precondition of its LogAndApply() call), invariant_failed(), and Finish().
7. Scheduling: read the GC branch and the retry code in BackgroundCompaction() (same file), and ColumnFamilyData::NeedsCompaction() in db/column_family.cc.
8. Last, read the purge rules in db/db_impl/db_impl_files.cc and the RepairDB guard in db/repair.cc.

## Terms used in this diff

The stack terms are defined in lower diffs: origin, original offset, stable identity, generation number, route, physical file, relocation file, exact reference metadata, indirect origin and blob file retirement in [Blob GC] 2/14; the file table (generation number -> live file or route) in [Blob GC] 4/14; census, coarse SST, holder and metadata-only commit (BeginMetadataCommit() / EndMetadataCommit()) in [Blob GC] 5/14; frontier and pin in [Blob GC] 7/14 (pin there is not the base RocksDB meaning).

The overview at the top of db/blob/blob_relocation_gc.h defines the terms of diff 8 (input, generation numbers of an input, output, live set, record bytes, stored CRC) and the job terms of this diff (stale job, input Version, candidate-local failure, deferred input, census entry, census snapshot, census heap, GC memory budget). The IndirectBlobGCJob class comment defines GC job registration and candidate stamp. Two more:

| Term | Meaning |
|---|---|
| suppress | Skip a file as a GC candidate, normally (until the file changes, the census rebuilds or, for a relocation file, the coarse frontier rises) or transiently (until a retry delay passes). The "Suppression" paragraph of the overview explains it; the IndirectBlobGCJob class comment lists every reason |
| queue head | The point where GC's MANIFEST edit is first in the MANIFEST writer queue, under the DB mutex. GC checks its inputs again there |

## Stack context

The goal, the read and lifecycle diagrams, the stack map and the terms for later diffs are in [Blob GC] 2/14, section Stack context. This diff is row 9 of the stack map: the indirect blob GC job (the "GC job" and "install" steps of the lifecycle diagram). Diff 10 adds flatten and route retirement.

Tracking issue: https://github.com/facebook/rocksdb/issues/15301

Differential Revision: D124855808
Summary:
Pull Request resolved: meta#15547

## Why the change is required

After diff 9, every indirect blob GC install leaves routes behind: each old generation number that SSTs still use keeps a route to the relocation file that holds its values. Without flatten, compaction keeps the old generation numbers, so a route stays as long as any SST holds its number. A route that no SST holds is deleted only when GC collects its target again. So the routes in the Version file table (and in the MANIFEST) keep growing, and every read of an old generation number takes the route hop. This diff lets compaction rewrite an old generation number to the relocation file that holds the value (flatten). Then route retirement, a step of the census job, deletes the routes that no SST uses any more. Both must stay correct while GC, flush and other compactions run at the same time.

## Previous behavior
Compaction kept the generation number of every indirect BlobIndex as it was. A route stayed in the MANIFEST for as long as its target file lived, even when no SST used its generation number. An indirect blob GC install routed only the live generation numbers of a relocation input to its output and deleted the routes of the others. Compaction-time blob GC rewrote an indirect value only when its generation number was below the age cutoff, with enable_blob_indirection on or off.

## New behavior
- Flatten: with enable_blob_indirection on, a local compaction that writes exact output rewrites each routed generation number to its route target. Coarse L0 output and remote compaction do not flatten.
- Compaction-time blob GC of indirect values: with the option on, exact output never rewrites an indirect value, so the value keeps its stable identity and indirect blob GC can collect it later. With the option off, compaction-time blob GC rewrites every indirect value it meets into a legacy blob file or an inline value, with no age cutoff, so reads stop depending on routes and relocation files over time. Coarse L0 output keeps the age cutoff in both cases. Cost: after the option is turned off, compactions with compaction-time blob GC on rewrite every indirect value they meet. Forced blob GC (blob_garbage_collection_force_threshold) cannot speed up this drain: it marks only the SSTs linked to the oldest normal blob file, and an SST whose indirect references are all flattened or routed links to no blob file. So the drain depends on ordinary compactions that reach those SSTs. The rewrite also reads indirect values without readahead, because the compaction prefetch buffers cover only normal blob files.
- Compaction safety: no compaction waits for GC or route retirement. Three checks make sure that every number an output writes can still be read at install; a failed check fails the compaction with Corruption. With paranoid_checks (the default), this Corruption is a background error, so the compaction does not run again. With paranoid_checks off, the column family can be picked again, as after any other compaction Corruption.
- Route retirement: after each census publish, the census job deletes, in batches, the routes that no SST holds, except routes that a running compaction or the running GC job may still need.
- GC install: a relocation input that gets an output keeps a route for all of its generation numbers, because a compaction may flatten to it while GC runs.
- Remote compaction: some compactions in a column family with blob indirection run locally instead of on a CompactionService.
- Monitoring: a new ticker and a new key of rocksdb.indirect-blob-gc-stats report route retirement.

## Implementation

### Flatten

- With the option on, when compaction writes an indirect BlobIndex whose generation number has a route in the compaction's input Version, it sets the generation number to the route target (BlobIndex::SetGenerationFileNumber()). Routes are one hop, so the target holds the value. The origin, the original offset and both CRCs do not change, and no value is read.
- The new generation number decides the encoding: equal to the origin writes kIndirectBlob, above the origin writes kIndirectFlattenedBlob, and below the origin is InvalidArgument.
- Plain values and wide-column blob columns are both flattened.
- Flatten checks every indirect value, so it has two fast paths. If the input Version has no route (checked once per subcompaction, at its first indirect value), it does no route lookup. Otherwise it remembers the last generation number and its route target, because consecutive keys usually share a generation number. The input Version is fixed for the whole compaction, so a remembered answer cannot go stale. Each skipped call is one Version file table lookup. Without the fast paths, these lookups were a visible part of compaction CPU in a profile. The fast paths were not profiled on their own.
- Coarse L0 output does not flatten. It keeps compaction-time blob GC (age cutoff). A coarse SST has no reference list, so the census could not see a flattened reference in it, and indirect blob GC could remove the relocation file it points to. The coarse frontier protects only unflattened references, whose generation number is an indirect origin.
- Remote compaction does not flatten (AllowBlobIndexFlattening() is false); diff 11 validates remote output.
- With the option off and compaction-time blob GC on, compaction rewrites the indirect values it meets into legacy blob files or inline values. In coarse L0 output (an L0 compaction that is not bottommost and has no exact input), it rewrites only values below the age cutoff. With compaction-time blob GC off, indirect values stay as they are and stay readable. The table in CompactionIterator::GarbageCollectBlobIfNeeded() lists which values compaction-time blob GC rewrites.
- For normal blob file liveness (oldest_blob_file_number), compaction output ignores flattened references and references whose generation number has a route. Neither keeps a normal blob file alive. This check runs once per output reference. To save CPU, it returns early when the generation number is at or above the output's current oldest_blob_file_number, because such a number cannot lower it, and it looks up a route only when the Version has routes.

### Compaction safety protocol
The overview comment "Compaction safety protocol for blob relocation" in db/compaction/compaction_job.h has the full argument. While a compaction runs, indirect blob GC and route retirement can change routes and remove files. The rules below make sure that every number an output writes can still be read at install.
- Why a kept number stays readable: the job's input SSTs hold the number, and they stay in the current Version until the job installs. So the census counts the number as held, and route retirement deletes only routes that no SST holds. GC never removes a route into a relocation input that gets an output (see "Indirect blob GC install and flattening").
- Why a flattened number stays readable: the running-compaction rule in route retirement. See "Route retirement" for why it is needed.
- Coarse L0 inputs have no reference list. Until the install, a coarse input is still in the current Version, and its coarse frontier pins every generation number at or above it: route retirement keeps those routes, and indirect blob GC does not select the indirect-origin blob files at or above the frontier. Coarse L0 output does not flatten.

The job runs three checks:
1. Input check, before the run (ValidateBlobRelocationInputGenerations()): for each indirect reference group of the exact inputs, it checks the generation number in the job's own input Version with Version::ValidateBlobReferenceGeneration(). The number must be a live indirect-origin blob file, a live relocation file, or a route to a live relocation file. The check follows the route, so one check per group covers both the kept and the flattened number. It uses the per-SST reference summaries that the job read at its start for the census (diff 5), and reads a summary only for an input that has none. If that read fails too, the check skips the input with a WARN line (see "Safety, compatibility and limitations"). An origin that an open with best_efforts_blob_db_repair dropped passes: the compaction turns its references into deletions (MissingBlobRepairIterator), so the output never writes it. Any other number that the input Version cannot read (for example, its blob file was lost and best_efforts_recovery left it out of the Version) fails the job with Corruption. With paranoid_checks (the default), this is a background error, and the job does not run again: a later run on the same input files cannot do better. A failed input check skips the subcompactions, but the job still ends like any other failed run (timing stats, I/O stats, job status, log flush).
2. Output dependencies, after the run (PrepareBlobRelocationOutputDependencies()): for each indirect reference group of each output SST, the job records the physical file that the number resolves to in the input Version, with that file's metadata object. An output number that resolves to no file, or to a normal blob file that is not an indirect origin, is Corruption. The one exception is a new indirect-origin blob file that this compaction wrote: it is not in the input Version yet. An indirect number resolves to a normal blob file only when that file is its indirect origin, so the second case shows a bad reference; the input check rejects it too, but it skips an input SST whose summary cannot be read. The memory is charged to the block cache (CacheEntryRole::kBlobReferenceMetadataBuildingBuffer). Groups of many outputs can name the same generation number, so the job resolves each generation number once, with a set that lives only during the call.
3. Install check (ValidateBlobRelocationOutputDependencies()): it runs in the LogAndApply() precondition, against the current Version, only when the output has a flattened reference or output dependencies. The precondition runs once, at the MANIFEST queue head, where the current Version cannot change. For a file whose metadata object changed since the input Version, it checks every number again. For an unchanged file, the file still exists, so it checks only the routed numbers: kept numbers whose route leads to that file, which stay readable only while the route exists. A flattening job has no routed numbers, so it pays nothing for this. If a number cannot be read, the install fails with Corruption (a background error with paranoid_checks, the default). This should never happen: the check guards the rules above, so that a future bug fails loudly instead of losing data.

Because the install passes a precondition, the compaction install is a batch barrier (diff 6): its precondition runs once at the MANIFEST queue head, its edit is applied under the DB mutex as in base, and it shares no MANIFEST write with other callers. The output dependencies come only from exact outputs, so in a column family with blob indirection this applies to most compaction installs (an estimate). Benchmark C1 (see "Performance") found no measurable cost from this.

### Route retirement
- The census keeps, per column family, the set of routed generation numbers that no SST holds (retirement_generations). It is rebuilt once at the end of each census build, and each delta keeps it up to date. Its memory is charged to the block cache. It normally has no more entries than the Version has routes. During a delta it can briefly hold a few more, so the charge uses the larger of the two counts.
- Route retirement runs only in the census job, after the census is published (DBImpl::BGWorkBlobReferenceCensus(), after DBImpl::BuildBlobReferenceCensus() returns). The apply step that a flush or compaction thread runs after its install does not run it, because a MANIFEST write can be slow and can fail. Route retirement runs after the census job releases the census run lock (worker_run_mutex()), so an apply after an install is not skipped while route retirement waits for its MANIFEST write. An install that lands after route retirement pinned its Version makes the precondition fail, and route retirement ends with TryAgain. If the census moves to a newer Version before the pin, route retirement uses that Version and checks every selected number again there. A route deletion installs a new Version, so the census job runs again to catch up.
- If an install publishes the census itself while the census job runs the column family, the job runs it once more (ColumnFamilyData::blob_reference_census_rerun_), so no retirement is missed.
- Before each census publish, the census worker selects up to 64 such generation numbers (SelectWorkerRetirementSources()). It skips generation numbers at or above the coarse frontier, and generation numbers whose route target is an input of the running indirect blob GC job. The coarse frontier skip is defense in depth: no known path gives a route to a number that a coarse SST holds, because indirect blob GC does not select an indirect origin at or above the frontier, and a coarse SST holds no routed or flattened number. The selection does not know the running compactions; route retirement checks them later. It starts after the last generation number it visited, so generation numbers that stay skipped do not starve the others.
- DBImpl::RetireBlobRelocationRoutes() pins the current Version and reads a census snapshot of the selected numbers without the DB mutex. Then, under the DB mutex, it keeps a generation number G only if no SST holds it in the snapshot, it is below the coarse frontier of the pinned Version (or there is none), it still has a route, its route target is not an input of the running GC job, and the running-compaction rule does not apply. The frontier check repeats the check of the selection, because the census worker can apply newer Versions between the selection and the snapshot read. It writes one MANIFEST edit with the route deletion records. Its comment in db_impl.h has the numbered steps.
- Why the running-compaction rule is needed: a compaction may write a number that no installed SST holds yet. In this example, the file numbers are examples only. Compaction C runs with an input Version that has route 12 -> 20, so its output SSTs say 20 (flattened). Then GC moves relocation file 20 into file 30 and writes route 20 -> 30. C has not installed, so no installed SST holds 20, and the census sees route 20 -> 30 as unused. If route retirement deleted it, C would install SSTs that name 20, and 20 would have no file and no route: those values could not be read. So route retirement skips route G -> X while G is a live blob file or relocation file in the input Version of a running compaction. When C installs, its SSTs become holders of 20; a later route retirement deletes the route only after no SST holds 20.
- A compaction picked after route retirement pinned its Version has that Version as its input Version (if the current Version changes, the precondition fails). There G is already a route, not a live file, and file numbers are never reused, so it cannot write G. A compaction stays in compactions_in_progress() until its output Version is installed, so the rule covers it until its SSTs are holders.
- The running-compaction rule costs one Version file table lookup per selected number and per running compaction whose input Version is not the pinned Version. Route retirement runs it twice per commit, both under the DB mutex: once when it filters the selected numbers (step 3 in db_impl.h), and once in the LogAndApply() precondition for the numbers it keeps for deletion. With at most 64 selected numbers, this is small (an estimate, not measured). The retirement edit is applied under the DB mutex; it holds at most one deletion per route of one batch.
- It skips a route whose target is an input of the running GC job. BeginGcJob() records the job's candidate files, and IsGcInputFile() checks them. The GC install checks the route count of each relocation input as an invariant, so a route deletion would fail that check (an assert in debug builds, a stale job in release builds). When the input gets an output, the GC edit re-points such a route to the output, and a later route retirement deletes it if it is still unheld. When the input gets no output, the GC edit deletes the route (see "Indirect blob GC install and flattening").
- Batching: route retirement writes an edit only when one call can delete a full selection of 64 routes (kBlobRouteRetirementBatchSize), when it selected 64 numbers and can delete at least 32 of them (for example, running compactions hold the others), or when routes have waited 10 minutes (kBlobRouteRetirementMaxPendingMicros, checked when the census job runs). 64, 32 and 10 minutes are fixed choices, not measured. The half-batch case keeps route retirement going while a long compaction holds a few numbers of each selection; it costs at most twice the MANIFEST writes of full batches. Batching is only a cost choice; skipping routes that a running compaction may write is a correctness rule. A pending route costs only Version memory and space in a new MANIFEST snapshot: when no SST uses a relocation file, indirect blob GC removes it as an empty input, and that edit deletes the routes into it. A deferred call still reads the census snapshot, because the number of routes to delete is known only after that read. Pending routes are not written at close; the next census build finds them again after reopen. When no route can be deleted, the pending time is reset, unless running compactions hold some of the selected numbers: those routes still wait.
- The edit is a metadata commit: the LogAndApply() precondition calls BeginMetadataCommit(). Before that, the precondition returns TryAgain if the current Version is not the pinned Version, if the census changed, if a route target became a GC input, or if the running-compaction rule now applies to a number that it keeps for deletion. With TryAgain, route retirement writes nothing, and the next census publish tries again. If no pending time is set yet (a full batch), route retirement sets it, so retirement-pending-micros shows routes that keep getting TryAgain.
- Route retirement is optional cleanup. When it fails (for example, background work is stopped), the census stays ready and the next publish tries again. A Corruption of the route retirement MANIFEST write (from VersionBuilder) means that a check of the protocol failed. It is not a census mismatch, so the census also stays ready. Route retirement logs it and sets a background error with the compaction reason, so it follows paranoid_checks: with paranoid_checks (the default), it stops writes and background work until the DB is reopened; without it, the next publish tries again. Only a shutdown, a dropped column family and a Corruption of the census snapshot read stop the census; the last means that the census itself is broken, so it is rebuilt.

### Unknown MANIFEST result of a metadata commit

- When the MANIFEST write of route retirement fails with an I/O error, the edit may or may not be on disk. Route retirement sets a background error (kManifestWrite), so MANIFEST recovery decides the result. The failed edit is not applied to the in-memory Version, so the route stays.
- Until a new MANIFEST file with the full state is written (by Resume(), or by the next MANIFEST write), BeginGcJob() returns Busy, so no indirect blob GC job starts, and a new metadata commit gets TryAgain. A GC install with an unknown result causes the same state.
- Compactions never wait for the commit result itself. The background error that route retirement sets stops background work, as after any failed MANIFEST write, until Resume() or automatic recovery writes a new MANIFEST. No compaction runs again because of the unknown result: both possible results keep every number that a running compaction may write. After a failed MANIFEST write, VersionSet::ProcessManifestWrites() drops the new Versions of the batch and resets the MANIFEST log, so the next write starts a new MANIFEST from the in-memory state, which does not hold the failed edit.

### Indirect blob GC install and flattening

- Rule: in the GC edit, a relocation input that gets an output routes every generation number to that output, held or not. This includes the input's own file number and every number routed to it (keeps_all_generations in DBImpl::IndirectBlobGCJob::BuildEdit()). An input without an output still loses its unheld routes, and a normal input still keeps only its live generation numbers.
- Why: the GC job takes its census snapshot at its input Version and does not follow later Version changes (diff 9). Most changes add no holder of an input's generation number. Flattening can: a compaction rewrites a reference to the route target in its own input Version, which can be older than the GC job's input Version. For example (the file numbers are examples only), compaction C is picked while route 10 -> 400 exists. An earlier GC job then moves file 400 into file 500, and a new GC job starts on file 500. No SST holds 400, so the census snapshot of the new job shows 400 without a holder. C then rewrites generation number 10 to 400 and installs. Without the rule, the new GC edit would delete route 400 -> 500 and the value would become unreadable. With the rule, it writes route 400 -> output.
- Cost: the edit can keep routes that no SST holds. Route retirement deletes them later.
- An input without an output had no holder of any of its generation numbers in the snapshot. A compaction that flattens to one of them holds a generation number that routes to the same input, and the snapshot counts that holder. So nothing can flatten to such an input.
- The "Install protocol" comment in DBImpl::IndirectBlobGCJob::Install() has the full argument.

### Remote compaction rules

With a CompactionService, a feature-aware compaction (its input Version has the indirection format, or it runs with the option on) runs locally in these cases:
1. The input Version has the indirection format, the option is off and compaction-time blob GC is on. The compaction rewrites indirect values. It runs locally as a conservative choice, because remote workers have not been validated for this rewrite.
2. The job overrides enable_blob_garbage_collection or blob_garbage_collection_age_cutoff. The current CompactionService protocol rebuilds these options from the options file.
3. The job has several subcompactions, or it is the first activation compaction (its input Version does not have the indirection format yet). Feature-aware output must be accepted or rejected as a whole, and CompactionService runs each remote subcompaction as a separate job.

### Garbage meter

- BlobGarbageMeter skips flattened references (generation number != origin). The census tracks the live bytes of the relocation file they point to. Unflattened references still count toward legacy garbage.

## Monitoring

- New key retirement-pending-micros of rocksdb.indirect-blob-gc-stats: how long routes that route retirement can delete have waited for a batch (see "Batching" under "Route retirement"), 0 when no route waits. A written batch, or a call that can delete no route, resets it. A full batch whose MANIFEST write gets TryAgain starts it, so the key also shows a full batch that keeps getting TryAgain.
- BLOB_RELOCATION_ROUTES_RETIRED (ticker) counts the routes that route retirement removed.
- Route retirement runs in the census job, so PauseBackgroundWork() stops it too, and ContinueBackgroundWork() starts it again.
- Feature off: only a column family with a census has routes to retire, so the key is 0 and the ticker does not change.

## Also in this diff

These are CPU and plumbing changes on the compaction and flush paths that flatten needs:
- db/compaction/compaction_outputs.cc: CompactionOutputs::AddToOutput() reuses the BlobIndex decode that the compaction iterator made in FlattenBlobIfNeeded() (CompactionIterator::OutputBlobIndex()), so it does not decode the value again. With the shared decode and the on-demand stored CRC of diff 2, this lowers the extra compaction CPU of the option (see B3 in "Performance").
- CompactionOutputs and CompactionIterator each read once, when they are created, whether the input Version has the blob indirection format (input_has_blob_indirection_format_). FlattenBlobIfNeeded() runs only with it, and AddToOutput() uses the route-aware UpdateBoundaries() overload (db/version_edit.{h,cc}) only with it. So a compaction without the format skips the flatten and route-aware paths. The route-aware overload calls a separate out-of-line function (UpdateFileMetaDataBoundariesWithRoutes()), and the plain overload keeps its code from the earlier diffs, so the per-key code of compaction without the format and of flush does not grow.
- db/builder.cc: BuildTable() (flush, WAL recovery, RepairDB) passes allow_blob_index_flattening = false. db/flush_job.cc: MemPurge() passes allow_blob_index_flattening = false.
- db/compaction/subcompaction_state.h: has_flattened_blob_index tells InstallCompactionResults() that the output has a flattened reference.
- db/db_impl/db_impl_compaction_flush.cc: BeginGcJob() is called under the DB mutex with the job's candidate files, so a route retirement that has not reached the MANIFEST queue head sees them in its precondition. BackgroundCompaction() has a debug-only sync point after the compaction run, for tests.
- Comment updates: step 7 of "Lifecycle of one value" in db/blob/blob_relocation_manifest.h, the list of routes that the install edit writes in db/blob/blob_relocation_gc.h, and the note in db/blob/blob_reference_metadata.h that route retirement skips route sources at or above the coarse frontier.

## Safety, compatibility and limitations

- Option gate: at this diff, ColumnFamilyData::ValidateOptions rejects enable_blob_indirection outside tests (diff 2 adds the gate, diff 14 removes it). The behavior described here with the option on is reachable only through the internal test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production.
- Persisted data:
  - SSTs: compaction writes flattened references (kIndirectFlattenedBlob). Diff 2 defines this encoding, and every reader of the stack since diff 2 decodes it. Existing SSTs keep their unflattened references, which stay readable through routes.
  - MANIFEST: route retirement writes the route deletion record of diff 4. Diff 4 states its compatibility: it is a required tag, so an older binary fails to open the DB instead of misreading it.
- Public API: new ticker BLOB_RELOCATION_ROUTES_RETIRED, added after the base tickers with the other tickers of this stack, so the values of the tickers after it change. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used. New key retirement-pending-micros of rocksdb.indirect-blob-gc-stats.
- Block cache charge: a compaction charges its output dependency lists to CacheEntryRole::kBlobReferenceMetadataBuildingBuffer (documented in include/rocksdb/table.h). If the charge fails because the block cache is full (strict_capacity_limit), the compaction goes on with the lists uncharged and logs one WARN line with the number of failed charges. It sets no background error. Route retirement charges its census snapshot the same way: when the cache is full, the snapshot stays uncharged, the census counts it (census-uncharged-charges, one WARN line per census build), and retirement still deletes the routes, because a cache that stays full must not stop routes and relocation files from being freed.
- An indirect blob GC job cannot start while route retirement writes its MANIFEST edit: route retirement holds a metadata commit, and BeginGcJob() returns TryAgain during it. Route retirement also checks the GC inputs again at the MANIFEST queue head, so a GC job that registers later and takes a route target as input makes route retirement end with TryAgain.
- Generation numbers at or above the coarse frontier keep their routes, including the file numbers of old relocation files, which a coarse SST can never hold. Such routes wait until the frontier moves past them. This only delays route retirement.
- A route whose number is a live file in the input Version of a running compaction waits until that compaction ends. A long compaction only delays route retirement.
- The install check and the input check fail the compaction with Corruption; there is no internal retry. With paranoid_checks (the default), the Corruption is a background error and stops writes and background work until the DB is reopened. With paranoid_checks off, the column family can be picked again, and a failed install check repeats the whole compaction each time, as for any other compaction Corruption. The input check fails when a number is already unreadable in the job's own input Version; an origin that best_efforts_blob_db_repair dropped is not unreadable, and the compaction turns its references into deletions. The install check guards the protocol invariants and should never fail.
- An input SST whose reference summary cannot be read (for example, a corrupt reference metadata block) does not block its compaction: the input check skips it with a WARN line, as the read at job start does, because compacting that SST is the way to repair it. The skip gives up the input check for that SST. The output dependency check still fails the job when an output number resolves to no file or to a normal blob file that is not an indirect origin. A number that resolves to a relocation file marked lost passes; this loses no value, because such a value cannot be read before the compaction either.
- A coarse, unknown or unready state never proves that a generation number is unused. The census includes keys hidden by newer versions and wide-column blob references.
- Route retirement checks the 10-minute wait only when the census job runs. The census job runs only when something queues it: a SuperVersion install (for example after a flush, a compaction, a GC install or a route retirement), DB open, ContinueBackgroundWork(), the end of a GC job, a rebuild after a census mismatch, a census wakeup when a pending install ends, or the periodic census task for a column family on the census retry list. So in an idle column family, waiting routes usually stay until the next install. They cost only Version memory and space in a new MANIFEST snapshot, because indirect blob GC still removes a relocation file that no SST uses.
- Not supported: routes are flattened only when a compaction rewrites an SST for another reason, so a cold SST can keep routes alive for a long time (Version memory, MANIFEST snapshot size, one route lookup per read). No compaction is scheduled to flatten routes. Remote compaction does not flatten.

## Performance

Benchmark F: compaction cost with the feature off. It compares release builds of base, of this diff, and of the whole stack (diff 14).
- Configurations: base, and the stack with enable_blob_indirection off and no format fence. Blob GC is off.
- Workloads: (1) fillrandom of 5M keys of 16 bytes with 4 KB values in blob files (min_blob_size 512), then one full manual compaction, so every key in the compaction is a blob index (the B3 workload below); (2) the same steps with 100-byte values, no blob files and LZ4 compression.
- Method: six runs per build in rotating order, a fresh DB per run, on one shared host with 192 cores (AMD EPYC Genoa). Each step is pinned to 32 cores and starts only when the load average is below 20. CPU is the user plus system time of the db_bench process that opens the DB and runs the full compaction. perf stat counts the instructions of that process. Medians, with ranges.
- Why fixed alignment: in plain release builds, the compaction CPU moves by about ±10% with code layout alone. For example, on workload 1 a plain build of diff 9 used 12.5% less compaction CPU than base, while plain builds of this diff used 3.3% to 9.3% more. All of them run about the same number of instructions (13.0 to 13.2 G), and the builds that used more CPU had more instruction cache misses. So plain builds cannot isolate a difference of a few percent. The main result uses the same alignment flags in all builds (-falign-functions=64 -falign-loops=32 -falign-jumps=32; 64 bytes is the cache line size, and 32 bytes is half of it, a common alignment for loop and jump targets), so that function and loop placement does not decide the result.
- Result: no measurable compaction cost with the feature off. All CPU differences are inside the run-to-run range. On workload 1, this diff and the stack run about 4% fewer instructions than base. On workload 2, they run about 1.5% more instructions than base (20.9 against 20.6 G).

| Workload | Build | Compaction CPU (s) | vs base | Instructions |
|---|---|---|---|---|
| 1 (4 KB values in blob files) | base | 1.165 (1.13-1.20) | | 13.8 G |
| | this diff | 1.150 (1.14-1.18) | -1.3% | 13.2 G |
| | whole stack | 1.190 (1.15-1.21) | +2.1% | 13.2 G |
| 2 (100-byte values, no blob files) | base | 2.260 (2.19-2.46) | | 20.6 G |
| | this diff | 2.235 (2.13-2.41) | -1.1% | 20.9 G |
| | whole stack | 2.250 (2.19-2.39) | -0.4% | 20.9 G |

- Plain builds (without the alignment flags) of this diff: on workload 1, two plain builds with the same compaction code used 3.3% and 9.3% more CPU than base (1.240 s (1.21-1.26) against 1.200 s (1.18-1.29), and 1.295 s (1.28-1.33) against 1.185 s (1.16-1.22)). They ran fewer instructions than base (13.1-13.2 G against 13.8-13.9 G), but had more instruction cache misses, so the difference comes from code layout. On workload 2, a plain build used 2.305 s (2.29-2.37) against 2.215 s (2.15-2.32) (+4.1%; the ranges overlap).

Benchmark B3: compaction cost of enable_blob_indirection (db_bench, release builds).
- Builds: three earlier builds of the stack, each with more CPU changes. The latest of them has the route lookup fast path of this diff, the shared decode and lazy stored CRC of diff 2, the stored CRC skip of the reference collector, and the reuse of the flatten decode. It does not have two CPU changes of this diff: the early return in the liveness check, and resolving each generation number once for the output dependencies.
- Configurations: A is the stack with the option off, B with it on. Blob GC is off in both.
- Workload: fillrandom of 5M keys of 16 bytes (about 3.2M unique) with 4 KB values in blob files, then one full manual compaction.
- Method: three runs per configuration, a fresh DB per run, on one shared host with 192 cores (each step pinned to 32 cores). Medians.
- Results on the latest of the three builds:
  - Compaction time 1.78 s (1.70-1.82) against 1.12 s (1.11-1.16) (1.59x; the ranges do not overlap), and CPU 1.78 s against 1.13 s (1.58x). The extra CPU is 0.65 s. A build without these CPU changes used 0.87 s of extra CPU (1.71x time), and a build with only the first three used 0.70 s. The last step is small: the CPU ranges of the two builds touch, and A was also 3% faster in the same runs, so part of it may be host noise.
  - SST bytes 70.6 MB against 37.3 MB (1.89x): 22.3 against 11.8 bytes per stored entry. About 55% of the extra bytes come from the larger BlobIndex and about 45% from the exact reference metadata (measured on the build without the CPU changes; they do not change the SST bytes).
- Limits and tradeoffs:
  - The whole LSM is only 37 to 300 MB, because the values are in blob files. So these numbers are the SST-side cost only, with no blob I/O.
  - On the build without the CPU changes, a larger setup (20M keys of 16 bytes, 1 KB values) gave 2.76x time, 2.75x CPU and 1.98x SST bytes. With the option on, the LSM had two levels instead of one, so the full compaction read about 21.1M input keys against 12.7M.
  - Peak memory of the compaction process on the latest build: 48 MB against 41 MB.
  - On the build without the CPU changes, fillrandom, with its flushes and automatic compactions, was not slower (within about 1%) and used 6% (5M setup) and 8% (20M setup) more CPU.

Benchmark C1: cost of the compaction install precondition (db_bench, release builds).
- Builds: an earlier build of the stack, against the same build with a benchmark-only change that lets compaction installs join MANIFEST group commit.
- Workload: the B2 workload of diff 9 (5M keys of 16 bytes, 4 KB values in blob files, enable_blob_indirection and enable_blob_garbage_collection on, blob_garbage_collection_age_cutoff 0.25, 16 background jobs; fillrandom, then three rounds of 2.5M overwrites).
- Method: three runs each, interleaved, on the same host.
- Result: no measurable difference. Overwrite throughput, P99 write latency and write stall time are inside the run-to-run range, which is about 20% on this busy host. MANIFEST syncs were 1,108 against 1,110, with a total sync time of 436 ms in both. MANIFEST writes are rare in this workload (about 10 per second), so a compaction install seldom has another writer to group with. A workload with many more MANIFEST writes was not measured.

## Validation and known limitations

Unit tests cover flatten of plain and wide-column references, re-GC of flattened files, the three compaction checks (with injected failures), the unknown MANIFEST result, route retirement with running compactions, GC jobs and column family drops, its timing and selection, and the monitoring signals. See the Test Plan.

Known limitations:
- The compaction iterator unit tests (compaction_iterator_test) do not test flatten directly; flatten is tested through DB tests.
- This diff has no db_stress coverage; diff 14 adds it.
- Untested paths and the test environment: see the Test Plan.

## How to read this diff

1. Read "Terms used in this diff" below, then the summary sections "Flatten", "Compaction safety protocol", "Route retirement" and "Indirect blob GC install and flattening". For background, read steps 4 to 7 of "Lifecycle of one value" at the top of db/blob/blob_relocation_manifest.h (step 6 is flatten, step 7 is route deletion). This diff changes only step 7, to say that route retirement in the census job writes the route deletion record.
2. Read flatten. First read BlobIndex::SetGenerationFileNumber() in db/blob/blob_index.h. It depends on nothing else in this diff. It rewrites the generation number and picks the encoding. Then read the comment on FlattenBlobIndexIfNeeded() in db/compaction/compaction_iterator.h, and FlattenBlobIndexIfNeeded(), FlattenBlobIfNeeded(), FlattenBlobIndexesIfNeeded(), FlattenEntityBlobIndexesIfNeeded() and PrepareOutput() in compaction_iterator.cc, and the rewrite table in GarbageCollectBlobIfNeeded().
3. Read Version::ValidateBlobReferenceGeneration() in db/version_set.{h,cc}. Then read the overview "Compaction safety protocol for blob relocation" in db/compaction/compaction_job.h. Then read its three checks in compaction_job.cc: ValidateBlobRelocationInputGenerations(), PrepareBlobRelocationOutputDependencies() with BlobOutputDependency in compaction_job.h, and ValidateBlobRelocationOutputDependencies() with the relocation_state_precondition lambda in CompactionJob::InstallCompactionResults().
4. Read the census retirement set in db/blob/blob_reference_census.{h,cc}: retirement_generations, its rebuild in WorkerState::Finalize(), the delta updates (MarkRetirementIfRouted()) and SelectWorkerRetirementSources(). Also read BeginGcJob(version_number, candidate_files, token) and IsGcInputFile().
5. Read the comment on DBImpl::RetireBlobRelocationRoutes() in db/db_impl/db_impl.h, then its body in db/db_impl/db_impl_compaction_flush.cc (held_by_running_compaction is the running-compaction rule), and its caller after the census publish in DBImpl::BGWorkBlobReferenceCensus() (db/db_impl/db_impl_open.cc).
6. Read the GC install change in db/db_impl/db_impl_compaction_flush.cc: keeps_all_generations and the route loop in DBImpl::IndirectBlobGCJob::BuildEdit(), then the "Install protocol" comment, which explains with an example why a relocation input that gets an output keeps all of its routes.
7. Last, read the side changes: the remote compaction rules in CompactionJob::ShouldUseLocalCompaction() (compaction_job.cc), the UpdateBoundaries() overloads in db/version_edit.cc, and BlobGarbageMeter.

## Terms used in this diff

The stack terms are defined in lower diffs: origin, original offset, stable identity, generation number, unflattened reference, route, physical file, indirect origin, relocation file, stored CRC, logical CRC, exact reference metadata, blob file retirement, route deletion and reference group in [Blob GC] 2/14; the Version file table in [Blob GC] 4/14; coarse SST, census, census job and holder in [Blob GC] 5/14; the coarse frontier in [Blob GC] 7/14. "The option" is enable_blob_indirection.

Terms of this diff:

| Term | Meaning |
|---|---|
| flatten | Compaction rewrites the generation number of a reference to the route target, the relocation file that holds the value. Only flatten makes generation number != origin |
| flattened reference | Index with generation number != origin |
| kept number / flattened number | For one indirect reference group, the output writes the group's generation number (kept), its route target in the compaction's input Version (flattened), or neither (compaction-time blob GC rewrites the value) |
| coarse L0 output | L0 compaction output without exact reference metadata. It does not flatten |
| output dependency | One physical file (a normal blob file or a relocation file) that an output number resolves to in the compaction's input Version, with the file's metadata object (BlobOutputDependency) |
| install check | The check of the output dependencies against the current Version, in the LogAndApply() precondition of the compaction install (CompactionJob::ValidateBlobRelocationOutputDependencies()) |
| route retirement | DBImpl::RetireBlobRelocationRoutes(). The census job runs it after each census publish. It writes route deletion records in batches |
| running-compaction rule | Route retirement does not delete the route of a generation number while that number is a live blob file or relocation file in the input Version of a running compaction of the column family (a compaction in CompactionPicker::compactions_in_progress()) |
| census publish | The step where the census job makes a new census ready for readers |
| metadata commit | A MANIFEST write that changes only relocation metadata, between BeginMetadataCommit() and EndMetadataCommit() (diff 5): route retirement (this diff) or an indirect blob GC install (diff 9). At most one runs per column family. While one runs, a new GC job registration (BeginGcJob()) gets TryAgain. A GC install registered its job before its commit, so it does not block itself. db/blob/blob_reference_census.h also calls it a "metadata-only commit" |
| unknown commit result | A metadata commit whose MANIFEST write failed with an I/O error. The edit may or may not be on disk (EndMetadataCommit(false)) |
| feature-aware compaction | A compaction whose input Version has the indirection format, or that runs with the option on |

## Stack context

The goal, the read and lifecycle diagrams, the stack map and the terms for later diffs are in [Blob GC] 2/14, section Stack context. This diff is row 10 of the stack map: flatten generation numbers and route retirement (the "flatten" and "route delete" steps of the lifecycle diagram). It also adds one rule to the "install" step: a relocation input that gets an output keeps a route for all of its generation numbers.

Tracking issue: meta#15301

Differential Revision: D124905374
Summary:
Pull Request resolved: meta#15548

## Background

With CompactionService, a remote worker runs the compaction and the primary installs its output. Before the primary installs output of a column family that uses blob indirection, it must know that the worker used the same stable identities, the same routes, the same metadata layout and the same output placement rules. Otherwise the primary could install SSTs whose blob references it cannot read.

## Overview

This diff adds a contract between the primary and the remote worker for compactions of a column family that uses blob indirection (feature-aware jobs). The primary sends three values: a protocol version, a hash of the options and format versions that change what the worker writes, and a hash of the relocation files and routes of the job's input Version. The worker runs the job only when its own values match and its Version has the format fence, and it never creates blob files. When it declines, it says which check failed, and the primary logs and counts the decline. The primary checks the result before it imports the output SSTs, and checks each SST again after the import: it reads and checks all of the SST's exact reference metadata, and it accepts only generation numbers that the job's inputs hold or route to. When any check fails, the primary runs the job locally. Compactions of other column families (legacy jobs) keep the existing remote BlobDB protocol, with one new check: the primary declines a legacy result that holds blob indirection metadata.

## How to read this diff

1. Read "Terms used in this diff". Then read "New behavior", which starts with a diagram of the remote flow, then "Implementation: why the worker can run the job safely", and "Safety, compatibility and limitations".
2. Read Version::ValidateBlobReferenceGroup() in db/version_set.h and db/version_set.cc. It depends on nothing else in this diff.
3. Read TableReader::VerifyBlobReferenceMetadata() in table/table_reader.h, then its implementation in table/block_based/block_based_table_reader.cc, and the call in BlockBasedTable::VerifyChecksum() in the same file. It also depends on nothing else in this diff.
4. Read the comment at the new CompactionServiceInput fields in db/compaction/compaction_job.h, then ComputeBlobIndirectionCompactionServiceOptionsFingerprint() in db/compaction/compaction_service_job.cc.
5. Read the worker: the contract check in DBImplSecondary::CompactWithoutInstallation() (db/db_impl/db_impl_secondary.cc), the TryAgain branch at the end of that function, then AllowBlobFileCreation() and AllowBlobIndexFlattening() of CompactionServiceCompactionJob (db/compaction/compaction_job.h). Then read the decline check: CompactionIterator::SetSstOnlyBlobOutputPolicy() and DeclineSstOnlyBlobOutput() (db/compaction/compaction_iterator.{h,cc}), and the call in CompactionJob::CreateCompactionIterator() (db/compaction/compaction_job.cc).
6. Read ValidateBlobIndirectionCompactionServiceResult() in db/compaction/compaction_service_job.cc.
7. Read the per-file check: the friend change in db/table_cache.h, the comment at ValidateRemoteExactBlobMetadata() in db/compaction/compaction_job.h, then PrepareRemoteAllowedBlobGenerations() and ValidateRemoteExactBlobMetadata() in db/compaction/compaction_service_job.cc. The safety comment above ValidateBlobRelocationInputGenerations() in compaction_job.h (diff 10) explains the running-compaction rule that the allowed generation numbers rely on.
8. Read CompactionJob::ProcessKeyValueCompactionWithCompactionService() in this order: the feature_aware_compaction flag and the coarse-output local path, the TryAgain branch (where the primary logs and counts a worker decline), the call to step 6, the garbage filter, the per-file check in the import loop and fall_back_after_validation, and the COMPACTION_OUTPUT_BLOB_REFERENCES record after the import. Last, read the tests in db/compaction/compaction_service_test.cc. Each test name says which path it covers.

## Terms used in this diff

This diff uses these terms unchanged from lower diffs: the stack terms of [Blob GC] 2/14 (origin, original offset, stable identity, generation number, unflattened and flattened reference, flatten, route, physical file, indirect origin, relocation file, exact reference metadata, reference group, census, blob file retirement, route deletion, option gate), the format fence (diff 4), the legacy marker (diff 5), the coarse SST and its frontier (diff 7), the Version file table (diff 4), and the install check and the running-compaction rule (diff 10). "The option" is enable_blob_indirection.

Other terms used here ("route target" is the "target" of [Blob GC] 4/14):

| Term | Meaning |
|---|---|
| name | In code and comments, the generation number of a reference (its key in the Version file table) |

Terms of this diff:

| Term | Meaning |
|---|---|
| feature-aware job | A compaction whose column family has the per-CF format fence (VersionStorageInfo::HasBlobIndirectionFormat()) or has the option on (the "feature-aware compaction" of diff 10). Its remote run uses the contract of this diff |
| legacy job | Any other compaction. It uses the existing remote BlobDB protocol |
| contract values | The three values that a feature-aware request carries: the protocol version, the options fingerprint and the relocation state fingerprint |
| options fingerprint | A 64-bit hash (ComputeBlobIndirectionCompactionServiceOptionsFingerprint()) of the options and format versions that change what the worker writes and that the request does not carry. The comment at the CompactionServiceInput fields lists them |
| relocation state fingerprint | A 128-bit hash of the relocation files, routes and format version of a Version (VersionStorageInfo::ComputeBlobRelocationStateFingerprint()). The descriptor fields route_snapshot_fingerprint_high and _low hold the same value |
| SST-only output policy | A compaction that may not create blob files ends with TryAgain when a value needs blob-file output (CompactionIterator::DeclineSstOnlyBlobOutput()). This diff adds the check (with the virtual CompactionJob::AllowBlobFileCreation(), true in the base class) and turns it on for feature-aware workers |
| decline | The worker or the primary refuses a remote attempt, and the primary runs the job locally (kUseLocal). The worker always declines with TryAgain inside an OK result. The message of the TryAgain says why |
| feature metadata | An exact descriptor or a coarse classification property on an output SST, or an indirect-origin blob file |
| per-file check | The checks that the primary runs on each output SST after it imports the SST (ValidateRemoteExactBlobMetadata()) |
| allowed generation numbers | The generation numbers of the indirect reference groups of the job's exact inputs, plus the route target of each of them in the input Version (CompactionJob::remote_allowed_blob_generations_). See "Allowed generation numbers" below |
| kFailure | The CompactionServiceJobStatus that marks the compaction as failed. The primary does not run the job locally, and the error goes to the normal compaction error path |

## Previous behavior

CompactionService had no versioned contract for blob indirection. Diff 10 keeps some feature-aware jobs local (see "Which jobs"). Every other feature-aware job went to the worker through the base protocol. The worker did not flatten, and it could return output without the exact reference metadata that the primary needs, or with generation numbers that the primary never checked. Legacy remote compaction already supports BlobDB: the primary imports the worker's blob file output, blob garbage and oldest_blob_file_number, and it removes imported files again when the install fails. The primary already declines a result that reports garbage for a blob file that is not in the input Version (for example, a blob file that GC already collected).

## New behavior

### Flow

```
  primary picks a compaction
    |
    +-- legacy job ----------------> existing remote BlobDB protocol; the
    |                                primary declines a result with feature
    |                                metadata -> run locally
  feature-aware job
    |
  local-only case (see Which jobs)
  or coarse output? ----------------- yes --> run locally
    | no
  request with the contract values
    |
  worker: contract checks pass? ------ no ---> TryAgain in OK result,
    | yes                                      names the failed check
    |                                          -> log, count, run locally
  worker: SST-only run; new blob
  file output needed? --------------- yes --> TryAgain in OK result
    | no                                       -> log, count, run locally
  primary: check before the import --- fail -> run locally
    |
  primary: drop garbage of files that have no garbage counters
    |
  primary: import each SST, then
  the per-file check ---------------- fail -> delete the imported files,
    |                                         run locally
  install (MANIFEST write)
```

Every failed contract or output check runs the job locally. Other import errors (for example a failed rename) keep their existing kFailure handling.

### Which jobs

- A job is feature-aware when its column family has the per-CF format fence or has the option on. Legacy jobs use the existing remote BlobDB protocol unchanged, except for the feature metadata check below.
- A feature-aware job whose output would be coarse (output level 0, the compaction is not bottommost, and no input has exact metadata; for example an intra-L0 compaction above older overlapping data, or a universal compaction that writes to level 0 and is not bottommost) runs locally from the start. The primary accepts only exact feature output, so a worker would do the work for nothing.
- CompactionJob::ShouldUseLocalCompaction() (diff 10) also keeps these feature-aware jobs local:
  - The first activation compaction. Its input Version has no format fence yet, and the worker requires one.
  - A job with a manual override of enable_blob_garbage_collection (the worker rebuilds it from the OPTIONS file) or of blob_garbage_collection_age_cutoff (kept local as a conservative choice; the worker uses the primary's cutoff file number).
  - A job with several subcompactions. Feature-aware output must be accepted or rejected as a whole, and CompactionService runs each remote subcompaction as a separate job.
  - A job with the option off and blob GC on, in a CF with the format fence. It rewrites indirect values into legacy blob files or inline values. It runs locally as a conservative choice, because remote workers have not been validated for this rewrite.

### Request

- A feature-aware request carries the three contract values: the protocol version (kBlobIndirectionCompactionServiceProtocolVersion, value 1), the options fingerprint, and the relocation state fingerprint of the input Version.
- The options fingerprint covers the values that change what the worker writes and that the request does not carry: the protocol version, the column family ID, enable_blob_indirection (which is also the flattening permission), enable_blob_garbage_collection, enable_blob_files, min_blob_size and blob_file_starting_level (they decide whether a value needs blob output, and so whether the worker declines or writes the value inline), and the format versions of the BlobIndex, the reference metadata, the MANIFEST records and the relocation directory. It does not cover blob_garbage_collection_age_cutoff, because the worker uses the cutoff file number that the primary sends. It does not cover the blob file format, because a feature-aware worker creates no blob files. The comment at the CompactionServiceInput fields in compaction_job.h has the same list.
- The worker declines the job when the protocol version differs, when its Version has no per-CF format fence, when its options fingerprint differs, or when its relocation state fingerprint differs. It returns OK with TryAgain in its result, and the TryAgain message names the failed check (for example "relocation state fingerprint differs"). The result has no output, so the primary runs the job locally before it imports anything.

### Worker

- A feature-aware worker never creates blob files (CompactionServiceCompactionJob::AllowBlobFileCreation() is false), so the primary reserves no blob file numbers for it. This turns on the SST-only output policy. When a value, a merge result or legacy blob GC needs new blob output, the worker declines the whole attempt. It returns OK with TryAgain in its result, so a CompactionService that maps a failed worker call to kFailure still forwards the decline, and no background error is set. SST-only output is accepted when no new blob output is needed. A compaction without the policy and without a blob file builder runs the same per-key tests as base RocksDB: CompactionIterator tests one precomputed bool (check_large_values_, true when there is a builder or the policy is set) in place of the builder pointer, and only cold functions check the policy. With a builder, the iterator tests the builder pointer once more per value (once per entity for wide columns) before it adds the value to the blob file, and the column loop has no policy check.
- The worker flattens when its options allow it (CompactionServiceCompactionJob::AllowBlobIndexFlattening()). The result returns the worker's protocol version and whether it flattened references (has_flattened_blob_index).
- Resumable compaction progress is off for feature-aware jobs, because the progress format does not store the contract.

### Check before the import

ValidateBlobIndirectionCompactionServiceResult() runs before any output is imported.
- A legacy job whose worker returns feature metadata is declined and runs locally. This happens in two cases:
  1. The worker's OPTIONS file has the option on, and the CF still has no format fence. Installing the worker's feature output would fail with Corruption, a background error that stops writes, because a Version without the fence rejects exact metadata. The local run writes legacy output, which installs.
  2. The format fence is added after the job is built but before the worker opens the DB. The legacy install path does not check feature metadata (the fingerprint, the origins and the allowed generation numbers), so the primary declines the result instead of installing it unchecked. At this diff, the local run also fails to install (see "Validation and known limitations").
- A feature-aware result is declined when it has another protocol version, flattening that the primary's options do not allow, any blob file addition, or another output level.
- In a feature-aware result, each output must have a valid SST file name and report an exact metadata descriptor that has the SST identity fields (the CF ID and the SST file number when built; BlobReferenceMetadataDescriptor::HasSstIdentity()), the primary's CF ID, its own SST file number, and the request's relocation state fingerprint. An output must not also report a coarse classification property. The import would fail on an SST that has both (Corruption from UpdateTableProperties()), so the check declines it and the job runs locally. A worker that runs this code fails its own check on such an SST first, so only a worker of another version or a worker bug can return it.

### Garbage filter

In a feature-aware result, the primary drops the garbage that the worker reports for a file that has no garbage counters in the Version: a routed generation number (a blob file that indirect blob GC collected, or a deleted relocation file), or a live relocation file. Local compaction drops the same garbage. The comment at the filter in compaction_service_job.cc has an example.

### Per-file check

Inside the existing remote import loop, ValidateRemoteExactBlobMetadata() checks each imported SST. It first opens one short-lived reader of the SST, which serves every step and gives the table properties that the primary installs. This reader does not go into the table cache and does not put table metadata into the shared block cache. So the first table cache open of an installed output happens later at its output level, as for a local output, and a rejected output leaves nothing in either cache. The steps are:
1. The descriptor stored in the imported file must equal the reported one, and the file must not also store a coarse classification property. The import reads these stored properties, so this covers a worker that leaves the classification out of its result.
2. The file's real CF ID (from its table properties) must be the primary's, and the descriptor must name the same CF ID and the file's original file number.
3. TableReader::VerifyBlobReferenceMetadata() reads and checks all of the file's exact reference metadata (see the next section).
4. The primary reads the reference summary (the list of groups) of the file.
5. For every reference group in the summary, Version::ValidateBlobReferenceGroup() checks the generation number and the origin against the captured input Version (its comment has the origin rules). The summary holds only indirect groups; it leaves out kDirect groups, which hold legacy references. The generation number must also be an allowed generation number, or a number that a coarse input SST of this job pins (see rule 3 in "Allowed generation numbers").

A failed check deletes the outputs that were already imported (existing cleanup helpers) and runs the job locally. Each imported SST is recorded as an output path, so the cleanup of an aborted compaction (CompactionJob::CleanupAbortedSubcompactions()) deletes it.

### Full metadata check (VerifyBlobReferenceMetadata)

Where it runs: on the primary, in step 3 of the per-file check, after the SST is imported and before it is added to the compaction outputs. It runs without the DB mutex. TableReader has a default that returns NotSupported; BlockBasedTable implements it.

What it checks: it reads the index block of the reference metadata and decodes it against the expected descriptor, which checks the index checksum and the descriptor totals. Then it reads every data block in file order, including the blocks of legacy kDirect references, and checks each block checksum, the key order across runs and blocks, and every group total. It does not read the table's key/value entries. The reads use readahead that starts at 256 KB and grows to 1 MB (estimates, not tuned), do not fill the block cache, and use the compaction's rate limiter priority.

Why: the reference summary read in step 4 and the census read only the index block. A worker bug or a damaged file could leave bad data blocks that no install-time read sees. Indirect blob GC reads these data blocks later to find the live values. When it finds a bad block, it does not lose data: it fails that GC input, counts INDIRECT_BLOB_GC_CORRUPT_INPUTS and writes an ERROR line. But it then cannot reclaim the blob files that this SST references, and GC keeps failing on this SST until a compaction rewrites it. Checking at import finds the damaged file while the job can still run locally from its intact inputs, so a damaged file never gets installed. A local compaction does not run this check by default, because the primary built that metadata itself; it runs it only when verify_output_flags asks for block checksum checks (see "VerifyChecksum of SSTs with exact reference metadata" below). The check is always on for feature-aware remote outputs, and does not follow verify_output_flags, because it protects space reclamation for the SST: a bad reference block found later blocks GC of the blob files that this SST references. Only at import can the primary still run the job locally from its intact inputs instead.

### VerifyChecksum of SSTs with exact reference metadata

The meta index of an SST names only the index block of the exact reference metadata, not its data blocks. So BlockBasedTable::VerifyChecksum() also calls VerifyBlobReferenceMetadata() when the SST has the descriptor property. DB::VerifyChecksum(), `sst_dump --command=verify` (SstFileDumper::VerifyChecksum()), SstFileReader::VerifyChecksum(), the checksum check before an external file ingestion and the kVerifyBlockChecksum output check of a compaction all reach this through BlockBasedTable::VerifyChecksum(), so they also find a damaged reference data block. The call also runs with meta_blocks_only, because the reference blocks are metadata that a scan of the table's entries does not read. Cost: these checks also read all reference blocks of each such SST, in proportion to the size of the reference metadata. SSTs without exact reference metadata read nothing more; they pay one table property lookup per check.

### Allowed generation numbers

Background: the worker is a separate process, and the primary does not trust it to write only safe generation numbers. A generation number in an output is safe only if its file or route cannot go away between the pick and the install. The install check (diff 10) finds a number whose file or route went away: it checks every routed number, also when the route's target file did not change. But it then fails the install with Corruption, which is a background error. The rule below finds such a number earlier, when the primary can still run the job locally from its inputs.

Rule: the primary accepts an indirect group of a remote output only when its generation number is one of these:
1. A generation number that an indirect reference group of the job's exact inputs holds. The input SSTs stay in the current Version until the install, so the census still counts them, and route retirement keeps the route of such a number.
2. The route target of such a number in the input Version. The target is a live relocation file in the input Version, so the running-compaction rule keeps any route from it that GC adds during the job. The worker flattens only to these targets: it runs only when its relocation state fingerprint equals the one of the primary's input Version, so it sees the same routes.
3. A number that a coarse input SST of this job pins (checked directly, not stored in the list). A coarse SST has no reference groups, so the primary cannot list its numbers, and it accepts any number that such an SST could hold. A coarse reference has generation number == origin and names an indirect-origin blob file at or above the frontier of its SST. So the primary accepts such a number only when all of these hold: it is at or above the lowest frontier of the job's own coarse inputs (remote_coarse_input_frontier_), it equals the group's origin, it has no route, it is not a relocation file, and it is a live blob file in the input Version with BlobFileMetaData::IsIndirectOrigin(). The frontier comes from the job's inputs only, not from the whole input Version, because an SST outside the job can be removed while the job runs. The coarse input stays in the current Version until the install, so the frontier of the current Version stays at or below the number. Route retirement and GC use that frontier, so the blob file is not collected while the job runs.

A number outside these cases, for example a routed number that no input holds, could lose its route while the job runs. The install check would then fail the install with Corruption. So the primary rejects such an output early and runs the job locally. A correct worker never writes such a number, because compaction only copies the generation numbers of its inputs or flattens them to their route targets.

How the list is built: on the first per-file check of a job, PrepareRemoteAllowedBlobGenerations() visits the indirect groups of the exact inputs (ForEachIndirectInputReferenceGroup(), which reuses the input summaries that were read for the census, and reads a missing one). The list then stays fixed for the rest of the job. It is a sorted vector without duplicates, searched with binary search. While it is filled, each time the vector is full it drops duplicates, and it doubles its capacity (to at least 16 numbers, a small start size) only when it is still at least half full after that. This way it does not sort the whole list on almost every push. Most groups of one job share their generation numbers, so the list stays near the number of distinct numbers. Each growth is charged to the block cache (CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, 8 bytes per number) through ReserveBlobRelocationDependencyMemory(), together with the output dependencies of the install check. When the block cache is full, the list stays uncharged and the job logs a WARN line (see ReserveBlobRelocationDependencyMemory()).

### Monitoring

- REMOTE_COMPACT_COARSE_FALLBACK_COUNT (ticker) counts feature-aware compactions that run locally from the start because their output would be coarse (see "Which jobs"). Each one also has an INFO line.
- The histogram COMPACTION_OUTPUT_BLOB_REFERENCES (from a lower diff of this stack) also gets one sample per installed remote output SST, as for a local output. The primary records it after every output of the job passed the per-file check and was imported, before the install. The sample is the reference count of the output's descriptor, so it counts all references, kDirect (legacy) references included. A rejected remote result adds no sample; the local rerun records its own outputs.
- The base ticker REMOTE_COMPACT_BLOB_RESULT_DECLINED_COUNT also counts three new declines:
  - The worker declines with TryAgain: a worker contract check failed, or the job needs new blob output. The primary writes an INFO line with the worker's message, which names the cause. INFO, not WARN, because these declines can be frequent (for example after each GC install, see "Safety, compatibility and limitations").
  - The blob indirection contract check of the result (ValidateBlobIndirectionCompactionServiceResult()) fails. WARN line.
  - The check of an output file fails. WARN line. The primary removes the output files it already copied and runs the job locally.
- Feature off: only feature-aware jobs reach these paths.

## Implementation: why the worker can run the job safely

The design keeps the worker simple and puts the trust decision on the primary. These four choices are enough:

1. Same file table. The worker opens the DB as a secondary instance (DB::OpenAndCompact()), so it reads the relocation files, the routes and the format fence from the MANIFEST, as the primary does. The relocation state fingerprint shows that its Version has the same relocation files and routes as the primary's input Version, and the options fingerprint shows that it uses the same blob options and format versions (see "Request").
2. No census needed. Only the primary uses the census: for GC selection and route retirement. The coarse frontier is a Version value (VersionStorageInfo::OldestCoarseIndirectOriginFileNumber()), so the worker's Version has it too. A compaction only copies the generation numbers of its inputs, or flattens them to route targets, and both are in the Version. The worker builds the exact reference metadata of its outputs from the keys it writes, as a local compaction does. A secondary instance has no census, and the compaction skips the census read when there is none.
3. No blob files, and no indirect blob GC in the worker. A feature-aware worker never creates blob files (see "Worker"). Base remote compaction runs compaction-time blob GC inside the compaction: the worker writes new blob files and the primary imports them. Indirect blob GC is not a compaction: its inputs are blob files, and it needs the census and a MANIFEST install. So it always runs on the primary and never in a remote worker. Remote indirect blob GC is a possible follow-up.
4. The primary checks what the worker returns. The check before the import, the per-file check and the allowed generation numbers decide what the primary installs, and the install check runs as for a local compaction. The primary does not scan every key again (see "Safety, compatibility and limitations"). The routes that the output may use cannot disappear before the install: the job's input SSTs stay in the Version, so the census still counts their generation numbers and route retirement keeps their routes. The running-compaction rule keeps any route that GC adds from a route target during the job (see "Allowed generation numbers").

Code that the sections above do not name:
- The four new request fields and the two new result fields are in the OptionTypeInfo tables of CompactionServiceInput and CompactionServiceResult (db/compaction/compaction_service_job.cc), next to the existing remote BlobDB fields. The protocol version and fingerprint fields start with blob_indirection_ or blob_relocation_, so they are not confused with the existing blob_gc_ fields of legacy blob GC.
- The per-file check opens the imported SST with the compaction's file options (file_options_), through a short-lived reader (TableCache::OpenEphemeralBlobReferenceReader()). db/table_cache.h makes CompactionJob a friend, so that it can get such a reader.
- The metadata block read in block_based_table_reader.cc takes an optional prefetch buffer, which only the full metadata check uses.
- db/table_cache.cc has a new debug-only sync point (TableCache::FindTable:OpenCachedReader) that reports the table cache, the file number and the level of each reader that goes into a table cache. A test uses it.

## Also in this diff

- BlockBasedTable::VerifyChecksum() also checks the exact reference metadata (see "VerifyChecksum of SSTs with exact reference metadata").
- A test hook in db/compaction/compaction_outputs.cc (sync point CompactionOutputs::AddToOutput:Value) can replace the output value, so that tests can build malformed remote compaction output. When the hook replaced the value, AddToOutput() decodes the new value instead of using the compaction iterator's decode. The value compare that detects a replaced value exists only in debug builds, like the sync point.
- A test hook in db/builder.cc (sync point ExtractBlobReferenceClassificationFromTableProperties:BothProperties) can clear the Corruption for an SST that has both an exact descriptor and a coarse classification. A test uses it on the worker only, to build such a remote output.
- Comment updates: db/blob/blob_reference_metadata.h (the descriptor fingerprint and the file number of an imported output), db/compaction/compaction_iterator.h (which remote jobs flatten), and include/rocksdb/table.h (the list of allowed generation numbers of a remote compaction is charged with the other lists that check compaction outputs).

## Safety, compatibility and limitations

- Changes visible to existing users: with BlobDB on (enable_blob_files) and enable_blob_indirection off, every flush and compaction that can write blob files (it has a blob file builder; flush and recovery build their CompactionIterator with one in BuildTable()) runs one more branch per plain value and per wide-column entity, never per column: CompactionIterator tests check_large_values_ before BlobFileBuilder::Add(). The branch always goes the same way, so it is well predicted; its cost was not measured. Without BlobDB, the per-key tests are the same as in base RocksDB.
- Public API: new ticker REMOTE_COMPACT_COARSE_FALLBACK_COUNT, appended before TICKER_ENUM_MAX. It has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used. The histogram COMPACTION_OUTPUT_BLOB_REFERENCES also counts installed remote outputs (see "Monitoring"). The comment of the base ticker REMOTE_COMPACT_BLOB_RESULT_DECLINED_COUNT also says that it counts the worker TryAgain declines of feature-aware jobs (see "Monitoring").
- Serialized remote compaction messages (not persisted in the DB): CompactionServiceInput and CompactionServiceResult get new fields. Both Read() functions parse with ignore_unknown_options, so a peer that does not know the fields ignores them. A worker built from a lower diff of this stack does not return the protocol version (0), so the primary runs the job locally before it imports output. A worker binary without blob indirection cannot open a DB with the format fence (required MANIFEST tags), so its DB::OpenAndCompact() fails. The CompactionService's normal failure handling then applies. Because of the DB-global fence, this also holds for legacy jobs of other column families in the same DB. A request from a primary without this diff has no contract values (protocol version 0), so the worker runs it as a legacy job. This diff adds no new on-disk format: the descriptor fingerprint fields are from diff 2.
- The worker is trusted to list the references it writes correctly. The primary checks that the list is well formed and that every group is allowed, but it does not scan every key again.
- A relocation file's MANIFEST record holds no list of its origins, so the group check cannot prove that a relocation file holds a given origin. A read checks the stored key (origin, original offset) instead.
- Feature-aware jobs never use remote blob file output: a job that needs new blob output runs locally. Remote indirect blob GC is not supported (see item 3 of "Implementation"). In a column family with the option on that still has legacy blob data, with compaction-time blob GC on (or after lowering min_blob_size), the remote compactions that need blob output all run locally.
- With blob_file_starting_level of 1 or more, a flush writes large values inline below the starting level. A remote compaction from a level below the starting level into the starting level or above must write those values to new blob files. So the worker declines it with TryAgain at the first value of min_blob_size bytes or more, after a full DB open on the worker, and the job runs locally. Every such compaction that holds such a value declines. With steady writes into a column family with blob_file_starting_level of 1, this is every L0 to L1 compaction, so these jobs always run locally after a wasted worker open. The primary counts each such decline in REMOTE_COMPACT_BLOB_RESULT_DECLINED_COUNT and logs the worker's message. The primary does not predict this case and keep such jobs local from the start.
- The per-file check does not read the SST's filter blocks or data blocks. Damage there is first found by VerifyOutputFiles(), which fails the compaction instead of running it locally, as for legacy remote outputs.
- An interrupted feature-aware job restarts from the beginning.
- A 64-bit options fingerprint collision is the only case that the worker check would miss; each output's descriptor is still checked.
- The TryAgain decline reaches the primary only if the CompactionService returns the serialized result. If Wait() reports kFailure without a readable result, the normal remote failure path applies instead of the local run.
- The worker declines a job when the relocation state fingerprint of its Version differs from the request. So any GC install or route retirement between the pick and the worker's open makes the job run locally. With continuous GC, many remote jobs may run locally. This rate was not measured. The primary counts these declines and logs them with the message "relocation state fingerprint differs", so the rate can be seen in production.
- The full metadata check reads all reference data blocks of each remote output once. This adds I/O on the primary in proportion to the size of the metadata, not to the size of the SST data. This cost was not measured.
- Option gate: at this diff the option gate of diff 2 is still in place, so the behavior with the option on is reachable only through the test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production. Diff 14 removes the gate.

## Validation and known limitations

The Test Plan lists the tests and what they do not cover. A test simulates a worker without the contract: a sync point clears the protocol version in the result (BlobIndirectionRejectsIncapableWorkerResult).

Known limitation at this diff: if the format fence is added after a legacy job is built, the primary declines the worker's feature output, and the local run writes an SST without exact reference metadata. The install of that SST fails with Corruption, because a Version with the format fence rejects such an SST. This sets a background error. Diff 12 closes this case: the MANIFEST writer marks such local outputs as legacy SSTs, and the fenced Version accepts them.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 11 of the map: "Remote compaction validation".

Tracking issue: meta#15301

Differential Revision: D124930422
Summary:
Pull Request resolved: meta#15549

## Background

enable_blob_indirection can be changed with SetOptions(). A user can turn it on, turn it off and turn it on again while flushes, compactions and ingestions run. Data that was written while the option was on must stay readable after it is turned off. The files and metadata of such data must also stay correct in the maintenance APIs: metadata listing, ldb, export, import and ingestion.

This diff makes the option a runtime policy. The option decides how new output is written. It is not a read gate. The diff tracks flushes and compactions that may still write output with the option on, checks every writer against that state, and makes the maintenance APIs handle relocation files and fenced column families.

## How to read this diff

1. Read "Terms used in this diff" near the top of this summary. Then read the format fence entries in the "MANIFEST records" section of db/blob/blob_relocation_manifest.h. The per-CF fence is read with VersionStorageInfo::HasBlobIndirectionFormat().
2. Pending activation tracking. It depends on no other part of this diff, and most later checks read it. Read the "Pending activation" comment and HasPendingBlobIndirectionOutput() in db/column_family.h, then MemTableList::BeginBlobIndirectionActivation() and EndBlobIndirectionActivation() in db/memtable_list.{h,cc}, and the per-memtable mark in db/memtable.h. Then read the callers: db/flush_job.cc, db/compaction/compaction.cc, and FlushMemTablesToOutputFiles() and AtomicFlushMemTablesToOutputFiles() in db/db_impl/db_impl_compaction_flush.cc.
3. Outputs made before activation. Read FileMetaData::blob_reference_output_predates_indirection in db/version_edit.h and VersionEdit::MarkBlobReferenceOutputsPredatingIndirectionLegacy() in db/version_edit.cc. Then read where the flag is set: db/flush_job.cc, db/compaction/compaction_job.cc with SubcompactionState::AddOutputsEdit() (db/compaction/subcompaction_state.h), CopyTrivialCompactionFiles(), and ingestion. Then read how LogAndApplyImpl() in db/version_set.cc sets has_predating_blob_reference_output and activates_blob_indirection on each ManifestWriter. Last, read the classification block in ProcessManifestWrites() (sync point MarkPredatingBlobReferenceOutputs).
4. Format checks. Read HasBlobIndirectionStateOrPendingActivation(), MayUseBlobIndirection() and CheckBlobIndirectionTableWriter() in db/column_family.h, and the pending check in PrepareMutableCFOptions() in db/column_family.cc. Then read, in ProcessManifestWrites() in db/version_set.cc, the per-edit Block-Based Table check ("A CF with the format fence needs a Block-Based Table writer") and the check before the options of SetOptions() are published ("DBImpl::SetOptions() prepared its options").
5. Ingestion and import checks. Read the "Blob indirection checks of an ingestion" comment in db/external_sst_file_ingestion_job.h, the Prepare() scan in the .cc file, and the SetBlobIndirectionPendingAtPrepare() calls in db/db_impl/db_impl.cc. Then read RejectBlobIndirectionTableProperties() in db/builder.h, which import also uses (db/import_column_family_job.cc).
6. Leaf parts, in any order. Maintenance APIs: GetColumnFamilyMetaData(), GetAllColumnFamilyMetaData() and GetColumnFamilyMetaDataForExport() in db/db_impl/db_impl.cc, ExportColumnFamily() in utilities/checkpoint/checkpoint_impl.cc, and DumpBlobFile() in tools/ldb_cmd.cc. Removal of files with no live value: NeedsCompaction() in db/column_family.cc and empty_files_only in BackgroundCompaction(). Census: BatchActivatesBlobIndirection() and ReserveBlobReferenceCensusInstalls() in db/version_set.cc, and the ScheduleBlobReferenceCensus() call after SetOptions() in db/db_impl/db_impl.cc. Trivial moves: Compaction::EndPendingBlobIndirectionActivation() in db/compaction/compaction.{h,cc} and its call in DBImpl::PrepareTrivialMoveEdit().
7. MANIFEST batch rules and the ingestion precondition. Read the ManifestWriter fields and the numbered rules in VersionSet::ManifestBatchEndsBefore() in db/version_set.cc. Then read the ingestion commit in DBImpl::CommitFileIngestionHandles() in db/db_impl/db_impl.cc: it passes the publication check as a MANIFEST precondition only when ExternalSstFileIngestionJob::HasUnscannedDbGeneratedFile() is true, and its comment says why one run of the check is enough.
8. Tests: db/blob/db_blob_basic_test.cc (toggles, pending activation, the SetOptions() publish window, trivial moves, import, census, removal of files with no live value), db/external_sst_file_test.cc (ingestion, and the MANIFEST precondition of ingestion), db/version_set_test.cc (batch barriers), tools/ldb_cmd_test.cc (relocation file dump), db/compaction/compaction_service_test.cc (a legacy remote job after the fence), db/memtable_list_test.cc (a pending blob indirection activation in the memtable list).

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, generation number, flattened reference, route, relocation file, physical file, indirect origin, exact reference metadata, census, blob file retirement, option gate) and the format fence and fenced CF of diff 4, unchanged. "The option" is enable_blob_indirection.

Terms of this diff:

| Term | Meaning |
|---|---|
| activation | The MANIFEST edit that sets the per-CF fence of a column family for the first time. (Diff 4 and the term list at the top of db/blob/blob_relocation_manifest.h use the word for the first such edit in the whole DB; this diff uses it per column family.) The first flush or compaction output written with the option on carries it. The MANIFEST writer of that edit is the activating writer |
| pending activation | A flush or compaction that copied or picked its options with the option on and has not finished. It can still activate the column family, also after the option is turned off. ColumnFamilyData tracks it with two counters and a per-memtable mark (HasPendingBlobIndirectionOutput()). A trivial move writes no output, so it stops counting before its MANIFEST write |
| predating output | An output SST that may have been written before the column family used the option. It is marked in memory with FileMetaData::blob_reference_output_predates_indirection |
| legacy SST | An SST in a fenced CF that has no exact metadata and no coarse frontier (diff 5 adds the legacy marker). There are three cases: an SST created before activation, an SST whose table properties record coarse frontier 0 (it has no indirect references), and an ingested SST (new in this diff). The MANIFEST stores this as FileMetaData::blob_reference_legacy_metadata, so that recovery accepts the SST |
| candidate Version | The Version that a MANIFEST batch builds from its edits before the MANIFEST write. It is installed only if the write succeeds |
| census install | The census update that a MANIFEST batch prepares for a new Version and installs together with it, so that the census follows the Version (BlobReferenceCensusInstallBatch in db/version_set.h, diff 5) |
| same-file / separate-file reference | A same-file blob reference is a kBlob or kBlobTTL BlobIndex whose blob record is in the same file as the table entry (BlobIndex::IsSameFile()). The ingestion scan rejects every other BlobIndex: a reference to another blob file (legacy or indirect, flattened or not) and an inlined TTL value. The error says that ingestion supports only same-file blob references |

## Previous behavior

The option could already change through SetOptions(), and diff 4 already set the per-CF fence on the first output written with the option on. But nothing tracked a flush or compaction that started with the option on and had not installed its output yet. Such a job could still set the fence after SetOptions() turned the option off. Diff 4 already checked a fenced column family in SetOptions() and at a read-write DB open: the options need a Block-Based Table writer and a compaction style other than FIFO. These checks did not cover a pending job, and the MANIFEST writer did not check the options. For example, one SetOptions() call could turn the option off and switch to PlainTable while the first flush with the option on was still running. That flush then set the fence on a column family that now had a PlainTable writer. Ingestion, import and export did not check the fence or such pending jobs. Base import and export reject an SST whose metadata names a blob file (oldest_blob_file_number is not 0). But an SST whose blob references are all flattened, or all use a generation number that has a route, can have oldest_blob_file_number 0, so this base check does not catch every SST with indirect references. GetColumnFamilyMetaData() and ldb did not know about relocation files. With automatic compactions disabled, files with no live value stayed on disk. File ingestion had no precondition. A remote compaction built as a legacy job before the fence could not install its local rerun (the known limitation of diff 11).

## New behavior

### Policy

- enable_blob_indirection decides how new output is written and how indirect blob GC picks files. It is not a read gate. With the option off, new output uses legacy blobs, existing indirect data stays readable, and ordinary compaction can rewrite it into legacy blobs.
- The per-CF fence is set by the first flush or compaction output written with the option on. No MANIFEST edit clears it.

### Pending activation

- The pending state has three parts: two counters and a per-memtable mark. A flush with the option on marks the first memtable it picks (ReadOnlyMemTable::pending_blob_indirection_activation_), and MemTableList counts the marked memtables. HasPendingBlobIndirectionOutput() is true while any count or mark is set. The option checks and the MANIFEST writer use it to reject incompatible writers, also after the option is turned off.
- A flush whose options copy has the option on is pending from that copy on (BeginBlobIndirectionFlush()). This includes the time when it syncs closed WALs without the DB mutex, before it picks its memtables. After the pick, the mark on its first memtable keeps it pending until the memtable is installed or rolled back.
- A compaction picked with the option on is pending until it releases its input Version. A trivial move writes no output file, so its edit cannot set the fence; it ends its pending activation before its MANIFEST write (Compaction::EndPendingBlobIndirectionActivation()). With a BOTTOM priority thread pool, a compaction to the last level goes to that pool in every compaction style, and with compaction_options_universal.reduce_file_locking (the default, read for every style) it is forwarded as an intended compaction, which only holds its input files until the bottom priority thread repicks. It writes no output either, so it ends its pending activation right after Compaction::FinalizeInputInfo(); the repicked compaction counts with its own options. ReFitLevel and the placeholder compactions of ingestion never count, because they do not call Compaction::FinalizeInputInfo().

### Outputs made before activation

- Three producers mark an output SST as a predating output: a flush or compaction with the option off on an input Version without the fence, every ingested file, and the file copy (FIFO temperature change), for a copy of an input SST that has no reference metadata and no coarse frontier; the copy keeps the input's coarse frontier. FIFO cannot use blob indirection, so the third path never meets a fence; it stays as a guard.
- If the MANIFEST writer sees the fence, or the same writer sets it, it marks each predating output without exact reference metadata as a legacy SST. The marking sets one flag per new file of the writer, so it runs with the DB mutex held.
- This closes the remote compaction case from diff 11 where a legacy job is followed by the format fence. The primary declines the worker's result and runs the compaction locally. The local outputs are predating outputs (the compaction was picked with the option off on a Version without the fence), so the MANIFEST writer marks them as legacy SSTs, and the fenced Version accepts them.
- Parallel flushes can complete in reverse order. When one MANIFEST caller holds both an older flush output made before activation and a newer activating flush, the older output is classified as legacy. Recovery accepts a legacy SST only after the fence of its column family was replayed, or in the edit that sets the fence. So the first edit of the activating writer also sets the fence. The edits are not reordered or split, so if the MANIFEST ends inside this writer's edits, recovery still sees the fence before any legacy SST. The comment on FileMetaData::blob_reference_output_predates_indirection in db/version_edit.h explains the whole path.

### Format checks

Diff 4 checks the options of a fenced column family in SetOptions() and at DB open. This diff extends the SetOptions() check to a column family with a pending activation, and adds a check in the MANIFEST writer. The DB open check does not change: at open, no flush or compaction has started, so no activation can be pending.
- SetOptions() (PrepareMutableCFOptions()) treats a column family with a pending activation like a fenced CF: the new options need a Block-Based Table writer and a compaction style other than FIFO.
- SetOptions() checks its new options at the head of the MANIFEST queue, in pre_cb. LogAndApply() then releases the DB mutex while it finishes the new Versions (VersionBuilder::SaveBlobFilesAndCheckTo()), and publishes the options after it locks the mutex again. A flush or compaction that copies or picks the options in that gap still sees the old options. With the option on, it becomes a pending activation after the check ran. For example, one SetOptions() call turns the option off and switches to PlainTable, and a flush copies the options in the gap. If SetOptions() published PlainTable, that flush could not install its output: the Block-Based Table check below would fail it with a background error, and writes would stop until the DB is reopened. So the MANIFEST writer checks the new options again just before it publishes them, in the same mutex hold (CheckBlobIndirectionTableWriter()). If a pending activation or the fence now needs a Block-Based Table writer, SetOptions() fails with NotSupported and publishes nothing, the same result as when the flush starts first. The check is O(1) per column family.
- For a fenced or fence-setting edit, the MANIFEST writer also checks that the latest options have a Block-Based Table writer. With the check above, no known path fails here. The check stays as the last guard, so that a fenced CF never installs a non-Block-Based Table writer. The compaction style cannot change after DB open, and FIFO with the fence is rejected earlier, so the writer only asserts the compaction style.

### Ingestion and import

- Prepare() checks the table properties of every file, in every column family, before any scan (RejectBlobIndirectionTableProperties()). It rejects an SST that has exact metadata or a coarse frontier other than 0. An SST written with the option on has an exact descriptor even when it holds no blob reference, so it is rejected too. The properties are already loaded, so the check reads nothing.
- An SstFileWriter file (ingestion without allow_db_generated_files) is not scanned. Base accepts only SstFileWriter files there (it checks the external SST version property and sequence numbers of 0), and the SstFileWriter API cannot write a separate-file blob reference, so such a file holds none. Prepare() checks only its table properties (bullet above) and marks it checked. This trusts the file as base trusts its properties and sequence numbers.
- A DB-generated file (allow_db_generated_files) can hold legacy blob references, so Prepare() scans its entries when the column family is fenced, has the option on, or has a pending activation (a pending activation needs the scan even when the column family has no fence and the option is off). The pending state is read under the DB mutex before Prepare(). The scan, and the TryAgain result in the next bullet, are a best-effort early check, not part of the guard that indirect blob GC relies on (the property check is that guard). The scan rejects a separate-file reference (kBlob or kBlobTTL to another blob file) and an inlined TTL value. Such references never reach the census, indirect blob GC, blob file retirement or route retirement: these skip direct references and legacy SSTs. A read of a blob file that the DB does not have fails with Corruption, as in base, which accepts such files into any column family. A legacy column family accepts the same file without a scan, and it reaches the same state when it activates later. The one case that only the scan catches is an SST that holds indirect references but lost its blob indirection properties.
- At the MANIFEST install, ValidateBlobIndirectionPublication() returns TryAgain if the column family is fenced, has the option on or is pending, and a DB-generated file was not scanned (SstFileWriter files and files that the ingestion generated itself are exempt). The TryAgain status goes back to the user. When the user calls the ingestion again, it reads the state again, and if the column family still needs the scan, Prepare() now scans, so the check passes. The comment "Blob indirection checks of an ingestion" in db/external_sst_file_ingestion_job.h lists the steps.
- Base import rejects an SST whose import metadata names a blob file (oldest_blob_file_number is not 0). This is not enough for blob indirection: the caller writes the metadata, and an SST whose references are all flattened or routed can have oldest_blob_file_number 0. So import also checks the table properties of each SST. Ingestion does the same check for every file in every column family; base ingestion has no blob check. Both read only the table properties, not the entries. They reject an SST that has exact metadata or a coarse frontier other than 0. Such an SST can hold indirect references, which need the routes of the DB that wrote it. The target DB does not have those routes. The property check is enough, because every SST with indirect references carries one of these two properties. SstFileWriter cannot write an indirect BlobIndex.
- These rejects are also the guard that indirect blob GC relies on: a GC install assumes that no ingested or imported SST holds an indirect reference to a generation number of a GC input. The base import check alone is not this guard, for the reason above.

### Maintenance APIs

- GetColumnFamilyMetaData() (the overload without GetColumnFamilyMetaDataOptions) and GetAllColumnFamilyMetaData() list relocation files after the blob files, and count them in blob_file_count and blob_file_size (metadata.h says so). They list them in the same DB mutex hold as the SST and blob files, with the same work per file as a blob file. This API is a control path, and base already lists every SST and blob file under the mutex.
- ExportColumnFamily() returns NotSupported for a column family that has the option on, a pending activation or the fence (ColumnFamilyData::MayUseBlobIndirection()), because the export does not carry relocation files and routes. It takes the DB mutex from the handle's own DBImpl (ColumnFamilyHandleImpl::db()), so it does not depend on GetRootDB(). This check runs before the export directory is created and the column family is flushed, and GetColumnFamilyMetaDataForExport() checks again under the lock that reads the SST list. The base export check, which rejects an SST whose metadata names a blob file, runs later and does not catch an SST whose references are all flattened or routed. The checkpoint.h comments describe this limit.
- ldb dump recognizes a relocation file and does not decode it as a blob log file.
- VerifyFileChecksums() also checks the full-file checksum of each relocation file in the current Version, in the same way as for blob files (DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc).
- Checkpoints, backups and the live-file APIs already handle relocation files from diff 4.

### Census

- A MANIFEST batch that activates a column family reserves a census install for it (ReserveBlobReferenceCensusInstalls()), also when the new options have the option off. A pending flush or compaction can set the fence after the option is turned off. The CF then holds indirect references, and the census must count them so that indirect blob GC and route retirement stay correct.
- SetOptions() calls ScheduleBlobReferenceCensus() for each column family it changes. It queues census work only if the column family is fenced and its census needs a run. A new column family has no fence, so CreateColumnFamily() does not call it.
- An ingestion with a replace range already uses the census rebuild path of diff 5. This diff adds only a test for it.
- A file ingestion and an import free the deferred census cleanup of the VersionSet after their SuperVersion install (VersionSet::ReleaseDeferredPublicationCleanup()), as CompactFiles() and SetOptions() do. An ingestion into a fenced column family and an import into a new column family with the option on (in a DB with the format fence) get a census install, and the census state that it replaces waits in that list. While background work is paused, no census job, flush or compaction frees it, so without this call it would stay in memory until background work continues or the DB closes. An ingestion with a replace range can leave the whole old census of the column family there.

### Removal of files with no live value

- NeedsCompaction() checks for blob files and relocation files with no live value (HasEmptyBlobGcCandidate()) before it checks disable_auto_compactions.
- When normal indirect blob GC cannot run (blob files, blob GC or blob indirection off, or automatic compactions disabled), the GC job still removes such files (GetEmptyBlobGcCandidates(), empty_files_only). It writes the blob file retirement of a normal blob file, or a relocation file deletion record (kBlobRelocationFileDeletion) of a relocation file. No SST uses a value in such a file, so the job copies no value and rewrites no SST. The early return in IndirectBlobGCJob::Start() for options that turn GC off applies only to a normal job, so it does not end an empty-files-only job.
- A block cache that stays full does not stop this removal. The GC job copies the census entries of its inputs and charges that copy to the block cache (CacheEntryRole::kIndirectBlobGcWorkingMemory). For an empty-files-only job, a charge that fails because the cache is full does not fail the copy: the copy goes on uncharged, and census-uncharged-charges counts each failed charge. The job logs a WARN line only when that count reaches a new power of two, because a job that fails later with a stale input is retried soon and can copy uncharged again. Otherwise a cache that stays full would keep these files on disk forever. The copy is small. The job has at most 8 inputs, and no SST holds their generation numbers. So the copy holds no SST numbers: it holds one entry for each input and for each old file routed to it. If an SST does hold a selected number, the charge stays strict. Normal indirect blob GC keeps the strict charge.
- So with automatic compactions disabled, the DB still writes these MANIFEST records and deletes the files. The enable_blob_indirection comment in advanced_options.h says so.

### MANIFEST precondition of ingestion

An ingestion passes the publication check (ValidateBlobIndirectionPublication()) as a MANIFEST precondition only when one of its jobs holds a DB-generated file that Prepare() did not scan, because only such a file can fail the check. Every other ingestion calls plain LogAndApply() with no precondition, as in base, and shares MANIFEST batches with other callers as in base.

A caller with a precondition is a batch barrier: its batch holds only its own writers (rule 1 of VersionSet::ManifestBatchEndsBefore()), and a later writer with a precondition starts a new batch (rule 5). So an ingestion of an unscanned DB-generated file leads its own batch, and its check runs once, at the head of the MANIFEST queue, with the DB mutex held. Its edit is applied under the DB mutex. If the check fails, the ingestion returns TryAgain and the user's next call scans the file.

The check runs once, as diff 6 requires for every precondition, but it also reads the pending activation state, which can change outside the MANIFEST queue. This is safe: the check passes only when the latest options have the option off, the options cannot change while the ingestion holds the queue head, and a flush or compaction becomes pending only while the latest options have the option on. The comment at the call in DBImpl::CommitFileIngestionHandles() gives the full reason.

The rules of ManifestBatchEndsBefore() replace the two batch barrier checks that diff 6 added to the grouping loop of ProcessManifestWrites(). They are numbered in the function and checked in order:
1. A queue leader with a precondition ends the batch after its own writers. So the Versions that the call installs hold only its own edits (indirect blob GC applies its job-start suppressions to the new Version), and no other caller's edit can fail its batch, or the other way (route retirement treats a VersionBuilder Corruption as a failed check of its own protocol).
2. Outputs made before activation and an activation from different callers do not share a batch. Within one caller they stay together (see "Outputs made before activation").
3. A batch that writes no MANIFEST record holds one caller.
4. A writer with prepared options (SetOptions()) does not share a batch with another caller.
5. A later writer with a precondition is not taken into the batch. It reaches the queue head, and its precondition runs there.
6. A column family add or drop, and a dummy edit, have their own batch.

## Implementation

The essential choices, and why they are enough:
- One cheap pending signal. Two counters and a per-memtable mark cover every job that may still activate a column family: a flush from its options copy to its install or rollback, and a compaction from its pick to the release of its input Version. The check is O(1).
- The MANIFEST writer is the final check. A job can become pending after SetOptions() checked its options, while the writer has the DB mutex released, so the writer checks the new options again in the mutex hold that publishes them. For each fenced or fence-setting edit it also checks for a Block-Based Table writer, and it classifies predating outputs as legacy SSTs. The first edit of an activating writer also sets the fence, so recovery always sees the fence before a legacy SST of the same writer.
- Ingestion decides at Prepare() and re-checks at install. A scan at Prepare() costs a read of the file, so it runs only when the column family needs it. If the state changed after Prepare(), the install returns TryAgain to the user, and the user's next call scans.
- Import and ingestion read the table properties of every SST. Every SST with indirect references has exact metadata or a coarse frontier other than 0, so the property check needs no scan.

Code that the sections above do not name:
- db/builder.{h,cc}: RejectBlobIndirectionTableProperties(), shared by import and ingestion.
- db/db_impl/db_impl.h: GetColumnFamilyMetaDataForExport(), and the empty_files_only argument of RunIndirectBlobGCBatch().
- db/compaction/compaction_service_job.cc: the comment for the local rerun after the primary declines a remote result, and the sync point BlobGCResultDeclined for tests.

## Also in this diff

- db/compaction/compaction_job.h: the comment of the compaction safety protocol says that ingestion and import reject indirect references.
- db/db_impl/db_impl_debug.cc: the test hook passes empty_files_only=false, because RunIndirectBlobGCBatch() gets this argument in this diff.

## Performance

This benchmark compares ingestion with concurrent flushes against base. It used release builds of base RocksDB and of an earlier build of this stack (all diffs of the stack as of 2026-11-20), measured on 2026-11-21, not on this commit. That stack build differs from this commit in two ways: its flush and compaction output code used more CPU, and every ingestion had a MANIFEST precondition (see the last bullet).
- Tool: db_bench cannot run ingestions from several threads together with writes, so this used a small benchmark-only tool (not part of the stack), linked against each build's static library.
- Workload: one DB with 8 column families, blob files on (min_blob_size 512), 4 MB write buffers, max_background_jobs 16. 4 ingestion threads each ingest into their own column family at a fixed rate of 25 small SSTs per second per thread, 100 per second in total (each a pre-built SstFileWriter file of 100 keys with 256-byte inline values, move_files). Ingested keys never overlap written keys. At the same time, 4 writer threads write 1 KB values to all 8 column families as fast as they can, so flushes run all the time (about 58 per second). 60 s per run.
- Configurations: base; the stack with enable_blob_indirection off (OFF); the stack with it on (ON).
- Method: 6 rounds, the 3 configurations in a rotating order, a fresh DB per run, on a shared virtual machine with 192 vCPUs (AMD EPYC Genoa; each run pinned to 32 vCPUs; MANIFEST syncs take about 0.4 ms on its disk). Medians.
- OFF matches base in every measure (ingest latency, write throughput, flushes, MANIFEST syncs and bytes; all ranges overlap).
- ON against OFF: ingest latency P50 +7% (4.13 against 3.85 ms) and P99 +19% (10.1 against 8.5 ms); neither range overlaps OFF. MANIFEST bytes +6% (the range overlaps OFF because of one OFF outlier run; it does not overlap base). Write throughput, flushes and the number of MANIFEST syncs show no clear change. Where the extra ingestion time goes was not measured.
- The OFF and ON numbers above come from that build, with a MANIFEST precondition on every ingestion. At this commit, an ingestion of SstFileWriter files, as in this workload, has no precondition and is batched as in base. That case was not measured. It can only remove MANIFEST batch ends for ingestions, so we expect no added cost (an expectation, not a measurement).
- The ingestion rate is fixed, so this measures latency at that load, not the maximum ingestion rate.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag or field. It sets the existing legacy marker (kBlobReferenceLegacyMetadata, an unignorable NewFile field from diff 5) on more SSTs: predating outputs and ingested files in a fenced CF. Older MANIFESTs read as before. Only a fenced CF gets the marker, and a binary without the feature already fails to open a DB with the format fence.
- Activation does not run a one-time full-key scan. The binary cannot be downgraded after activation.
- These are rejected: activation that conflicts with blob direct write, PlainTable transitions once an activation is pending or the column family is fenced, and ingestion of a DB-generated SST with a blob reference that is not a same-file reference when the column family is fenced, has the option on or has a pending activation.
- An ingestion checks the blob references of DB-generated files before it copies files if it sees the activation during Prepare(). If the activation starts after Prepare(), an ingestion of an unscanned DB-generated file returns TryAgain before the MANIFEST install, and its copied files are rolled back.
- SstFileWriter files are trusted to hold no separate-file blob reference, as base trusts their properties and sequence numbers. A full scan of every DB-generated file costs a read of the whole file; a table property with the count of separate-file references would avoid it (follow-up, TODO at the scan).
- ExportColumnFamily() refuses a fenced CF. Turning the option off does not lift this limit. Full checkpoints are supported.
- A DB that never activated, with the option off, keeps its base behavior, except for these changes visible to existing users:
  - Ingestion or import of an SST that carries blob indirection properties returns NotSupported (base import already rejects such an SST when its metadata names a blob file).
  - An ingestion with allow_db_generated_files takes the DB mutex once more per job, to read the pending state before Prepare(). Other ingestions do not.
  - A file ingestion has no MANIFEST precondition, as in base, unless it holds a DB-generated file that Prepare() did not scan (possible only with allow_db_generated_files). Such an ingestion runs the check at the head of the MANIFEST queue and leads its own MANIFEST batch.
  - ExportColumnFamily() uses the DBImpl of the column family handle instead of the root DB. The result is the same for a DB opened by DB::Open().
- Public API: no signature change. The comments of IngestExternalFile(), IngestExternalFiles(), PrepareFileIngestion() and CommitFileIngestionHandles() and of CreateColumnFamilyWithImport() (db.h), ExportColumnFamily() (checkpoint.h), ColumnFamilyMetaData::blob_files (metadata.h) and enable_blob_indirection (advanced_options.h) describe the new NotSupported and TryAgain cases, the relocation files in the metadata, and the removal of files with no live value.
- A blob file written with the option on is not dropped by the base rule (no SST links it and all its values are garbage). It stays until the cleanup removes it. The cleanup runs on a compaction thread (Env::Priority::LOW) only when that thread finds no compaction to run, so under constant compaction work such files stay longer. Read-only and secondary instances never run the cleanup.
- Option gate: at this diff the option gate of diff 2 is still in place, so the behavior with the option on is reachable only through the test hook ColumnFamilyData::TEST_SetAllowBlobIndirection, not in production. Diff 14 removes the gate.

## Validation and known limitations

Unit tests cover option toggles, pending activation for normal flush, atomic flush and compaction, a flush that becomes pending while SetOptions() waits to publish, trivial moves, legacy classification of outputs made before activation (also after a reopen), ingestion scans and retries, the MANIFEST precondition of ingestion and the batch barriers, the property checks of import and of ingestion into legacy and fenced CFs, the census after a replace-range ingestion, the flush window before the memtable pick, ldb dump of a relocation file, and removal of files with no live value with automatic compactions off.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 12 of the map: "Dynamic options and operations".

Tracking issue: meta#15301

Differential Revision: D124975457
Summary:
Pull Request resolved: meta#15720

## Background

Base RocksDB has a repair open: with best_efforts_blob_db_repair, an open records a missing or corrupt normal blob file as dropped (kDroppedBlobFile), and reads and compactions then treat its values as deleted. A column family with blob indirection has two more kinds of physical file that can go missing: indirect-origin blob files and relocation files. Earlier diffs of this stack already apply the base dropped-file record to a missing indirect-origin blob file: reads treat its values as deleted, and a compaction of an SST that references a dropped origin turns those references into deletions (10/14). Without this diff, two problems are left:

- A missing relocation file makes the repair open fall back in time. A fallback past an indirect blob GC edit can lose values that a relocation file on disk still holds.
- skip_missing_blob_files drops live values that a route still serves.

This diff makes a missing file leave the DB readable. The references to it go away without a read of the file. The open fails instead of losing values that a relocation file on disk still holds, in the cases that the fallback checks cover (see "Fallback checks"). It also adds an open check for missing relocation files (see "Open check").

The option gate of diff 2 stays in this diff, so blob indirection is still usable only in tests here. [Blob GC] 14/14 removes the gate, in the same diff that adds the crash-test support for the option.

Only a relocation file can be marked lost. A normal or indirect-origin blob file that is missing uses the base dropped-file record instead. A relocation file cannot use the base record, for two reasons:
- The base dropped list keeps a file only while some SST has an oldest_blob_file_number at or below it. Flattened and routed references do not set oldest_blob_file_number, so the dropped list would forget a relocation file while SSTs still use it.
- A route target must be a relocation file in the Version.

So a lost relocation file stays in the Version, marked lost, until indirect blob GC removes it.

## How to read this diff

1. Overview: read "Terms used in this diff" below. Then read "Lost relocation files" in db/blob/blob_relocation_manifest.h. It gives the life of a lost file and says why a relocation file is marked lost and not dropped. The "Accepted loss (kBlobPhysicalFileLoss)" bullet above it describes the record itself. The bullet title and a few comments say "accepted loss"; it means the same thing as a loss record.
2. How a file becomes lost: the relocation file loop in db/version_builder.cc (the branch under best_efforts_blob_db_repair). The open check in db/db_impl/db_impl_open.cc (DBImpl::CheckRelocationFilesExist() and its two calls in DBImpl::Recover()) is the case of a normal open (not a best-efforts recovery open). db/db_impl/db_impl_files.cc keeps the blob file numbers of the directory listing for it.
3. The loss check: db/version_set.h and db/version_set.cc (VersionStorageInfo::HasLostBlobRelocationFiles(), IsBlobReferenceLost(), IsBlobGenerationLost(), Version::IsBlobValueLost()), then db/blob/blob_fetcher.h (BlobFetcher::IsBlobValueLost(), HasBlobValueLoss(), has_lost_blob_relocation_files_), then the compaction iterator loss check in db/compaction/compaction_iterator.{h,cc} (CheckBlobValueLoss(), lost_blob_value_, blob_value_loss_possible_).
4. Point reads and merges: table/get_context.cc (GetContext::SaveValue()) and db/merge_helper.cc. Both turn a lost value into kTypeDeletion and use the repaired entity.
5. Iterator: db/db_iter.h (CurrentValue(), SaveCurrentValue(), the loss fields), then db/db_iter.cc (ParseKey(), CheckDeletedByDroppedBlobFiles(), the forward and reverse range tombstone changes).
6. Compaction: db/compaction/compaction.h (RepairsLostBlobReferences(), CollectExactBlobReferences()), db/blob/missing_blob_repair_iterator.h (Mode), then db/compaction/compaction_job.cc (CreateInputIterator(), ShouldUseLocalCompaction(), ValidateBlobRelocationInputGenerations()).
7. Fallback checks: db/version_builder.h (RecordsMissingBlobFilesAsDropped(), IsBlobFileRemovedByGc()), db/version_edit_handler.cc (VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc()), then db/version_set.cc (VersionSet::TryRecover()).
8. Side changes and public comments: db/db_filesnapshot.cc (live-file lists skip lost files), Version::AppendBlobRelocationFileMetaData() and VersionSet::GetTotalBlobFileSize() in db/version_set.cc (they skip lost files too), BlobRelocationState::SetFile() and DeleteFile() in db/blob/blob_relocation_manifest.cc (the relocation byte totals leave out lost files), DBImpl::VerifyChecksumInternal() in db/db_impl/db_impl.cc (VerifyFileChecksums() skips lost files), CheckSkipMissingBlobFilesSupported() in db/db_impl/db_impl_compaction_flush.cc, the property in db/internal_stats.cc, and the comments of best_efforts_blob_db_repair and CompactRangeOptions::skip_missing_blob_files in include/rocksdb/options.h. A first-time reader can skip the skip_missing_blob_files guard; the rest of the diff does not depend on it.

## Terms used in this diff

This diff uses the stack terms of [Blob GC] 2/14 (origin, original offset, generation number, unflattened and flattened reference, route, physical file, indirect origin, relocation file, exact reference metadata, census, blob file retirement, option gate), the format fence (diff 4), the coarse SST and its frontier (diff 7), and the holder (diff 5), unchanged.

Stack term with a new name:

| Term | Meaning |
|---|---|
| loss record | MANIFEST record (kBlobPhysicalFileLoss) that marks a relocation file lost. Diff 4 adds it under the name "accepted loss", and code comments still use that name. A lost file stays in the Version, but its values read as deleted |

Terms of this diff:

| Term | Meaning |
|---|---|
| repair open | An open with best_efforts_blob_db_repair (base option) |
| dropped blob file | A normal or indirect-origin blob file that a repair open recorded as dropped (kDroppedBlobFile, base). It leaves the Version, and reads treat its values as deleted |
| lost reference | An indirect reference whose generation number is a lost relocation file, or is routed to one (VersionStorageInfo::IsBlobReferenceLost()) |
| base gate | Compaction::RepairsMissingBlobReferences() (base). It holds when the input Version has dropped blob files and an input SST has an oldest_blob_file_number at or below the newest dropped file; the compaction then repairs references to dropped files. It also holds when skip_missing_blob_files is set; the compaction then repairs references to every missing blob file |
| loss gate | Compaction::RepairsLostBlobReferences(): the input Version has a lost relocation file |
| fallback in time | Best-efforts recovery opens an older point of the MANIFEST when the newest state needs a file that is missing, for example a non-L0 SST |

## Previous behavior

Only tests could create a loss. A repair open already put a missing indirect-origin blob file on the base dropped list, even when all its values count as garbage; reads treated its values as deleted, and compactions repaired its references (10/14). VersionBuilder already applied a loss record and kept the file in the Version, marked lost. A fetch from a lost relocation file returned NotFound. Compaction failed on a reference to a lost file, because Version::ValidateBlobReferenceGeneration() returned NotFound. A wide-column entity with a lost blob column could not be read. A repair open treated a missing relocation file like a missing SST and fell back in time. DB::GetLiveFiles(), GetLiveFilesStorageInfo(), GetLiveFilesChecksumInfo(), GetColumnFamilyMetaData(), the rocksdb.total-blob-file-size property and the relocation byte totals (rocksdb.live-blob-file-size, rocksdb.blob-stats, EstimateLiveDataSize() and relocation-file-bytes) listed or counted lost relocation files. A normal open did not check that relocation files exist, so a missing one failed only later reads. CompactRangeOptions::skip_missing_blob_files treated a routed (relocated) generation number as missing and dropped live values.

## New behavior

### Repair open

- A repair open marks a missing or corrupt relocation file lost and writes the loss record into its new MANIFEST. A missing relocation file does not cause a fallback in time. Without the flag, a normal open fails with NotFound (see "Open check"), and a plain best_efforts_recovery open falls back to an earlier consistent point, or fails (see "Fallback checks").
- A dropped indirect origin needs nothing more: an origin that is still in the Version has no route (indirect blob GC adds the route and retires the origin in one edit), GC selects only files in the Version, and the census counts of a dropped origin drain to 0 as compactions remove its references.
- Loss marks survive MANIFEST replay and rotation, checkpoints and backup. DB::GetLiveFiles(), GetLiveFilesStorageInfo(), GetLiveFilesChecksumInfo(), GetColumnFamilyMetaData() and GetAllColumnFamilyMetaData() leave out lost files, because they have no readable values (a corrupt file that a repair open marked lost can still be on disk until GC removes its record). The blob size statistics do not count them either: the relocation state's byte totals (BlobRelocationState::PhysicalFileBytes() and RecordBytes()) leave out lost files, so rocksdb.total-blob-file-size, rocksdb.live-blob-file-size, rocksdb.blob-stats (size and space amp), EstimateLiveDataSize() and relocation-file-bytes of rocksdb.indirect-blob-gc-stats count only the blob files on disk. The census leaves the garbage of a lost file out of the relocation garbage total, so the garbage stays below the total size. So SstFileManager tracking at open and ldb dump_live_files do not count or open a missing file. DB::VerifyFileChecksums() skips lost files too, because they have no bytes to check; it still checks every relocation file that is not lost.
- The public comments of best_efforts_blob_db_repair and CompactRangeOptions::skip_missing_blob_files describe what this diff adds for column families with blob indirection: lost relocation files, the compactions that a loss starts (see "Compaction"), the two fallback checks, and that skip_missing_blob_files returns NotSupported there.

### Reads

- A lost reference acts as a same-sequence point deletion, before any cache lookup. An iterator uses kTypeDeletionWithTimestamp when user-defined timestamps are on; Get and merges use kTypeDeletion. A reference to a dropped origin reads as deleted through the base dropped check.
- Every read path checks for loss before it fetches. A fetch that reaches a lost relocation file anyway returns Corruption, as base does for a dropped file.
- Get checks for loss after the range tombstone check, like the base dropped-file check. A key that a newer range tombstone covers is decided by the tombstone, so its value is not parsed and the read is not counted as a lost read.
- A wide-column entity loses only its lost blob columns, as with skip_missing_blob_files. It becomes a deletion only when every column is lost or dropped. An iterator runs the base dropped check on the entity after it removes the lost columns (DBIter::CheckDeletedByDroppedBlobFiles() reads the repaired entity from DBIter::CurrentValue()). So an entity whose blob columns are partly lost and partly dropped, with no other column, reads as deleted. Get on an entity whose default column is lost or dropped returns an empty value.
- Get, MultiGet, iterators (forward, reverse and with unprepared values) and merges use the base helper WideColumnSerialization::RemoveBlobColumns(), which MissingBlobRepairIterator also uses.
- The blob fetcher records, when it is made, whether its Version has lost files. DBIter and GetContext copy that bool when they are made, and MergeHelper::MergeUntil() reads it once per call. With no lost file, the read path pays one predictable branch for each entry and never reads the Version for the loss check. A tailing iterator keeps its fetcher after it drops its reference to that Version, so a flush can free the Version during a scan.
- Read-path range tombstone conversion (min_tombstones_for_range_conversion) never counts lost keys. A lost key ends a tombstone run like a live key, in both iteration directions, so a loss never becomes a real range tombstone.

### Compaction

- A compaction wraps its input in MissingBlobRepairIterator when the base gate or the loss gate holds. The loss gate is needed because flattened and routed references do not set oldest_blob_file_number, so an SST that holds only such references to a lost relocation file never matches the base gate. Without skip_missing_blob_files, the iterator uses MissingBlobRepairIterator::Mode::kDroppedOrLostFiles: it repairs references to dropped files (base) and lost references. skip_missing_blob_files is allowed only on a plain column family (see "skip_missing_blob_files guard") and keeps the base Mode::kMissingFiles.
- The loss gate is column-family wide: while the input Version has any lost relocation file, every compaction of that column family runs locally (bypassing DBOptions::compaction_service), repairs the references it reads, and writes exact reference metadata at every output level, including L0. Nothing schedules the compactions that rewrite the remaining holders, so this state lasts until compactions have rewritten every SST that references a lost file. The public comment of best_efforts_blob_db_repair recommends CompactRange() of the column family with bottommost_level_compaction set to kForce after an open that marks relocation files lost. With the default setting (kIfHaveCompactionFilter) and no compaction filter, CompactRange() does not rewrite the bottommost level by itself, so SSTs there can keep their references to the lost file, and the loss mode can stay. Universal compaction always rewrites in CompactRange().
- The reason for the L0 rule: a coarse SST records only its frontier, and it pins every generation number at or above the frontier. A lost relocation file stays pinned while an old number routed to it is at or above that frontier. So a coarse output could keep the lost file pinned, and the lost file would not be removed. In normal operation a coarse L0 input never holds a routed number (a flush references only its own new blob files), so the rule matters only for SSTs whose blob indexes were written directly, for example with WriteBatchInternal::PutBlobIndex().
- A lost reference becomes a same-sequence deletion (kTypeDeletionWithTimestamp when user-defined timestamps are on), also with snapshots or older keys below. A SingleDelete in the same compaction pairs with it as with skip_missing_blob_files.
- The compaction's input check (CompactionJob::ValidateBlobRelocationInputGenerations()) accepts a lost generation number (VersionStorageInfo::IsBlobGenerationLost()), because the repair iterator turns its references into deletions and the output never writes them. The same check already accepts a dropped origin without a route (10/14). The output checks do not accept a lost file. Remote output validation uses Version::ValidateBlobReferenceGeneration(), which returns NotFound for it. The install-time output check (CompactionJob::ValidateBlobRelocationOutputDependencies()) fails with Corruption when an output depends on a lost relocation file, also by the file's own number (a flattened reference), which its same-file rule would otherwise accept. The repair iterator removes such references first, so this check is only a safety net. A generation number that the input Version cannot resolve in any other way still fails the job with Corruption.
- CompactionIterator gets its own loss check: it reads HasBlobValueLoss() once (blob_value_loss_possible_, set in the constructor and in SetBlobFetcher()), and calls the out-of-line CheckBlobValueLoss() for each blob index or entity only when that bool is true; a lost value is treated as deleted but keeps its Put type (lost_blob_value_). It is for callers that give it a blob fetcher without the repair iterator (BuildTable() for flush and recovery). In a CompactionJob run this check finds no lost reference, because the repair iterator has already turned lost references into deletions. In a flush, its effect is that the compaction filter does not run on a lost blob index or on an entity whose blob columns are all lost, so the filter does not read the lost file for them and the flush does not fail. An entity with only some lost blob columns still reaches the filter, and a filter that reads its columns reads the lost one too. A flush meets a lost value only when a blob index or blob column was written directly into the memtable.
- When the census finds no holder of a lost relocation file, indirect blob GC deletes it as an empty input, without reading it (diff 9). The loss record leaves with the file record.

### Fallback checks

- Fallback in time past a GC edit: with best_efforts_blob_db_repair, a missing non-L0 SST can still make the open fall back to an older MANIFEST point. That point can be older than an indirect blob GC edit, so it names origins that GC already moved into a relocation file and deleted. Under the repair flag, base drops a blob file only when its data is gone from disk. A fallback past a GC edit would drop old origin files whose values are still on disk in a relocation file, and the purge at open would then delete that relocation file. So the open fails with Corruption instead. The check is VersionEditHandlerPointInTime::CheckRepairFallbackAgainstGc(). The message holds the column family ID and the file numbers. When this check fails, VersionSet::TryRecover() stops and does not try an older MANIFEST file: that file never saw the GC edit, so it would drop the same origins.
- Older MANIFEST file: when recovery from the newest MANIFEST file fails for another reason (for example, the file is empty), base best-efforts recovery tries an older MANIFEST file. That file does not know the indirect blob GC edits of the newer ones, so the check above cannot run. So if a repair open succeeds from an older MANIFEST file, and a column family with the format fence has dropped blob files or lost relocation files, the open fails with Corruption.
- Scope: the two checks cover a missing SST file, a missing or corrupt relocation file, and an older MANIFEST file. They cannot cover lost MANIFEST bytes. If the synced bytes of an indirect blob GC edit are cut off, no part of recovery sees the edit, and the open treats the point before it as the newest state; it then deletes the relocation file as an unknown file. Base RocksDB has the same limit for any edit whose synced bytes are lost (for example, the outputs of a compaction whose input files were already deleted), so this case is out of scope.
- Plain best_efforts_recovery (without the repair flag) never marks a file lost. With a missing relocation file, VersionBuilder refuses the Version, and recovery goes back to an earlier consistent point or fails, as for a missing SST. A read-only open with plain best_efforts_recovery can still fall back to an older MANIFEST file, as in base RocksDB.

### Open check

Every read-write or read-only open checks that each relocation file that is not marked lost exists in its canonical path (the first cf_path of its column family), before any column family is visible. An open with best_efforts_recovery or best_efforts_blob_db_repair skips this check. If one is missing, the open fails with NotFound. The message names the file path, its number and the column family. It says to restore the file, or to open once with best_efforts_blob_db_repair, and that such an open reads the lost values as deleted and does not replay the WAL. The check compares with a directory listing instead of calling FileExists per file. A read-write open reuses the listing that MaybeUpdateNextFileNumber() already makes of every DB path, so the check runs after it, still before WAL replay. A read-only open lists each needed path once.

Only relocation files get this check. Normal and origin blob files keep the behavior of base RocksDB, which does not check blob files at open: a missing one fails only the reads of its values until a repair open drops it. The check runs whether or not paranoid_checks is set, and it checks only that the file exists: a truncated relocation file fails the reads of its values, and a repair open marks it lost.

### skip_missing_blob_files guard

skip_missing_blob_files returns NotSupported on a column family that may hold blob indirection references: the option is on, an enabled flush or compaction may still publish the first format fence, or the per-CF fence is set. CompactRangeInternal() checks before any work. RunManualCompaction() checks again with the picked compaction's options and input Version, and it releases its inputs if rejected. Plain column families keep the base path.

### Monitoring

- BLOB_DB_LOST_BLOB_READ_COUNT (ticker) counts entries that reads treat as deleted, or as wide-column entities with missing columns, because their values are in a lost relocation file. A point read counts only the entry that decides its result. An iterator counts every such entry that it reads, also hidden older versions, entries newer than its snapshot and entries past its bounds, and it can count an entry again when it moves back to it.
- rocksdb.blob-relocation-lost-files (DB::Properties::kBlobRelocationLostFiles, an int property) and the new map key lost-relocation-files of rocksdb.indirect-blob-gc-stats return the number of relocation files of the column family that are marked lost.
- An open with best_efforts_blob_db_repair logs one ERROR line per column family that has lost relocation files (VersionSet::LogDroppedBlobFiles()), also for files that an earlier open marked lost: "Lost blob relocation files after best-efforts BlobDB repair (their values read as deleted): count N, files #a #b ... and K more". The line names at most kMaxLoggedLostFileNumbers (16) files, so it stays short. The property has the count. ldb manifest_dump prints the count, and ldb manifest_dump --verbose prints each loss record (BlobPhysicalFileLoss) with its file number.
- LogDroppedBlobFiles() runs at the end of VersionSet::TryRecover(), after the older-MANIFEST check. So an open that fails that check does not log files as lost or dropped. The WARN line for dropped blob files of base keeps its text.
- Feature off: only a column family with blob indirection can have lost relocation files, so the ticker does not change and the count is 0.

## Implementation

The essential choices, and why they are enough:
- Mark, do not drop. A lost relocation file stays in the Version with a loss mark, so every route to it stays valid and every holder still names a known file. The reasons are in "Background".
- One loss check before every fetch. VersionStorageInfo::IsBlobReferenceLost() follows the route of the generation number and checks the loss mark. The blob fetcher caches whether its Version has any lost file, and the read paths copy that bool, so a DB without a loss pays one predictable branch per entry and no Version read.
- Repair through the base repair iterator. The loss gate makes compaction use MissingBlobRepairIterator in the new mode kDroppedOrLostFiles, so lost and dropped references follow the base rules for deletions, SingleDelete pairs and partial entities.
- Accept a lost file only where it is repaired. The compaction input check accepts a lost generation number; the output checks still reject it.
- Fail instead of losing data. The two fallback checks stop a repair open that would drop origin files whose values a relocation file on disk still holds.

## Also in this diff

- The public comment of RepairDB in include/rocksdb/db.h says that RepairDB does not support a DB that has blob indirection data. When it finds such data, it returns NotSupported and does not change the DB (the RepairDB guard of diff 4).
- db_bench gets the flags --enable_blob_indirection, --blob_indirection_max_references_per_sst, --indirect_blob_gc_read_coalesce_bytes and --indirect_blob_gc_garbage_ratio. Until the option gate goes away in 14/14, an open with --enable_blob_indirection fails with NotSupported.
- A release note (unreleased_history) describes the new enum values BlobFileCreationReason::kIndirectBlobGC, TableReaderCaller::kBlobRelocationFileRead and the cache entry roles CacheEntryRole::kBlobReferenceMetadataBuildingBuffer, kBlobReferenceCensus and kIndirectBlobGcWorkingMemory. The release note that announces the option and its monitoring comes with 14/14.
- The comment of enable_blob_indirection in include/rocksdb/advanced_options.h names the new L0 rule for outputs while a relocation file is lost.

## Changes visible to existing users

- A DB that never uses blob indirection has no lost relocation file. Its reads pay one predictable branch per entry in DBIter::ParseKey() and per matched blob or entity entry in GetContext::SaveValue(), and MergeHelper::MergeUntil() reads the bool once per call. DBIter keeps two more std::string members (empty unless a file is lost).
- Compaction and flush pay one predictable branch per blob index or entity (blob_value_loss_possible_, fixed for the job) and a few predictable tests of lost_blob_value_ per key. While a file is lost, a compaction checks each blob entry twice: once in the repair iterator and once in CompactionIterator.
- With best_efforts_blob_db_repair, the WARN line for dropped blob files is logged at the end of VersionSet::TryRecover() instead of after each MANIFEST file that recovery reads. The text is the same, and an open that succeeds logs it once, as before.
- skip_missing_blob_files returns NotSupported only for a column family with blob indirection. Plain column families keep the base behavior.

## Safety, compatibility and limitations

- Persisted data: this diff adds no MANIFEST tag. Diff 4 added the loss record (kBlobPhysicalFileLoss) as a required tag (not under kTagSafeIgnoreMask), so a binary that does not know it fails to open the MANIFEST instead of ignoring the loss. Such a binary also fails on the format fence. In this diff, only a test can turn on blob indirection, so only tests write the loss record; production can write it from 14/14 on.
- Public API: new ticker BLOB_DB_LOST_BLOB_READ_COUNT, appended before TICKER_ENUM_MAX, and new property rocksdb.blob-relocation-lost-files. The new ticker has no Java mapping, as for recent base tickers: all 256 byte values of org.rocksdb.TickerType are used.
- No live repair API: only a repair open marks files lost or dropped. It marks a missing or corrupt relocation file lost, and, as in base, it records a missing or corrupt normal or origin blob file as dropped.
- Legacy kBlobIndex references keep base behavior: a repair open drops a missing legacy blob file, and skip_missing_blob_files repairs it on a plain column family.
- A lost Put repaired into a Delete makes a later SingleDelete of that key fail with Corruption when they meet in compaction (enforce_single_del_contracts). Base skip_missing_blob_files behaves the same.
- Loss repair compaction runs locally, not on a remote compaction service. This is a conservative choice: a worker reads the loss records from the MANIFEST and could repair the references itself, but the primary does not check a worker's result for that.
- One lost file puts the whole column family into loss mode (see "Compaction"). Possible follow-ups, not planned yet: mark the SSTs that reference a lost file for compaction, using the census, or a per-input loss gate.
- When a Version has a loss record, a tailing iterator reads that Version again for each blob key. A flush can free that Version during the scan (see "Reads"), so the read can touch freed memory. Base RocksDB has the same problem when it fetches a blob value. This diff does not fix it.
- A lost file is removed only after compactions have rewritten all its holders. Automatic compactions may never rewrite some of them, so the user should run CompactRange() with bottommost_level_compaction set to kForce (see "Compaction").
- The fallback checks do not cover lost synced MANIFEST bytes (see "Fallback checks").
- The two fallback checks can fail a repair open in rare cases where nothing new would be lost:
  - The older MANIFEST file check fails when that file holds drops that an earlier repair open already recorded.
  - The check against indirect blob GC edits fails for an origin that GC retired with no route.
  - Both checks can fail for a relocation file that an earlier loss record marked lost and that GC later removed. Its values were already lost.
  A plain best_efforts_recovery open (without best_efforts_blob_db_repair) is the workaround.

## Validation and known limitations

Unit tests cover the repair open, the read paths, loss repair compaction, the fallback checks, the open check and the skip_missing_blob_files guard (see the Test Plan). The tailing iterator test covers only a Version without a loss; the tailing iterator limitation above is known and not fixed here. The crash test does not reach loss repair: the crash test never deletes blob files, and skip_missing_blob_files is rejected on column families with blob indirection.

## Stack context

[Blob GC] 2/14, section "Stack context", has the goal of the stack, the read and lifecycle diagrams and the stack map. This diff is row 13 of the map: "Lost relocation files".

Tracking issue: meta#15301

 ---

Differential Revision: D132305446

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant