Skip to content

Add WAL index support to log::Writer (#15221) - #15221

Open
JustinGaoF wants to merge 3 commits into
meta:mainfrom
JustinGaoF:export-D118369607
Open

JustinGaoF wants to merge 3 commits into
meta:mainfrom
JustinGaoF:export-D118369607

Conversation

@JustinGaoF

@JustinGaoF JustinGaoF commented Sep 16, 2026 •

Copy link
Copy Markdown

Summary:

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

@meta-cla meta-cla Bot added the CLA Signed label Sep 16, 2026
@JustinGaoF
JustinGaoF force-pushed the export-D118369607 branch 3 times, most recently from 077170f to a597eae Compare September 17, 2026 22:18
@meta-codesync

meta-codesync Bot commented Sep 17, 2026

Copy link
Copy Markdown

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

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

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 466.4s.

@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 1e18adc


Summary

Well-structured writer-side WAL index implementation with a clever zero-copy prefix approach for uncompressed records. The design is sound: fail-closed downgrade safety via sub-128 record types, split prefix to avoid payload copies, and strict monotonicity enforcement. The defaulted wal_index parameter on AddRecord is a CLAUDE.md violation worth discussing. Several medium-severity issues around missing validation, test coverage gaps, and the compression path interaction.

High-severity findings (1):

  • [db/log_writer.h:127] New defaulted parameter uint64_t wal_index = 0 on AddRecord -- CLAUDE.md's Miss Spelling in README #1 refactoring trap.
Full review (click to expand)

Findings

🔴 HIGH

H1. Defaulted parameter on AddRecord -- db/log_writer.h:127
  • Issue: The PR adds uint64_t wal_index = 0 as a new defaulted parameter to AddRecord(). CLAUDE.md explicitly warns: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" This is particularly dangerous because existing callers (e.g., DBImpl::WriteToWAL at db/db_impl/db_impl_write.cc:2293) silently compile without passing a wal_index, meaning a future caller that should pass one can accidentally omit it and get the default-0 path, which silently disables WAL indexing for that record rather than failing.
  • Root cause: Convenience for incremental rollout -- the caller-side allocation isn't landed yet, so all callers pass 0.
  • Suggested fix: Make wal_index a required parameter (no default). Add an explicit overload AddRecord(write_options, slice, seqno) that forwards to AddRecord(write_options, slice, seqno, 0) if backward compatibility is needed. Alternatively, use a separate method like AddIndexedRecord().

🟡 MEDIUM

M1. No DB::Open rejection of kWALIndexPartitionByColumnFamily -- include/rocksdb/options.h:475
  • Issue: The PR description says "NOT YET IMPLEMENTED: DB::Open rejects this value" for kWALIndexPartitionByColumnFamily, but there is no validation code in this diff. A user who sets this option will get WAL-indexed single-file behavior (since WALIndexEnabled() returns true for it) without any column-family partitioning, silently violating their intent.
  • Suggested fix: Add validation in DBImpl::Open() or SanitizeOptions() that returns Status::NotSupported() for kWALIndexPartitionByColumnFamily.
M2. No test for fragmented records with WAL index -- db/log_test.cc
  • Issue: The fragment loop's prefix-splitting logic (where the 8-byte wal_index prefix is split across block boundaries) is the most complex new code path, but no test writes a record large enough to trigger fragmentation with WAL index enabled. The existing tests use small payloads ("a", "b", "c", "d", "foo") that always fit in a single fragment.
  • Suggested fix: Add a test with a payload close to kBlockSize - kHeaderSize - kWALIndexSize and one significantly larger to exercise First/Middle/Last fragments with the prefix.
M3. No test for WAL compression + WAL index -- db/log_test.cc
  • Issue: The compression path has distinct logic (copies wal_index into indexed_payload string, sets payload to the combined buffer, leaves wal_index_prefix empty). This path is completely untested. The test parameterization only uses kNoCompression.
  • Suggested fix: Add a test parameterization or explicit test that enables both WAL compression (e.g., kZSTD) and WAL index simultaneously.
M4. Marker record ordering not enforced -- db/log_writer.cc
  • Issue: The PR description claims "an older binary fails on record Miss Spelling in README #1 rather than partway through replay." However, MaybeAddWALIndexMarkerRecord() does not assert or check that block_offset_ == 0 (unlike AddCompressionTypeRecord() which does). If MaybeAddPredecessorWALInfo() or MaybeAddUserDefinedTimestampSizeRecord() is called before the marker, the marker is no longer the first record, breaking the downgrade-safety claim.
  • Suggested fix: Either add assert(block_offset_ == 0) or document the required call ordering with a runtime check. Verify that the caller (future diff) enforces the ordering.
M5. SetPartitionWALUsage has no guard against post-write calls -- db/log_writer.h
  • Issue: SetPartitionWALUsage() has assert(partition_wal_usage_ == PartitionWALUsage::kNone) but no check that no records have been written yet. In release builds, the assert is stripped, and calling this after writing records would produce a file with mixed indexed and non-indexed records, which no reader could parse correctly.
  • Suggested fix: Add a debug-mode check on block_offset_ or record count, or convert to a runtime check returning Status.
M6. Compression path compresses input that includes wal_index -- db/log_writer.cc
  • Issue: When compression is enabled, the wal_index is prepended to the payload before compression: PutFixed64(&indexed_payload, wal_index); indexed_payload.append(slice.data(), slice.size()). The compress call then compresses payload.data(), payload.size() which includes the index. This means the reader will need to decompress the record and then strip the first 8 bytes to get the actual wal_index. This coupling between writer compression and reader decompression for wal_index extraction is not documented and could be error-prone for the future reader implementation.
  • Suggested fix: Add a comment or design note documenting this coupling for the reader implementer.

🟢 LOW / NIT

L1. std::string indexed_payload allocated on every AddRecord call -- db/log_writer.cc
  • Issue: Even when WAL index is disabled, std::string indexed_payload is constructed (empty) on every AddRecord call. While the SSO optimization means no heap allocation for empty strings, it's still unnecessary construction on a hot path.
  • Suggested fix: Move the declaration inside the if (WALIndexEnabled()) block.
L2. encoded_wal_index stack array allocated unconditionally -- db/log_writer.cc
  • Issue: char encoded_wal_index[kWALIndexSize] (8 bytes) is allocated on the stack on every AddRecord call regardless of whether WAL index is enabled. Minimal overhead but unnecessary.
  • Suggested fix: Move inside the if (WALIndexEnabled()) block.
L3. Crc32cCombine for two-part payload may be slower than single Value -- db/log_writer.cc
  • Issue: For indexed records, the CRC is computed as Crc32cCombine(prefix_crc, payload_crc, payload_size) followed by Crc32cCombine(type_crc, combined, total_payload_size). Computing a single CRC over an iovec-style buffer might be faster. However, the PR's benchmark results show the separate-prefix approach is faster overall (due to avoiding the payload copy), so the CRC overhead is acceptable.
  • Suggested fix: No action needed; documenting for awareness.
L4. DecodeWALIndices test helper doesn't account for fragmented records -- db/log_test.cc
  • Issue: The helper assumes each record fits in a single physical record (walks by header_size + kWALIndexSize + payload_size). If tests are added for fragmented records, this helper won't work.
  • Suggested fix: Document the limitation or extend the helper when fragment tests are added.
L5. C API uses static_cast<decltype(...)>(v) without validation -- db/c.cc
  • Issue: Any int value is cast directly to PartitionWALUsage. Invalid values produce undefined behavior for enum class. This matches the pattern used for other enum options in the C API, so it's consistent, but still a concern.
  • Suggested fix: Consider adding bounds checking, or at minimum document valid values.
L6. WALIndexEnabled() free function has trailing return false after exhaustive switch -- db/log_writer.h
  • Issue: The switch has no default: case (good -- forces compile error on new enum values), but has return false after the switch. Some compilers may warn about this being unreachable.
  • Suggested fix: Consider assert(false); return false; or compiler-specific unreachable hints.

Cross-Component Analysis

Context Impact Assessment
Reader (log_reader.cc) Reader's is_recyclable_type check does NOT include new recyclable WAL index types. If a recyclable WAL-indexed file is read, wrong header size = corruption. By design: reader support deferred. Fail-closed behavior (types < 128) is correct.
FragmentBufferedReader Same hardcoded recyclable check at line 979. Same behavior. By design: same as above.
DBImpl::WriteToWAL Calls AddRecord with 3 args (relying on default wal_index=0). Safe for now but see H1.
WritePreparedTxnDB Uses same write path. wal_index defaults to 0. Safe while feature is disabled.
VersionSet/MANIFEST Uses separate Writer instance, never calls SetPartitionWALUsage. Not affected.
WAL Manager File-level operations, doesn't parse record types. Not affected.
External tools (ldb) Would encounter unknown types, report corruption. Correct fail-closed behavior.

Positive Observations

  • The split prefix/payload design for zero-copy on the uncompressed path is well-engineered and shows measurable performance benefits (4-15% latency reduction for large values).
  • The static_assert in HeaderSelectionUnchangedForPreWALIndexTypes() is an excellent regression guard ensuring the IsRecyclableRecordType() refactor doesn't change behavior for existing types.
  • The WALIndexEnabled() free function with exhaustive switch and no default is a good pattern that forces future enum values to be explicitly classified.
  • The monotonicity check uses IOStatus::Corruption rather than assert, correctly handling the case in release builds.
  • The static_asserts on record type values being below kRecordTypeSafeIgnoreMask are a strong safeguard for downgrade safety.
  • The construct-on-first-use pattern for GetPartitionWALUsageStringMap() correctly addresses CERT ERR58-CPP.

ℹ️ 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::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
@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 df6f5f7


Summary

Clean, well-structured writer-side change with solid performance optimization (separate prefix avoids payload copy). The design of fail-closed record types and the static_assert for backward compatibility are well-thought-out. Two high-severity findings relate to a CLAUDE.md guideline violation (new defaulted parameter on AddRecord) and missing validation for the unimplemented kWALIndexPartitionByColumnFamily enum value.

High-severity findings (2):

  • [db/log_writer.h:98] New defaulted parameter wal_index = 0 on AddRecord violates CLAUDE.md's Miss Spelling in README #1 refactoring trap rule.
  • [include/rocksdb/options.h:~473] kWALIndexPartitionByColumnFamily is declared as "NOT YET IMPLEMENTED: DB::Open rejects this value" but no rejection code exists anywhere in the codebase.
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord — db/log_writer.h:98
  • Issue: The PR adds uint64_t wal_index = 0 as a new defaulted parameter to Writer::AddRecord. CLAUDE.md explicitly states: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!"
  • Root cause: The writer-side change is deployed before the caller-side integration. With a default of 0, any caller that enables WAL index mode via SetPartitionWALUsage but forgets to pass a wal_index will get IOStatus::Corruption("WAL index was not assigned") at runtime rather than a compile error. More subtly, when the integration PR lands, a caller that passes (write_options, slice, seqno) without wal_index will silently compile and get 0, which the writer rejects only if WAL index is enabled.
  • Suggested fix: Remove the default. Have callers that don't use WAL index explicitly pass /*wal_index=*/0. This ensures the caller-side integration PR cannot accidentally omit the argument. Alternatively, split into two methods (one with wal_index, one without) or use a struct to bundle the parameters.
H2. kWALIndexPartitionByColumnFamily accepted without validation — include/rocksdb/options.h
  • Issue: The enum value kWALIndexPartitionByColumnFamily = 0x02 is declared with the comment "NOT YET IMPLEMENTED: DB::Open rejects this value." However, no validation or rejection code exists in this PR or in the current codebase. A user could set this option and the writer would happily emit WAL index records (since WALIndexEnabled() returns true for it), but the partitioning behavior would be absent.
  • Root cause: The validation was deferred, but the WALIndexEnabled() allowlist already returns true for this value.
  • Suggested fix: Either (a) add validation in DBImpl::Open or ValidateOptions to reject kWALIndexPartitionByColumnFamily with a clear error, or (b) remove it from the WALIndexEnabled() allowlist until it's implemented.

🟡 MEDIUM

M1. Reader-side recyclable type detection not updated — db/log_reader.cc:571-574,979-981
  • Issue: The reader has two hardcoded recyclable-type detection lists in ReadPhysicalRecord and FragmentBufferedReader::TryReadFragment that do not include the new recyclable WAL index types (18-21). This is intentional for fail-closed behavior on older readers, but it means a current reader (compiled with this PR) also cannot read indexed WALs. The reader is not using the new IsRecyclableRecordType() helper.
  • Root cause: Reader changes are deferred to a later PR.
  • Suggested fix: This is acceptable as a staged rollout, but document clearly that reader changes MUST update these two hardcoded lists to use IsRecyclableRecordType() (or equivalent). Consider adding a // TODO(PR#XXXX) comment in the reader at both locations to ensure the next PR doesn't miss them. The two locations are: ReadPhysicalRecord line 571-574 and TryReadFragment line 979-981.
M2. Missing test coverage for WAL index + compression — db/log_test.cc
  • Issue: The compressed path (indexed_payload buffer creation) is a significant code path with heap allocation and data joining, but no test explicitly exercises WAL index with compression_type != kNoCompression. The INSTANTIATE_TEST_CASE_P at the end of the test file does not include WAL index variants with compression enabled.
  • Root cause: The test infrastructure parameterizes on compression but EnableWALIndex() is only called in specific tests, not in the parameterized fixture.
  • Suggested fix: Add at least one test that enables both WAL compression and WAL index, writes a record, and verifies the wal_index is correctly encoded. This exercises the indexed_payload.reserve(kWALIndexSize + slice.size()) and PutFixed64(&indexed_payload, wal_index) path.
M3. Missing test for fragmented records with WAL index — db/log_test.cc
  • Issue: No test writes a record large enough to require fragmentation (spanning multiple physical records) with WAL index enabled. The prefix-splitting logic (prefix_length = min(fragment_length, wal_index_prefix.size()), wal_index_prefix.remove_prefix(prefix_length)) in the fragmentation loop is untested.
  • Root cause: All WAL index tests use small payloads that fit in a single block.
  • Suggested fix: Add a test with a payload near or exceeding kBlockSize - header_size - kWALIndexSize to exercise the fragmentation loop with the wal_index prefix.
M4. No release notes or HISTORY.md entry — missing file
  • Issue: The PR adds a new public DBOption (partition_wal_usage) and a new enum (PartitionWALUsage) but does not include a release note entry in unreleased_history/. This is a new experimental feature with on-disk format implications.
  • Suggested fix: Add a brief entry in unreleased_history/ under "New Features" noting the new experimental partition_wal_usage option.
M5. #include "rocksdb/options.h" added to db/log_writer.h — db/log_writer.h:19
  • Issue: Adding #include "rocksdb/options.h" to log_writer.h pulls the entire public options header (a large header) into every translation unit that includes log_writer.h. The only thing needed is the PartitionWALUsage enum.
  • Suggested fix: Forward-declare PartitionWALUsage in log_writer.h and move the #include "rocksdb/options.h" to log_writer.cc, or move PartitionWALUsage to log_format.h alongside the other WAL format definitions.

🟢 LOW / NIT

L1. MaybeSwitchToNewBlock called with std::string for marker — db/log_writer.cc
  • Issue: MaybeAddWALIndexMarkerRecord creates const std::string empty_payload and passes it to MaybeSwitchToNewBlock. The function takes const std::string& and uses .size() — an empty string works but a Slice or size_t parameter would avoid the allocation.
  • Suggested fix: Minor nit; the empty string is stack-allocated with SSO so cost is negligible.
L2. SelectRecordType could be static or constexpr — db/log_writer.cc
  • Issue: SelectRecordType depends only on begin, end, WALIndexEnabled(), and recycle_log_files_, all of which are known at call time. It's a simple dispatch function.
  • Suggested fix: Nit; current design is fine. The compiler will likely inline it.
L3. assert(seqno >= last_seqno_recorded_) is debug-only — db/log_writer.cc
  • Issue: The sequence number ordering check is an assert, while the wal_index ordering check is a runtime IOStatus::Corruption return. The PR comment explains the asymmetry (seqno check is weaker by design), which is acceptable.
L4. DecodeWALIndices test helper assumes no fragmentation — db/log_test.cc
  • Issue: The helper manually walks the raw WAL bytes assuming each record fits in a single physical record (no fragmentation). This is fine for the current tests but would break silently if someone adds a large-record WAL index test that uses it.
  • Suggested fix: Add a comment documenting this assumption.
L5. C API uses int for PartitionWALUsage enum — include/rocksdb/c.h, db/c.cc
  • Issue: The setter uses static_cast<decltype(opt->rep.partition_wal_usage)>(v) from int, which accepts any integer value without validation. This is consistent with how other enum options (e.g., wal_compression) are handled in the C API, so it's not a regression, but invalid values would be silently accepted.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
WAL compression enabled YES - joins wal_index + payload into indexed_payload YES No, but needs test (M2)
Recycled log files YES - new recyclable types 18-21 YES on writer; reader needs update (M1) Reader update in next PR
MANIFEST writer NO - SetPartitionWALUsage not called on MANIFEST writers N/A Safe; no guard needed
WritePreparedTxnDB Writer-side only YES No
ReadOnly DB No WAL writes N/A No
kWALIndexPartitionByColumnFamily YES - WALIndexEnabled returns true NO - partitioning logic absent H2: validate/reject
User-defined timestamps Orthogonal - UDT records are separate YES No

Positive Observations

  • The separate-prefix design for the uncompressed path is elegant and avoids copying the full payload, with meaningful performance wins (4-15% latency reduction in benchmarks).
  • The static_assert(HeaderSelectionUnchangedForPreWALIndexTypes) in the test file is an excellent safeguard that pins backward compatibility at compile time.
  • The WALIndexEnabled() allowlist switch without a default case is good forward-looking design — adding a new PartitionWALUsage value will cause a compile error until classified.
  • The static_asserts that WAL index types stay below kRecordTypeSafeIgnoreMask prevent silent data loss on downgrade.
  • The construct-on-first-use pattern for GetPartitionWALUsageStringMap() correctly follows CERT ERR58-CPP.
  • CRC computation with Crc32cCombine is mathematically correct for split prefix+payload, producing the same result as a contiguous CRC computation.

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

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

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::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::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
@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 22b9266


Summary

Well-structured PR that adds WAL index write-side support to log::Writer with a clean separation between the uncompressed zero-copy path and the compressed fallback. The format design (fail-closed on older readers, static_asserts on type numbering) is solid. Two high-severity findings relate to reader-side inconsistencies that will cause problems when the reader is updated in a subsequent diff.

High-severity findings (2):

  • [db/log_reader.cc:571-574, 979-981] Reader's recyclable-type detection is a hardcoded whitelist that does not include the new WAL index recyclable types. When the reader is updated in a later diff, this check MUST be updated or recyclable WAL index records will be parsed with wrong header size, causing CRC mismatches or data corruption.
  • [db/log_writer.h:123] New defaulted parameter uint64_t wal_index = 0 on AddRecord violates CLAUDE.md's Miss Spelling in README #1 refactoring trap rule ("Avoid new defaulted parameters").
Full review (click to expand)

Findings

🔴 HIGH

H1. Reader recyclable-type detection must be updated with WAL index types — db/log_reader.cc:571-574
  • Issue: Both Reader::ReadPhysicalRecord (line 571) and FragmentBufferedReader::TryReadFragment (line 979) use hardcoded whitelists to detect recyclable record types:

    const bool is_recyclable_type =
        ((type >= kRecyclableFullType && type <= kRecyclableLastType) ||
         type == kRecyclableUserDefinedTimestampSizeType ||
         type == kRecyclePredecessorWALInfoType);

    This does not include kRecyclableWALIndexMarkerType (13), kRecyclableWALIndexFullType (18), or kRecyclableWALIndex{First,Middle,Last}Type (19-21). When a recyclable WAL index record is encountered, the reader will:

    1. Use kHeaderSize (7) instead of kRecyclableHeaderSize (11)
    2. Parse the length field from the wrong offset
    3. Compute CRC over wrong bytes
    4. Report corruption (fail-closed, but for the wrong reason)

    Currently this is moot because the reader falls through to the default case and reports "unknown record type" anyway. But when the reader is updated in the next diff to handle WAL index types, this check must be updated simultaneously, or the reader will silently misparse recyclable WAL index records. The writer already centralizes this in IsRecyclableRecordType() -- the reader should use it too.

  • Root cause: Writer was refactored to use IsRecyclableRecordType() but reader retains hardcoded whitelists.

  • Suggested fix: When updating the reader in the follow-up diff, replace both hardcoded checks with IsRecyclableRecordType(type) from log_format.h, or at minimum add the WAL index recyclable types to the whitelists. Consider adding a static_assert or compile-time test that verifies Reader and Writer agree on which types are recyclable.

H2. Defaulted wal_index parameter on AddRecord — db/log_writer.h:123
  • Issue: The signature change AddRecord(..., uint64_t wal_index = 0) introduces a new defaulted parameter. CLAUDE.md states: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" The seqno parameter already defaults to 0, making this the second defaulted parameter. A future caller that intends to pass wal_index but accidentally omits it will silently get 0, which -- when WAL index is enabled -- causes a Corruption return. While the Corruption return provides a safety net, the defaulted parameter pattern is still a maintenance hazard.
  • Root cause: Convenience for existing callers that don't use WAL index.
  • Suggested fix: Consider making wal_index a required parameter and updating all call sites (they all currently pass the default). Alternatively, provide a separate overload AddRecord(write_options, slice) that delegates to the full form with seqno=0, wal_index=0. This makes the caller's intent explicit.

🟡 MEDIUM

M1. Missing test for WAL index + compression path — db/log_test.cc
  • Issue: The compression path with WAL index enabled has specific logic: it copies the wal_index into indexed_payload and compresses the combined buffer. There is no test exercising this path. The INSTANTIATE_TEST_CASE_P at the end of log_test.cc explicitly says "Do NOT enable compression for this instantiation." A separate test or test instantiation is needed.
  • Suggested fix: Add a test that enables both WAL index and compression, writes records, and verifies the output is decodable. Even without reader-side changes, the test can verify the writer doesn't crash and that the compressed output has the expected size characteristics.
M2. SetPartitionWALUsage has assert-only guard — db/log_writer.h:146-148
  • Issue: SetPartitionWALUsage asserts that partition_wal_usage_ == kNone but has no release-mode check. If called twice in a release build, it silently overwrites. This could lead to a file where the first records are non-indexed and later records are indexed (or vice versa), violating the "all or none" invariant.
  • Suggested fix: Add a release-mode check that returns IOStatus::InvalidArgument or IOStatus::Corruption if called after the first record is written.
M3. PartitionWALUsage enum gap: 0x01 is unused — include/rocksdb/options.h:469-476
  • Issue: The enum has kNone = 0x00 and kPartitionByColumnFamily = 0x02, skipping 0x01. The options_test.cc test explicitly checks that kRecordOrderingSingleFile / record_ordering_single_file are rejected. This suggests a value was removed. The gap is not documented in the enum definition.
  • Suggested fix: Add a brief comment noting that 0x01 is reserved (or was removed) so future contributors don't assign it.
M4. kWALIndexStartNumber should guard against UINT64_MAX exhaustion — db/log_writer.h:31-40
  • Issue: The comment says "Reaching UINT64_MAX is unreachable at any real write rate" and AddRecord does not check for overflow. While practically unreachable, a check like if (wal_index == std::numeric_limits<uint64_t>::max()) return Corruption(...) would be consistent with the "never wraps" contract stated in the comment.
  • Suggested fix: Add an explicit check, or document why it's intentionally omitted.

🟢 LOW / NIT

L1. #include "rocksdb/options.h" in log_writer.h — db/log_writer.h:20
  • Issue: This is a heavyweight public header pulled into an internal header. It's needed for PartitionWALUsage type. A forward declaration would not suffice since the enum is used by value in the inline WALIndexEnabled() function. However, log_reader.h already includes rocksdb/options.h, so this doesn't change the include graph for translation units that include both.
  • Suggested fix: Consider moving PartitionWALUsage to a lightweight header, or accept the include.
L2. Static constexpr test could also verify WAL index types — db/log_test.cc:856-886
  • Issue: HeaderSelectionUnchangedForPreWALIndexTypes only checks pre-WAL-index types. A complementary check verifying WAL index types (e.g., IsRecyclableRecordType(kRecyclableWALIndexFullType) == true and IsRecyclableRecordType(kWALIndexFullType) == false) would add confidence.
  • Suggested fix: Add explicit static_assert checks for the new types.
L3. partition_wal_usage option Dump format — options/db_options.cc:1044-1045
  • Issue: Logs static_cast<int>(partition_wal_usage) which shows 0 or 2. Consistent with wal_recovery_mode but less readable than the string name.
  • Suggested fix: Accept for consistency with existing patterns.

Cross-Component Analysis

Context Executes? Assumptions hold? Action needed?
WritePreparedTxnDB YES (uses DBImpl::WriteToWAL) YES - default wal_index=0 Integration in later diff
ReadOnly DB NO (no writes) N/A Safe
MANIFEST writes (VersionSet) YES (uses AddRecord) YES - separate Writer instances, default wal_index=0 Safe
Recycled log files YES YES - tested OK
WAL compression YES PARTIAL - compressed path works but untested M1
Old reader / downgrade YES YES - fail-closed by design OK
New reader (future diff) WILL EXECUTE MUST update recyclable check H1
User-defined timestamps YES (separate record type) YES - independent OK

Positive Observations

  • Zero-copy prefix design: The prefix Slice in EmitPhysicalRecord elegantly avoids copying the entire record payload to prepend 8 bytes. The benchmark numbers (-4% to -16% latency improvement) demonstrate this matters.
  • Fail-closed downgrade safety: The static_assert ensuring all WAL index types are below kRecordTypeSafeIgnoreMask guarantees older readers reject rather than silently ignore these records.
  • HeaderSelectionUnchangedForPreWALIndexTypes static_assert: Excellent defensive assertion that prevents the IsRecyclableRecordType refactoring from silently changing behavior for existing record types.
  • Strict monotonicity check: Rejecting non-increasing wal_index values with Corruption (not just assert) is the right choice for a production invariant.
  • WALIndexEnabled as allowlist: Using a switch without default forces explicit classification of each PartitionWALUsage value, preventing future values from inheriting "indexed" by omission.

ℹ️ 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::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::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
@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 7325f11


Summary

This PR cleanly implements the writer-side of WAL index support with good attention to backward compatibility (downgrade safety via record types below the safe-ignore mask) and performance (zero-copy prefix on the uncompressed path). The design is sound and the code is well-structured.

High-severity findings (1):

  • [db/log_writer.h:126] New defaulted parameter uint64_t wal_index = 0 on AddRecord() violates CLAUDE.md's Miss Spelling in README #1 refactoring trap rule.
Full review (click to expand)

Findings

🔴 HIGH

H1. New defaulted parameter on AddRecord — db/log_writer.h:126
  • Issue: CLAUDE.md explicitly states "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" The PR adds uint64_t wal_index = 0 as a fourth defaulted parameter to AddRecord(). Both seqno and wal_index are uint64_t, making it easy for a future caller to accidentally pass a wal_index value in the seqno position (or vice versa), with the compiler silently accepting it.
  • Root cause: The existing seqno parameter was already defaulted (= 0), and adding another defaulted parameter of the same type compounds the risk.
  • Suggested fix: Use a separate overload or a named-parameter struct. For example:
    IOStatus AddRecord(const WriteOptions& write_options, const Slice& slice,
                       const SequenceNumber& seqno, uint64_t wal_index);
    IOStatus AddRecord(const WriteOptions& write_options, const Slice& slice) {
      return AddRecord(write_options, slice, 0, 0);
    }
    This forces callers that supply a wal_index to also supply seqno explicitly, preventing silent type confusion. Alternatively, wrap wal_index in a strong type.

🟡 MEDIUM

M1. Missing option plumbing per add_option.md checklist — multiple files
  • Issue: The partition_wal_usage option is added to DBOptions, ImmutableDBOptions, options parsing, C API, and options tests. However, per claude_md/add_option.md, several integration points are missing:
    • db_stress_tool/db_stress_common.h (DECLARE)
    • db_stress_tool/db_stress_gflags.cc (DEFINE)
    • db_stress_tool/db_stress_test_base.cc (apply flag)
    • tools/db_bench_tool.cc (flag definition and application)
    • tools/db_crashtest.py (randomized stress test values)
    • unreleased_history/ (release note)
  • Root cause: This PR focuses on the writer infrastructure; stress/bench integration may be planned for a later diff that wires the option to the DB.
  • Suggested fix: Confirm these are tracked for the follow-up diff. At minimum, add the unreleased_history/ release note and consider db_crashtest.py coverage now to ensure the option is exercised.
M2. No test for WAL index + compression — db/log_test.cc
  • Issue: The PR has dedicated code for the compressed path (indexed_payload.reserve(...); PutFixed64(&indexed_payload, wal_index); ...) but no test exercises it. The CompressionLogTest parameterized test does not enable WAL index, and no WAL-index-specific test uses compression.
  • Root cause: The CompressionLogTest fixture doesn't call EnableWALIndex().
  • Suggested fix: Add a test (e.g., CompressionLogTest.WALIndexWithCompression or a new parameterized variant) that enables both compression and WAL index, writes multiple records, and verifies the wal_index values survive the compress/decompress round-trip (once reader support is available) or at least that the write succeeds without error.
M3. No test for fragmented WAL index record (prefix spanning blocks) — db/log_test.cc
  • Issue: The wal_index prefix is 8 bytes. If a record starts near the end of a block with fewer than header_size + 8 bytes remaining, the prefix will be split across fragments. The fragmentation code (prefix_length = std::min(fragment_length, wal_index_prefix.size())) handles this, but no test exercises the boundary case where the wal_index prefix itself is split.
  • Root cause: Existing fragmentation tests don't enable WAL index.
  • Suggested fix: Add a test that positions the writer near the block boundary (so only a few bytes remain after the header), enables WAL index, and writes a record. Verify the write succeeds and the on-disk bytes are correct.
M4. C API enum validation gap — db/c.cc, c_api_gen/c_generated_option_structs_auto.cc.inc
  • Issue: rocksdb_options_set_partition_wal_usage(opt, int v) uses static_cast<decltype(opt->rep.partition_wal_usage)>(v) to convert any int to PartitionWALUsage. An invalid integer value (e.g., 3, 99) would silently produce an invalid enum value. The WALIndexEnabled() function has a switch without default that handles only kNone and kPartitionByColumnFamily, followed by return false. An unrecognized enum value would fall through to return false, which is safe, but the invalid value would be stored and serialized.
  • Root cause: The auto-generated C API binding doesn't validate enum range.
  • Suggested fix: Add validation in the setter, or document that invalid values default to kNone behavior. Consider adding a static_assert or range check.

🟢 LOW / NIT

L1. MaybeSwitchToNewBlock called with std::string for marker — db/log_writer.cc
  • Issue: In MaybeAddWALIndexMarkerRecord(), MaybeSwitchToNewBlock(write_options, empty_payload) is called with a local std::string empty_payload. The function takes const std::string& and checks header_size_ + content_to_write.size(). This works correctly (size=0), but the empty_payload local variable is unnecessary.
  • Suggested fix: Pass std::string{} directly or refactor MaybeSwitchToNewBlock to accept a size_t content_size.
L2. PartitionWALUsage::kPartitionByColumnFamily = 0x02 skips 0x01 — include/rocksdb/options.h
  • Issue: The enum skips value 0x01 (the removed kRecordOrderingSingleFile). While the test confirms the removed name no longer parses, having a gap in a new experimental enum could be confusing.
  • Suggested fix: Consider adding a comment in the enum explaining the gap (e.g., "0x01 was removed before public release").
L3. Reader is_recyclable_type not updated — db/log_reader.cc:571-574,979-981
  • Issue: The reader's is_recyclable_type check doesn't include the new recyclable WAL index types. This is intentional for backward compatibility. For non-recyclable WAL index types (12, 14-17), the header size is correctly 7 bytes, so the CRC check passes but the type falls to default: and reports corruption. For recyclable types (13, 18-21), the wrong header size (7 instead of 11) causes a CRC mismatch first.
  • Suggested fix: No action needed now (reader changes are follow-up), but document the reader-side TODO prominently. Consider adding a code comment at the is_recyclable_type check noting the WAL index types need to be added when reader support lands.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
MANIFEST writer (version_set.cc) Uses log::Writer but WALIndexEnabled defaults false Yes Safe
WritePreparedTxnDB wal_index not plumbed to AddRecord caller N/A Future work
ReadOnly DB No writes N/A Safe
Compressed WAL Yes - dedicated code path Needs test (M2) Add test
Recycled log files Yes - SelectRecordType handles Correct Safe
Concurrent memtable write AddRecord called under log_write_mutex Yes Safe

Assumption stress-test: "With indexing disabled the output is byte-identical to before"

  • CRC path: When prefix.empty(), combined_payload_crc = payload_crc. When payload_size == 0, the new code uses 0 while old used crc32c::Value(ptr, 0). Since Value(ptr, 0) = Extend(0, ptr, 0) = 0, these are identical. Claim holds.
  • Append path: The condition (payload_size > 0 || prefix.empty()) with empty prefix always evaluates to true (since prefix.empty() is true), producing a single Append call as before. Claim holds.
  • Header size selection: IsRecyclableRecordType() is verified by the HeaderSelectionUnchangedForPreWALIndexTypes static_assert to agree with the old hardcoded condition for all pre-WAL-index types. Claim holds.

Assumption stress-test: "WAL index values strictly increase"

  • First record: last_wal_index_recorded_ starts at 0. First wal_index >= kWALIndexStartNumber (1). 1 <= 0 is false. Correct.
  • Concurrent access: AddRecord is called under log_write_mutex_ in db_impl_write.cc:2337. Safe.
  • Failed write: If EmitPhysicalRecord fails, last_wal_index_recorded_ is NOT updated (update is after if (s.ok())). The burned index TODO is documented. Acceptable for now.

Positive Observations

  • Downgrade safety design: Record types below the safe-ignore mask (128) ensure old readers reject WAL index files rather than silently misreading them. The static_assert pins this invariant.
  • Zero-copy prefix: The uncompressed path passes the 8-byte wal_index as a separate Slice, avoiding a full payload copy. Benchmark numbers confirm meaningful improvement for large values.
  • Static validation: HeaderSelectionUnchangedForPreWALIndexTypes is an excellent compile-time guard ensuring the refactoring of EmitPhysicalRecord's header-size logic doesn't change behavior for existing types.
  • Allowlist pattern: WALIndexEnabled() uses an explicit switch without default, so adding a new PartitionWALUsage value forces a build failure until classified. This is better than != kNone.
  • Defensive validation: The wal_index monotonicity check uses IOStatus::Corruption rather than assert, ensuring production builds catch violations.

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

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

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit c64d7f0


Summary

Well-structured PR that adds WAL index writer support with good separation of concerns. The split-prefix design to avoid payload copies on the uncompressed path is well-motivated by benchmarks. The fail-closed design for older readers via sub-128 record types is correct.

High-severity findings (2):

  • [log_reader.cc:571-574] Reader's recyclable-type check is not updated for new kRecyclableWALIndex* types, causing misframed CRC verification on recycled logs (intended fail-closed, but error message will be misleading "checksum mismatch" instead of "unknown record type").
  • [log_writer.h:123] AddRecord adds a defaulted parameter uint64_t wal_index = 0, violating CLAUDE.md's Miss Spelling in README #1 refactoring trap rule ("Avoid new defaulted parameters").
Full review (click to expand)

Findings

🔴 HIGH

H1. Reader recyclable-type detection not updated for kRecyclableWALIndex* types — log_reader.cc:571-574
  • Issue: Both Reader::ReadPhysicalRecord() (line 571-574) and FragmentBufferedReader::TryReadFragment() (line 979-981) have hardcoded recyclable type checks:
    const bool is_recyclable_type =
        ((type >= kRecyclableFullType && type <= kRecyclableLastType) ||
         type == kRecyclableUserDefinedTimestampSizeType ||
         type == kRecyclePredecessorWALInfoType);
    The new recyclable WAL index types (18-21) are NOT included. When a recyclable WAL index record is encountered, the reader will use kHeaderSize (7) instead of kRecyclableHeaderSize (11). The CRC verification will compute over the wrong byte range, producing kBadRecordChecksum instead of falling through to the default case that would report "unknown record type".
  • Root cause: The reader was intentionally not updated in this PR (reader support is a later diff), but the fail-closed mechanism produces a misleading error on recyclable logs. On a non-recyclable log, the new types (12-17) correctly reach the default case and report "unknown record type".
  • Impact: For recycled indexed WAL files, error diagnostics will say "checksum mismatch" rather than naming the unrecognized record type, making debugging harder. The file IS still rejected (fail-closed holds), but the error path is accidental rather than intentional.
  • Suggested fix: Either (a) add the new recyclable types to the reader's is_recyclable_type check now so they get proper header framing and reach the default switch case with a clear error, or (b) document this as a known limitation. Option (a) is better since it costs nothing, improves error messages, and the reader should ideally use IsRecyclableRecordType() from log_format.h rather than maintaining a separate hardcoded list.
H2. Defaulted parameter on AddRecord — log_writer.h:123
  • Issue: uint64_t wal_index = 0 is a new defaulted parameter, directly violating CLAUDE.md's guidance: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" While AddRecord is a private API, it has ~40+ call sites across production code, tests, and MANIFEST writers. A future caller could silently compile without providing the wal_index, masking a missing assignment.
  • Root cause: Convenience for the many existing callers that don't use WAL indexing.
  • Suggested fix: Remove the default. Add an overload AddRecord(write_options, slice, seqno) that forwards with wal_index=0, or require all callers to pass the value explicitly.

🟡 MEDIUM

M1. Compound defaulted parameters create silent misuse risk — log_writer.h:123
  • Issue: The pre-existing const SequenceNumber& seqno = 0 combined with the new uint64_t wal_index = 0 creates two consecutive defaulted parameters of compatible types. A caller writing AddRecord(opts, slice, wal_index_value) intending to pass a wal_index but forgetting seqno would silently compile with the value interpreted as seqno and wal_index defaulting to 0.
  • Suggested fix: See H2 - remove defaults, use overloads.
M2. No test coverage for WAL-indexed records with compression enabled — log_test.cc
  • Issue: The WAL index tests only run with kNoCompression. The compressed path in AddRecord has different handling (prepends wal_index into indexed_payload buffer), but no test exercises this. The CompressionLogTest doesn't enable WAL indexing.
  • Suggested fix: Add WAL index tests that also run with compression enabled to cover the indexed_payload path.
M3. No test for fragmented records with WAL index prefix — log_test.cc
  • Issue: None of the new tests write records large enough to span block boundaries (32KiB). The prefix fragmentation logic (prefix_length = std::min(fragment_length, wal_index_prefix.size()) and wal_index_prefix.remove_prefix()) is novel and untested at block boundaries.
  • Suggested fix: Add a test that writes a record of size ~kBlockSize with WAL index enabled, forcing the prefix to be in the First fragment and payload to span into Middle/Last fragments.
M4. SetPartitionWALUsage uses assert-only guard — log_writer.h:153
  • Issue: SetPartitionWALUsage asserts partition_wal_usage_ == kNone but doesn't return an error in release builds. If called twice due to a bug, the assert fires in debug but the value silently changes in release, potentially mixing indexed and non-indexed records in the same file.
  • Suggested fix: Consider a stronger guard (e.g., return IOStatus or use a bool flag checked in release).
M5. C API allows invalid enum values for PartitionWALUsage — c_api_gen/c_generated_option_structs_auto.cc.inc
  • Issue: The C API setter does static_cast<decltype(opt->rep.partition_wal_usage)>(v). Since kPartitionByColumnFamily = 0x02 with a gap at 0x01, passing 1 produces an invalid enum value with no validation. Stored configuration files could contain partition_wal_usage=1.
  • Suggested fix: Add validation in the C API setter or in DB::Open() to reject unrecognized enum values.

🟢 LOW / NIT

L1. #include "rocksdb/options.h" added to private header — log_writer.h:22
  • Issue: This is a heavyweight include. Only PartitionWALUsage is needed. Consider a forward declaration or a smaller header to reduce compile times.
L2. const std::string empty_payload in MaybeAddWALIndexMarkerRecord — log_writer.cc:291
  • Issue: Creates a heap-allocated std::string just to pass to MaybeSwitchToNewBlock. Could use a Slice() or std::string_view. Cold path, so no performance concern.
L3. SelectRecordType has duplicate structure — log_writer.cc:237-280
  • Issue: Two structurally identical if-else blocks for indexed and non-indexed types. A table-driven approach would be more compact but the current code is clear.

Cross-Component Analysis

Context Affected? Impact Verdict
MANIFEST writer (version_set.cc) No Default wal_index=0, WALIndexEnabled()=false Safe
Recycled WAL + reader Yes Reader misframes recyclable WAL index records (H1) Misleading error, still fails
Non-recycled WAL + reader Yes Unknown type correctly reported Works as designed
Compressed WAL + index Yes Uses indexed_payload buffer (untested - M2) Likely correct but untested
WritePreparedTxnDB No Writer-only change Safe
ReadOnly / Secondary DB No Writer not used Safe
User-defined timestamps No Orthogonal feature Safe

Positive Observations

  • The static_assert(HeaderSelectionUnchangedForPreWALIndexTypes()) in log_test.cc is excellent regression prevention when adding new record types.
  • The static_assert ensuring WAL index types are below kRecordTypeSafeIgnoreMask guarantees fail-closed on older readers.
  • The split-prefix design in EmitPhysicalRecord avoids an O(n) copy on the common uncompressed path, well-motivated by benchmarks.
  • WALIndexEnabled() using a switch with no default forces build-time classification of new enum values.
  • The burned-index hazard is honestly documented with a TODO naming specific remedies.
  • CRC computation for split prefix+payload uses Crc32cCombine correctly: the mathematical properties of CRC combine guarantee Combine(prefix_crc, payload_crc, payload_len) equals CRC(prefix||payload).

ℹ️ 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#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 20, 2026
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 Nov 19, 2026
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. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build. Non-decreasing sequence numbers per writer are checked only by a debug assert.

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. `wal_index_single_file` is an earlier spelling of what is now `partition_by_column_family` and no longer parses; the numbers were not re-measured:

| 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% |

Test Plan:
Writer-side tests in `db/log_test.cc`, parameterised over recycling x retry-read. They assert on raw file bytes, since nothing above this diff can read an indexed record yet:

- `WALIndexMarkerRecordIsEmpty` — marker is first, right type, zero payload length.
- `WALIndexAssignedConsecutively` — four records encode the four indices they were handed.
- `WALIndexValuesCanSpanWriters` — two writers encode indices drawn from one external sequence.
- `WALIndexMissingAssignmentFailsWrite` — indexing enabled with no assigned index is rejected.
- `WALIndexNonIncreasingFailsWrite` -- an index not above the previous one is rejected with `Corruption`.
- `static_assert(HeaderSelectionUnchangedForPreWALIndexTypes())` — compile-time proof that header selection is unchanged for every pre-existing record type.

Byte-layout and round-trip coverage of the separate-prefix encoding (first-fragment layout, empty record, an index straddling a block boundary) lives in the reader diff above, where a reader exists to complete the round trip.

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

`arc lint -a` on `log_writer.cc`, `log_writer.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: 231 pass.

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

Subscribers: jewoongh, rbanerjee2, anand76

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

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