Skip to content

Cover burned WAL indices with a void record (#15223) - #15223

Open
JustinGaoF wants to merge 7 commits into
meta:mainfrom
JustinGaoF:export-D119751506
Open

JustinGaoF wants to merge 7 commits into
meta:mainfrom
JustinGaoF:export-D119751506

Conversation

@JustinGaoF

@JustinGaoF JustinGaoF commented Sep 16, 2026 •

Copy link
Copy Markdown

Summary:

Closes the burned-index hole recorded by the TODO(justingao) in log_writer.cc.

DBImpl::AllocateSequenceAndWALIndex consumes a wal_index inside its critical section, but the append happens later in log::Writer::AddRecord. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

Every allocated wal_index is on a data record, or under a void record covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types kWALIndexVoidType (22) and kRecyclableWALIndexVoidType (23) carry a closed range as fixed64 lo | fixed64 hi, so a burst of burns costs one record. Both stay below kRecordTypeSafeIgnoreMask with their own static_assert, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

Writer::AddWALIndexVoidRecord mirrors MaybeAddWALIndexMarkerRecord. It deliberately does not advance last_wal_index_recorded_ and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave last_read_wal_index_ alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

DBImpl::CoverBurnedWALIndex is called on every path where an index was allocated and the append did not reach disk: WriteImpl, PipelinedWriteImpl, and ConcurrentWriteGroupToWAL. The last is unreachable today (two_write_queues is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in db_impl_open.cc is a documented exception: a failure there fails Open(), so the DB never becomes writable and nothing can be acknowledged above the hole.

Worth knowing for review -- this is the third clause above: at kWALIndexSingleFile an IO error can never be covered. The error poisons the WritableFileWriter, so MaybeHandleSeenFileWriterError fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, PrepareIOOptions, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at ERROR, rather than being incidental.

The ordering rule for the future durability watermark is recorded on AllocateSequenceAndWALIndex and not implemented here: a failed append leaves its entry in pending_low[p], and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of MergeBatch and PrepareIOOptions above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of next_wal_index_, and kWALIndexPartitionByColumnFamily.

M1: Absorbs GC02 Q1: CoverBurnedWALIndex early return + cover comment + log::Writer::last_wal_index_recorded() (its test lives in D123701876).

Differential Revision: D119751506

@meta-codesync

meta-codesync Bot commented Sep 16, 2026

Copy link
Copy Markdown

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

JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 16, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

Differential Revision: D119751506
@meta-codesync meta-codesync Bot changed the title Cover burned WAL indices with a void record Cover burned WAL indices with a void record (#15223) Sep 16, 2026
@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

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

Completed in 1550.9s.

Summary by check

Check Count
performance-inefficient-string-concatenation 1
Total 1

Details

test_util/testutil.cc (1 warning(s))
test_util/testutil.cc:613:42: warning: string concatenation results in allocation of unnecessary temporary strings; consider using 'operator+=' or 'string::append()' instead [performance-inefficient-string-concatenation]

JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 17, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

Differential Revision: D119751506
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 17, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

Differential Revision: D119751506
@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit 7308133


Summary

Well-designed addition establishing the WAL index void record mechanism for burned indices. The three-clause invariant is sound, the record type layout is well-reasoned, and the coverage of all write paths is thorough. The static_asserts for downgrade safety and the HeaderSelectionUnchangedForPreWALIndexTypes compile-time check are particularly good defensive measures.

High-severity findings (1):

  • [db/log_reader.cc] Checksum handling for WAL-indexed Full records differs from the non-indexed path: the non-indexed path has special handling for uncompress_ == nullptr, but the indexed path always recomputes via MaybeStripAndVerifyWALIndex without checking compression state, potentially producing mismatched checksums when WAL compression is enabled alongside WAL indexing.
Full review (click to expand)

Findings

🔴 HIGH

H1. WAL compression + WAL index checksum interaction — db/log_reader.cc
  • Issue: The existing kFullType/kRecyclableFullType case computes record_checksum only when uncompress_ == nullptr (line 113 of existing code). The new kWALIndexFullType case calls MaybeStripAndVerifyWALIndex() which unconditionally recomputes *record_checksum = XXH3_64bits(record->data(), record->size()) when record_checksum != nullptr. With WAL compression enabled, the physical-record-level decompression already produces a fragment_checksum through uncompress_hash_state_, and the existing code relies on that rather than recomputing at the logical record level. The indexed path's unconditional recomputation may produce a correct checksum (since it hashes the stripped payload), but it skips the decompression integrity check that the uncompressed path performs and may conflict with the caller's expectations if compressed fragment checksums were already accumulated.
  • Root cause: MaybeStripAndVerifyWALIndex does not account for the uncompress_ path's different checksum flow.
  • Suggested fix: Either (a) reject WAL compression + WAL index at ValidateOptions (simplest), or (b) make MaybeStripAndVerifyWALIndex compression-aware, mirroring the existing uncompress_ == nullptr guard. The test suite does not include a compressed + indexed WAL test, so this interaction is unverified.

🟡 MEDIUM

M1. unordered_write + WAL index is silently allowed but untested — db/db_impl/db_impl_open.cc
  • Issue: The diff validates against two_write_queues but not unordered_write. ConcurrentWriteGroupToWAL runs for both (assert(two_write_queues_ || immutable_db_options_.unordered_write) at db_impl_write.cc:2431). The diff correctly adds WAL index support to ConcurrentWriteGroupToWAL, and the cover path works, so this is not a correctness bug. However, unordered_write with WAL index is entirely untested — no unit test and no db_stress coverage.
  • Suggested fix: Either add explicit validation rejecting the combination (and a test for the rejection), or add test coverage for unordered_write + WAL index. The PR description's comment "The last is unreachable today" is slightly misleading since unordered_write reaches it.
M2. AddRecord signature change uses defaulted wal_index parameter — db/log_writer.h
  • Issue: The diff (truncated, but implied by test code writer_->AddRecord(WriteOptions(), Slice(msg), /*seqno=*/0, wal_index)) adds a uint64_t wal_index parameter. CLAUDE.md explicitly says "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" If wal_index defaults to 0, existing callers (MANIFEST writes in version_set.cc at 8+ call sites, wal_manager_test, checkpoint_test) continue to compile but silently pass 0. Since WALIndexEnabled() guards the writer-side logic and the MANIFEST writer never calls SetPartitionWALUsage, this is safe today, but the defaulted parameter pattern is fragile — a future caller that forgets to pass the index gets no compile-time error.
  • Suggested fix: Consider an overload rather than a default, or verify all callers explicitly pass the parameter.
M3. Missing option infrastructure — diff is truncated
  • Issue: The diff shows 28 files changed but the provided diff is truncated. Per CLAUDE.md's add_option.md checklist, a new DB option requires: options_settable_test.cc, options_helper.cc/db_options.cc registration, db_stress support, db_bench support, db_crashtest.py, and release notes. The C API (c_api_gen/) is present, but it's unclear whether the other files are included in the full PR. If any are missing, CI will fail.
  • Suggested fix: Verify the full PR includes all files from the option checklist.
M4. next_wal_index_ is not seeded from recovery — db/db_impl/db_impl.h:3413
  • Issue: next_wal_index_ starts at kWALIndexStartNumber on every Open(). The test WALIndexNumberingRestartsAcrossLiveWALs explicitly documents this as a known limitation. Two live WAL files from different sessions can have overlapping index values. The PR description says "Out of scope: recovery seeding of next_wal_index_" — acceptable as long as gap detection (future) accounts for it.
  • Suggested fix: Consider adding a TODO comment on next_wal_index_ initialization noting the recovery seeding requirement for gap detection.
M5. AllocateSequenceAndWALIndex catch-up race with WriteRecoverableState — db/db_impl/db_impl_write.cc
  • Issue: AllocateSequenceAndWALIndex reads versions_->LastSequence() and advances LastAllocatedSequence if it trails. WriteRecoverableState() (at line 2495) advances last_sequence_ directly under mutex_ + optionally wal_write_mutex_. The race is prevented by write thread serialization, not by the mutex. Correct but fragile.
  • Suggested fix: Add a comment in AllocateSequenceAndWALIndex noting the reliance on write thread serialization for the catch-up safety.

🟢 LOW / NIT

L1. hash_state_ not reset by void record in Reader — db/log_reader.cc
  • Issue: The void record case sets in_fragmented_record = false and clears scratch, but does not reset hash_state_ when record_checksum != nullptr. The marker case does (XXH3_64bits_reset(hash_state_)). This asymmetry means a void record interrupting a fragmented record with checksum tracking leaves stale hash state. Not a functional bug (next First record resets it), but inconsistent.
  • Suggested fix: Add XXH3_64bits_reset(hash_state_) in the void record case for consistency.
L2. Void record lo > hi is not validated — db/log_writer.cc (implied)
  • Issue: AddWALIndexVoidRecord takes lo and hi parameters. No validation that lo <= hi is visible.
  • Suggested fix: Add assert(lo <= hi) in AddWALIndexVoidRecord.
L3. DecodeWALIndices test helper assumes no block-boundary padding — db/log_test.cc
  • Issue: The helper walks the WAL image by summing header + payload sizes. If a block boundary causes padding, the walk misaligns. Only works for small payloads fitting in one block.
  • Suggested fix: Add a comment noting the single-block assumption.
L4. Missing test coverage for WAL compression + WAL index — db/db_wal_test.cc
  • Issue: No test exercises WAL compression with WAL index enabled. This is the scenario that H1 flags.
  • Suggested fix: Either add a test or reject the combination.
L5. Missing test for FragmentBufferedReader with WAL index — db/log_test.cc
  • Issue: The log_test.cc tests use Reader (the standard reader). FragmentBufferedReader is separately implemented with parallel changes. While the code changes mirror each other, there are no dedicated tests for the buffered reader's handling of WAL index types.
  • Suggested fix: Add at least one round-trip test using FragmentBufferedReader to verify marker, void, and indexed record handling.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
WritePreparedTxnDB NO (two_write_queues rejected) N/A Safe
WriteUnpreparedTxnDB NO (two_write_queues rejected) N/A Safe
ReadOnly DB NO (no writes) N/A Safe
unordered_write YES (not rejected) YES (allocation + cover work) Test coverage needed (M1)
User-defined timestamps YES (orthogonal) YES Safe
WAL compression YES (not rejected) UNCERTAIN (H1) Validate or reject
WAL recycling YES (recyclable types 18-21, 23) YES Safe
PipelinedWriteImpl YES (tested) YES Safe
External file ingestion YES (tested) YES Safe
Manual WAL flush YES YES (cover inherits durability) Safe

Positive Observations

  • The static_assert chain ensuring WAL index types stay below kRecordTypeSafeIgnoreMask is excellent defensive design
  • HeaderSelectionUnchangedForPreWALIndexTypes compile-time check prevents silent regressions to record header selection
  • The three-clause invariant is clearly stated with the terminal case explicitly documented
  • The ConcurrentWriteGroupToWAL cover path is added proactively even for currently-unreachable paths
  • NoWALIndexIsLostWhenAppendFails verifies the completeness property (union of data + void = contiguous run)
  • Both Reader and FragmentBufferedReader are consistently updated with identical handling for all new types

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

JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Oct 7, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

Differential Revision: D119751506
Summary:
Pull Request resolved: meta#15219

Defines the `PartitionWALUsage` enum and plumbs `DBOptions::partition_wal_usage` through the options machinery. This is the API surface for per-record WAL ordering numbers; no WAL format code and no on-disk change yet.

The enum has three values. Every value other than `kNone` prefixes each WAL record with a persisted monotonically increasing ordering number, so they share one on-disk format change and differ only in WAL layout:

- `kNone` (0x00) -- disabled, WAL stays bit-for-bit compatible with older versions.
- `kRecordOrderingSingleFile` (0x01) -- records carry an ordering number, WAL layout unchanged. Isolates the format change from any routing change so the two roll out separately.
- `kPartitionByColumnFamily` (0x02) -- reserved for partitioning WALs by column family. Not implemented, and `DBImpl::ValidateOptions` now rejects it with `NotSupported` **in this diff** rather than in a later one, so no revision of the tree ever accepts an option value it cannot honor. Without that, the value would be accepted and inert here, and once the writer diffs land it would silently mean "ordering numbers, no partitioning".

Why three values rather than a boolean: they are a rollout ladder, not a taxonomy. `kRecordOrderingSingleFile` exists to be the middle rung -- it turns on the persisted on-disk format change while leaving WAL routing untouched, so the format can bake in production before any routing behavior changes. A boolean cannot express that: "partitioned or not" forces the format change and the routing change to ship as one flip, which is precisely the rollout risk the middle rung removes. `kPartitionByColumnFamily` is the top rung, and rejecting it until it works keeps the ladder from ever exposing a rung that is accepted but inert.

The value names describe observable behavior rather than the mechanism: `wal_index` stays the internal term for the ordering number, in implementation code and in the WAL record format, but it no longer appears in the public enum. Nothing has shipped, so there are no compatibility aliases for the previous spellings (`kWALIndexSingleFile`, `kWALIndexPartitionByColumnFamily`).

Documentation: the `partition_wal_usage` field comment and the `PartitionWALUsage` enum contract disagreed -- the field comment said a non-`kNone` value also tags the WAL file with an identifying marker record, which the enum's own documentation never mentioned. The on-disk contract now lives in one place, the enum header comment, and the field comment points at it instead of restating it.

Wiring: the field on `DBOptions` (default `kNone`) and `ImmutableDBOptions`, propagation in `BuildDBOptions`, registration via `OptionTypeInfo::Enum` against `GetPartitionWALUsageStringMap()`, the copy constructor, and `ROCKS_LOG_HEADER`. The string map accepts six keys -- a `kFoo` and a `snake_case` spelling for each of the three values -- so OPTIONS files and the tooling flags all parse through one table.

`BuildDBOptions` propagation is easy to miss: `partition_wal_usage` lives only in `ImmutableDBOptions`, and `options_settable_test`, which would otherwise catch a missing assignment, is compiled out under clang.

Differential Revision: D118367634
Summary:
Pull Request resolved: meta#15220

Adds the WAL index record types to the log format. Header-only; no writer, reader or on-disk change yet.

Marker types `kWALIndexMarkerType` (12) and `kRecyclableWALIndexMarkerType` (13) tag a file as carrying per-record ordering numbers. Indexed data record types `kWALIndexFullType`..`kRecyclableWALIndexLastType` (14-21) mirror the existing full/first/middle/last set, with a recyclable twin for each, so every existing record shape has an indexed counterpart. Each fragment is self-describing: the marker is not required to decode a record, and the marker itself carries no payload.

Also adds `IsWALIndexRecordType`, extends `IsRecyclableRecordType` to cover the new recyclable types, and defines `kWALIndexSize = 8` for the fixed64 prefix.

All new types stay below `kRecordTypeSafeIgnoreMask`, which is what makes indexed WALs fail closed: an older binary must reject an indexed record rather than silently ignore it and report success. A `static_assert` naming all ten WAL index types enforces that, so renumbering any of them into the ignorable range breaks the build instead of turning into silent data loss.

Differential Revision: D118369740
Summary:
Pull Request resolved: meta#15221

Teaches `log::Writer` to emit WAL index records. The writer does not allocate the index — it receives one from the caller and encodes it. Allocation lands in a later diff, where the sequence number is also assigned.

`SetPartitionWALUsage` turns indexing on for a writer; `WALIndexEnabled` reports it. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries **no payload** — the record type alone identifies the file, and its value is positional: it is the first record, so an older binary fails on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the matching indexed record type via `SelectRecordType`. Because the index counts as part of the record's payload for checksum and fragmentation, it survives both. Debug asserts enforce that indices are strictly increasing and sequence numbers non-decreasing per writer; a zero index with indexing enabled is rejected outright.

The uncompressed path passes the index to `EmitPhysicalRecord` as a **separate 8-byte prefix**, so the caller's payload is never copied. Compression still requires one contiguous input, so that path keeps the joined buffer. `wal_compression` defaults to `kNoCompression`, so the common path avoids the allocation and the full write-batch copy. On-disk bytes, record boundaries and checksums are identical either way.

`EmitPhysicalRecord` now selects the header size via `IsRecyclableRecordType` rather than a hand-maintained whitelist. With indexing disabled the output is byte-identical to before, and a `static_assert` in the tests pins that by checking the new predicate agrees with the old whitelist on every pre-existing record type.

One hazard is documented rather than fixed: a failed append burns an allocated index. Harmless until a completeness check exists; the `TODO` names the two remedies.

Measured on the no-copy path, with the full stack applied so `db_bench` can drive it — `--benchmarks=fillseq --partition_wal_usage=wal_index_single_file --wal_compression=none --compression_type=none --disable_auto_compactions=true --threads=1`, medians of 3 runs on one AMD EPYC-Genoa host, ~512 MiB written per run:

| Value size | Entries | Copying prefix | Separate prefix | Latency change |
| 64 KiB | 8,192 | 224.908 us/op, 4,445 ops/s | 215.764 us/op, 4,628 ops/s | -4.1% |
| 1 MiB | 512 | 2,813.432 us/op, 355 ops/s | 2,373.035 us/op, 421 ops/s | -15.7% |

Differential Revision: D118369607
Summary:
Pull Request resolved: meta#15222

Teaches `log::Reader` and `FragmentBufferedReader` to decode WAL index records.

`MaybeStripAndVerifyWALIndex` extracts the leading fixed64 into `last_read_wal_index_`, strips it from the record, and recomputes the logical-record checksum over the stripped payload so upper layers see the same bytes and checksum they would without indexing. It reports corruption if a record's type claims an index but the payload is too short to hold one, and clears the index for records that carry none, so `GetLastReadWALIndex()` always describes the record just returned.

**There is no gap or continuity checking here, deliberately.** wal_index is consecutive across the WAL partition as a whole, not within any single file, so a jump between successive records in one file is normal. Treating it as a gap would be a false positive, and the response to a detected gap is truncation — so the detector is left out until the sequence-to-index correlation it would depend on is resolved.

Decoding is driven purely by the record type at all eight dispatch sites in both readers, so a file may hold indexed and plain records and each is handled on its own terms. The marker record is not required to decode anything; it is only checked for position, reporting corruption if it appears after a data record, matching how `kSetCompressionType` is handled. `ReadPhysicalRecord` selects header size via `IsRecyclableRecordType`, and `FragmentBufferedReader` tracks whether the in-progress fragmented record is indexed so mismatched fragment types are reported.

Exposes one accessor, `GetLastReadWALIndex()`. Per-record state, zero when the record carried no index.

Differential Revision: D118369608
Summary:
Pull Request resolved: meta#15226

Makes `DBImpl` the owner of WAL index allocation, and wires indexing into the write path.

WAL recovery treats `wal_index` order as the durable proxy for sequence-number order. Allocating the two with independent atomics lets concurrent partition writers reverse those orders, so truncating an index prefix could leave an undetectable hole in sequence space. `AllocateSequenceAndWALIndex` reserves the sequence block and, when a WAL record will be written, its `wal_index`, under one short DB-wide `InstrumentedMutex`. The assigned index is then passed into `log::Writer::AddRecord`.

A mutex was chosen over a 16-byte atomic so the future durability-watermark `RegisterPending` can join the same critical section. The lock covers only counter updates — batch merging, WAL append, compression, sync and all other I/O stay outside it. The `kNone` path never takes it. An exhausted counter fails the write inside the lock rather than wrapping, since wrapping would break the monotonicity ordering depends on.

Also binds `SetPartitionWALUsage` on each newly created WAL writer and emits the marker from `StartWALFile`, so both WAL-creation paths — DB open and WAL switch — are covered by one call site.

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. (`kPartitionByColumnFamily` is also rejected at `DB::Open`, but that rejection now lands with the enum itself in D118367634 rather than here, so no revision of the tree accepts a value it cannot honor.)

The counter is **not** restored across restarts — it starts at `kWALIndexStartNumber` on every open, so indices are unique among WALs written by one process, not for all time. This is reachable with plain writes rather than only in theory: any write after a reopen starts a second live WAL numbering from `kWALIndexStartNumber` again, and `WALIndexNumberingRestartsAcrossLiveWALs` pins that state so a future fix has to change the test deliberately. Harmless while nothing consumes the index; to be resolved before anything does.

The burned-index window from the diff below is wider here, because allocation now precedes write-group merging and payload preparation rather than happening inside `AddRecord`. It still spans no additional I/O, and the existing `TODO` continues to track it.

Differential Revision: D119600943
…#15227)

Summary:
Pull Request resolved: meta#15227

Exposes `partition_wal_usage` in the tooling. No production behaviour change — everything it drives was built in the diffs below.

Adds `--partition_wal_usage` to db_bench and db_stress, and randomises it in db_crashtest between `none` and `wal_index_single_file`. Both tools parse the flag through `GetDBOptionsFromString` rather than a private string table, so they accept exactly what `DBOptions` accepts and cannot drift from it as values are added.

Adds the release note: indexed WALs are fail-closed for older binaries, and rolling back means setting `kNone`, flushing every column family so indexed WALs become obsolete, waiting for those files to be deleted, then downgrading.

Also adds the compressed-path coverage that needs the whole feature working end to end.

Differential Revision: D118371518
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

M1: Absorbs GC02 Q1: `CoverBurnedWALIndex` early return + cover comment + `log::Writer::last_wal_index_recorded()` (its test lives in D123701876).

Differential Revision: D119751506
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 10, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is unreachable today (`two_write_queues` is rejected alongside indexing) but is covered rather than asserted, so enabling it later cannot silently reintroduce a hole. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** at `kWALIndexSingleFile` an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (assert plus comment) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and `kWALIndexPartitionByColumnFamily`.

M1: Absorbs GC02 Q1: `CoverBurnedWALIndex` early return + cover comment + `log::Writer::last_wal_index_recorded()` (its test lives in D123701876).

Test Plan:
No existing test needed edits. The byte-layout tests (`WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`) pass unmodified, so WAL bytes on the success path are unchanged at every `partition_wal_usage` value.

New in `db/log_test.cc`, parameterised over recycling x retry-read so both readers are covered:

- `WALIndexVoidRecordByteLayout` -- record type, payload length, and decoded `[lo, hi]` asserted on the raw bytes.
- `WALIndexVoidRecordIsSkipped` -- the void record is not returned as a logical record and does not disturb `GetLastReadWALIndex()` on either side.
- `WALIndexVoidRecordMayTrailTheHighWaterMark` -- a cover behind the mark is accepted and does not move it.
- `WALIndexVoidInsidePartialRecordReportsCorruption` -- a void interrupting a fragmented record reports corruption and abandons the record.
- `CompressionLogTest.WALIndexVoidRecordIsNotCompressed` -- on a compressed WAL the void payload is still plain bytes: the record is located in the file and its `[lo, hi]` decoded directly, and the data records either side still round-trip. `AddWALIndexVoidRecord` bypasses the compressor the way the marker does and the reader's metadata allowlist keeps it out of decompression, so this pins behaviour that was previously only exercised incidentally by a crashtest that happened to draw `zstd`.

New in `db/db_wal_test.cc`:

- `BurnedWALIndexIsCovered` -- an append that fails after allocation produces a void record covering exactly the burned index.
- `NoWALIndexIsLostWhenAppendFails` -- the union of indices on data records and indices under covers is exactly the contiguous run the allocator handed out.
- `UncoveredWALIndexFailsSubsequentWrites` -- with `FaultInjectionIOType::kWrite` the cover fails too; the write and the next write both return errors, and no data record above the burned index reaches the WAL.
- `DefaultUsageWritesNoVoidRecords` -- `kNone` emits no void record even when a write fails.

Each new corruption/fallback test was verified to fail without the code it covers:

```
# CoverBurnedWALIndex neutered to write nothing
BurnedWALIndexIsCovered       expected { (17, 17) }  actual {}
NoWALIndexIsLostWhenAppendFails  expected { 1..17 }  actual { 1..16 }

# Reader void fragment handling neutered
WALIndexVoidInsidePartialRecordReportsCorruption/0 and /2 FAILED
(/1 and /3 still pass -- FragmentBufferedReader has its own branch)
```

```
$ buck2 run fbcode//internal_repo_rocksdb/repo:log_test
[==========] 339 tests from 4 test suites ran.
[  PASSED  ] 339 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:db_wal_test -- --gtest_filter='DBWALIndexTest.*'
[==========] 13 tests from 1 test suite ran.
[  PASSED  ] 13 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:options_test
[==========] 80 tests from 6 test suites ran.
[  PASSED  ] 80 tests.
```

One `db_crashtest` run with indexing forced on and the queues off. It happened to draw `zstd` WAL compression, which exercises the compressed branch of the burn window:

```
$ python3 db_crashtest.py blackbox --partition_wal_usage=wal_index_single_file \
    --two_write_queues=0 --duration=180 --interval=30 \
    --max_key=10000 --ops_per_thread=20000
WAL compression           : zstd
(Re-)verified 5417 unique IDs
Crash-recovery verification passed :)
[exited with code 0]
```

`arc lint -a` on all nine changed files -- no issues. clang-format clean.

M1: covered by tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; db_wal_test + log_test: 2340 pass.

M5 fold: Absorbs 1 A.1 entry (GC27 1): GC27 Q9 (d) void writer returns Corruption.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_wal_test, log_test); 2340 tests, 0 failed.

Reviewers: xbw, rajivharlalka, huixiao, taopeng, dyao, rbanerjee2, #rocksdb, kinbertchou, anand76

Subscribers: jewoongh, rbanerjee2, anand76

Differential Revision: https://phabricator.intern.facebook.com/D119751506
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is reached by `unordered_write` writes through `WriteImplWALOnly` (only `two_write_queues` is rejected alongside indexing), and it writes the cover with `wal_write_mutex_` already held. With `manual_wal_flush`, the other two paths take `wal_write_mutex_` for the cover, as `WriteToWAL` does, so an application `FlushWAL` cannot interleave with it. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** with one WAL file at a time an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (a comment in `CoverBurnedWALIndex`, which also logs whether the writer had already failed) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and writing more than one WAL file at a time.

M1: Absorbs GC02 Q1: `CoverBurnedWALIndex` early return + cover comment + `log::Writer::last_wal_index_recorded()` (its test lives in D123701876).

Test Plan:
No existing test needed edits. The byte-layout tests (`WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`) pass unmodified, so WAL bytes on the success path are unchanged at every `partition_wal_usage` value.

New in `db/log_test.cc`, parameterised over recycling x retry-read so both readers are covered:

- `WALIndexVoidRecordByteLayout` -- record type, payload length, and decoded `[lo, hi]` asserted on the raw bytes.
- `WALIndexVoidRecordIsSkipped` -- the void record is not returned as a logical record and does not disturb `GetLastReadWALIndex()` on either side.
- `WALIndexVoidRecordMayTrailTheHighWaterMark` -- a cover behind the mark is accepted and does not move it.
- `WALIndexVoidInsidePartialRecordReportsCorruption` -- a void interrupting a fragmented record reports corruption and abandons the record.
- `CompressionLogTest.WALIndexVoidRecordIsNotCompressed` -- on a compressed WAL the void payload is still plain bytes: the record is located in the file and its `[lo, hi]` decoded directly, and the data records either side still round-trip. `AddWALIndexVoidRecord` bypasses the compressor the way the marker does and the reader's metadata allowlist keeps it out of decompression, so this pins behaviour that was previously only exercised incidentally by a crashtest that happened to draw `zstd`.

New in `db/db_wal_test.cc`:

- `BurnedWALIndexIsCovered` -- an append that fails after allocation produces a void record covering exactly the burned index.
- `BurnedWALIndexCoverHoldsWALMutexWithManualFlush` -- with `manual_wal_flush`, a concurrent `FlushWAL` waits until the cover has been written.
- `NoWALIndexIsLostWhenAppendFails` -- the union of indices on data records and indices under covers is exactly the contiguous run the allocator handed out.
- `UncoveredWALIndexFailsSubsequentWrites` -- with `FaultInjectionIOType::kWrite` the cover fails too; the write and the next write both return errors, and no data record above the burned index reaches the WAL.
- `DefaultUsageWritesNoVoidRecords` -- `kNone` emits no void record even when a write fails.

Each new corruption/fallback test was verified to fail without the code it covers:

```
# CoverBurnedWALIndex neutered to write nothing
BurnedWALIndexIsCovered       expected { (17, 17) }  actual {}
NoWALIndexIsLostWhenAppendFails  expected { 1..17 }  actual { 1..16 }

# Reader void fragment handling neutered
WALIndexVoidInsidePartialRecordReportsCorruption/0 and /2 FAILED
(/1 and /3 still pass -- FragmentBufferedReader has its own branch)
```

```
$ buck2 run fbcode//internal_repo_rocksdb/repo:log_test
[==========] 339 tests from 4 test suites ran.
[  PASSED  ] 339 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:db_wal_test -- --gtest_filter='DBWALIndexTest.*'
[==========] 13 tests from 1 test suite ran.
[  PASSED  ] 13 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:options_test
[==========] 80 tests from 6 test suites ran.
[  PASSED  ] 80 tests.
```

One `db_crashtest` run with indexing forced on and the queues off. It used `wal_index_single_file`, an earlier spelling of what is now `partition_by_column_family` that no longer parses, and was not re-run. It happened to draw `zstd` WAL compression, which exercises the compressed branch of the burn window:

```
$ python3 db_crashtest.py blackbox --partition_wal_usage=wal_index_single_file \
    --two_write_queues=0 --duration=180 --interval=30 \
    --max_key=10000 --ops_per_thread=20000
WAL compression           : zstd
(Re-)verified 5417 unique IDs
Crash-recovery verification passed :)
[exited with code 0]
```

`arc lint -a` on all nine changed files -- no issues. clang-format clean.

M1: covered by tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; db_wal_test + log_test: 2340 pass.

M5 fold: Absorbs 1 A.1 entry (GC27 1): GC27 Q9 (d) void writer returns Corruption.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_wal_test, log_test); 2340 tests, 0 failed.

Reviewers: xbw, rajivharlalka, huixiao, taopeng, dyao, rbanerjee2, #rocksdb, kinbertchou, anand76

Subscribers: jewoongh, rbanerjee2, anand76

Differential Revision: https://phabricator.intern.facebook.com/D119751506
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15223

Closes the burned-index hole recorded by the `TODO(justingao)` in `log_writer.cc`.

`DBImpl::AllocateSequenceAndWALIndex` consumes a `wal_index` inside its critical section, but the append happens later in `log::Writer::AddRecord`. Anything failing in between leaves the index allocated but absent from the WAL, and a burned index is indistinguishable from a record that was written and then lost. Once gap detection exists it would read as a real gap, and the response to a gap is truncation -- so a benign error would silently discard durable, acknowledged data.

This establishes the invariant, in the form gap detection will have to be written against -- all three clauses matter:

> Every allocated `wal_index` is on a data record, or under a *void record* covering it, or above every index whose write was acknowledged.

The first two clauses are the ones this diff adds. The third is the terminal case and is not a caveat to skim past: when neither the record nor its cover can be written, the write path fails and nothing above the burned index is ever acknowledged, so a gap check that stops at the highest acknowledged index never reaches it. Stating only the first two clauses would be stronger than what is actually guaranteed.

New record types `kWALIndexVoidType` (22) and `kRecyclableWALIndexVoidType` (23) carry a closed range as `fixed64 lo | fixed64 hi`, so a burst of burns costs one record. Both stay below `kRecordTypeSafeIgnoreMask` with their own `static_assert`, since an older binary skipping a void record would take the covered range for missing data. A void record consumes no index and, unlike the marker, is not positionally constrained -- a cover is written after the append it stands in for failed, so it can appear anywhere. That is also why it gets its own types rather than a marker payload: the reader enforces the marker's "first record" rule, which a cover would violate by construction.

`Writer::AddWALIndexVoidRecord` mirrors `MaybeAddWALIndexMarkerRecord`. It deliberately does not advance `last_wal_index_recorded_` and is not subject to the strictly-increasing check, because its range is behind the high-water mark by construction.

Both readers skip void records as metadata, leave `last_read_wal_index_` alone, and abandon an interrupted fragmented record exactly as the marker does -- a cover written after a torn append lands on that path, so the two readers must agree.

`DBImpl::CoverBurnedWALIndex` is called on every path where an index was allocated and the append did not reach disk: `WriteImpl`, `PipelinedWriteImpl`, and `ConcurrentWriteGroupToWAL`. The last is reached by `unordered_write` writes through `WriteImplWALOnly` (only `two_write_queues` is rejected alongside indexing), and it writes the cover with `wal_write_mutex_` already held. With `manual_wal_flush`, the other two paths take `wal_write_mutex_` for the cover, as `WriteToWAL` does, so an application `FlushWAL` cannot interleave with it. The recovery dummy write in `db_impl_open.cc` is a documented exception: a failure there fails `Open()`, so the DB never becomes writable and nothing can be acknowledged above the hole.

**Worth knowing for review -- this is the third clause above:** with one WAL file at a time an IO error can never be covered. The error poisons the `WritableFileWriter`, so `MaybeHandleSeenFileWriterError` fails the cover too. The cover therefore serves the non-poisoning failures inside the window -- batch checksum, `PrepareIOOptions`, compression -- while an IO error falls through to the terminal path, where the same poisoned writer is what guarantees no write above the burned index is acknowledged. That dependency is now explicit (a comment in `CoverBurnedWALIndex`, which also logs whether the writer had already failed) and the uncovered index is logged at `ERROR`, rather than being incidental.

The ordering rule for the future durability watermark is recorded on `AllocateSequenceAndWALIndex` and not implemented here: a failed append leaves its entry in `pending_low[p]`, and the cover must be written and synced before that entry may be popped, or the watermark advances past an uncovered hole.

Not included: the optional hoist of `MergeBatch` and `PrepareIOOptions` above the allocation. It would shrink the burn window, but it also removes the only non-poisoning failures that this diff's cover path can be exercised through, so the two are better done in that order rather than together.

Out of scope: gap detection, the durability watermark, recovery seeding of `next_wal_index_`, and writing more than one WAL file at a time.

M1: Absorbs GC02 Q1: `CoverBurnedWALIndex` early return + cover comment + `log::Writer::last_wal_index_recorded()` (its test lives in D123701876).

Test Plan:
No existing test needed edits. The byte-layout tests (`WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`) pass unmodified, so WAL bytes on the success path are unchanged at every `partition_wal_usage` value.

New in `db/log_test.cc`, parameterised over recycling x retry-read so both readers are covered:

- `WALIndexVoidRecordByteLayout` -- record type, payload length, and decoded `[lo, hi]` asserted on the raw bytes.
- `WALIndexVoidRecordIsSkipped` -- the void record is not returned as a logical record and does not disturb `GetLastReadWALIndex()` on either side.
- `WALIndexVoidRecordMayTrailTheHighWaterMark` -- a cover behind the mark is accepted and does not move it.
- `WALIndexVoidInsidePartialRecordReportsCorruption` -- a void interrupting a fragmented record reports corruption and abandons the record.
- `CompressionLogTest.WALIndexVoidRecordIsNotCompressed` -- on a compressed WAL the void payload is still plain bytes: the record is located in the file and its `[lo, hi]` decoded directly, and the data records either side still round-trip. `AddWALIndexVoidRecord` bypasses the compressor the way the marker does and the reader's metadata allowlist keeps it out of decompression, so this pins behaviour that was previously only exercised incidentally by a crashtest that happened to draw `zstd`.

New in `db/db_wal_test.cc`:

- `BurnedWALIndexIsCovered` -- an append that fails after allocation produces a void record covering exactly the burned index.
- `BurnedWALIndexCoverHoldsWALMutexWithManualFlush` -- with `manual_wal_flush`, a concurrent `FlushWAL` waits until the cover has been written.
- `NoWALIndexIsLostWhenAppendFails` -- the union of indices on data records and indices under covers is exactly the contiguous run the allocator handed out.
- `UncoveredWALIndexFailsSubsequentWrites` -- with `FaultInjectionIOType::kWrite` the cover fails too; the write and the next write both return errors, and no data record above the burned index reaches the WAL.
- `DefaultUsageWritesNoVoidRecords` -- `kNone` emits no void record even when a write fails.

Each new corruption/fallback test was verified to fail without the code it covers:

```
# CoverBurnedWALIndex neutered to write nothing
BurnedWALIndexIsCovered       expected { (17, 17) }  actual {}
NoWALIndexIsLostWhenAppendFails  expected { 1..17 }  actual { 1..16 }

# Reader void fragment handling neutered
WALIndexVoidInsidePartialRecordReportsCorruption/0 and /2 FAILED
(/1 and /3 still pass -- FragmentBufferedReader has its own branch)
```

```
$ buck2 run fbcode//internal_repo_rocksdb/repo:log_test
[==========] 339 tests from 4 test suites ran.
[  PASSED  ] 339 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:db_wal_test -- --gtest_filter='DBWALIndexTest.*'
[==========] 13 tests from 1 test suite ran.
[  PASSED  ] 13 tests.

$ buck2 run fbcode//internal_repo_rocksdb/repo:options_test
[==========] 80 tests from 6 test suites ran.
[  PASSED  ] 80 tests.
```

One `db_crashtest` run with indexing forced on and the queues off. It used `wal_index_single_file`, an earlier spelling of what is now `partition_by_column_family` that no longer parses, and was not re-run. It happened to draw `zstd` WAL compression, which exercises the compressed branch of the burn window:

```
$ python3 db_crashtest.py blackbox --partition_wal_usage=wal_index_single_file \
    --two_write_queues=0 --duration=180 --interval=30 \
    --max_key=10000 --ops_per_thread=20000
WAL compression           : zstd
(Re-)verified 5417 unique IDs
Crash-recovery verification passed :)
[exited with code 0]
```

`arc lint -a` on all nine changed files -- no issues. clang-format clean.

M1: covered by tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; db_wal_test + log_test: 2340 pass.

M5 fold: Absorbs 1 A.1 entry (GC27 1): GC27 Q9 (d) void writer returns Corruption.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_wal_test, log_test); 2340 tests, 0 failed.

Reviewers: xbw, rajivharlalka, huixiao, taopeng, dyao, rbanerjee2, #rocksdb, kinbertchou, anand76

Subscribers: jewoongh, rbanerjee2, anand76

Differential Revision: https://phabricator.intern.facebook.com/D119751506

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