Repository navigation
Allocate WAL index with the sequence number in DBImpl (#15226) - #15226
JustinGaoF wants to merge 5 commits into
Conversation
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
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
9f2a1fc to
1c5d4bd
Compare
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
1c5d4bd to
0dfeca6
Compare
✅ clang-tidy: No findings on changed linesCompleted in 720.2s. |
Claude Code Review - OBSOLETESuperseded by a newer AI review. Expand to see the original review.✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit 0dfeca6 SummaryWell-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):
Full review (click to expand)Findings🔴 HIGHH1. Missing validation:
|
| 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
HeaderSelectionUnchangedForPreWALIndexTypescompile-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
ReaderandFragmentBufferedReader. - 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
0dfeca6 to
c9a2fb5
Compare
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
c9a2fb5 to
d1c891d
Compare
|
@JustinGaoF has exported this pull request. If you are a Meta employee, you can view the originating Diff in D119600943. |
✅ Claude Code ReviewAuto-triggered after CI passed — reviewing commit d1c891d SummaryWell-structured PR that correctly centralizes WAL index allocation into No high-severity findings. Full review (click to expand)Findings🟡 MEDIUMM1. New defaulted parameter on
|
| 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_assertfor downgrade safety (kRecyclableWALIndexLastType < kRecordTypeSafeIgnoreMask) is excellent.- Compile-time regression check via
HeaderSelectionUnchangedForPreWALIndexTypes()is creative. WALIndexEnabled()allowlist with exhaustiveswitch(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_indexrejected 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
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
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
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
Summary:
Makes
DBImplthe owner of WAL index allocation, and wires indexing into the write path.WAL recovery treats
wal_indexorder 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.AllocateSequenceAndWALIndexreserves the sequence block and, when a WAL record will be written, itswal_index, under one short DB-wideInstrumentedMutex. The assigned index is then passed intolog::Writer::AddRecord.A mutex was chosen over a 16-byte atomic so the future durability-watermark
RegisterPendingcan 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. ThekNonepath 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
SetPartitionWALUsageon each newly created WAL writer and emits the marker fromStartWALFile, 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;
disableWALis covered directly. External-file ingestion already fences both write queues across its sequence assignment, so no indexed allocation can interleave with it.two_write_queuesis rejected, since its second allocation site would need a broader ordering change.kWALIndexPartitionByColumnFamilyis rejected as unimplemented, rather than silently leaving the DB unpartitioned.The counter is not restored across restarts — it starts at
kWALIndexStartNumberon 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 fromkWALIndexStartNumberagain, andWALIndexNumberingRestartsAcrossLiveWALspins 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 existingTODOcontinues to track it.Differential Revision: D119600943