Skip to content

Add WAL index stripping and verification to log::Reader (#15222) - #15222

Open
JustinGaoF wants to merge 4 commits into
meta:mainfrom
JustinGaoF:export-D118369608
Open

JustinGaoF wants to merge 4 commits into
meta:mainfrom
JustinGaoF:export-D118369608

Conversation

@JustinGaoF

@JustinGaoF JustinGaoF commented Sep 16, 2026 •

Copy link
Copy Markdown

Summary:

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

@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 D118369608.

JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 16, 2026
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
@meta-codesync meta-codesync Bot changed the title Add WAL index stripping and verification to log::Reader Add WAL index stripping and verification to log::Reader (#15222) Sep 16, 2026
@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 510.9s.

JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 17, 2026
Summary:

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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 17, 2026
Summary:

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
@github-actions

github-actions Bot commented Sep 17, 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 14bf790


Summary

Well-structured, carefully implemented addition of WAL index support to log::Reader and log::Writer. The on-disk format change is designed for safe downgrade (indexed types fail-closed on older readers). The code correctly handles fragmentation, compression, checksums, mixed indexed/plain records, and both Reader and FragmentBufferedReader. One high-severity finding (defaulted parameter violates CLAUDE.md policy), one medium-severity finding, and several low-severity items.

High-severity findings (1):

  • [db/log_writer.h:126] AddRecord adds a new defaulted parameter wal_index = 0, violating CLAUDE.md's "Miss Spelling in README #1 trap on refactoring" policy.
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord -- db/log_writer.h:126
  • Issue: The PR changes AddRecord from (write_options, slice, seqno=0) to (write_options, slice, seqno=0, wal_index=0). CLAUDE.md explicitly identifies "new defaulted parameters" as the "Miss Spelling in README #1 trap on refactoring" and says to avoid them.
  • Root cause: Adding wal_index as a trailing default allows all ~40 existing call sites (version_set.cc, db_impl_write.cc, tests, etc.) to compile without changes. But it also means any future caller that should pass a wal_index can silently omit it and get 0, which will trigger a runtime IOStatus::Corruption("WAL index was not assigned") only if WALIndexEnabled() is true on the writer.
  • Mitigation in the code: The writer does check wal_index == 0 and returns Corruption when WAL index is enabled. This is a decent runtime guard, but CLAUDE.md policy prefers compile-time prevention.
  • Suggested fix: Either (a) add a separate overload AddRecord(write_options, slice, seqno, wal_index) without defaults and keep the existing 2-3 arg form, or (b) accept this as an intentional deviation with a code comment explaining the safety rationale (runtime check catches all misuse). Note that seqno = 0 is a pre-existing default in the same signature.

🟡 MEDIUM

M1. kWALIndexPartitionByColumnFamily is accepted but not implemented -- include/rocksdb/options.h:474
  • Issue: The enum value kWALIndexPartitionByColumnFamily = 0x02 is defined and fully plumbed through options, C API, and serialization, but the PR description says "NOT YET IMPLEMENTED: DB::Open rejects this value." No code in this diff actually rejects it during DB::Open. The WALIndexEnabled() function returns true for this value, meaning a user could set it and get WAL indexing enabled without the column-family partitioning they requested.
  • Root cause: The validation that rejects kWALIndexPartitionByColumnFamily at DB::Open time is not included in this diff.
  • Suggested fix: Either add the DB::Open rejection in this PR, or add a clear TODO/comment in WALIndexEnabled() noting that kWALIndexPartitionByColumnFamily support is incomplete and must be rejected until implemented.

🟢 LOW / NIT

L1. Test uses EXPECT_EQ where ASSERT_EQ may be better -- db/log_test.cc:221
  • Issue: The PR changes assert(actual_record_checksum == record_checksum) to EXPECT_EQ. Using EXPECT instead of ASSERT means the test continues after a checksum mismatch, which could mask the root cause. The change from raw assert to a gtest macro is an improvement, but ASSERT_EQ would fail fast.
L2. seqno parameter passed by const reference -- db/log_writer.h:126
  • Issue: Pre-existing: const SequenceNumber& seqno passes a uint64_t by const reference, slightly less efficient than by value. If touching the signature anyway, could be cleaned up.
L3. DecodeWALIndices test helper assumes no fragmentation -- db/log_test.cc:308-326
  • Issue: Walks raw file bytes assuming each record is header + kWALIndexSize + payload with no fragmentation. Works for the small payloads used in tests. A comment noting this limitation would help future test authors.
L4. Compression + WAL index copy is unavoidable but worth noting -- db/log_writer.cc:136-145
  • Issue: When both compression and WAL index are enabled, the writer copies the entire payload into indexed_payload. The code comment correctly explains this is necessary because the compressor needs contiguous input.

Cross-Component Analysis

Context Executes? Assumptions hold? Action needed?
WritePreparedTxnDB No new interaction N/A Safe
ReadOnly DB Reader-only YES Safe
WAL compression Writer merges index before compress; reader decompresses before strip YES Safe
Recycled WAL files All WAL index types have recyclable variants YES Safe
User-defined timestamps Coexists; both are metadata records YES Safe
Old RocksDB readers static_assert ensures types < 128 (fail-closed) YES Safe

Positive Observations

  1. Excellent downgrade safety: static_asserts ensure WAL index types stay below the safe-ignore mask. The constexpr HeaderSelectionUnchangedForPreWALIndexTypes test catches backward compatibility regressions at compile time.

  2. Thorough test coverage: 20+ new test cases covering round-trip, byte layout, boundary conditions (index straddling block boundary), fragmentation, large values, cross-file indices, marker validation, corruption detection, and mixed record types. Tests are well-structured and parameterized across recyclable/non-recyclable modes.

  3. Clean refactoring: IsRecyclableRecordType() and IsWALIndexRecordType() helpers consolidate previously scattered inline checks, reducing duplication in both readers.

  4. Correct CRC computation: The Crc32cCombine-based approach in EmitPhysicalRecord correctly handles the split prefix+payload without unnecessary copies, with a proper null-pointer guard for empty payloads.

  5. Exhaustive switch in WALIndexEnabled(): No default case means adding a new PartitionWALUsage enum value forces explicit classification at compile time.

  6. Well-documented TODO: The burned-index TODO clearly identifies the gap where a failed write after index allocation loses the index, and outlines solutions.


ℹ️ 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 Sep 18, 2026
Summary:

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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 18, 2026
Summary:

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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 18, 2026
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
@github-actions

github-actions Bot commented Sep 18, 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 3d6870d


Summary

Well-structured PR that adds WAL index (LSN) stripping and verification to log::Reader and FragmentBufferedReader. The implementation correctly handles record fragmentation, CRC computation, checksum recomputation after stripping, and downgrade safety. The design is sound — each physical record is self-describing, marker records are positional, and the reader transparently strips the index prefix so upper layers see unchanged payloads.

High-severity findings (2):

  • [include/rocksdb/options.h:473] kWALIndexPartitionByColumnFamily enum doc says "DB::Open rejects this value" but no validation exists — a user could set it and get silent misbehavior.
  • [db/log_writer.h:98-99] New defaulted parameter uint64_t wal_index = 0 added to AddRecord — this is the Miss Spelling in README #1 refactoring trap per CLAUDE.md guidelines.
Full review (click to expand)

Findings

🔴 HIGH

H1. Missing kWALIndexPartitionByColumnFamily rejection in DB::Open — include/rocksdb/options.h:473
  • Issue: The PartitionWALUsage::kWALIndexPartitionByColumnFamily enum value is documented as "NOT YET IMPLEMENTED: DB::Open rejects this value," but no validation exists anywhere in the codebase. DBImpl::ValidateOptions (db/db_impl/db_impl_open.cc:245) does not check partition_wal_usage. A user who sets this option will get WALIndexEnabled() == true (per the WALIndexEnabled() function in db/log_writer.h) but without the partition-by-CF routing, leading to undefined behavior.
  • Root cause: The option validation was not implemented alongside the enum definition.
  • Suggested fix: Add validation to DBImpl::ValidateOptions:
    if (db_options.partition_wal_usage ==
        PartitionWALUsage::kWALIndexPartitionByColumnFamily) {
      return Status::NotSupported(
          "kWALIndexPartitionByColumnFamily is not yet implemented");
    }
H2. New defaulted parameter on AddRecord — db/log_writer.h:98-99
  • Issue: AddRecord gains a new trailing defaulted parameter uint64_t wal_index = 0. CLAUDE.md explicitly flags this as the "Miss Spelling in README #1 trap on refactoring" because existing call sites silently compile without the new argument. While Writer is internal (not under include/rocksdb/), the pattern is still hazardous: all existing callers (e.g., version_set.cc:6242, db_impl_open.cc:372, compaction_job.cc) now silently pass wal_index=0, which is only correct because none of them enable WAL indexing. A future change that enables WAL indexing globally could miss updating one of these ~10 call sites.
  • Root cause: Using a defaulted parameter instead of requiring explicit arguments.
  • Suggested fix: Make wal_index non-defaulted and update all callers, or add an overload that takes (write_options, slice, seqno) and delegates with wal_index=0, so the intent is explicit.

🟡 MEDIUM

M1. No WAL-index + compression integration tests — db/log_test.cc
  • Issue: WAL index tests are in the LogTest suite, which is instantiated only with kNoCompression. The CompressionLogTest suite does not call EnableWALIndex(). Consequently, the compressed WAL + WAL index path (indexed_payload in Writer::AddRecord, decompression then stripping in Reader) is untested.
  • Root cause: The WAL index tests were added to LogTest without extending the compression test suite.
  • Suggested fix: Add at least one WAL index round-trip test to CompressionLogTest, e.g., CompressionLogTest.WALIndexReadWrite.
M2. MaybeStripAndVerifyWALIndex does not prevent the caller from returning a corrupt record — db/log_reader.cc:481-483
  • Issue: When a WAL-indexed record is too short (less than kWALIndexSize bytes), the method calls ReportCorruption and returns without modifying *record. The caller then returns true (for Full records) or continues assembling fragments (for Last records). For the Full case, the caller returns the unstripped record to upper layers, which will contain the raw WAL index bytes (or truncated data). Upper layers will try to interpret this as a WriteBatch and likely fail later with a confusing error.
  • Root cause: MaybeStripAndVerifyWALIndex reports corruption but doesn't prevent the caller from returning the corrupt record.
  • Suggested fix: Have MaybeStripAndVerifyWALIndex return a bool indicating success, and have the caller skip returning the record on failure.
M3. No integration with the DB write path — entire PR
  • Issue: No production code calls SetPartitionWALUsage() or MaybeAddWALIndexMarkerRecord(). The db_impl_write.cc AddRecord call at line 2293 does not pass a wal_index. There is no code that allocates WAL index values or plumbs the partition_wal_usage option to the Writer. This means the feature is dormant in production — format layer only.
  • Root cause: Intentional — format-layer change preceding DB-layer integration.
  • Suggested fix: Document the planned integration in a follow-up issue/task. Consider a simple end-to-end db_test to validate the path.

🟢 LOW / NIT

L1. PartitionWALUsage C API uses int without range validation — db/c.cc:9924-9931
  • Issue: rocksdb_options_set_partition_wal_usage casts an int to PartitionWALUsage via static_cast. Any integer outside {0, 1, 2} produces an invalid enum value. The WALIndexEnabled() function's switch with no default will produce UB for invalid values.
  • Suggested fix: Clamp or validate the input v.
L2. seqno and wal_index are adjacent same-typed parameters — db/log_writer.h:98-99
  • Issue: Both are uint64_t with defaults. Easy to swap at call sites.
  • Suggested fix: Consider a named-parameter pattern or distinct wrapper type.
L3. Writer::MaybeAddWALIndexMarkerRecord calls MaybeSwitchToNewBlock but AddCompressionTypeRecord does not — db/log_writer.cc:296
  • Issue: Asymmetry in marker record emission. Not a bug (compression record asserts block_offset_ == 0), but worth noting for maintainers.
L4. Test WALIndexMixedWithPlainRecords covers only a synthetic scenario — db/log_test.cc
  • Issue: The writer never produces mixed indexed/plain files. The test manually relabels records. This is good defensive testing but no integration test guards against accidental mixing in the writer.

Cross-Component Analysis

Context Executes? Assumptions hold? Action needed?
WritePreparedTxnDB Not yet (no DB integration) N/A Safe
ReadOnly DB Reader decodes during recovery YES None
WAL compression Writer prepends index before compress; reader strips after decompress YES but untested (M1) Add test
Recycled logs Recyclable WAL index types exist; IsRecyclableRecordType updated YES None
Downgrade WAL index types < safe-ignore bit → older binary reports corruption YES — correct fail-closed None
User-defined timestamps Independent metadata; no interaction YES None

Positive Observations

  • The IsRecyclableRecordType() refactoring eliminates 3 duplicated inline checks. The HeaderSelectionUnchangedForPreWALIndexTypes compile-time test is an excellent regression guard.
  • Static asserts ensuring WAL index types stay below kRecordTypeSafeIgnoreMask provide strong downgrade safety.
  • Self-describing fragment design is robust against partial writes and mixed files.
  • The TODO about burned WAL index values on write failure is honest and well-placed.
  • The WALIndexEnabled() allowlist switch with no default forces compile-time review of new enum values.
  • CRC computation in EmitPhysicalRecord using Crc32cCombine for the prefix+payload is mathematically correct and avoids an extra memory copy.

ℹ️ About this response

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

Limitations:

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

Commands:

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

Summary:
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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Oct 1, 2026
Summary:

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
@github-actions

github-actions Bot commented Oct 1, 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 09f5958


Summary

This PR adds WAL index record types and reader/writer support for stripping and verifying per-record ordering numbers. The design is well-structured with proper downgrade safety, comprehensive tests, and a clean separation of reader-side decoding from future DB-level integration. The CRC computation for the prefix+payload split is correct, fragmented record handling is consistent across both Reader and FragmentBufferedReader, and the IsRecyclableRecordType() refactoring is verified to preserve pre-WAL-index behavior.

High-severity findings (1):

  • [db/log_writer.h:125] AddRecord gains a defaulted wal_index parameter, violating CLAUDE.md's "Miss Spelling in README #1 refactoring trap" rule against new defaulted parameters.
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord — db/log_writer.h:125
  • Issue: The new signature AddRecord(..., uint64_t wal_index = 0) adds a defaulted parameter to a widely-called function. CLAUDE.md explicitly states: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" There are 50+ callers of AddRecord across the codebase (version_set.cc, db_impl_write.cc, flush_job_test.cc, wal_manager_test.cc, compaction_job.cc, etc.). While the default of 0 is currently safe (WAL index is disabled by default), a future refactoring that reorders parameters or adds another parameter could silently change semantics for any caller that positionally relies on this.
  • Root cause: Convenience -- avoiding touching all 50+ callers that don't need WAL index yet.
  • Suggested fix: Remove the default value and add an explicit wal_index = 0 argument at every existing call site, OR create a separate overload that delegates to the four-parameter version:
    IOStatus AddRecord(const WriteOptions& wo, const Slice& s,
                       const SequenceNumber& seqno = 0) {
      return AddRecord(wo, s, seqno, /*wal_index=*/0);
    }
    Note: seqno already has a default parameter (pre-existing). An overload avoids compounding the problem.

🟡 MEDIUM

M1. PartitionWALUsage::kPartitionByColumnFamily enum value is 0x02, skipping 0x01 — include/rocksdb/options.h
  • Issue: The enum jumps from kNone = 0x00 to kPartitionByColumnFamily = 0x02. The gap is undocumented. The C API casts to/from int, so rocksdb_options_set_partition_wal_usage(opt, 1) sets an unnamed enumerator value that falls through WALIndexEnabled()'s switch to the trailing return false -- silently accepted but meaningless. The WALIndexEnabled() switch without default would normally catch this at compile time for C++, but the C API bypasses that safety.
  • Suggested fix: Either document why 0x01 is reserved, add C API validation to reject unknown values, or use consecutive values.
M2. No DB-level integration of partition_wal_usage — throughout
  • Issue: The option is plumbed through ImmutableDBOptions, option serialization, and C API, but nothing in DBImpl reads it, calls SetPartitionWALUsage, or calls MaybeAddWALIndexMarkerRecord. Setting the option has no effect. The PartitionWALUsageOpenValidation test verifies the DB opens but not that WAL behavior changes. While marked EXPERIMENTAL, exposing a no-op option with full serialization and C API support may confuse users who enable it expecting partitioned WALs.
  • Suggested fix: Consider deferring the C API and option string plumbing to the PR that adds DB-level integration, or add a log message/warning at DB open when the option is set but not yet effective.
M3. MaybeStripAndVerifyWALIndex reports corruption but record is still returned — db/log_reader.cc
  • Issue: When record->size() < kWALIndexSize, the function calls ReportCorruption and returns early without modifying *record. The caller then returns true with the corrupted/malformed record. Upper layers receive a record that claimed to carry a wal_index but couldn't be decoded, presented as a valid record with its raw (unstripped) bytes.
  • Suggested fix: Either return a bool from MaybeStripAndVerifyWALIndex so the caller can skip the record, or document that this design follows the existing pattern where corruption is reported but records are still delivered for recovery-mode flexibility (matching how kBadRecordChecksum in some modes still allows continued reading).
M4. Fragment consistency check only reports -- doesn't drop the record — db/log_reader.cc:163-167
  • Issue: When a middle/last fragment has inconsistent WAL index type vs the first fragment, ReportCorruption is called but the fragment is still appended to scratch and the record can be assembled and returned. The assembled record will have some fragments with the wal_index prefix and some without, producing garbled data.
  • Suggested fix: After reporting the inconsistency, set in_fragmented_record = false and clear scratch to drop the malformed logical record, similar to how other corruption cases in the middle/last handlers work.

🟢 LOW / NIT

L1. indexed_payload heap allocation in hot path — db/log_writer.cc
  • Issue: When compression is enabled and WAL index is active, indexed_payload.reserve(kWALIndexSize + slice.size()) allocates on every AddRecord call. For the non-compressed path, the separate wal_index_prefix Slice elegantly avoids this. This is acceptable since WAL compression itself is expensive, but worth noting.
L2. Test assert changed to EXPECT_EQ — db/log_test.cc:221
  • Issue: The change from assert(actual_record_checksum == record_checksum) to EXPECT_EQ(actual_record_checksum, record_checksum) is a correctness improvement (asserts are compiled out in release, EXPECT_EQ always reports). Good change.
L3. DecodeWALIndices test helper assumes unfragmented layout — db/log_test.cc
  • Issue: The helper walks the raw WAL image assuming consecutive unfragmented records. The trailing EXPECT_EQ(contents.size(), offset) safeguards against layout drift but the helper would silently produce wrong results for fragmented records before hitting that check. This is fine since the tests using it only write small records.

Cross-Component Analysis

Context Affected? Analysis
WritePreparedTxnDB No WAL index is writer/reader infrastructure only; no DB integration yet
ReadOnly DB No Reader changes are passive (new record types in dispatch)
WAL Recovery Partially ReadRecord now handles new types; all recovery modes pass through the same dispatch. Marker-after-data corruption respects existing mode handling.
Compressed WAL Yes Compression path correctly builds indexed_payload with prefix before compression. Reader decompresses first, then strips. Verified correct.
Recycled WAL Yes IsRecyclableRecordType correctly includes new recyclable WAL index types. Verified by static_assert(HeaderSelectionUnchangedForPreWALIndexTypes()).
User-defined timestamps No UDT records are orthogonal; no interaction.

Positive Observations

  • Downgrade safety: The static_assert ensuring WAL index types stay below kRecordTypeSafeIgnoreMask is excellent -- old readers reject indexed WALs rather than silently misreading them.
  • Self-describing format: Each physical fragment carries its own type, so the marker is not required for correct decoding. Robust design.
  • Compile-time backward compat verification: HeaderSelectionUnchangedForPreWALIndexTypes() is a constexpr function with static_assert proving the IsRecyclableRecordType refactoring preserves header selection for all pre-WAL-index types. Defensive engineering at its best.
  • WALIndexEnabled() as allowlist with exhaustive switch: Adding a new PartitionWALUsage value forces a build failure. Prevents accidental opt-in.
  • Consistent dual-reader handling: Both Reader and FragmentBufferedReader handle the new types with parallel structure, including marker interruption and fragment consistency checks.
  • Comprehensive test coverage: 20+ new test cases covering round-trip, byte layout, fragmentation, block boundary straddling, large values, mixed records, corruption detection, non-consecutive indices, cross-writer interleaving, and marker positioning. Well-structured.
  • TODO for burned index: The db/log_writer.cc comment acknowledging the burned-index problem (index allocated but write fails) shows production awareness with appropriate deferral.

ℹ️ 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 1, 2026
Summary:

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
@github-actions

github-actions Bot commented Oct 1, 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 19119ea


Summary

Well-structured PR that lays clean groundwork for WAL indexing in log::Reader/log::Writer. The new record types, stripping logic, and checksum recomputation are generally correct. Test coverage is strong for the reader/writer layer.

High-severity findings (1):

  • [log_writer.h:125] AddRecord adds a new defaulted parameter (uint64_t wal_index = 0), which CLAUDE.md identifies as the "Miss Spelling in README #1 trap on refactoring."
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord -- db/log_writer.h:125
  • Issue: The PR changes AddRecord(const WriteOptions&, const Slice&, const SequenceNumber& seqno = 0) to AddRecord(const WriteOptions&, const Slice&, const SequenceNumber& seqno = 0, uint64_t wal_index = 0). CLAUDE.md explicitly warns: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" There are ~30+ existing callers (WriteToWAL, VersionSet, tests) that all silently pick up wal_index = 0.
  • Root cause: Convenience of not updating all callers in this PR.
  • Suggested fix: Make wal_index a required parameter (no default). Update all call sites to pass 0 explicitly. This forces every future call site to consciously choose a value, preventing silent omission when WAL indexing is actually enabled at the DB level. Alternatively, use an overload pattern:
    IOStatus AddRecord(const WriteOptions&, const Slice&, const SequenceNumber& = 0);
    IOStatus AddRecord(const WriteOptions&, const Slice&, const SequenceNumber&, uint64_t wal_index);

🟡 MEDIUM

M1. MaybeStripAndVerifyWALIndex returns corrupt record as valid -- db/log_reader.cc:~480
  • Issue: When an indexed record is too short to contain a wal_index (record->size() < kWALIndexSize), the function reports corruption but returns without modifying *record. The caller (ReadRecord) then returns true, handing the malformed record to upper layers (e.g., DBImpl::RecoverLogFiles). The upper layer will attempt to decode it as a WriteBatch, likely producing a confusing secondary error rather than a clean corruption report.
  • Root cause: MaybeStripAndVerifyWALIndex cannot signal "skip this record" to the caller.
  • Suggested fix: After reporting corruption, either (a) clear *record and return false from ReadRecord, or (b) document explicitly that this corruption is non-fatal and the record is returned as-is (with the wal_index bytes still present). Option (a) is safer.
M2. Missing test coverage for WAL index with compression -- db/log_test.cc
  • Issue: All WAL index tests are instantiated only with CompressionType::kNoCompression. The compressed WAL path has distinct logic in AddRecord (builds indexed_payload contiguously instead of using the prefix Slice). The CompressionLogTest suite does not include any WAL index tests. The writer-side compression+index path and the reader-side decompression+stripping path are untested.
  • Suggested fix: Add WAL index tests to CompressionLogTest or create a separate test fixture that exercises the compressed+indexed path. At minimum, add a round-trip test like WALIndexReadWrite under compression.
M3. fragmented_record_has_wal_index_ not explicitly reset in FragmentBufferedReader marker handler -- db/log_reader.cc:~985
  • Issue: In FragmentBufferedReader::ReadRecord, the WAL index marker handler resets in_fragmented_record_ to false and clears fragments_, but does not reset fragmented_record_has_wal_index_. The stale value is harmless because the next kFirstType/kWALIndexFirstType overwrites it, but explicit reset would be clearer and more defensive. In Reader::ReadRecord, the equivalent local variable has the same characteristic but is naturally scoped.
  • Suggested fix: Add fragmented_record_has_wal_index_ = false; in the marker handler for clarity.
M4. PartitionWALUsage enum skips value 0x01 without explanation -- include/rocksdb/options.h
  • Issue: The enum defines kNone = 0x00 and kPartitionByColumnFamily = 0x02, skipping 0x01. The test verifies kRecordOrderingSingleFile no longer parses, but the public header has no comment explaining the gap. A future developer might assign 0x01 to a new value, not realizing it was historically used.
  • Suggested fix: Add a brief comment like // 0x01 was previously used and is reserved.

🟢 LOW / NIT

L1. Extra dest_->Append call when WAL index is enabled -- db/log_writer.cc:~490
  • Issue: When prefix is non-empty, EmitPhysicalRecord makes 3 Append calls instead of 2. Each call goes through WritableFileWriter buffering, so the overhead is minimal. When WAL index is disabled, the extra call is skipped.
L2. SelectRecordType could be inlined or constexpr -- db/log_writer.cc
  • Issue: Minor optimization opportunity. The function is trivial and called per-fragment.
L3. Test helper DecodeWALIndices assumes single-fragment records -- db/log_test.cc
  • Issue: Only used with small payloads in tests, so this is fine as-is.

Cross-Component Analysis

Context Executes? Assumptions hold? Notes
WritePreparedTxnDB Not yet (no DB integration) N/A DB-level code doesn't call SetPartitionWALUsage yet
ReadOnly DB Reader only Yes Reader handles new types correctly
WAL compression Yes (writer path) Needs testing (M2) Compressed+indexed path builds contiguous buffer
Recycled logs Yes Yes Both recyclable and non-recyclable variants exist
WAL recovery modes Yes Yes Marker corruption respects existing patterns
User-defined timestamps Yes Yes Independent record types, no interaction
Downgrade to older binary Yes Safe Types < 128 cause corruption report (desired)

Positive Observations

  • The static_assert ensuring all WAL index types are below kRecordTypeSafeIgnoreMask is excellent downgrade safety.
  • The HeaderSelectionUnchangedForPreWALIndexTypes constexpr validation prevents regressions cleverly.
  • The IsRecyclableRecordType() consolidation removes duplicated logic from 4 sites.
  • The WALIndexEnabled() allowlist pattern (switch without default) forces build failures on new enum values.
  • Comprehensive test coverage: 20+ tests covering round-trip, layout, corruption, fragmentation, cross-writer, and mixed record types.
  • The TODO about burned indices honestly acknowledges a known gap.
  • The marker record design mirrors kSetCompressionType handling, maintaining consistency.

ℹ️ 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 2, 2026
Summary:

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#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
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit 4b64c12


Summary

Well-structured PR that adds WAL index record types and reader/writer support. The design is sound — self-describing record types, fail-closed on older readers, and clean separation between indexing and the existing format. No high-severity correctness bugs found. The main concerns are a defaulted parameter addition (violating CLAUDE.md guidance), missing test coverage for compression+WAL-index interaction, a missing unreleased_history entry, and a few minor robustness issues.

High-severity findings (1):

  • [db/log_writer.h:125] New defaulted parameter uint64_t wal_index = 0 on AddRecord violates CLAUDE.md's Miss Spelling in README #1 refactoring trap rule and creates a silent type-compatible overload risk.
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord — db/log_writer.h:125
  • Issue: CLAUDE.md explicitly states: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" The new signature AddRecord(const WriteOptions&, const Slice&, const SequenceNumber& seqno = 0, uint64_t wal_index = 0) adds a fourth defaulted parameter. Since SequenceNumber is uint64_t, a caller writing AddRecord(opts, slice, seq, some_value) could silently pass a value as wal_index when they intended to pass a different argument. More importantly, any future parameter addition would compound the ambiguity. The production write path at db/db_impl/db_impl_write.cc:2337 currently calls AddRecord(write_options, log_entry, sequence) — the defaulted wal_index=0 kicks in correctly today, but this pattern is fragile.
  • Root cause: Convenience of backward compatibility via defaulted params vs. explicit overloads.
  • Suggested fix: Add a separate overload AddRecord(const WriteOptions&, const Slice&, const SequenceNumber&, uint64_t wal_index) and keep the old signature AddRecord(const WriteOptions&, const Slice&, const SequenceNumber& seqno = 0) without the wal_index parameter. The non-indexed overload delegates to the indexed one with wal_index=0.

🟡 MEDIUM

M1. No test coverage for WAL compression + WAL index interaction — db/log_test.cc
  • Issue: The WAL index tests are in the base LogTest parameterized test which uses CompressionType from GetParam(), but the CompressionLogTest subclass (which actually enables compression via AddCompressionTypeRecord) does not include any WAL index tests. The writer's AddRecord has a specific compression path that creates indexed_payload by concatenating the wal_index bytes with the payload before compression — this distinct code path is untested.
  • Root cause: WAL index tests call EnableWALIndex() + Write() within the base LogTest, but compression is only initialized by CompressionLogTest::SetupTestEnv(). No test combines both.
  • Suggested fix: Add a compression+WAL-index test, either as a new TEST_P(CompressionLogTest, WALIndexWithCompression) or by extending the existing WALIndexReadWrite test to also run under compression parameterization.
M2. Missing unreleased_history entry for new public option — unreleased_history/
  • Issue: PartitionWALUsage is a new public enum added to include/rocksdb/options.h with a new DBOptions::partition_wal_usage field. This is a public API change that should have a release note entry in unreleased_history/public_api_changes/ per project conventions.
  • Suggested fix: Add unreleased_history/public_api_changes/partition_wal_usage.md with a short note about the experimental option.
M3. PartitionWALUsage::kPartitionByColumnFamily = 0x02 — gap not documented — include/rocksdb/options.h:473
  • Issue: The enum uses 0x00 and 0x02, skipping 0x01. The PR description does not explain why 0x01 is reserved. This creates a maintenance hazard — a future contributor may assign 0x01 without understanding the reservation, or may be confused by the gap. If 0x01 was a removed value (the options_test.cc mentions "kRecordOrderingSingleFile" as a now-invalid string), this should be documented in the enum.
  • Suggested fix: Add a comment like // 0x01 is reserved (was kRecordOrderingSingleFile, removed before release).
M4. Reader MaybeStripAndVerifyWALIndex does not prevent returning a too-short record — db/log_reader.cc
  • Issue: When a WAL-indexed record is too short to hold the 8-byte index, ReportCorruption is called and the function returns early. But the caller (ReadRecord) still returns true with the original unstripped record data. This means the upper layer receives a corrupt/truncated record as valid data. Compare with how checksum mismatches are handled (they cause the record to be dropped entirely via kBadRecordChecksum).
  • Root cause: MaybeStripAndVerifyWALIndex reports corruption but does not signal to the caller that the record should be skipped.
  • Suggested fix: Return a bool from MaybeStripAndVerifyWALIndex and have the caller skip the record (continue the loop or return false) when it returns false. Alternatively, clear the record and set last_read_wal_index_ = 0 on the error path.
M5. EmitPhysicalRecord CRC null-pointer guard comment — db/log_writer.cc
  • Issue: The code const uint32_t payload_crc = payload_size == 0 ? 0 : crc32c::Value(ptr, payload_size); guards against a null pointer, and the comment says "Avoid passing a potentially null pointer for an empty payload." This is correct (crc32c::Value(anything, 0) returns 0), but the guard creates a subtle implication that ptr might be null. Since the marker record case passes empty_payload.data() which returns a valid (non-null) pointer for a default-constructed std::string, and other callers always pass valid pointers, this guard may be unnecessary. The correctness is fine but the comment could be misleading.
  • Suggested fix: Minor — consider simplifying to always call crc32c::Value(ptr, payload_size) since it handles zero-length correctly, or keep the guard with a clearer comment.

🟢 LOW / NIT

L1. Corrected comment in log_format.h:40
  • Issue: The old comment "For all the values >= 10, the 1 bit indicates whether it's recyclable" was misleading (not true for types >= 128). The new comment accurately describes the actual behavior. Good fix.
L2. PartitionWALUsageOpenValidation test is minimal — db/db_wal_test.cc:3582
  • Issue: The test only checks that TryReopen succeeds with each PartitionWALUsage value. No actual WAL write/read is verified. Acceptable for this PR since the DB layer integration is not yet done.
L3. C API static_cast<decltype(...)>(v) from int — db/c.cc
  • Issue: Casting arbitrary int to PartitionWALUsage enum class could produce undefined behavior for invalid values. Follows existing convention for other enum options in the C API.
L4. constexpr HeaderSelectionUnchangedForPreWALIndexTypes() — db/log_test.cc
  • Issue: Excellent compile-time guard ensuring IsRecyclableRecordType() refactoring doesn't change behavior for pre-existing types. Well done.
L5. WALIndexEnabled() allowlist pattern — db/log_writer.h
  • Issue: Good pattern — no default in switch forces compile-time classification of new enum values. The trailing return false after the switch correctly suppresses warnings.
L6. db_options.cc uses GetPartitionWALUsageStringMap() function-local static — options/db_options.cc
  • Issue: Correctly follows CERT ERR58-CPP (construct-on-first-use) unlike the existing wal_recovery_mode_string_map which is a namespace-scope static. The inconsistency is worth noting but the new code is the better pattern. Consider fixing the old map in a follow-up.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
WAL compression YES (writer compression path) YES — indexed_payload concatenation handles it Test needed (M1)
Recycled log files YES (kRecyclable* types) YES — IsRecyclableRecordType handles all new types None
User-defined timestamps N/A (orthogonal marker records) YES — processed independently None
WritePreparedTxnDB NO — WAL index not plumbed to DB layer yet N/A Future PR
ReadOnly DB / SecondaryInstance NO — WAL index not plumbed yet N/A Future PR
Manual WAL flush YES (marker record conditional flush) YES None
PredecessorWALInfo Orthogonal YES None
Big-endian YES — EncodeFixed64/DecodeFixed64 are little-endian YES — portable encoding None

Positive Observations

  • Fail-closed downgrade safety: The static_assert ensuring all WAL index types are below kRecordTypeSafeIgnoreMask (128) is excellent — older readers will reject rather than silently misinterpret indexed records.
  • Self-describing records: Each physical fragment's type indicates whether it carries a wal_index, so a file can hold mixed record types. This is a robust design that doesn't depend on file-level state.
  • constexpr HeaderSelectionUnchangedForPreWALIndexTypes(): Compile-time verification that the IsRecyclableRecordType() refactoring doesn't change behavior for existing types is a great defensive pattern.
  • WALIndexEnabled() as allowlist with no default: Forces compile-time classification of new PartitionWALUsage values rather than inheriting "indexed" by omission.
  • TODO for burned index: The comment acknowledging that a failed write burns an allocated wal_index and deferring resolution is honest and appropriate.
  • Thorough edge-case tests: Tests for block-boundary straddling, large values, inconsistent fragment types, marker positioning, cross-writer interleaving, and mixed indexed/plain records show excellent attention to edge cases.
  • Consistent reader behavior: Both Reader and FragmentBufferedReader handle all eight WAL index dispatch sites symmetrically, including fragment type consistency checking and marker interruption of partial records.

ℹ️ 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#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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Oct 20, 2026
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
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
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.

A marker that interrupts a fragmented record (before or after the first record has been returned) reports corruption and abandons the partial record in both readers, and `Reader` also resets its streaming checksum. Both readers therefore reject the same input instead of completing a record from its tail alone.

Test Plan:
Reader-focused tests added to `db/log_test.cc`, parameterised over recycling x retry-read (so both `Reader` and `FragmentBufferedReader` are covered):

- `WALIndexReadWrite` — round trip; four records read back as indices 1-4 with payloads intact.
- `WALIndexDisabledStaysVanilla` — with indexing off, no indexed or marker record types appear on disk.
- `WALIndexRecordsDoNotRequireMarker` — indexed records decode with no marker present.
- `WALIndexNonConsecutiveWithinFileIsAccepted` — a jump between indices in one file is not reported as corruption. Regression guard for the per-file gap check being reintroduced.
- `WALIndexMixedWithPlainRecords` — a plain record following an indexed one keeps its full payload and reports index 0.
- `WALIndexTooShortRecordReportsCorruption` — a record typed as indexed with a payload under 8 bytes is reported, not over-read.
- `WALIndexInconsistentFragmentTypesReportsCorruption` — fragments of one logical record disagreeing about carrying an index is reported.
- `WALIndexMarkerAfterDataRecordReportsCorruption` — a marker following a data record is reported.
- `WALIndexLargeValueRoundTrips` — a high-bit index survives the fixed64 encoding.
- `WALIndexLargeRecord` — the index survives fragmentation across 32KiB blocks.
- `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord` -- a marker interrupting a fragmented record is reported and the partial record dropped, before and after the first returned record.
- `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary` -- raw-byte layout and round trip of the writer's separate 8-byte prefix, including an index split across a block boundary.
- `WALIndexNotAssignedWhenDisabled` -- with indexing off, a `wal_index` passed to `AddRecord` is not written and the reader reports 0.
- `WALIndexConsecutiveAcrossFilesInPartition` — two writers sharing one counter; each file alone skips values, while the union read back from both files is exactly the contiguous run the counter issued.

Corruption-path tests were verified to fail without the checks they cover: neutering both `ReportCorruption` calls fails all 8 parameterisations, and the mixed-records test fails on all 4 without the index reset.

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

`arc lint -a` on `log_reader.cc`, `log_reader.h`, `log_test.cc` — no issues.

Formatting verified per file rather than asserted: `clang-format <file> | diff - <file>` is empty for every changed file, using the repo-pinned `tools/third-party/clang-format/clang-format`.

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

M5 fold: Absorbs 4 A.1 entries (GC27 4): GC27 Q9 (c) rename in ReadRecord.

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

Reviewers: kinbertchou, huixiao, dyao, taopeng, rajivharlalka, anand76, xbw, rbanerjee2, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2, anand76

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

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