Skip to content

Allocate WAL index with the sequence number in DBImpl (#15226) - #15226

Open
JustinGaoF wants to merge 5 commits into
meta:mainfrom
JustinGaoF:export-D119600943
Open

JustinGaoF wants to merge 5 commits into
meta:mainfrom
JustinGaoF:export-D119600943

Conversation

@JustinGaoF

@JustinGaoF JustinGaoF commented Sep 16, 2026 •

Copy link
Copy Markdown

Summary:

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; disableWAL is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. two_write_queues is rejected, since its second allocation site would need a broader ordering change. kWALIndexPartitionByColumnFamily is rejected as unimplemented, rather than silently leaving the DB unpartitioned.

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

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

Differential Revision: D119600943

Summary:
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 (`wal_index`); 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 `wal_index`, 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.
- `kWALIndexSingleFile` (0x01) — records carry a `wal_index`, WAL layout unchanged. Isolates the format change from any routing change so the two roll out separately.
- `kWALIndexPartitionByColumnFamily` (0x02) — reserved for partitioning WALs by column family. Not implemented; a later diff rejects it at `DB::Open` rather than silently leaving the DB unpartitioned.

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:
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. Two `static_assert`s enforce that, so renumbering into the ignorable range breaks the build instead of turning into silent data loss.

Differential Revision: D118369740
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:
Teaches `log::Reader` and `FragmentBufferedReader` to decode WAL index records.

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

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

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

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

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

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. `kWALIndexPartitionByColumnFamily` is rejected as unimplemented, rather than silently leaving the DB unpartitioned.

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

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

Differential Revision: D119600943
@meta-codesync meta-codesync Bot changed the title Allocate WAL index with the sequence number in DBImpl Allocate WAL index with the sequence number in DBImpl (#15226) Sep 17, 2026
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Sep 17, 2026
Summary:

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. `kWALIndexPartitionByColumnFamily` is rejected as unimplemented, rather than silently leaving the DB unpartitioned.

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

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

Differential Revision: D119600943
@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

✅ clang-tidy: No findings on changed lines

Completed in 720.2s.

@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 0dfeca6


Summary

Well-structured PR that correctly wires WAL index allocation into the write path with proper atomicity guarantees. The WAL record format extensions are clean and backward-compatible. Two configuration gaps need attention.

High-severity findings (1):

  • [db/db_impl/db_impl_open.cc] unordered_write + WAL index is not rejected, but the code path through ConcurrentWriteGroupToWAL acquires sequence_wal_index_mutex_ while wal_write_mutex_ is held, creating an undocumented lock ordering that could deadlock if any future code path acquires them in reverse order.
Full review (click to expand)

Findings

🔴 HIGH

H1. Missing validation: unordered_write + WAL index not rejected — db/db_impl/db_impl_open.cc
  • Issue: The PR rejects two_write_queues + partition_wal_usage (line ~267) but does NOT reject unordered_write + partition_wal_usage. The unordered_write path calls WriteImplWALOnly (db_impl_write.cc:1058-1069) which calls ConcurrentWriteGroupToWAL (line 1967). In the diff, ConcurrentWriteGroupToWAL acquires wal_write_mutex_ (line ~2446) then calls AllocateSequenceAndWALIndex which acquires sequence_wal_index_mutex_. This creates lock ordering wal_write_mutex_ -> sequence_wal_index_mutex_, while all other WAL-index call sites acquire sequence_wal_index_mutex_ alone (no wal_write_mutex_ held). While not an immediate deadlock (no reverse ordering exists today), this is a latent ordering constraint that is undocumented and fragile.
  • Root cause: The validation in ValidateOptions only checks two_write_queues but not unordered_write, even though both use ConcurrentWriteGroupToWAL.
  • Suggested fix: Add validation:
    if (log::WALIndexEnabled(db_options.partition_wal_usage) &&
        db_options.unordered_write) {
      return Status::NotSupported(
          "partition_wal_usage is not supported with unordered_write. ");
    }
    Alternatively, document the lock ordering constraint and add a test for unordered_write + WAL index.

🟡 MEDIUM

M1. AddRecord retains default parameter for seqno — db/log_writer.h:98-99
  • Issue: The old signature AddRecord(write_options, slice, seqno = 0) has a default parameter. The diff adds wal_index but the header diff is truncated. Since many callers (version_set.cc:6242, db_impl_open.cc:372, wal_manager_test.cc:80, etc.) call AddRecord(write_options, record) with only 2 arguments, the new signature must maintain defaults. CLAUDE.md says "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" The existing seqno = 0 default is already a violation, and adding wal_index = 0 as another default compounds the risk.
  • Root cause: Backward compatibility with ~40+ callers that pass only (write_options, record).
  • Suggested fix: Consider adding an overload instead of a default parameter, or explicitly passing all arguments at call sites.
M2. No test for WAL compression + WAL index interaction — db/log_test.cc, db/db_wal_test.cc
  • Issue: The writer has special handling for WAL compression + WAL index (constructing indexed_payload by concatenating the wal_index prefix with the record payload before compression). There is no test that enables both WAL compression and WAL index simultaneously to verify this code path.
  • Root cause: The log_test.cc instantiation at the bottom of the file says "Do NOT enable compression for this instantiation" and the compression tests use a separate LogCompressionTest fixture that doesn't include WAL index tests.
  • Suggested fix: Add at least one test that combines WAL compression with WAL index (e.g., WALIndexWithCompression in the compression test fixture or a new parameterized combination).
M3. No stress test coverage (db_stress) — tools/
  • Issue: The PR adds a new option partition_wal_usage but does not appear to wire it into db_stress. CLAUDE.md says "When adding a new feature, make sure stress test covers the new option."
  • Root cause: The option definition and stress test wiring may be in the truncated part of the diff, but no files under tools/ are in the changed file list.
  • Suggested fix: Add partition_wal_usage to db_stress options with random selection between kNone and kWALIndexSingleFile.
M4. No test for pipelined write path with WAL index — db/db_wal_test.cc
  • Issue: PipelinedWriteImpl has unique and complex sequence assignment logic with WAL index (zero-based numbering then shifted by allocated block). The DB-level tests do not exercise enable_pipelined_write = true with WAL index.
  • Suggested fix: Add a DBWALIndexTest variant with options.enable_pipelined_write = true.
M5. Burned-index window wider than documented — db/db_impl/db_impl_write.cc
  • Issue: The allocation now happens before write-group merging and payload preparation. If the write group merge fails (MergeBatch returns non-OK in WriteGroupToWAL), the allocated wal_index is burned but the sequence was already consumed via FetchAddLastAllocatedSequence. The TODO in the writer acknowledges this but the gap is now wider in the DB-level allocator.
  • Root cause: Moving allocation earlier in the pipeline for atomicity with sequence numbers.
  • Suggested fix: This is documented and acceptable for now, but the TODO should be updated to reflect the DB-level allocation widening.

🟢 LOW / NIT

L1. EmitPhysicalRecord empty-payload edge case — db/log_writer.cc
  • Issue: The condition if (s.ok() && (payload_size > 0 || prefix.empty())) preserves the original behavior of appending an empty Slice for non-prefixed empty records. This is correct but subtle. A comment explaining why would help future maintainers.
L2. static_assert for downgrade safety is well-placed — db/log_format.h
  • Positive: The static_asserts ensuring WAL index types stay below kRecordTypeSafeIgnoreMask are an excellent defensive measure. The HeaderSelectionUnchangedForPreWALIndexTypes compile-time check in log_test.cc is also thorough.
L3. Test helper DecodeWALIndices assumes no compression and single-fragment records — db/log_test.cc
  • Issue: The DecodeWALIndices helper walks the raw file bytes assuming each record is a single physical record (marker header + data header + wal_index + payload). It would silently produce wrong results for multi-fragment records. This is fine for the tests that use it (small payloads), but a comment noting this limitation would be helpful.
L4. WALIndexNumberingRestartsAcrossLiveWALs is a documented limitation, not a finding — db/db_wal_test.cc
  • Positive: The test deliberately pins the restart behavior so a future fix must change the test. Good engineering practice.
L5. C API uses int for enum — c_api_gen/c_generated_option_structs_auto.cc.inc
  • Issue: The C API getter/setter uses int for PartitionWALUsage. This is consistent with other enum options in the C API (e.g., wal_compression) so it follows the existing pattern.

Cross-Component Analysis

Context Does code execute? Assumptions hold? Action needed?
two_write_queues Rejected at validation N/A None (correct)
unordered_write YES - via ConcurrentWriteGroupToWAL Lock ordering undocumented Reject or document
ReadOnly DB No write path Reader handles indexed WALs during recovery None
SecondaryInstance Follows replay path Reader handles indexed WALs None
WAL compression YES - special handling in AddRecord Correct concatenation before compress Add test
Pipelined writes YES - unique sequence logic Shift loop looks correct Add test
External file ingestion Bypasses allocator, catch-up handles it Correct via LastSequence() catch-up None
WriteRecoverableState Bypasses allocator Correct via LastSequence() catch-up None
User-defined timestamps Orthogonal - timestamp records handled separately Compatible None
FIFO / Universal compaction Orthogonal - compaction doesn't interact with write-path allocation Compatible None

Positive Observations

  • The overall design is sound: combining sequence and WAL index allocation under one mutex prevents the ordering inversion described in the PR summary.
  • The WALIndexEnabled() function using an allowlist with no-default switch is excellent defensive coding.
  • The static_asserts for type numbering and the HeaderSelectionUnchangedForPreWALIndexTypes compile-time check are thorough.
  • The reader correctly handles mixed indexed/non-indexed records within a single file.
  • Fragment consistency checking (ensuring all fragments of a logical record agree on WAL index presence) is correctly implemented in both Reader and FragmentBufferedReader.
  • The catch-up mechanism in AllocateSequenceAndWALIndex (syncing with LastSequence() before allocating) correctly handles WriteRecoverableState and external file ingestion advancing the sequence independently.
  • Test coverage is generally strong, including: atomicity under concurrent allocation, disableWAL skipping index, external file ingestion not consuming index, block-boundary straddling, large-value round-trip, non-consecutive indices within a file, mixed indexed/plain records, marker positioning rules, and recovery replay.

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

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. `kWALIndexPartitionByColumnFamily` is rejected as unimplemented, rather than silently leaving the DB unpartitioned.

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

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

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

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. `kWALIndexPartitionByColumnFamily` is rejected as unimplemented, rather than silently leaving the DB unpartitioned.

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

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

Differential Revision: D119600943
@meta-codesync

meta-codesync Bot commented Sep 18, 2026

Copy link
Copy Markdown

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

@github-actions

Copy link
Copy Markdown

✅ Claude Code Review

Auto-triggered after CI passed — reviewing commit d1c891d


Summary

Well-structured PR that correctly centralizes WAL index allocation into DBImpl with proper mutex serialization. The design is sound for the single-write-queue and pipelined-write paths. The test coverage is thorough at both the log and DB level.

No high-severity findings.

Full review (click to expand)

Findings

🟡 MEDIUM

M1. New defaulted parameter on AddRecord — db/log_writer.h
  • Issue: The wal_index parameter added to Writer::AddRecord appears to use a default value (callers in version_set.cc call AddRecord(write_options, record) with only 2 args). CLAUDE.md explicitly warns: "Avoid new defaulted parameters. This is the Miss Spelling in README #1 trap on refactoring!" A future caller could silently get wal_index=0 on a WAL writer that has WALIndexEnabled(), triggering the "WAL index was not assigned" corruption error at runtime rather than at compile time.
  • Root cause: Existing callers like version_set.cc:6242 and db_impl_open.cc:372 must be using defaults for both seqno and wal_index.
  • Suggested fix: Remove the default and add an explicit /*wal_index=*/0 at each non-WAL callsite (MANIFEST writers, compaction progress writers, etc.). This makes it a compile-time error if a new WAL callsite forgets the argument.
M2. Missing validation for unordered_write + WALIndexEnabled — db/db_impl/db_impl_open.cc
  • Issue: The PR rejects two_write_queues + WALIndexEnabled but does NOT reject unordered_write + WALIndexEnabled (with two_write_queues=false). With unordered_write, the write path goes through WriteImplWALOnly → ConcurrentWriteGroupToWAL (assertion at db_impl_write.cc:2431 allows unordered_write without two_write_queues). While the PR correctly modifies ConcurrentWriteGroupToWAL to support WAL index, this configuration is untested. The PR description focuses on rejecting two_write_queues but unordered_write without it is a distinct and reachable combination.
  • Suggested fix: Either add a test for unordered_write + kWALIndexSingleFile or add validation rejecting it.
M3. PipelinedWriteImpl tracer sees wrong sequences — db/db_impl/db_impl_write.cc:1631
  • Issue: In the WAL-indexed pipelined path, writers are first numbered from offset 0 (writer->sequence = next_sequence where next_sequence starts at 0). The tracer loop at line 1631 runs BEFORE AllocateSequenceAndWALIndex and the sequence shift. If tracing is enabled, it observes sequences like 0, 1, 2 instead of the real allocated sequences.
  • Root cause: The tracer loop's position relative to the allocation changed semantically. Previously current_sequence was always correct; now with WAL index it starts at 0.
  • Suggested fix: Move the tracer loop after the allocation and sequence shift, or gate it on !wal_index_enabled.
M4. Lock ordering for sequence_wal_index_mutex_ not documented — db/db_impl/db_impl.h:3387
  • Issue: The codebase documents lock ordering (e.g., mutex_ before wal_write_mutex_). In ConcurrentWriteGroupToWAL, sequence_wal_index_mutex_ is acquired while wal_write_mutex_ is held, creating the ordering wal_write_mutex_ → sequence_wal_index_mutex_. In WriteImpl and PipelinedWriteImpl, sequence_wal_index_mutex_ is taken alone. No circular dependency, but the ordering should be documented to prevent future deadlocks.
  • Suggested fix: Add a comment: "Lock ordering: if both wal_write_mutex_ and sequence_wal_index_mutex_ are needed, acquire wal_write_mutex_ first."

🟢 LOW / NIT

L1. Missing test for WAL compression + WAL index — db/db_wal_test.cc, db/log_test.cc
  • Issue: Neither test file covers the combination of WAL compression with WAL index. The writer has specific logic for this path (building indexed_payload buffer before compression), and the reader must decompress then strip the wal_index. This interaction should be tested.
  • Suggested fix: Add a test case in LogTest or DBWALIndexTest with compression enabled.
L2. WriteRecoverableState bypasses the allocator — db/db_impl/db_impl_write.cc:2507
  • Issue: WriteRecoverableState calls FetchAddLastAllocatedSequence directly, bypassing AllocateSequenceAndWALIndex. This is safe because it only runs under mutex_ during recovery or with two_write_queues (rejected), and the catch-up logic in AllocateSequenceAndWALIndex handles the gap. If two_write_queues support is added later, this bypass will need revisiting.
L3. EmitPhysicalRecord guard for empty appends is subtle — db/log_writer.cc:~492
  • Issue: The condition if (payload_size > 0 || prefix.empty()) preserves the original zero-length Append for unprefixed empty records while skipping it for prefixed-only records (where the prefix Append already happened). This is correct but could use a brief comment since the intent isn't immediately obvious.

Cross-Component Analysis

Context Executes? Safe? Action
two_write_queues Rejected Yes N/A
kWALIndexPartitionByColumnFamily Rejected Yes N/A
unordered_write (no two_write_queues) Yes Probably, but untested M2
Pipelined writes Yes Tracer sees wrong seqs M3
WAL compression Yes Logic correct but untested L1
Recycled log files Yes Covered by parameterized tests Safe
External file ingestion Fenced; catch-up logic handles Yes Safe
MANIFEST/compaction writers Use default wal_index=0 Yes Safe
ReadOnly DB No writes N/A Safe

Positive Observations

  • Dedicated mutex with future extensibility (RegisterPending) is well-justified.
  • static_assert for downgrade safety (kRecyclableWALIndexLastType < kRecordTypeSafeIgnoreMask) is excellent.
  • Compile-time regression check via HeaderSelectionUnchangedForPreWALIndexTypes() is creative.
  • WALIndexEnabled() allowlist with exhaustive switch (no default) ensures new enum values must be explicitly classified.
  • Test pinning the counter-restart limitation (WALIndexNumberingRestartsAcrossLiveWALs) is good practice.
  • Comprehensive byte-level format verification tests.
  • Reader correctly resets last_read_wal_index_ before each record, preventing stale values.
  • Exhausted counter fails rather than wrapping; non-increasing wal_index rejected in writer.

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

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

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

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

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

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

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

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

Differential Revision: D119600943
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Oct 20, 2026
Summary:
Pull Request resolved: meta#15226

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

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

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

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

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

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

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

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

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

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

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

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

Sequence-only writes use the same allocator without consuming an index; `disableWAL` is covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it. `two_write_queues` is rejected, since its second allocation site would need a broader ordering change. `kPartitionByColumnFamily` is not rejected: in this diff it means indexed records in one WAL file at a time, which is what this diff writes. Writing more than one WAL file at a time is the separate `wal_partitions` option (D117251769), which `DB::Open` rejects above 1.

Upstream's WAL sequence-gap filler (facebook/rocksdb meta#15581, `MaybeAddWalSeqnoGapFiller`) is skipped for indexed WALs: a filler would need a `wal_index` below the next batch's. So with `partition_wal_usage` other than `kNone` and `recycle_log_file_num > 0`, a `disableWAL` write still returns `InvalidArgument`, as every such write did before meta#15581, and `TracksWalSeqnoGaps()` leaves `next_seq_after_last_wal_record_` alone. The `recycle_log_file_num` comment in options.h says so. `WriteToWAL` and `WriteGroupToWAL` take the `wal_index` after upstream's `seq_inc`.

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

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

M1: Absorbs GC05 Q3: `test::CountIndexedWALFiles` + 8 N=1 consumer tests (checkpoint, backup, secondary, wal x2, log_iter, repair, ldb). No consumer code fix.

To limit false sharing on the allocation path, `VersionSet::last_sequence_` and `last_allocated_sequence_` are each aligned to their own cache line, and `sequence_wal_index_mutex_` shares a cache line only with `next_wal_index_`, the state it guards. Debug-only hooks (`TEST_AllocateSequenceAndWALIndex`, `TEST_SetNextWALIndex`, `TEST_SequenceWalIndexMutexTakes`) support the new tests.

Changes visible to existing users:
- In VersionSet, `last_sequence_` and `last_allocated_sequence_` now each start their own cache line. This changes the memory layout of the sequence counters that every writer and reader touches, at any setting, and makes VersionSet up to about two cache lines larger.
- Each DBImpl gains a cache-line-aligned mutex and a counter (`sequence_wal_index_mutex_`, `next_wal_index_`). The mutex is never taken at kNone.

Test Plan:
DB-level tests in `db/db_wal_test.cc`, in a new `DBWALIndexTest` fixture (13 tests):

- `TwoWriteQueuesIsRejected` — `DB::Open` returns `NotSupported`.
- `SequenceAndWALIndexAllocationIsAtomic` — concurrent allocation never reverses sequence and index order relative to each other.
- `DisableWALDoesNotConsumeWALIndex` — a `disableWAL` write advances the sequence but not the index.
- `IngestExternalFileDoesNotConsumeWALIndex` — ingestion assigns sequence numbers without consuming an index.
- `IndexedWALReplaysThroughRecovery` — 16 keys survive two reopens.
- `ReadOnlyOpenReadsIndexedWAL` — a read-only open recovers an indexed WAL, with the option on and with it off.
- `WalFilterSeesEveryIndexedRecordOnce` — a `WalFilter` sees every record of two indexed WALs exactly once, in sequence order.
- `WALIndexNumberingRestartsAcrossLiveWALs` — after a reopen and a second round of writes, both live WALs carry `[kWALIndexStartNumber .. +15]`, pinning the documented restart-seeding limitation.
- `DefaultUsageWritesNoIndexedRecords` — with `kNone`, no indexed or marker record type reaches the WAL.
- `IndexedWALCarriesWALIndexOnDisk` — the marker is the first physical record, all 16 data records use indexed types, and the decoded indices are exactly `[kWALIndexStartNumber .. +15]`.
- `SwitchedWALCarriesWALIndexOnDisk` — after `TEST_SwitchWAL()`, the new WAL starts with the marker, its 16 data records use indexed types, and its indices continue from the old WAL (`kWALIndexStartNumber + 16 ..`), so the WAL-switch path is covered as well as Open.
- `ExhaustedWALIndexFailsOnlyWALWrites` — with the counter set to `UINT64_MAX` via `TEST_SetNextWALIndex`, a `disableWAL` write still succeeds and the next WAL write fails with `Corruption: WAL index exhausted`.
- `RecycledIndexedWALWritesNoSeqnoGapFiller` — with `recycle_log_file_num = 3`, an indexed DB rejects a `disableWAL` write with `InvalidArgument` and writes no gap filler into a WAL that starts past an ingested file's sequence number; `kNone` accepts the write and writes the filler. All keys survive a reopen. Neutered separately, the `WriteImpl` check and the `TracksWalSeqnoGaps()` indexing term each make it fail.

Consumer tests (N=1), one per consumer, using the new `test::CountIndexedWALFiles`: `DBWalIteratorTest.IndexedWALsInArchiveAndLive`, `DBSecondaryTest.CatchUpReadsIndexedWAL`, `RepairTest.UnflushedIndexedWAL`, `LdbCmdTest.DumpWalPrintsIndexedRecords`, `BackupEngineTest.BackupWithoutFlushCopiesIndexedWAL`, `CheckpointTest.CheckpointCopiesIndexedWAL` (plus `ReadOnlyOpenReadsIndexedWAL` and `WalFilterSeesEveryIndexedRecordOnce` above).

`IndexedWALCarriesWALIndexOnDisk` was verified to fail without the wiring: disabling the binding makes it report all-zero indices, while the replay tests still pass — a vanilla WAL replays fine, which is why the on-disk assertion is the one that tests this diff.

(The `DBWALIndexTest` run recorded here earlier showed 8 tests and predates the last four tests above; current results for this diff are in the M3 B.1 line at the end.)

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

**Concurrent write throughput.** The earlier `fillseq --threads=1` number could not say anything about `sequence_wal_index_mutex_`, whose entire risk is contention. Measured with an opt build, DB on tmpfs so disk variance does not swamp the signal, `none` and the indexed format run alternately on the same binary. That A/B is clean in the sense that the `kNone` path never enters the allocator, and alternating makes the runs paired, so each pair shares its machine conditions.

```
$ db_bench --benchmarks=fillrandom --threads=N --num=250000 --db=/dev/shm/... \
      --partition_wal_usage={none,partition_by_column_family}      # 166-core host, 22 pairs each

threads=16   none median 722,632 ops/s   indexed median 687,920 ops/s
             paired delta: median -4.1%, mean -3.6%, range -11.2%..+4.9%
             indexed slower in 18 of 22 pairs   (sign test p = 0.0022, one-sided)

threads=64   none median 1,116,295 ops/s  indexed median 1,018,020 ops/s
             paired delta: median -8.8%, mean -9.2%, range -21.3%..+2.1%
             indexed slower in 21 of 22 pairs   (sign test p < 0.0001, one-sided)
```

The indexed runs used the spelling `record_ordering_single_file`, which was removed when the enum went to two values and no longer parses. The same one-file indexed format is now `partition_by_column_family` with the default `wal_partitions=1`. The numbers above were not re-measured.

The paired counts are the result, not the medians: at 16 threads the two ranges overlap almost completely, so the medians on their own look like noise. It took 22 pairs to show they are not. The first 7 pairs gave 4/7 at 16 threads (p = 0.5, indistinguishable from a coin flip) and 6/7 at 64 -- that sample was simply too small, and reporting only its medians would have overstated what had been measured.

The gap widens with thread count, which is consistent with contention but is not isolated to it. The A/B covers the whole indexed path, not the lock: the 8-byte prefix on every record and the marker are in there too. And one effect cuts the other way -- larger write groups at higher thread counts mean the mutex is taken once per group rather than once per write, so per-write lock cost should *fall* as threads rise. Naming the mutex specifically would need a third build with the lock removed and the record format unchanged; that has not been done.

With one WAL file at a time (`wal_partitions=1`) the exposure is bounded regardless: every write already funnels through a serialized group leader. It matters for what comes next -- under partitioning N leaders hit the allocator concurrently and it becomes the one global serialization point in an otherwise parallel write path. Recording the number here so that work starts from a measurement.

An earlier attempt with the DB on the default disk-backed path produced a 19-22% run-to-run spread that straddled zero -- one iteration had the indexed path faster -- and could not resolve an effect this size. The tmpfs numbers above are what the comparison rests on.

`arc lint -a` on all changed files — 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`.

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

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; backup_engine_test + checkpoint_test + db_log_iter_test + db_secondary_test + db_wal_test + ldb_cmd_test + repair_test: 2281 pass.

M5 fold: Absorbs 10 A.1 entries (GC28 5, GC31 4, GC29b 1): GC28 Q8: SequenceWalIndexLock, its debug counter and TEST_SequenceWalIndexMutexTakes, the scope block of AllocateSequenceAndWALIndex (its D119600943 slice), the allocation-section comment; GC31 Q2 (c): VersionSet cache lines, sequence_wal_index_mutex_ with next_wal_index_. Not here after B.1: GC31#362 goes to D123701876 (X26-M5, X33-M5). Exceptions: X28-M5: GC31#363 (db_impl.h) split: removing the old next_wal_index_ declaration goes with GC31#361's new one at D119600943 (else it is declared twice), the cache-line moves stay at D123701876. Hand-splits (rows below the hunk's top row get their slice by a per-row edit): GC28#46 (AllocateSequenceAndWALIndex re-indent, H5): D119600943 takes the scope block, SequenceWalIndexLock, the Allocated sync point and re-indents its lines; D123079329 re-indents the three lines it brings in; D123476301 registers both trackers inside the scope.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of backup_engine_test, checkpoint_test, db_log_iter_test, db_secondary_test, db_wal_test, ldb_cmd_test, repair_test, ldb); 2281 tests, 0 failed.

Reviewers: kinbertchou, xbw, huixiao

Subscribers: jewoongh, rbanerjee2, anand76, huixiao

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

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