Skip to content

Option related Improvements - #653

Closed
SherlockNoMad wants to merge 1 commit into
meta:masterfrom
SherlockNoMad:OptionChanges
Closed

SherlockNoMad wants to merge 1 commit into
meta:masterfrom
SherlockNoMad:OptionChanges

Conversation

@SherlockNoMad

Copy link
Copy Markdown
Contributor
  • Use PlainTableOptions for plaint_table_builder/factory/reader
  • Added GetPlainTableOptionsFromMap() for string option parser
  • Added corresponding test for GetPlainTableOptionsFromMap()

- Use PlainTableOptions for plaint_table_builder/factory/reader
- Added GetPlainTableOptionsFromMap() for string option parser
- Added corresponding test for GetPlainTableOptionsFromMap()
@SherlockNoMad

Copy link
Copy Markdown
Contributor Author

Can somebody help reviewing this change? Thanks.

@SherlockNoMad
SherlockNoMad deleted the OptionChanges branch November 5, 2015 06:47
gz pushed a commit to gz/rocksdb that referenced this pull request Dec 13, 2022
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 9, 2026
Summary:
Reviewer question: does every completion-gate waiter wake and fail promptly when a partition establishes a background error, while an error-free slow partition still waits forever by policy?

What: stalled-partition handling (M2.7). The durability watermark is a minimum, so one hung or failed partition pins every completion gate behind it. A slow partition must keep waiting (no timeout, no watchdog, no new option); a failed partition must fail every parked gate promptly with the background error instead of leaving them to the 1ms poll. This diff closes that notification gap and nothing else: no rerouting, no retry, no failover, no recovery, no rotation, no pipelined N>1, no synced frontier, no change to what a WAL failure means.

How: `WALIOStatusCheck` now calls `SignalWalDurabilityWaitersOnBGError` after releasing `mutex_`. The notifier stores the `wal_durability_bg_error_` predicate flag (release) and then signals `wal_durability_cv_` under `sequence_wal_index_mutex_` when waiters exist. The waiter checks frontier-or-flag under that same mutex before parking, so an error published between the check and the park either lands before the waiter's check (flag observed, sleep skipped) or after it (waiter parked, signal delivered): no lost wake in either order, with no new lock edge (`mutex_` is never held with the sequence mutex) and no behavior change at N=1 (no waiters; one relaxed load on the error path only). The flag mirrors `GetBGError` only as a park predicate and is cleared in `ErrorHandler::ClearBGError`, the single transition of the background error back to OK. The gate's post-wait `SyncWAL`/`FlushWAL(true)` failure needs no new reporting: `SyncWalImpl`/`FlushWAL` already route it to `WALIOStatusCheck` (verified: exactly one notification per failure, no double-report). The 1ms timed wait stays as defense only; correctness never depends on its interval. `Open` still rejects production N>1; only the rejection message changes (stalled-partition handling now exists, recovery and rotation do not).

Neuter checks: `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` (both unmodified, both pass); `WalFailureMatchesSingleWALBehavior` (new: identical injection at N=1 vs N=2, equal code/subcode/severity/message); `SlowPartitionParksInGateWithoutError` (new) plus the unmodified `CompletionWaitsForPriorPartitionAppend` for the slow-not-failed wait. Without a dedicated neuter: paranoid-checks-off WAL failure (no background error exists to notify on, so waiters keep waiting exactly as on the base; covered by reasoning, not by a test, since asserting a hang is not a test).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
This replaces the How paragraph above in two ways: the wake now lives in the error handler, and the park has no timer.
- Every recorded background error wakes parked gates. The wake moved into `ErrorHandler::CheckAndSetRecoveryAndBGError`, so flush, compaction and MANIFEST errors (and future sources) can't be missed. `WALIOStatusCheck` and `TEST_SetBGError` no longer signal directly. The signal always runs under `sequence_wal_index_mutex_` with no waiter-count shortcut. Waiters use a plain `Wait()`; the 1 ms timed wait is gone.
- At N=1, `ErrorHandler` decides exactly what the parent decided (12.1). `HandleKnownErrors` keeps the strict `>` guard. A repeat at the recorded severity wakes gates from the less-severe branch, which still returns early and records nothing. Both wake sites fire only while `bg_error_` is non-OK. So an ignored error, such as a compaction failure under `paranoid_checks=false`, never sets the flag or starts recovery.
- Tests: `CompactionErrorWakesParkedGate`, `LeadershipSyncFailureWakesParkedGate`, `SuppressedErrorLeavesGateUndisturbed`, `CheckThenParkRaceWakesWaiter` (now waits for the flag instead of sleeping), `WalErrorFailsGatedGroupWithFollowers`, `DBErrorHandlingFSTest.IgnoredCompactionErrorStartsNoRecovery`, `DBErrorHandlingFSTest.EqualSeverityRepeatStartsNoRecovery`. `DBIOFailureTest.DropWrites` passes.
- Neuters, run against the full partition suite:
  - Compaction errors stored without the wake -> only `CompactionErrorWakesParkedGate` fails.
  - Signal before the flag store -> only `CheckThenParkRaceWakesWaiter` fails.
  - A suppressed error still wakes -> only `SuppressedErrorLeavesGateUndisturbed` fails.
  - Guard back to `>=` -> both new error-handler tests fail and then hang in `Close()`.
  - No repeat wake -> `GatePostWaitSyncFailureWakesParkedGate` fails.
- LOCK ORDER comment has six rules and lists all 15 multi-take sites. Open takes `sequence_wal_index_mutex_` under `mutex_` alone, and the error signal now does too, so the "no new lock edge" claim above no longer holds.
- Still deferred: a failed append pinning the frontier (round 12 Q6, D-1 / doc 13).

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07's waiter-based tests: `PublicationStopsBelowHeldLowerWrite`, `DisableWalWritesWaitOnlyForLowerRanges` (replaces `DisableWalWritesBypassCompletionGate`, AMB-M2-8(a)), the `HigherSequenceRecoverableStateWins` wait, `DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite` with the AMB-M2-9 tracking line; the waiter-count form of `FillAndSwitchMemtable` (X13); GC06's bypasses; GC10's LOCK ORDER rule 7 (AMB-M2-6).

M3 fold: Absorbs
- GC08 Q1 (paranoid_checks=false is rejected at N>1; Busy/Incomplete escalate), Q6 (the failed WAL range is recorded and released; WALIOStatusCheck pins the failed partition; ClearWalDurabilityBGError out of line), Q7 (SnapshotCommitPublishesAboveHeldLowerWrite enabled), WalPartitionsRequireParanoidChecks, and PublicationBoundedForParallelGroup (exception X6: here because it needs WaitForDurabilityWaiters).
- GC09 Q1, Q3-Q5: completion-gate fences (InstallWalGateFence, WalGateFenceStatus(Locked), UnreleasedWalGateFenceLow) and the park loop's fence exits (X8); the recovery flush drops entries at or above the unreleased fence (FlushJob SequenceFloorIterator); HandleMemTableInsertFailure installs a fence and its call sites pass the first sequence; error_handler ordering; the 24 converted gate tests; the WaitForWalDurability doc (AMB-M3-6).
- GC17 Q7: the ErrorHandler::ClearBGError:BeforeClearStopped sync point; LOCK ORDER rule 8 (AMB-M3-8).
Known verification gap (X6): the DBWalAppendFailureTest fixture tests of this diff's D-1 code first run at D123928339.

Test Plan:
Fault injection is the test; every N>1 case uses the `AllowWalPartitions` hook (production `Open` still rejects N>1).

- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 114 (includes 8 new `DBWritePartitionTest` cases x2 params: slow-park, error-wakes-followers, post-wait-sync-failure wake, error-first, advance-first, barrier race, N=1-equivalence, flag-clear; all pre-existing tests unmodified and passing).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` -- Pass 70.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_io_failure_test` -- Pass 84.
- TSan (`buck2 test @fbcode//mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_write_test -- 'DBWritePartitionTest'`) -- Pass 44, no races.
- `arc lint -a` on all 7 touched files: clean. `arc f`: clean.
- Verification 1 (slow-not-failed): `SlowPartitionParksInGateWithoutError` plus unmodified `CompletionWaitsForPriorPartitionAppend` -- waiter parks (count 1), stays blocked over a bounded observation, both groups OK on release.
- Verification 2 (append I/O error wakes leader and followers): `BackgroundErrorWakesParkedGateWithFollowers` -- forced 2-writer group, one gate install, both wake with IOError, read-only follow-up fails, append outcomes show exactly-once attempts on home partitions.
- Verification 3 (sync failure including post-wait path): `GatePostWaitSyncFailureWakesParkedGate` (standard path only; with two write queues the leadership sync itself goes through SyncWAL so the failure cannot be aimed at the post-wait sync alone, same exclusion as the base test) -- W wakes with the error while M still held; exactly one SyncWAL and one notification per failure.
- Verification 4 (advance-vs-error race, both orders): `DurabilityWaitErrorBeforeAdvanceFailsWaiter`, `DurabilityWaitAdvanceBeforeErrorCompletesWaiter`, `DurabilityWaitAdvanceRacesError` (10 barrier iterations) -- no hang, no stale OK (OK implies a covering frontier), no waiter-count leak, notification fires in every order including with zero waiters.
- Verification 5 (no retry/move, reconciliation exactly once): append-outcome assertions in the tests above (exact attempts, home partitions, allocation order); `ResumeImpl:SyncLastSequenceWithAllocated` fires once per Resume iff two_write_queues, else zero (existing path only, counted, never added).
- Verification 6 (N=1 path and pipelined-N>1 rejection unchanged): unmodified `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` pass; `WalFailureMatchesSingleWALBehavior` compares N=1 vs N=2 status triples exactly.
- N>1 reopen/crash-recovery check: not run -- indexed multi-WAL recovery is unimplemented and production `Open` rejects N>1 (out of scope); the prefix contract is tested in process via statuses plus append outcomes instead.
- N>1 `db_stress` blackbox check: not run -- the tool has no `wal_partitions` support (out of scope); the focused concurrency/fault-injection suite runs under TSan instead.
- Full-suite TSan: not run -- partition-focused TSan (44 tests) covers the changed concurrency code (same scope as the base diff).

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 222, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/26177172892455465).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.
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.

M2 fold: new or moved tests here: PublicationStopsBelowHeldLowerWrite, DisableWalWritesWaitOnlyForLowerRanges, DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + error_handler_fs_test + transaction_test + write_prepared_transaction_test 6337 pass.

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

M4 fold: Absorbs
- GC18 Q8: what survives of the failed-gate-sync fence (TEST_WalGateFences, PublishAppliedFrontierLocked) and Q11's GateSyncFailureWakesParkedGate rename; GC20 Q3's frontier form (exception X4) and Q8 remnants; GC20 Q6's wal_partitions paragraph on a failed sync write as GC25 rewrote it (AMB-M4-7).
- GC20 Q5 / GC21 Q3: the failure half of the epoch hand-split (exception X2: failed epoch and status, shared failure).
- GC21 Q1: ExplainBurnedWALIndices and burned_wal_indices_ (exception X8: hand-ported with CurrentWalOrNull(0) written inline; D123971668 re-extracts it, AMB-M4-2), the LOCK ORDER wording, WalManager::TEST_HasIndeterminateWriteSequence; GC24 Q5 sync point; GC26 Q1: BurnedWALIndexLanded, BurnedWalIndicesPending, BurnedWalIndex::wal_offset and the read-back, zeroing and landed skip in ExplainBurnedWALIndices.
- GC25 Q3/Q4: FailUnpublishedSyncRange (replacing D123551605's hole branch in RunSyncGate, exception X17) and the two-argument HandleMemTableInsertFailure in RunSyncGate; the open-ended InstallWalGateFence; ClearWalDurabilityBGError's fence close; the D-9 doc paragraph; GatePostWaitSyncFailureWakesParkedGate as rewritten; tests ZeroCountMarkerNeverPublishesInFlightSequence (exception X7), FailedSyncPrepareLeavesNoStaleFence (with the test hook, exception X14), EmptyDisableWalCommitSnapshotIsPublished (exception X20).
- Net-zero pairs dropped here (rule 2.7): 77 hunks (699 added lines): the read mask and its read paths, masked memtables, flush drops, mask retirement, exact fences, the fence intent and sync-group registration (GC20 Q5-Q7, GC21 Q3/Q4, GC24 Q2-Q4) cancel with GC25's removals; db/db_impl/wal_gate_read_mask.h is never created.
Known verification gaps: this diff's code is first exercised by fixture tests at D123928339, GC26's Q1 code by DBWalLandedAppendTest at D127093323.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6363 tests, 0 failed.

M5 fold: Absorbs 187 A.1 entries (GC28 30, GC27 15, GC30 55, GC29a 8, GC31 15, GC32 17, GC29b 47): GC30's write pipeline (insert during append, wal_status, leader_exits, callbacks after the fsync, WaitUntilRangesBelowPublished, the inserted failure branch, write_thread.{h,cc}, the flush range-tombstone floor) with its Q1–Q4/Q7 tests; GC27 Q4's 2PC wait and its 2PC tests; GC27 Q6 (BurnedWALIndexLanded's torn begin); GC32's file-scoped resume (guard, reservation, sync points, WALIOStatusCheck push, ClearWalDurabilityBGError's two applied ranges, ExplainBurnedWALIndices(retired_below)); the LOCK ORDER note (GC28, GC31, GC29b); GC28's wait-mutex lock lines; GC31 Q11/Q13 (e); GC29b T4; the X25-M5 tests (GC27's two tailing tests, FrontierNeverPassesAllocatedRange). Not here after B.1: GC30LiveSstHasKey and the three tests that use it go to D123928339 (X34-M5), and so does SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5); GC32#447 goes to D127093323 (X39-M5). M5-F1 (A.8): F1.1 (straggler sequence reuse): HoldSequencesForWalRecoveryRelease and ReleaseSequenceReservation, the allocation wait on sequence_reservation_released_cv_, the release in ClearWalDurabilityBGError, ResumeImpl's step 7, the members and LOCK ORDER rule 3; F1.3: "Ruling 4d:" dropped from WriteImpl's comment. Exceptions: X5-M5; X6-M5; H-M5-1; X21-M5; X25-M5; X26-M5: GC31#362 (WalDurabilityParking::min_target_ on its own cache line) moved here from D119600943: it edits GC28#26's WalDurabilityParking, whose part lands here (X33-M5); X27-M5: GC28#110 (options.h pre-flip wal_partitions doc) split: the manual_wal_flush paragraph at D117251769, the sync-write sentence of the visibility paragraph at D123701876, which writes that paragraph; 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; X29-M5: GC28#16 (db_impl.h): its two edits of D123701876 comment lines land here; the rest of the hunk joins them by X33-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X33-M5: GC28 Q8's parking cluster moved here from D123551605: GC28#1, #2, #16, #26 (its D123551605 part), meta#51, GC31#361's wal_durability_wait_mutex_ cache line, GC31#362, FrontierLockTakenOnlyForAllocation with GC29b#598 (B.1 at D123551605: M4's TimedWait poll on wal_durability_cv_, which this commit replaces, does not compile against GC28's parking type); X36-M5: WalPartitionsOptionRefusalsUnchanged (GC30#245, with GC29b#616) moved from D123079329 to D123701876: the pipelined-write and paranoid_checks refusals it pins first exist here (B.1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.AsyncCommitUnderFailedSyncLeaderNeverVisibleAfterError (after its ClearAllCallBacks, before Reopen); found by B.1: RecoverableStateSlotsTakeHighest (Reopen after DisableProcessing), DBWritePartitionTest.WalPartitionsOptionRefusalsUnchanged and NGreaterThan1FollowerExitHandsFailureToLeader; FLIP removes it.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6407 tests, 0 failed.

M6 fold: Absorbs GC34 Q2 (`ErrorHandler::SetBGErrorBeforeFence` and the `fences_writes` rule: a fence error at N>1 cannot be suppressed by a listener; both fence sites, `HandleMemTableInsertFailure` at N>1 and `FailUnpublishedSyncRange`) and GC34 Q3 (`WaitForWalDurability` gains `applied`; only a waiter whose range is not applied fails on shutdown; every caller passes it; `include/rocksdb/options.h` notes that a write failed by Close()/CancelAllBackgroundWork() before its sync is never visible in the session but may be recovered on reopen), plus GC34 Q5 (b) EXPECT sweeps in tests owned here. Exception (rule 3, -Wunused-parameter): Q3's signature and callers land here with the shutdown leg rather than at D123551605 as GC34's split proposed. Hand-port: `RunCompletionGate`'s earlier body passes `/*applied=*/published` here; D123971668's rewrite carries it.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test transaction_test write_prepared_transaction_test: 6407/6407).

Differential Revision: https://phabricator.intern.facebook.com/D123701876
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 9, 2026
…partitions (M2.9)

Summary:
**Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers.

**Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches.

| | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) |
|---|---|---|
| WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B |
| files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 |
| bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same |
| WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable |

The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on.

**Changes**

- **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global.
- **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file.
- **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, `SwitchMemtable` now wakes parked completion gates (`SignalWalDurabilityWaitersOnBGError`, with `mutex_` released) the same way an append failure does. Before, it set the background error without the durability flag or the wake. It wakes only when the background error is actually non-OK, so it does not take on 09's listener-suppression issue (09.1 #3).
- **Change (R7):** the N>1 rejection message drops "WAL rotation". It now reads "unindexed multi-WAL recovery is not implemented". The rejection itself stays.
- **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`.

**Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them.

**Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0.

**R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure.

**Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, which replaces the R6 Fix bullet above. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0.
- Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`.
  - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A.
  - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent.
  - A `Defer` closes the DB on every exit path.
  - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here).

M3 fold: Absorbs
- GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys.
- GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13).
- GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6).
- GC14a Q5: RotationWalCreationFailureWakesGates comment.
- GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10).

Test Plan:
Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched.

**Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout.
- `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass.
- `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass.
- Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers.

**New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true):
- `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary.
- `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both.
- `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails.
- `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too.
- `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0.
- `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds.
- `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent.
- `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker.
- Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass.

**Neuter checks** (each production change reverted locally, test rerun):
- `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail.
- Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter.
- Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert.
- `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false).
- `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window.
- No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design.

**R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff.
- Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below.
- Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports.

**db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope.

**Known 09 issues (09.1):** none observed; no new test was flaky or slow through them.

**Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/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.

M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeFailsOnPristineHoleAndSaysWhy, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass.

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

M4 fold: Absorbs
- Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip).
- GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20).
- GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses.
- GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal.
- GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen.
- Net-zero pairs dropped (rule 2.7): none.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed.

M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it.

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

M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070).

Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 9, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the two sync-claim walks. Callers: `PreprocessWrite`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gains the `wal_sync_mark_mutex_` rules for the new accessors.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes, unmodified. No test changes in this diff.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 9, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: MaybeInitLogReader peeks with log::ReadWALPartition, and RecoverLogFiles checks again.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 10, 2026
Summary:
Reviewer question: does every completion-gate waiter wake and fail promptly when a partition establishes a background error, while an error-free slow partition still waits forever by policy?

What: stalled-partition handling (M2.7). The durability watermark is a minimum, so one hung or failed partition pins every completion gate behind it. A slow partition must keep waiting (no timeout, no watchdog, no new option); a failed partition must fail every parked gate promptly with the background error instead of leaving them to the 1ms poll. This diff closes that notification gap and nothing else: no rerouting, no retry, no failover, no recovery, no rotation, no pipelined N>1, no synced frontier, no change to what a WAL failure means.

How: `WALIOStatusCheck` now calls `SignalWalDurabilityWaitersOnBGError` after releasing `mutex_`. The notifier stores the `wal_durability_bg_error_` predicate flag (release) and then signals `wal_durability_cv_` under `sequence_wal_index_mutex_` when waiters exist. The waiter checks frontier-or-flag under that same mutex before parking, so an error published between the check and the park either lands before the waiter's check (flag observed, sleep skipped) or after it (waiter parked, signal delivered): no lost wake in either order, with no new lock edge (`mutex_` is never held with the sequence mutex) and no behavior change at N=1 (no waiters; one relaxed load on the error path only). The flag mirrors `GetBGError` only as a park predicate and is cleared in `ErrorHandler::ClearBGError`, the single transition of the background error back to OK. The gate's post-wait `SyncWAL`/`FlushWAL(true)` failure needs no new reporting: `SyncWalImpl`/`FlushWAL` already route it to `WALIOStatusCheck` (verified: exactly one notification per failure, no double-report). The 1ms timed wait stays as defense only; correctness never depends on its interval. `Open` still rejects production N>1; only the rejection message changes (stalled-partition handling now exists, recovery and rotation do not).

Neuter checks: `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` (both unmodified, both pass); `WalFailureMatchesSingleWALBehavior` (new: identical injection at N=1 vs N=2, equal code/subcode/severity/message); `SlowPartitionParksInGateWithoutError` (new) plus the unmodified `CompletionWaitsForPriorPartitionAppend` for the slow-not-failed wait. Without a dedicated neuter: paranoid-checks-off WAL failure (no background error exists to notify on, so waiters keep waiting exactly as on the base; covered by reasoning, not by a test, since asserting a hang is not a test).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
This replaces the How paragraph above in two ways: the wake now lives in the error handler, and the park has no timer.
- Every recorded background error wakes parked gates. The wake moved into `ErrorHandler::CheckAndSetRecoveryAndBGError`, so flush, compaction and MANIFEST errors (and future sources) can't be missed. `WALIOStatusCheck` and `TEST_SetBGError` no longer signal directly. The signal always runs under `sequence_wal_index_mutex_` with no waiter-count shortcut. Waiters use a plain `Wait()`; the 1 ms timed wait is gone.
- At N=1, `ErrorHandler` decides exactly what the parent decided (12.1). `HandleKnownErrors` keeps the strict `>` guard. A repeat at the recorded severity wakes gates from the less-severe branch, which still returns early and records nothing. Both wake sites fire only while `bg_error_` is non-OK. So an ignored error, such as a compaction failure under `paranoid_checks=false`, never sets the flag or starts recovery.
- Tests: `CompactionErrorWakesParkedGate`, `LeadershipSyncFailureWakesParkedGate`, `SuppressedErrorLeavesGateUndisturbed`, `CheckThenParkRaceWakesWaiter` (now waits for the flag instead of sleeping), `WalErrorFailsGatedGroupWithFollowers`, `DBErrorHandlingFSTest.IgnoredCompactionErrorStartsNoRecovery`, `DBErrorHandlingFSTest.EqualSeverityRepeatStartsNoRecovery`. `DBIOFailureTest.DropWrites` passes.
- Neuters, run against the full partition suite:
  - Compaction errors stored without the wake -> only `CompactionErrorWakesParkedGate` fails.
  - Signal before the flag store -> only `CheckThenParkRaceWakesWaiter` fails.
  - A suppressed error still wakes -> only `SuppressedErrorLeavesGateUndisturbed` fails.
  - Guard back to `>=` -> both new error-handler tests fail and then hang in `Close()`.
  - No repeat wake -> `GatePostWaitSyncFailureWakesParkedGate` fails.
- LOCK ORDER comment has six rules and lists all 15 multi-take sites. Open takes `sequence_wal_index_mutex_` under `mutex_` alone, and the error signal now does too, so the "no new lock edge" claim above no longer holds.
- Still deferred: a failed append pinning the frontier (round 12 Q6, D-1 / doc 13).

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07's waiter-based tests: `PublicationStopsBelowHeldLowerWrite`, `DisableWalWritesWaitOnlyForLowerRanges` (replaces `DisableWalWritesBypassCompletionGate`, AMB-M2-8(a)), the `HigherSequenceRecoverableStateWins` wait, `DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite` with the AMB-M2-9 tracking line; the waiter-count form of `FillAndSwitchMemtable` (X13); GC06's bypasses; GC10's LOCK ORDER rule 7 (AMB-M2-6).

M3 fold: Absorbs
- GC08 Q1 (paranoid_checks=false is rejected at N>1; Busy/Incomplete escalate), Q6 (the failed WAL range is recorded and released; WALIOStatusCheck pins the failed partition; ClearWalDurabilityBGError out of line), Q7 (SnapshotCommitPublishesAboveHeldLowerWrite enabled), WalPartitionsRequireParanoidChecks, and PublicationBoundedForParallelGroup (exception X6: here because it needs WaitForDurabilityWaiters).
- GC09 Q1, Q3-Q5: completion-gate fences (InstallWalGateFence, WalGateFenceStatus(Locked), UnreleasedWalGateFenceLow) and the park loop's fence exits (X8); the recovery flush drops entries at or above the unreleased fence (FlushJob SequenceFloorIterator); HandleMemTableInsertFailure installs a fence and its call sites pass the first sequence; error_handler ordering; the 24 converted gate tests; the WaitForWalDurability doc (AMB-M3-6).
- GC17 Q7: the ErrorHandler::ClearBGError:BeforeClearStopped sync point; LOCK ORDER rule 8 (AMB-M3-8).
Known verification gap (X6): the DBWalAppendFailureTest fixture tests of this diff's D-1 code first run at D123928339.

Test Plan:
Fault injection is the test; every N>1 case uses the `AllowWalPartitions` hook (production `Open` still rejects N>1).

- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 114 (includes 8 new `DBWritePartitionTest` cases x2 params: slow-park, error-wakes-followers, post-wait-sync-failure wake, error-first, advance-first, barrier race, N=1-equivalence, flag-clear; all pre-existing tests unmodified and passing).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` -- Pass 70.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_io_failure_test` -- Pass 84.
- TSan (`buck2 test @fbcode//mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_write_test -- 'DBWritePartitionTest'`) -- Pass 44, no races.
- `arc lint -a` on all 7 touched files: clean. `arc f`: clean.
- Verification 1 (slow-not-failed): `SlowPartitionParksInGateWithoutError` plus unmodified `CompletionWaitsForPriorPartitionAppend` -- waiter parks (count 1), stays blocked over a bounded observation, both groups OK on release.
- Verification 2 (append I/O error wakes leader and followers): `BackgroundErrorWakesParkedGateWithFollowers` -- forced 2-writer group, one gate install, both wake with IOError, read-only follow-up fails, append outcomes show exactly-once attempts on home partitions.
- Verification 3 (sync failure including post-wait path): `GatePostWaitSyncFailureWakesParkedGate` (standard path only; with two write queues the leadership sync itself goes through SyncWAL so the failure cannot be aimed at the post-wait sync alone, same exclusion as the base test) -- W wakes with the error while M still held; exactly one SyncWAL and one notification per failure.
- Verification 4 (advance-vs-error race, both orders): `DurabilityWaitErrorBeforeAdvanceFailsWaiter`, `DurabilityWaitAdvanceBeforeErrorCompletesWaiter`, `DurabilityWaitAdvanceRacesError` (10 barrier iterations) -- no hang, no stale OK (OK implies a covering frontier), no waiter-count leak, notification fires in every order including with zero waiters.
- Verification 5 (no retry/move, reconciliation exactly once): append-outcome assertions in the tests above (exact attempts, home partitions, allocation order); `ResumeImpl:SyncLastSequenceWithAllocated` fires once per Resume iff two_write_queues, else zero (existing path only, counted, never added).
- Verification 6 (N=1 path and pipelined-N>1 rejection unchanged): unmodified `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` pass; `WalFailureMatchesSingleWALBehavior` compares N=1 vs N=2 status triples exactly.
- N>1 reopen/crash-recovery check: not run -- indexed multi-WAL recovery is unimplemented and production `Open` rejects N>1 (out of scope); the prefix contract is tested in process via statuses plus append outcomes instead.
- N>1 `db_stress` blackbox check: not run -- the tool has no `wal_partitions` support (out of scope); the focused concurrency/fault-injection suite runs under TSan instead.
- Full-suite TSan: not run -- partition-focused TSan (44 tests) covers the changed concurrency code (same scope as the base diff).

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 222, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/26177172892455465).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.
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.

M2 fold: new or moved tests here: PublicationStopsBelowHeldLowerWrite, DisableWalWritesWaitOnlyForLowerRanges, DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + error_handler_fs_test + transaction_test + write_prepared_transaction_test 6337 pass.

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

M4 fold: Absorbs
- GC18 Q8: what survives of the failed-gate-sync fence (TEST_WalGateFences, PublishAppliedFrontierLocked) and Q11's GateSyncFailureWakesParkedGate rename; GC20 Q3's frontier form (exception X4) and Q8 remnants; GC20 Q6's wal_partitions paragraph on a failed sync write as GC25 rewrote it (AMB-M4-7).
- GC20 Q5 / GC21 Q3: the failure half of the epoch hand-split (exception X2: failed epoch and status, shared failure).
- GC21 Q1: ExplainBurnedWALIndices and burned_wal_indices_ (exception X8: hand-ported with CurrentWalOrNull(0) written inline; D123971668 re-extracts it, AMB-M4-2), the LOCK ORDER wording, WalManager::TEST_HasIndeterminateWriteSequence; GC24 Q5 sync point; GC26 Q1: BurnedWALIndexLanded, BurnedWalIndicesPending, BurnedWalIndex::wal_offset and the read-back, zeroing and landed skip in ExplainBurnedWALIndices.
- GC25 Q3/Q4: FailUnpublishedSyncRange (replacing D123551605's hole branch in RunSyncGate, exception X17) and the two-argument HandleMemTableInsertFailure in RunSyncGate; the open-ended InstallWalGateFence; ClearWalDurabilityBGError's fence close; the D-9 doc paragraph; GatePostWaitSyncFailureWakesParkedGate as rewritten; tests ZeroCountMarkerNeverPublishesInFlightSequence (exception X7), FailedSyncPrepareLeavesNoStaleFence (with the test hook, exception X14), EmptyDisableWalCommitSnapshotIsPublished (exception X20).
- Net-zero pairs dropped here (rule 2.7): 77 hunks (699 added lines): the read mask and its read paths, masked memtables, flush drops, mask retirement, exact fences, the fence intent and sync-group registration (GC20 Q5-Q7, GC21 Q3/Q4, GC24 Q2-Q4) cancel with GC25's removals; db/db_impl/wal_gate_read_mask.h is never created.
Known verification gaps: this diff's code is first exercised by fixture tests at D123928339, GC26's Q1 code by DBWalLandedAppendTest at D127093323.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6363 tests, 0 failed.

M5 fold: Absorbs 187 A.1 entries (GC28 30, GC27 15, GC30 55, GC29a 8, GC31 15, GC32 17, GC29b 47): GC30's write pipeline (insert during append, wal_status, leader_exits, callbacks after the fsync, WaitUntilRangesBelowPublished, the inserted failure branch, write_thread.{h,cc}, the flush range-tombstone floor) with its Q1–Q4/Q7 tests; GC27 Q4's 2PC wait and its 2PC tests; GC27 Q6 (BurnedWALIndexLanded's torn begin); GC32's file-scoped resume (guard, reservation, sync points, WALIOStatusCheck push, ClearWalDurabilityBGError's two applied ranges, ExplainBurnedWALIndices(retired_below)); the LOCK ORDER note (GC28, GC31, GC29b); GC28's wait-mutex lock lines; GC31 Q11/Q13 (e); GC29b T4; the X25-M5 tests (GC27's two tailing tests, FrontierNeverPassesAllocatedRange). Not here after B.1: GC30LiveSstHasKey and the three tests that use it go to D123928339 (X34-M5), and so does SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5); GC32#447 goes to D127093323 (X39-M5). M5-F1 (A.8): F1.1 (straggler sequence reuse): HoldSequencesForWalRecoveryRelease and ReleaseSequenceReservation, the allocation wait on sequence_reservation_released_cv_, the release in ClearWalDurabilityBGError, ResumeImpl's step 7, the members and LOCK ORDER rule 3; F1.3: "Ruling 4d:" dropped from WriteImpl's comment. Exceptions: X5-M5; X6-M5; H-M5-1; X21-M5; X25-M5; X26-M5: GC31#362 (WalDurabilityParking::min_target_ on its own cache line) moved here from D119600943: it edits GC28#26's WalDurabilityParking, whose part lands here (X33-M5); X27-M5: GC28#110 (options.h pre-flip wal_partitions doc) split: the manual_wal_flush paragraph at D117251769, the sync-write sentence of the visibility paragraph at D123701876, which writes that paragraph; 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; X29-M5: GC28#16 (db_impl.h): its two edits of D123701876 comment lines land here; the rest of the hunk joins them by X33-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X33-M5: GC28 Q8's parking cluster moved here from D123551605: GC28#1, #2, #16, #26 (its D123551605 part), meta#51, GC31#361's wal_durability_wait_mutex_ cache line, GC31#362, FrontierLockTakenOnlyForAllocation with GC29b#598 (B.1 at D123551605: M4's TimedWait poll on wal_durability_cv_, which this commit replaces, does not compile against GC28's parking type); X36-M5: WalPartitionsOptionRefusalsUnchanged (GC30#245, with GC29b#616) moved from D123079329 to D123701876: the pipelined-write and paranoid_checks refusals it pins first exist here (B.1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.AsyncCommitUnderFailedSyncLeaderNeverVisibleAfterError (after its ClearAllCallBacks, before Reopen); found by B.1: RecoverableStateSlotsTakeHighest (Reopen after DisableProcessing), DBWritePartitionTest.WalPartitionsOptionRefusalsUnchanged and NGreaterThan1FollowerExitHandsFailureToLeader; FLIP removes it.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6407 tests, 0 failed.

M6 fold: Absorbs GC34 Q2 (`ErrorHandler::SetBGErrorBeforeFence` and the `fences_writes` rule: a fence error at N>1 cannot be suppressed by a listener; both fence sites, `HandleMemTableInsertFailure` at N>1 and `FailUnpublishedSyncRange`) and GC34 Q3 (`WaitForWalDurability` gains `applied`; only a waiter whose range is not applied fails on shutdown; every caller passes it; `include/rocksdb/options.h` notes that a write failed by Close()/CancelAllBackgroundWork() before its sync is never visible in the session but may be recovered on reopen), plus GC34 Q5 (b) EXPECT sweeps in tests owned here. Exception (rule 3, -Wunused-parameter): Q3's signature and callers land here with the shutdown leg rather than at D123551605 as GC34's split proposed. Hand-port: `RunCompletionGate`'s earlier body passes `/*applied=*/published` here; D123971668's rewrite carries it.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test transaction_test write_prepared_transaction_test: 6407/6407).

Differential Revision: https://phabricator.intern.facebook.com/D123701876
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 10, 2026
…partitions (M2.9)

Summary:
**Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers.

**Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches.

| | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) |
|---|---|---|
| WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B |
| files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 |
| bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same |
| WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable |

The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on.

**Changes**

- **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global.
- **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file.
- **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, `SwitchMemtable` now wakes parked completion gates (`SignalWalDurabilityWaitersOnBGError`, with `mutex_` released) the same way an append failure does. Before, it set the background error without the durability flag or the wake. It wakes only when the background error is actually non-OK, so it does not take on 09's listener-suppression issue (09.1 #3).
- **Change (R7):** the N>1 rejection message drops "WAL rotation". It now reads "unindexed multi-WAL recovery is not implemented". The rejection itself stays.
- **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`.

**Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them.

**Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0.

**R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure.

**Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, which replaces the R6 Fix bullet above. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0.
- Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`.
  - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A.
  - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent.
  - A `Defer` closes the DB on every exit path.
  - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here).

M3 fold: Absorbs
- GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys.
- GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13).
- GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6).
- GC14a Q5: RotationWalCreationFailureWakesGates comment.
- GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10).

Test Plan:
Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched.

**Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout.
- `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass.
- `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass.
- Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers.

**New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true):
- `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary.
- `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both.
- `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails.
- `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too.
- `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0.
- `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds.
- `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent.
- `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker.
- Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass.

**Neuter checks** (each production change reverted locally, test rerun):
- `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail.
- Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter.
- Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert.
- `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false).
- `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window.
- No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design.

**R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff.
- Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below.
- Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports.

**db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope.

**Known 09 issues (09.1):** none observed; no new test was flaky or slow through them.

**Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/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.

M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeFailsOnPristineHoleAndSaysWhy, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass.

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

M4 fold: Absorbs
- Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip).
- GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20).
- GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses.
- GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal.
- GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen.
- Net-zero pairs dropped (rule 2.7): none.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed.

M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it.

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

M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070).

Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 10, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the two sync-claim walks. Callers: `PreprocessWrite`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gains the `wal_sync_mark_mutex_` rules for the new accessors.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes, unmodified. No test changes in this diff.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 10, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: MaybeInitLogReader peeks with log::ReadWALPartition, and RecoverLogFiles checks again.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Reviewer question: does every completion-gate waiter wake and fail promptly when a partition establishes a background error, while an error-free slow partition still waits forever by policy?

What: stalled-partition handling (M2.7). The durability watermark is a minimum, so one hung or failed partition pins every completion gate behind it. A slow partition must keep waiting (no timeout, no watchdog, no new option); a failed partition must fail every parked gate promptly with the background error instead of leaving them to the 1ms poll. This diff closes that notification gap and nothing else: no rerouting, no retry, no failover, no recovery, no rotation, no pipelined N>1, no synced frontier, no change to what a WAL failure means.

How: `WALIOStatusCheck` now calls `SignalWalDurabilityWaitersOnBGError` after releasing `mutex_`. The notifier stores the `wal_durability_bg_error_` predicate flag (release) and then signals `wal_durability_cv_` under `sequence_wal_index_mutex_` when waiters exist. The waiter checks frontier-or-flag under that same mutex before parking, so an error published between the check and the park either lands before the waiter's check (flag observed, sleep skipped) or after it (waiter parked, signal delivered): no lost wake in either order, with no new lock edge (`mutex_` is never held with the sequence mutex) and no behavior change at N=1 (no waiters; one relaxed load on the error path only). The flag mirrors `GetBGError` only as a park predicate and is cleared in `ErrorHandler::ClearBGError`, the single transition of the background error back to OK. The gate's post-wait `SyncWAL`/`FlushWAL(true)` failure needs no new reporting: `SyncWalImpl`/`FlushWAL` already route it to `WALIOStatusCheck` (verified: exactly one notification per failure, no double-report). The 1ms timed wait stays as defense only; correctness never depends on its interval. `Open` still rejects production N>1; the rejection message changes (stalled-partition handling now exists, recovery and rotation do not), and N>1 now also requires `paranoid_checks=true` (NotSupported otherwise). The `wal_partitions` documentation in include/rocksdb/options.h gains the N>1 write visibility and failure semantics.

Neuter checks: `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` (both unmodified, both pass); `WalFailureMatchesSingleWALBehavior` (new: identical injection at N=1 vs N=2, equal code/subcode/severity/message); `SlowPartitionParksInGateWithoutError` (new) plus the unmodified `CompletionWaitsForPriorPartitionAppend` for the slow-not-failed wait. Without a dedicated neuter: paranoid-checks-off WAL failure (no background error exists to notify on, so waiters keep waiting exactly as on the base; covered by reasoning, not by a test, since asserting a hang is not a test).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
This replaces the How paragraph above in two ways: the wake now lives in the error handler, and the park has no timer.
- Every recorded background error wakes parked gates. The wake moved into `ErrorHandler::CheckAndSetRecoveryAndBGError`, so flush, compaction and MANIFEST errors (and future sources) can't be missed. `WALIOStatusCheck` and `TEST_SetBGError` no longer signal directly. The signal always runs under `wal_durability_wait_mutex_` with no waiter-count shortcut. Waiters use a plain `Wait()`; the 1 ms timed wait is gone.
- At N=1, `ErrorHandler` decides exactly what the parent decided (12.1). `HandleKnownErrors` keeps the strict `>` guard. A repeat at the recorded severity wakes gates from the less-severe branch, which still returns early and records nothing. Both wake sites fire only while `bg_error_` is non-OK. So an ignored error, such as a compaction failure under `paranoid_checks=false`, never sets the flag or starts recovery.
- Tests: `CompactionErrorWakesParkedGate`, `GateSyncFailureWakesParkedGate`, `SuppressedErrorLeavesGateUndisturbed`, `CheckThenParkRaceWakesWaiter` (now waits for the flag instead of sleeping), `WalErrorFailsGatedGroupWithFollowers`, `DBErrorHandlingFSTest.IgnoredCompactionErrorStartsNoRecovery`, `DBErrorHandlingFSTest.EqualSeverityRepeatStartsNoRecovery`. `DBIOFailureTest.DropWrites` passes.
- Neuters, run against the full partition suite:
  - Compaction errors stored without the wake -> only `CompactionErrorWakesParkedGate` fails.
  - Signal before the flag store -> only `CheckThenParkRaceWakesWaiter` fails.
  - A suppressed error still wakes -> only `SuppressedErrorLeavesGateUndisturbed` fails.
  - Guard back to `>=` -> both new error-handler tests fail and then hang in `Close()`.
  - No repeat wake -> `GatePostWaitSyncFailureWakesParkedGate` fails.
- LOCK ORDER comment has ten rules. Open takes `sequence_wal_index_mutex_` under `mutex_` alone, and the error signal takes `wal_durability_wait_mutex_` under `mutex_` (rule 9), so the "no new lock edge" claim above no longer holds.
- Still deferred: a failed append pinning the frontier (round 12 Q6, D-1 / doc 13).

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07's waiter-based tests: `PublicationStopsBelowHeldLowerWrite`, `DisableWalWritesWaitOnlyForLowerRanges` (replaces `DisableWalWritesBypassCompletionGate`, AMB-M2-8(a)), the `HigherSequenceRecoverableStateWins` wait, `DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite` with the AMB-M2-9 tracking line; the waiter-count form of `FillAndSwitchMemtable` (X13); GC06's bypasses; GC10's LOCK ORDER rule 7 (AMB-M2-6).

M3 fold: Absorbs
- GC08 Q1 (paranoid_checks=false is rejected at N>1; Busy/Incomplete escalate), Q6 (the failed WAL range is recorded and released; WALIOStatusCheck pins the failed partition; ClearWalDurabilityBGError out of line), Q7 (SnapshotCommitPublishesAboveHeldLowerWrite enabled), WalPartitionsRequireParanoidChecks, and PublicationBoundedForParallelGroup (exception X6: here because it needs WaitForDurabilityWaiters).
- GC09 Q1, Q3-Q5: completion-gate fences (InstallWalGateFence, WalGateFenceStatus(Locked), UnreleasedWalGateFenceLow) and the park loop's fence exits (X8); the recovery flush drops entries at or above the unreleased fence (FlushJob SequenceFloorIterator); HandleMemTableInsertFailure installs a fence and its call sites pass the first sequence; error_handler ordering; the 24 converted gate tests; the WaitForWalDurability doc (AMB-M3-6).
- GC17 Q7: the ErrorHandler::ClearBGError:BeforeClearStopped sync point; LOCK ORDER rule 8 (AMB-M3-8).
Known verification gap (X6): the DBWalAppendFailureTest fixture tests of this diff's D-1 code first run at D123928339.

Changes visible to existing users:
- At any wal_partitions, each background error that ErrorHandler records (or repeats at the recorded severity) now takes wal_durability_wait_mutex_ and broadcasts a condition variable while holding the DB mutex.
- DB::Resume() and automatic recovery (ErrorHandler::ClearBGError) now take wal_durability_wait_mutex_ once and walk two lists that are empty at wal_partitions = 1.
- WriteThread::WriteGroup grows by a Status and two bools.

Test Plan:
Fault injection is the test; every N>1 case uses the `AllowWalPartitions` hook (production `Open` still rejects N>1).

- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 114 (includes 8 new `DBWritePartitionTest` cases x2 params: slow-park, error-wakes-followers, post-wait-sync-failure wake, error-first, advance-first, barrier race, N=1-equivalence, flag-clear; all pre-existing tests unmodified and passing).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` -- Pass 70.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_io_failure_test` -- Pass 84.
- TSan (`buck2 test @fbcode//mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_write_test -- 'DBWritePartitionTest'`) -- Pass 44, no races.
- `arc lint -a` on all 7 touched files: clean. `arc f`: clean.
- Verification 1 (slow-not-failed): `SlowPartitionParksInGateWithoutError` plus unmodified `CompletionWaitsForPriorPartitionAppend` -- waiter parks (count 1), stays blocked over a bounded observation, both groups OK on release.
- Verification 2 (append I/O error wakes leader and followers): `BackgroundErrorWakesParkedGateWithFollowers` -- forced 2-writer group, one gate install, both wake with IOError, read-only follow-up fails, append outcomes show exactly-once attempts on home partitions.
- Verification 3 (sync failure including post-wait path): `GatePostWaitSyncFailureWakesParkedGate` (standard path only; with two write queues the leadership sync itself goes through SyncWAL so the failure cannot be aimed at the post-wait sync alone, same exclusion as the base test) -- W wakes with the error while M still held; exactly one SyncWAL and one notification per failure.
- Verification 4 (advance-vs-error race, both orders): `DurabilityWaitErrorBeforeAdvanceFailsWaiter`, `DurabilityWaitAdvanceBeforeErrorCompletesWaiter`, `DurabilityWaitAdvanceRacesError` (10 barrier iterations) -- no hang, no stale OK (OK implies a covering frontier), no waiter-count leak, notification fires in every order including with zero waiters.
- Verification 5 (no retry/move, reconciliation exactly once): append-outcome assertions in the tests above (exact attempts, home partitions, allocation order); `ResumeImpl:SyncLastSequenceWithAllocated` fires once per Resume iff two_write_queues, else zero (existing path only, counted, never added).
- Verification 6 (N=1 path and pipelined-N>1 rejection unchanged): unmodified `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` pass; `WalFailureMatchesSingleWALBehavior` compares N=1 vs N=2 status triples exactly.
- N>1 reopen/crash-recovery check: not run -- indexed multi-WAL recovery is unimplemented and production `Open` rejects N>1 (out of scope); the prefix contract is tested in process via statuses plus append outcomes instead.
- N>1 `db_stress` blackbox check: not run -- the tool has no `wal_partitions` support (out of scope); the focused concurrency/fault-injection suite runs under TSan instead.
- Full-suite TSan: not run -- partition-focused TSan (44 tests) covers the changed concurrency code (same scope as the base diff).

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 222, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/26177172892455465).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.
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.

M2 fold: new or moved tests here: PublicationStopsBelowHeldLowerWrite, DisableWalWritesWaitOnlyForLowerRanges, DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + error_handler_fs_test + transaction_test + write_prepared_transaction_test 6337 pass.

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

M4 fold: Absorbs
- GC18 Q8: what survives of the failed-gate-sync fence (TEST_WalGateFences, PublishAppliedFrontierLocked) and Q11's GateSyncFailureWakesParkedGate rename; GC20 Q3's frontier form (exception X4) and Q8 remnants; GC20 Q6's wal_partitions paragraph on a failed sync write as GC25 rewrote it (AMB-M4-7).
- GC20 Q5 / GC21 Q3: the failure half of the epoch hand-split (exception X2: failed epoch and status, shared failure).
- GC21 Q1: ExplainBurnedWALIndices and burned_wal_indices_ (exception X8: hand-ported with CurrentWalOrNull(0) written inline; D123971668 re-extracts it, AMB-M4-2), the LOCK ORDER wording, WalManager::TEST_HasIndeterminateWriteSequence; GC24 Q5 sync point; GC26 Q1: BurnedWALIndexLanded, BurnedWalIndicesPending, BurnedWalIndex::wal_offset and the read-back, zeroing and landed skip in ExplainBurnedWALIndices.
- GC25 Q3/Q4: FailUnpublishedSyncRange (replacing D123551605's hole branch in RunSyncGate, exception X17) and the two-argument HandleMemTableInsertFailure in RunSyncGate; the open-ended InstallWalGateFence; ClearWalDurabilityBGError's fence close; the D-9 doc paragraph; GatePostWaitSyncFailureWakesParkedGate as rewritten; tests ZeroCountMarkerNeverPublishesInFlightSequence (exception X7), FailedSyncPrepareLeavesNoStaleFence (with the test hook, exception X14), EmptyDisableWalCommitSnapshotIsPublished (exception X20).
- Net-zero pairs dropped here (rule 2.7): 77 hunks (699 added lines): the read mask and its read paths, masked memtables, flush drops, mask retirement, exact fences, the fence intent and sync-group registration (GC20 Q5-Q7, GC21 Q3/Q4, GC24 Q2-Q4) cancel with GC25's removals; db/db_impl/wal_gate_read_mask.h is never created.
Known verification gaps: this diff's code is first exercised by fixture tests at D123928339, GC26's Q1 code by DBWalLandedAppendTest at D127093323.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6363 tests, 0 failed.

M5 fold: Absorbs 187 A.1 entries (GC28 30, GC27 15, GC30 55, GC29a 8, GC31 15, GC32 17, GC29b 47): GC30's write pipeline (insert during append, wal_status, leader_exits, callbacks after the fsync, WaitUntilRangesBelowPublished, the inserted failure branch, write_thread.{h,cc}, the flush range-tombstone floor) with its Q1–Q4/Q7 tests; GC27 Q4's 2PC wait and its 2PC tests; GC27 Q6 (BurnedWALIndexLanded's torn begin); GC32's file-scoped resume (guard, reservation, sync points, WALIOStatusCheck push, ClearWalDurabilityBGError's two applied ranges, ExplainBurnedWALIndices(retired_below)); the LOCK ORDER note (GC28, GC31, GC29b); GC28's wait-mutex lock lines; GC31 Q11/Q13 (e); GC29b T4; the X25-M5 tests (GC27's two tailing tests, FrontierNeverPassesAllocatedRange). Not here after B.1: GC30LiveSstHasKey and the three tests that use it go to D123928339 (X34-M5), and so does SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5); GC32#447 goes to D127093323 (X39-M5). M5-F1 (A.8): F1.1 (straggler sequence reuse): HoldSequencesForWalRecoveryRelease and ReleaseSequenceReservation, the allocation wait on sequence_reservation_released_cv_, the release in ClearWalDurabilityBGError, ResumeImpl's step 7, the members and LOCK ORDER rule 3; F1.3: "Ruling 4d:" dropped from WriteImpl's comment. Exceptions: X5-M5; X6-M5; H-M5-1; X21-M5; X25-M5; X26-M5: GC31#362 (WalDurabilityParking::min_target_ on its own cache line) moved here from D119600943: it edits GC28#26's WalDurabilityParking, whose part lands here (X33-M5); X27-M5: GC28#110 (options.h pre-flip wal_partitions doc) split: the manual_wal_flush paragraph at D117251769, the sync-write sentence of the visibility paragraph at D123701876, which writes that paragraph; 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; X29-M5: GC28#16 (db_impl.h): its two edits of D123701876 comment lines land here; the rest of the hunk joins them by X33-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X33-M5: GC28 Q8's parking cluster moved here from D123551605: GC28#1, #2, #16, #26 (its D123551605 part), meta#51, GC31#361's wal_durability_wait_mutex_ cache line, GC31#362, FrontierLockTakenOnlyForAllocation with GC29b#598 (B.1 at D123551605: M4's TimedWait poll on wal_durability_cv_, which this commit replaces, does not compile against GC28's parking type); X36-M5: WalPartitionsOptionRefusalsUnchanged (GC30#245, with GC29b#616) moved from D123079329 to D123701876: the pipelined-write and paranoid_checks refusals it pins first exist here (B.1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.AsyncCommitUnderFailedSyncLeaderNeverVisibleAfterError (after its ClearAllCallBacks, before Reopen); found by B.1: RecoverableStateSlotsTakeHighest (Reopen after DisableProcessing), DBWritePartitionTest.WalPartitionsOptionRefusalsUnchanged and NGreaterThan1FollowerExitHandsFailureToLeader; FLIP removes it.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6407 tests, 0 failed.

M6 fold: Absorbs GC34 Q2 (`ErrorHandler::SetBGErrorBeforeFence` and the `fences_writes` rule: a fence error at N>1 cannot be suppressed by a listener; both fence sites, `HandleMemTableInsertFailure` at N>1 and `FailUnpublishedSyncRange`) and GC34 Q3 (`WaitForWalDurability` gains `applied`; only a waiter whose range is not applied fails on shutdown; every caller passes it; `include/rocksdb/options.h` notes that a write failed by Close()/CancelAllBackgroundWork() before its sync is never visible in the session but may be recovered on reopen), plus GC34 Q5 (b) EXPECT sweeps in tests owned here. Exception (rule 3, -Wunused-parameter): Q3's signature and callers land here with the shutdown leg rather than at D123551605 as GC34's split proposed. Hand-port: `RunCompletionGate`'s earlier body passes `/*applied=*/published` here; D123971668's rewrite carries it.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test transaction_test write_prepared_transaction_test: 6407/6407).

Differential Revision: https://phabricator.intern.facebook.com/D123701876
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
…partitions

Summary:
**Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers.

**Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches.

| | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) |
|---|---|---|
| WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B |
| files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 |
| bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same |
| WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable |

The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on.

**Changes**

- **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global.
- **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file.
- **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, the `SetBGError` call in `SwitchMemtable` wakes parked completion gates through the shared error-handler transition hook (`SignalWalDurabilityWaitersOnBGError`, see D123701876), the same path as an append failure. `SwitchMemtable` itself has no explicit wake.
- **Change (R7):** the N>1 rejection message no longer lists unimplemented features. It now reads "wal_partitions > 1 is not supported yet (for any partition_wal_usage)". The rejection itself stays.
- **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`.

**Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them.

**Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0.

**R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure.

**Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, as the R6 Fix bullet above now says. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0.
- Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`.
  - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A.
  - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent.
  - A `Defer` closes the DB on every exit path.
  - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here).

M3 fold: Absorbs
- GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys.
- GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13).
- GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6).
- GC14a Q5: RotationWalCreationFailureWakesGates comment.
- GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10).

Changes visible to existing users:
- ErrorHandler::ClearBGError (DB::Resume and automatic recovery) now wakes all bg_cv_ waiters after clearing the error, at any wal_partitions.
- log::Writer grows by 12 bytes. WAL bytes are unchanged at wal_partitions = 1, because partition 0 writes no marker payload.

Test Plan:
Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched.

**Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout.
- `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass.
- `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass.
- Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers.

**New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true):
- `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary.
- `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both.
- `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails.
- `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too.
- `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0.
- `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds.
- `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent.
- `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker.
- Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass.

**Neuter checks** (each production change reverted locally, test rerun):
- `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail.
- Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter.
- Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert.
- `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false).
- `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window.
- No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design.

**R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff.
- Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below.
- Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports.

**db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope.

**Known 09 issues (09.1):** none observed; no new test was flaky or slow through them.

**Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/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.

M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeSkipsPristineHole, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass.

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

M4 fold: Absorbs
- Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip).
- GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20).
- GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses.
- GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal.
- GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen.
- Net-zero pairs dropped (rule 2.7): none.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed.

M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it.

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

M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070).

Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
…partitions

Summary:
**Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers.

**Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches.

| | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) |
|---|---|---|
| WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B |
| files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 |
| bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same |
| WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable |

The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on.

**Changes**

- **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global.
- **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file.
- **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, the `SetBGError` call in `SwitchMemtable` wakes parked completion gates through the shared error-handler transition hook (`SignalWalDurabilityWaitersOnBGError`, see D123701876), the same path as an append failure. `SwitchMemtable` itself has no explicit wake.
- **Change (R7):** the N>1 rejection message no longer lists unimplemented features. It now reads "wal_partitions > 1 is not supported yet (for any partition_wal_usage)". The rejection itself stays.
- **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`.

**Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them.

**Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0.

**R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure.

**Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, as the R6 Fix bullet above now says. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0.
- Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`.
  - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A.
  - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent.
  - A `Defer` closes the DB on every exit path.
  - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here).

M3 fold: Absorbs
- GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys.
- GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13).
- GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6).
- GC14a Q5: RotationWalCreationFailureWakesGates comment.
- GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10).

Changes visible to existing users:
- ErrorHandler::ClearBGError (DB::Resume and automatic recovery) now wakes all bg_cv_ waiters after clearing the error, at any wal_partitions.
- log::Writer grows by 12 bytes. WAL bytes are unchanged at wal_partitions = 1, because partition 0 writes no marker payload.

Test Plan:
Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched.

**Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout.
- `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass.
- `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass.
- Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers.

**New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true):
- `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary.
- `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both.
- `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails.
- `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too.
- `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0.
- `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds.
- `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent.
- `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker.
- Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass.

**Neuter checks** (each production change reverted locally, test rerun):
- `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail.
- Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter.
- Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert.
- `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false).
- `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window.
- No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design.

**R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff.
- Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below.
- Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports.

**db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope.

**Known 09 issues (09.1):** none observed; no new test was flaky or slow through them.

**Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/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.

M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeSkipsPristineHole, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass.

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

M4 fold: Absorbs
- Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip).
- GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20).
- GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses.
- GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal.
- GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen.
- Net-zero pairs dropped (rule 2.7): none.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed.

M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it.

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

M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070).

Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Reviewer question: does every completion-gate waiter wake and fail promptly when a partition establishes a background error, while an error-free slow partition still waits forever by policy?

What: stalled-partition handling (M2.7). The durability watermark is a minimum, so one hung or failed partition pins every completion gate behind it. A slow partition must keep waiting (no timeout, no watchdog, no new option); a failed partition must fail every parked gate promptly with the background error instead of leaving them to the 1ms poll. This diff closes that notification gap and nothing else: no rerouting, no retry, no failover, no recovery, no rotation, no pipelined N>1, no synced frontier, no change to what a WAL failure means.

How: `WALIOStatusCheck` now calls `SignalWalDurabilityWaitersOnBGError` after releasing `mutex_`. The notifier stores the `wal_durability_bg_error_` predicate flag (release) and then signals `wal_durability_cv_` under `sequence_wal_index_mutex_` when waiters exist. The waiter checks frontier-or-flag under that same mutex before parking, so an error published between the check and the park either lands before the waiter's check (flag observed, sleep skipped) or after it (waiter parked, signal delivered): no lost wake in either order, with no new lock edge (`mutex_` is never held with the sequence mutex) and no behavior change at N=1 (no waiters; one relaxed load on the error path only). The flag mirrors `GetBGError` only as a park predicate and is cleared in `ErrorHandler::ClearBGError`, the single transition of the background error back to OK. The gate's post-wait `SyncWAL`/`FlushWAL(true)` failure needs no new reporting: `SyncWalImpl`/`FlushWAL` already route it to `WALIOStatusCheck` (verified: exactly one notification per failure, no double-report). The 1ms timed wait stays as defense only; correctness never depends on its interval. `Open` still rejects production N>1; the rejection message changes (stalled-partition handling now exists, recovery and rotation do not), and N>1 now also requires `paranoid_checks=true` (NotSupported otherwise). The `wal_partitions` documentation in include/rocksdb/options.h gains the N>1 write visibility and failure semantics.

Neuter checks: `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` (both unmodified, both pass); `WalFailureMatchesSingleWALBehavior` (new: identical injection at N=1 vs N=2, equal code/subcode/severity/message); `SlowPartitionParksInGateWithoutError` (new) plus the unmodified `CompletionWaitsForPriorPartitionAppend` for the slow-not-failed wait. Without a dedicated neuter: paranoid-checks-off WAL failure (no background error exists to notify on, so waiters keep waiting exactly as on the base; covered by reasoning, not by a test, since asserting a hang is not a test).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
This replaces the How paragraph above in two ways: the wake now lives in the error handler, and the park has no timer.
- Every recorded background error wakes parked gates. The wake moved into `ErrorHandler::CheckAndSetRecoveryAndBGError`, so flush, compaction and MANIFEST errors (and future sources) can't be missed. `WALIOStatusCheck` and `TEST_SetBGError` no longer signal directly. The signal always runs under `wal_durability_wait_mutex_` with no waiter-count shortcut. Waiters use a plain `Wait()`; the 1 ms timed wait is gone.
- At N=1, `ErrorHandler` decides exactly what the parent decided (12.1). `HandleKnownErrors` keeps the strict `>` guard. A repeat at the recorded severity wakes gates from the less-severe branch, which still returns early and records nothing. Both wake sites fire only while `bg_error_` is non-OK. So an ignored error, such as a compaction failure under `paranoid_checks=false`, never sets the flag or starts recovery.
- Tests: `CompactionErrorWakesParkedGate`, `GateSyncFailureWakesParkedGate`, `SuppressedErrorLeavesGateUndisturbed`, `CheckThenParkRaceWakesWaiter` (now waits for the flag instead of sleeping), `WalErrorFailsGatedGroupWithFollowers`, `DBErrorHandlingFSTest.IgnoredCompactionErrorStartsNoRecovery`, `DBErrorHandlingFSTest.EqualSeverityRepeatStartsNoRecovery`. `DBIOFailureTest.DropWrites` passes.
- Neuters, run against the full partition suite:
  - Compaction errors stored without the wake -> only `CompactionErrorWakesParkedGate` fails.
  - Signal before the flag store -> only `CheckThenParkRaceWakesWaiter` fails.
  - A suppressed error still wakes -> only `SuppressedErrorLeavesGateUndisturbed` fails.
  - Guard back to `>=` -> both new error-handler tests fail and then hang in `Close()`.
  - No repeat wake -> `GatePostWaitSyncFailureWakesParkedGate` fails.
- LOCK ORDER comment has ten rules. Open takes `sequence_wal_index_mutex_` under `mutex_` alone, and the error signal takes `wal_durability_wait_mutex_` under `mutex_` (rule 9), so the "no new lock edge" claim above no longer holds.
- Still deferred: a failed append pinning the frontier (round 12 Q6, D-1 / doc 13).

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07's waiter-based tests: `PublicationStopsBelowHeldLowerWrite`, `DisableWalWritesWaitOnlyForLowerRanges` (replaces `DisableWalWritesBypassCompletionGate`, AMB-M2-8(a)), the `HigherSequenceRecoverableStateWins` wait, `DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite` with the AMB-M2-9 tracking line; the waiter-count form of `FillAndSwitchMemtable` (X13); GC06's bypasses; GC10's LOCK ORDER rule 7 (AMB-M2-6).

M3 fold: Absorbs
- GC08 Q1 (paranoid_checks=false is rejected at N>1; Busy/Incomplete escalate), Q6 (the failed WAL range is recorded and released; WALIOStatusCheck pins the failed partition; ClearWalDurabilityBGError out of line), Q7 (SnapshotCommitPublishesAboveHeldLowerWrite enabled), WalPartitionsRequireParanoidChecks, and PublicationBoundedForParallelGroup (exception X6: here because it needs WaitForDurabilityWaiters).
- GC09 Q1, Q3-Q5: completion-gate fences (InstallWalGateFence, WalGateFenceStatus(Locked), UnreleasedWalGateFenceLow) and the park loop's fence exits (X8); the recovery flush drops entries at or above the unreleased fence (FlushJob SequenceFloorIterator); HandleMemTableInsertFailure installs a fence and its call sites pass the first sequence; error_handler ordering; the 24 converted gate tests; the WaitForWalDurability doc (AMB-M3-6).
- GC17 Q7: the ErrorHandler::ClearBGError:BeforeClearStopped sync point; LOCK ORDER rule 8 (AMB-M3-8).
Known verification gap (X6): the DBWalAppendFailureTest fixture tests of this diff's D-1 code first run at D123928339.

Changes visible to existing users:
- At any wal_partitions, each background error that ErrorHandler records (or repeats at the recorded severity) now takes wal_durability_wait_mutex_ and broadcasts a condition variable while holding the DB mutex.
- DB::Resume() and automatic recovery (ErrorHandler::ClearBGError) now take wal_durability_wait_mutex_ once and walk two lists that are empty at wal_partitions = 1.
- WriteThread::WriteGroup grows by a Status and two bools.

Test Plan:
Fault injection is the test; every N>1 case uses the `AllowWalPartitions` hook (production `Open` still rejects N>1).

- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 114 (includes 8 new `DBWritePartitionTest` cases x2 params: slow-park, error-wakes-followers, post-wait-sync-failure wake, error-first, advance-first, barrier race, N=1-equivalence, flag-clear; all pre-existing tests unmodified and passing).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` -- Pass 70.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_io_failure_test` -- Pass 84.
- TSan (`buck2 test @fbcode//mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_write_test -- 'DBWritePartitionTest'`) -- Pass 44, no races.
- `arc lint -a` on all 7 touched files: clean. `arc f`: clean.
- Verification 1 (slow-not-failed): `SlowPartitionParksInGateWithoutError` plus unmodified `CompletionWaitsForPriorPartitionAppend` -- waiter parks (count 1), stays blocked over a bounded observation, both groups OK on release.
- Verification 2 (append I/O error wakes leader and followers): `BackgroundErrorWakesParkedGateWithFollowers` -- forced 2-writer group, one gate install, both wake with IOError, read-only follow-up fails, append outcomes show exactly-once attempts on home partitions.
- Verification 3 (sync failure including post-wait path): `GatePostWaitSyncFailureWakesParkedGate` (standard path only; with two write queues the leadership sync itself goes through SyncWAL so the failure cannot be aimed at the post-wait sync alone, same exclusion as the base test) -- W wakes with the error while M still held; exactly one SyncWAL and one notification per failure.
- Verification 4 (advance-vs-error race, both orders): `DurabilityWaitErrorBeforeAdvanceFailsWaiter`, `DurabilityWaitAdvanceBeforeErrorCompletesWaiter`, `DurabilityWaitAdvanceRacesError` (10 barrier iterations) -- no hang, no stale OK (OK implies a covering frontier), no waiter-count leak, notification fires in every order including with zero waiters.
- Verification 5 (no retry/move, reconciliation exactly once): append-outcome assertions in the tests above (exact attempts, home partitions, allocation order); `ResumeImpl:SyncLastSequenceWithAllocated` fires once per Resume iff two_write_queues, else zero (existing path only, counted, never added).
- Verification 6 (N=1 path and pipelined-N>1 rejection unchanged): unmodified `CompletionGateNeverInstallsAtOnePartition` and `RejectsPipelinedWalPartitions` pass; `WalFailureMatchesSingleWALBehavior` compares N=1 vs N=2 status triples exactly.
- N>1 reopen/crash-recovery check: not run -- indexed multi-WAL recovery is unimplemented and production `Open` rejects N>1 (out of scope); the prefix contract is tested in process via statuses plus append outcomes instead.
- N>1 `db_stress` blackbox check: not run -- the tool has no `wal_partitions` support (out of scope); the focused concurrency/fault-injection suite runs under TSan instead.
- Full-suite TSan: not run -- partition-focused TSan (44 tests) covers the changed concurrency code (same scope as the base diff).

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 222, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/26177172892455465).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs GC02 Q1 test `SyncFailureAfterAppendWritesNoCover` (needs
`WriteGroupToWAL:AfterLeadershipSync`, first exists here), GC13 Q0
`#ifndef NDEBUG` around `append_outcome` (4-field form at this diff;
D123928339 adds the 5th field), GC13 Q3 test
`DurabilityWaitAndCompletionHistograms` (needs `WaitForDurabilityWaiters`),
GC13 Q1 gate comment line (AMB-10). `kWalPartitionsRejection` updated to
this diff's wording (X10). Gate: lib builds; `db_write_test` 161/0;
`db_wal_test` 2064/0; options matrix 3/3.
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.

M2 fold: new or moved tests here: PublicationStopsBelowHeldLowerWrite, DisableWalWritesWaitOnlyForLowerRanges, DISABLED_SnapshotCommitPublishesAboveHeldLowerWrite. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + error_handler_fs_test + transaction_test + write_prepared_transaction_test 6337 pass.

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

M4 fold: Absorbs
- GC18 Q8: what survives of the failed-gate-sync fence (TEST_WalGateFences, PublishAppliedFrontierLocked) and Q11's GateSyncFailureWakesParkedGate rename; GC20 Q3's frontier form (exception X4) and Q8 remnants; GC20 Q6's wal_partitions paragraph on a failed sync write as GC25 rewrote it (AMB-M4-7).
- GC20 Q5 / GC21 Q3: the failure half of the epoch hand-split (exception X2: failed epoch and status, shared failure).
- GC21 Q1: ExplainBurnedWALIndices and burned_wal_indices_ (exception X8: hand-ported with CurrentWalOrNull(0) written inline; D123971668 re-extracts it, AMB-M4-2), the LOCK ORDER wording, WalManager::TEST_HasIndeterminateWriteSequence; GC24 Q5 sync point; GC26 Q1: BurnedWALIndexLanded, BurnedWalIndicesPending, BurnedWalIndex::wal_offset and the read-back, zeroing and landed skip in ExplainBurnedWALIndices.
- GC25 Q3/Q4: FailUnpublishedSyncRange (replacing D123551605's hole branch in RunSyncGate, exception X17) and the two-argument HandleMemTableInsertFailure in RunSyncGate; the open-ended InstallWalGateFence; ClearWalDurabilityBGError's fence close; the D-9 doc paragraph; GatePostWaitSyncFailureWakesParkedGate as rewritten; tests ZeroCountMarkerNeverPublishesInFlightSequence (exception X7), FailedSyncPrepareLeavesNoStaleFence (with the test hook, exception X14), EmptyDisableWalCommitSnapshotIsPublished (exception X20).
- Net-zero pairs dropped here (rule 2.7): 77 hunks (699 added lines): the read mask and its read paths, masked memtables, flush drops, mask retirement, exact fences, the fence intent and sync-group registration (GC20 Q5-Q7, GC21 Q3/Q4, GC24 Q2-Q4) cancel with GC25's removals; db/db_impl/wal_gate_read_mask.h is never created.
Known verification gaps: this diff's code is first exercised by fixture tests at D123928339, GC26's Q1 code by DBWalLandedAppendTest at D127093323.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6363 tests, 0 failed.

M5 fold: Absorbs 187 A.1 entries (GC28 30, GC27 15, GC30 55, GC29a 8, GC31 15, GC32 17, GC29b 47): GC30's write pipeline (insert during append, wal_status, leader_exits, callbacks after the fsync, WaitUntilRangesBelowPublished, the inserted failure branch, write_thread.{h,cc}, the flush range-tombstone floor) with its Q1–Q4/Q7 tests; GC27 Q4's 2PC wait and its 2PC tests; GC27 Q6 (BurnedWALIndexLanded's torn begin); GC32's file-scoped resume (guard, reservation, sync points, WALIOStatusCheck push, ClearWalDurabilityBGError's two applied ranges, ExplainBurnedWALIndices(retired_below)); the LOCK ORDER note (GC28, GC31, GC29b); GC28's wait-mutex lock lines; GC31 Q11/Q13 (e); GC29b T4; the X25-M5 tests (GC27's two tailing tests, FrontierNeverPassesAllocatedRange). Not here after B.1: GC30LiveSstHasKey and the three tests that use it go to D123928339 (X34-M5), and so does SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5); GC32#447 goes to D127093323 (X39-M5). M5-F1 (A.8): F1.1 (straggler sequence reuse): HoldSequencesForWalRecoveryRelease and ReleaseSequenceReservation, the allocation wait on sequence_reservation_released_cv_, the release in ClearWalDurabilityBGError, ResumeImpl's step 7, the members and LOCK ORDER rule 3; F1.3: "Ruling 4d:" dropped from WriteImpl's comment. Exceptions: X5-M5; X6-M5; H-M5-1; X21-M5; X25-M5; X26-M5: GC31#362 (WalDurabilityParking::min_target_ on its own cache line) moved here from D119600943: it edits GC28#26's WalDurabilityParking, whose part lands here (X33-M5); X27-M5: GC28#110 (options.h pre-flip wal_partitions doc) split: the manual_wal_flush paragraph at D117251769, the sync-write sentence of the visibility paragraph at D123701876, which writes that paragraph; 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; X29-M5: GC28#16 (db_impl.h): its two edits of D123701876 comment lines land here; the rest of the hunk joins them by X33-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X33-M5: GC28 Q8's parking cluster moved here from D123551605: GC28#1, #2, #16, #26 (its D123551605 part), meta#51, GC31#361's wal_durability_wait_mutex_ cache line, GC31#362, FrontierLockTakenOnlyForAllocation with GC29b#598 (B.1 at D123551605: M4's TimedWait poll on wal_durability_cv_, which this commit replaces, does not compile against GC28's parking type); X36-M5: WalPartitionsOptionRefusalsUnchanged (GC30#245, with GC29b#616) moved from D123079329 to D123701876: the pipelined-write and paranoid_checks refusals it pins first exist here (B.1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.AsyncCommitUnderFailedSyncLeaderNeverVisibleAfterError (after its ClearAllCallBacks, before Reopen); found by B.1: RecoverableStateSlotsTakeHighest (Reopen after DisableProcessing), DBWritePartitionTest.WalPartitionsOptionRefusalsUnchanged and NGreaterThan1FollowerExitHandsFailureToLeader; FLIP removes it.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, transaction_test, write_prepared_transaction_test); 6407 tests, 0 failed.

M6 fold: Absorbs GC34 Q2 (`ErrorHandler::SetBGErrorBeforeFence` and the `fences_writes` rule: a fence error at N>1 cannot be suppressed by a listener; both fence sites, `HandleMemTableInsertFailure` at N>1 and `FailUnpublishedSyncRange`) and GC34 Q3 (`WaitForWalDurability` gains `applied`; only a waiter whose range is not applied fails on shutdown; every caller passes it; `include/rocksdb/options.h` notes that a write failed by Close()/CancelAllBackgroundWork() before its sync is never visible in the session but may be recovered on reopen), plus GC34 Q5 (b) EXPECT sweeps in tests owned here. Exception (rule 3, -Wunused-parameter): Q3's signature and callers land here with the shutdown leg rather than at D123551605 as GC34's split proposed. Hand-port: `RunCompletionGate`'s earlier body passes `/*applied=*/published` here; D123971668's rewrite carries it.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test transaction_test write_prepared_transaction_test: 6407/6407).

Differential Revision: https://phabricator.intern.facebook.com/D123701876
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
…partitions

Summary:
**Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers.

**Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches.

| | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) |
|---|---|---|
| WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B |
| files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 |
| bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same |
| WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable |

The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on.

**Changes**

- **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global.
- **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file.
- **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, the `SetBGError` call in `SwitchMemtable` wakes parked completion gates through the shared error-handler transition hook (`SignalWalDurabilityWaitersOnBGError`, see D123701876), the same path as an append failure. `SwitchMemtable` itself has no explicit wake.
- **Change (R7):** the N>1 rejection message no longer lists unimplemented features. It now reads "wal_partitions > 1 is not supported yet (for any partition_wal_usage)". The rejection itself stays.
- **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`.

**Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them.

**Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0.

**R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure.

**Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1).

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, as the R6 Fix bullet above now says. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0.
- Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`.
  - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A.
  - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent.
  - A `Defer` closes the DB on every exit path.
  - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here).

M3 fold: Absorbs
- GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys.
- GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13).
- GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6).
- GC14a Q5: RotationWalCreationFailureWakesGates comment.
- GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10).

Changes visible to existing users:
- ErrorHandler::ClearBGError (DB::Resume and automatic recovery) now wakes all bg_cv_ waiters after clearing the error, at any wal_partitions.
- log::Writer grows by 12 bytes. WAL bytes are unchanged at wal_partitions = 1, because partition 0 writes no marker payload.

Test Plan:
Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched.

**Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout.
- `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass.
- `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass.
- Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers.

**New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true):
- `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary.
- `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both.
- `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails.
- `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too.
- `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0.
- `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds.
- `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent.
- `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker.
- Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass.

**Neuter checks** (each production change reverted locally, test rerun):
- `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail.
- Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter.
- Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert.
- `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false).
- `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window.
- No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design.

**R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff.
- Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below.
- Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports.

**db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope.

**Known 09 issues (09.1):** none observed; no new test was flaky or slow through them.

**Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732).
- Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack.

M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test
(6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04
void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/
tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7
skew-test change (3). X5-X7 moved here (need
`recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at
D120649665, dropped). `TEST_WalSyncMarks` decl moved after
`TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe-
jection` updated to T0 text (X10). Gate: lib builds; `db_write_test`
189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/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.

M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeSkipsPristineHole, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass.

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

M4 fold: Absorbs
- Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip).
- GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20).
- GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses.
- GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal.
- GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen.
- Net-zero pairs dropped (rule 2.7): none.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed.

M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it.

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

M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070).

Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

The stack already replaced direct `logs_`/`alive_wal_files_` access with the interim `WalLogs(p)`/`AliveWalFiles(p)` helpers, which return entire mutable deques. This diff replaces that container-shaped seam with an operation-shaped surface extracted from the completed write stack's real usage (routing, N write threads, the watermark, rotation under skew). The trade is explicit: this no longer de-risks the container change, because that already happened. What it buys is an enforceable surface for every future change.

**Accessor surface** (all private `DBImpl` members; each states its `REQUIRES` contract and debug-asserts it):

Writer entries:
- `CurrentWal(p)` -- newest entry, asserts non-empty; `CurrentWal()` keeps the partition-0 seam and delegates to it. Callers: `SelectWalForWrite`, memtable-insert truncate path, `TEST_CurrentWalNumber`.
- `CurrentWalOrNull(p)` -- newest entry or `nullptr` at open/recovery/close boundaries. Callers: `FlushWAL`, `WALBufferIsEmpty`, `SyncWalImpl` safety check, rotation predecessor/flush, close markers, recovery replacement check.
- `OldestWalOrNull(p)` -- peek at the oldest entry; `PopOldestWal(p)` -- retire it (asserts the writer went to `WalsToFree(p)` first and the current WAL is never removed). Callers: `FindObsoleteFiles` phase 2, WAL-write-error recovery.
- `InstallCurrentWal(p, number, writer)` -- installs the writer entry and its live-file metadata together. Callers: open (both sites merged), coupled rotation.
- `ClaimWalPartitionForLeadershipSync(p)`, `ClaimWalPartitionForGateSync(p, claim_bound, ...)`, `ClaimWalPartitionForSyncWalImpl(p, include_current_wal, &wals_to_sync)` -- the three sync-claim walks. Callers: `PreprocessWrite`, `SyncWalsFromCompletionGate`, `SyncWalImpl`.
- `SyncWalPartitionFiles(p, write_options)`, `CloseAndClearWalPartition(p)`, `CollectOpenWalSizes(p, &map)`, `FinishWalPartitionSync(p, up_to, synced_wals)`, `CancelWalPartitionSync(p, up_to)` -- the ordered file-sync, close, size-snapshot, and sync-completion walks. One caller each.

Live-file entries:
- `CurrentAliveWal(p)` -- current entry, where appends accumulate sizes. Caller: `SelectWalForWrite` only.
- `TryPopObsoleteAliveWal(p, min, &retired)` -- pop the oldest entry when obsolete. Caller: `FindObsoleteFiles` phase 1.
- `AddRecoveredAliveWal(p, wal)` -- recovered-WAL insertion (marker-derived partition policy stays with `RestoreAliveLogFiles`). One caller.
- `OldestAliveWal(p)` (copy), `MarkOldestAliveWalGettingFlushed(p)` -- oldest-entry flush state. Callers: `SwitchWAL`, `TEST_IsLogGettingFlushed`.
- `NumAliveWalFiles(p)`, `WalPartitionHasTrackedWals(p)`, `SnapshotAliveWalFiles(p)` -- count, both-deques-non-empty, test snapshot. Callers: phase 1, `TEST_AliveWalFiles`.

**What happened to the interim helpers and the locking docs:** `WalLogs(p)`/`AliveWalFiles(p)` (all four overloads) are deleted; the const `CurrentWal()` overload is deleted (its only caller now delegates to `TEST_CurrentWalNumber(0)`). The 9 + 15 numbered locking cases above the containers are gone: each contract moved into the accessor that performs the operation, with a debug `AssertHeld` (or non-empty/protocol assert) where the mutex types allow. Four call sites that read without the documented mutex now take it (open's dummy-write bind and end-of-open sync, close-time markers, `WALIOStatusCheck`'s error reset) -- each is deadlock-free (nothing held, or mutex_-before-WAL order) and was verified by auditing every caller. `SelectWalForWrite` remains the only append-bind seam; its `REQUIRES` drops the open exception since open now holds the mutex too.

**Two lifetime models (R6):** retirement removes one entry at a time from the old end (`OldestWalOrNull`/`PopOldestWal`, `TryPopObsoleteAliveWal`) while the retirement predicate (today: the flush-driven global floor) stays with the caller, so a reference-driven scheme replaces the predicate and its loop without reshaping the containers or this surface. No accessor exposes positions, iterators, or the deque itself; the only other removal (`FinishWalPartitionSync`'s reclaim of fully-synced closed WALs) is contained in one accessor a reference-driven model would likewise own.

**Mechanical negative check:** no `WalLogs(`/`AliveWalFiles(` call remains anywhere in `db/`; raw `logs_`/`alive_wal_files_` names appear only in the two declarations, the two constructor sizing assignments, `NumWalPartitions`' layout asserts, the accessor bodies, and two explanatory group comments. `db/repair.cc`'s unrelated `logs_` untouched.

**Neuters and mistakes:** `db_wal_test`'s recovery cases caught a real mistake mid-refactor -- open's dummy-write `SelectWalForWrite` ran without the WAL mutex, tripping the new assert (422 failures, all `AssertHeld`). Fixed by taking the mutex at the call site. Neuter 1: `TryPopObsoleteAliveWal` predicate `>=` to `>`: 23 `db_wal_test` failures. Neuter 2: `InstallCurrentWal` dropping the alive install: 81 `db_flush_test` failures. Both reverted; suites green again. The rest is behaviour-preserving by construction (same operations, same order, same locks or strictly more) and has no further neuter.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Accessor races fixed. `WriteToWAL` holds the take_lock mutex across size bookkeeping. `OldestAliveWal` copies only `number` and `getting_flushed`, the only fields its callers read. `SnapshotAliveWalFiles` now requires the WAL mutex too. New test accessor: `TEST_OldestAliveWalStableFields`.
- Test: `LiveWalReadsRaceFreeUnderConcurrentWrites`, TSan clean. Neuters under TSan: unlock before bookkeeping -> data race; copy the full entry -> data race.
- Comments match the code. At N=1, with one write queue and no `manual_wal_flush`, the size is added without the WAL mutex, after the bind's unlock, as before partitioning. After that unlock, only the immutable number may escape `CurrentAliveWal`. The `alive_wal_files_`, `WalContext` and `SnapshotAliveWalFiles` comments are updated to match.
- LOCK ORDER gained `wal_sync_mark_mutex_` rules for the new accessors; the M5 fold (GC31 Q6) later removed that mutex and its rules.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q6/Q7 and GC07 Q8 (exception X3: this diff now carries real code and is no longer a behaviour-free move): close marker and post-open sync over every partition, `SwitchWAL` oldest partition as an inline loop over `OldestAliveWal(p)`, `CurrentWal()` comment, LOCK ORDER all-N line; the `CurrentWalOrNull` form of GC11's rotation lambda (X8); tests `CloseMarkerCoversEveryPartitionsWal`, `SwitchWALFindsOldestWalAcrossPartitions`. Its test move of `INSTANTIATE` + `WriteThreadTest` now also lands below the winner test blocks.

M3 fold: This diff carries behaviour (as since M2 X3): it re-extracts the sync code that D122412677, D123079329 and D123551605 hand-port. SyncWalPartitionFiles gains GC08's failed_wal_number out-param (Q4, X5) and is what GC17's SyncEveryWalPartition calls; SyncWalsFromCompletionGate claims through ClaimWalPartitionForLeadershipSync (X9); FlushWAL attributes a failure through current_wal->number (X5). GC08's SyncWalPartitionFiles call-site edit in WriteGroupToWAL is moot here: GC17 Q1 moved that loop into SyncEveryWalPartition. Also absorbs GC17 Q1's expectation changes in NonLeadershipSyncsAdvanceSyncedSize and SyncWalAdvancesOtherPartitionsSyncedSize. The sync-path functions in this diff equal the M3 tip's text.

Changes visible to existing users:
- DB::Open() now takes the WAL write mutex for its post-recovery WAL bind and for the WAL sync at the end of Open.
- Close() with optimize_manifest_for_recovery now takes every WAL write mutex to read the current WAL number.
- After a WAL write error with paranoid_checks=false, the reset-and-continue path now holds the WAL write mutex around reset_seen_error().
- With manual_wal_flush and without two_write_queues, WriteToWAL holds the WAL write mutex through the WAL size bookkeeping (a slightly longer hold per write).

Test Plan:
Base: `ee4e49b9116e` (pinned, D123928339). One new commit on top; nothing below touched.

**Required suites** (`buck2 test`, dev mode), 8 targets, all green:
- `db_wal_test`: 2031 pass, 0 fail.
- `db_write_test`: 128 pass, 0 fail.
- `db_basic_test`: 346 pass, 0 fail.
- `db_flush_test`: 89 pass, 0 fail.
- `db_options_test`: 51 pass, 0 fail.
- `repair_test`: 17 pass, 0 fail.
- `log_test`: 479 pass, 0 fail.
- `db_etc2_test`: 131 pass, 0 fail (the `DBTest2` replacement; `db_test2` does not exist at this base).
- Every test passing on the parent still passes. The tests this diff adds or edits in `db_write_test.cc` and `transaction_test.cc` come from the folds listed below.

**R8 byte identity, N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`:
- Unindexed: SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B -- matches the given parent hash exactly.
- Indexed (`--partition_wal_usage=kPartitionByColumnFamily`): SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B -- matches exactly.

**R8 byte identity, option matrix + N>1 (temporary vehicle, deleted before submit):** fixed deterministic workloads (400 puts/partition, close, reopen with `avoid_flush_during_recovery`, 100 more puts/partition, close), run at parent (refactor shelved) and child; per-partition WAL maps and every WAL file's SHA-256 compared:
- N=1 `two_write_queues` x `manual_wal_flush` (4 combos): maps identical, all WAL bytes identical.
- N=4 indexed, `two_write_queues=false`, `manual_wal_flush` off and on: per-partition maps identical (recovered WALs 4/5/6/7 return to partitions 0/1/2/3), all 16 WAL files byte-identical.
- Vehicle self-check: child rerun byte-identical.

**TSAN:** `@fbcode//mode/dev-tsan` `db_write_test` `DBWritePartitionTest`: 58/58 pass, 5 consecutive runs; the 4 named cases (`ReopenRestoresWalsToTheirPartitions`, `ReopenWithFewerPartitionsPlacesOrphansInZero`, `RotationWaitsForHeldAppendAndKeepsItsWal`, `CrashMidRotationUnderSkewRecoversPrefix`): 8/8 pass. One transient `MixedSyncWritesCompleteUnderConcurrency/1` failure in an earlier run passed on immediate rerun and in isolation (this diff removes no synchronization; flake, not reproduced in 5 runs).

**Neuters:** see Summary (23 + 81 failures, both reverted, suites green).

**db_stress N>1 blackbox:** not run -- the tool has no `wal_partitions` support at this base; out of scope for an accessor-only diff.

**Formatting / lint:** `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 6 files: no issues. Repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: applied 4 line-wrap hunks in `db_impl.cc`, re-verified clean.

**Not run:** CMake/Make builds, macOS, Windows.

**After folding in round 12 / 12.1 (D124911745, D125113461):**
- The tree at this commit is identical to the top of D125113461; only test order in `db_write_test.cc` differs.
- Required suites at this commit, `buck2 test` of `db_write_test`, `db_wal_test`, `db_basic_test`, `db_options_test`, `db_io_failure_test`, `error_handler_fs_test`, `transaction_test`, `write_callback_test`, `external_sst_file_test`: Pass 6222, Fail 0, Timeout 0 (https://www.internalfb.com/intern/testinfra/testrun/35465847111021383).
- Neuter, TSan, byte-identity and crash-test evidence for the folded-in items: see the Test Plans of D124911745 and D125113461.

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
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.

M2 fold: new or moved tests here: CloseMarkerCoversEveryPartitionsWal, SwitchWALFindsOldestWalAcrossPartitions. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + transaction_test 3356 pass.

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

M4 fold: Absorbs
- GC18 Q9: the SyncWalPartitionFiles:BeforeSyncPartition sync point; Q10 tests PartialGateSyncCutLosesHigherAsyncWrite, CoalescedGateSyncsFsyncEachPartitionOnce, ManualWalFlushSyncWriteSurvivesCrash.
- GC20 Q2: SyncWalPartitionFiles' previously_failed and its callers (exception X3: SyncEveryWalPartition and SyncWalsFromCompletionGate's error path), with the M-a repro GateSyncKeepsOtherPartitionsErrorResumable.
- Accessor forms of exceptions X8 (ExplainBurnedWALIndices) and X13 (WriteWALIndexHeadFloors): CurrentWalOrNull replaces the inline forms.
- CoalescedFailedGateSyncFencedWithItsError as GC25 rewrote it (exception X9).
- Net-zero pairs dropped (rule 2.7): 1: GC20's FailedGateSyncSparesZeroCountWriteAbove cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_write_test, transaction_test); 3458 tests, 0 failed.

M5 fold: Absorbs 166 A.1 entries (GC28 58, GC30 12, GC29a 3, GC31 37, GC32 4, GC33 1, GC29b 51): GC28 Q1–Q4 (the per-file claim fields, ClaimWalPartitionForGateSync, SyncWalsFromCompletionGate(claim_bound), RunCoalescedGateSync(claim_bound), SyncClaimedWalPartitions, helping, RunSyncGate's wait-then-sync, FlushWAL per partition) with its tests and the test edits that pin it; GC30 Q8 helping bound; GC31 Q1 SwitchWALWouldAct, Q4 marking, Q6 claims (removing wal_sync_mark_mutex_), Q10's RunCompletionGate signature; GC32's replacement check and retire sync points with three tests; GC33's gate-lambda capture (the other half of the frame restore). Not here after B.1: FileScopedResumeRacesSyncWalAndSyncWrite goes to D127093323 (X39-M5). M5-F1 (A.8): F1.3: join-first edits of UnlockedFsyncRacesWithSyncCallersAndRotation, ParkedWriterHelpsGateSyncButReturnsAfterIt and FailedGateSyncFailsZeroCountWriteAbove; F1.6: GateSyncFailureWakesParkedGate's WriteToWAL:AfterAddRecord callback reformatted (with GC28's lines, rule 2). Exceptions: X1-M5 (known); X2-M5; X8-M5; X9-M5; X10-M5; X15-M5; X20-M5; X23-M5; X30-M5: LOCK ORDER: GC28#23 split (rules 6-10 at D123701876, the re-flowed "all N" paragraph at D123971668), GC31#357 at D123971668 (rule 2), GC29b#491 split (its paragraph rewrite at D123971668, rules 1-10 at D123701876); X31-M5: GC29b#488 (RunSyncGate comment) moved here from D123701876 (rule 2: it edits only the comment lines GC30#210 wrote over GC28#20's, which land here by H-M5-1); X37-M5: GC28#53 (WaitForWalDurability's park loop) split: the per-waiter wait (waiter.cv.Wait(), the AfterWake sync point, Unpark) at D123701876 with the parking type (X33-M5), the HelpRunningGateSync branch at D123971668 (X1-M5) (B.1: writers hung on the shared condition variable while SignalCovered signals each waiter's own); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of TransactionPartitionedWalTest.SwitchWalQuiesceSkippedWhilePrepareRetainsOldestWal and DBWritePartitionTest.GateSyncDoesNotWaitBehindParkedMarker (the latter found by the redone hook simulation); FLIP removes it.

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

M6 fold: Absorbs GC34 Q3 (`RunCompletionGate` passes `applied=published`, with its comment), the GC34 Q2/Q3 tests `GC34SuppressedFenceFailureStopsDb`, `GC34ShutdownWakeKeepsStatusAndVisibilityTogether` and `GC34ShutdownFailsUnappliedWaiter` (rule 3: they use this diff's `DBImpl::SyncWalPartitionFiles:BeforeSyncPartition` sync point and gate-sync path, so they land here rather than at D123928339 as GC34's split proposed) and GC34 Q5 (b) EXPECT sweeps and test-local hold conversions in tests owned here (`CoalescedFailedGateSync...`, `GateSyncKeepsOtherPartitionsErrorResumable`, `FailedGateSyncFailsZeroCountWriteAbove`, `TargetedGateSync...`).

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_write_test transaction_test: 3592/3592).

Differential Revision: https://phabricator.intern.facebook.com/D123971668
JustinGaoF added a commit to JustinGaoF/rocksdb that referenced this pull request Nov 19, 2026
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

- Secondary instances refuse partitioned WALs: RecoverLogFiles runs CheckNoPartitionedWal over every WAL head before applying any record (also refusing a markerless WAL beside indexed ones), and checks each reader's partition again during replay.
- RepairDB refuses partitioned WALs (CheckWalsNotPartitioned) and leaves the DB unchanged.
- ldb dump_wal shows each record's partition and refuses --only_print_seqno_gaps.
- WalFilter doc: records arrive in merged order, each with its source file.
- GetUpdatesSince returns NotSupported at N>1 (DBImpl, and WalManager peeking at retained files; D-G32 (a)).
- Sequence-order audit tests: SecondaryRejectsPartitionedWalsWithoutApplying, ReadOnlyOpenerRecoversPartitionedCrashPrefix, RepairDBRejectsPartitionedWalsUnchanged, WalFilterSeesMergedOrderWithEachRecordsFile, GetUpdatesSinceRefusesPartitionedWals, WritePreparedRecoversAcrossPartitions, WritePreparedConcurrentPreparesKeepHeapSorted, PinnedPrepareWalRecoversAfterGenerationRetired (AMB-M3-4) and LdbCmdTest.DumpWalOnPartitionedWals; fixture helpers OpenWritePreparedTxnDB and CopyDBAsCrashImage.

This diff edits two D123928339 tests, both consequences of the GetUpdatesSince guard it adds: ChangeStreamStopsBelowHeldLowerWrite now expects NotSupported (AMB-M3-3), and FenceHidesFailedWriteFromWalIterator takes GC08's S2 assertion (X7, AMB-M3-13).

M3 fold: Absorbs GC08 (S2 restack): the NotSupported assertion of FenceHidesFailedWriteFromWalIterator.

M4 fold: Absorbs
- GC22 Q2: CheckNoPartitionedWal refuses a partitioned WAL before any record is applied (replacing MaybeInitLogReader's per-reader check); GC22RefusesMarkerlessIndexedWal; GC23 Q6 secondary tests (AMB-M4-14).
- GC21: the H7 repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash and RepeatedTwoPCHolesStayExplainedAfterCrash (exception X9: they call CopyDBAsCrashImage, first here, AMB-M4-4).
- GC26 Q1: DBWalLandedAppendTest with GC26ResumeExplainsOnlyWhatDidNotLand and GC26ResumeFailsWhenBurnedIndexReadBackFails (exception X22).
- GC25: FailedGateSyncAbsentUnderTransactionDB (exception X26: moved up from D123928339; it needs rocksdb/utilities/transaction_db.h in db_write_test.cc, first included here).
- Net-zero pairs dropped (rule 2.7): none.

M5 fold: Absorbs 45 A.1 entries (GC27 16, GC30 12, GC29a 1, GC32 6, GC29b 10): GC27 Q5 (d) (ReadWALPartition's tri-state, RepairDB, GetUpdatesSince, ldb refuse a damaged head), Q6/Q7 (DBWalLandedAppendTest fixture flag and tests); GC30 Q9 (CheckWalsReadableAndUnpartitioned, the MANIFEST-guard re-list in RepairDB and ldb) with its tests; GC29b comments. M5-F1 (A.8): F1.1: FileScopedResumeHoldsAllocationUntilFencesClose (X39-M5); F1.3: FileScopedResumeRacesSyncWalAndSyncWrite's guarded synced-size checks (X39-M5). Exceptions: X14-M5 (two ldb tests); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of LdbCmdTest.DumpWalRefusesDamagedHeadOfPartitionedWal and LdbDumpWalRefusesDamagedHeadWithoutOptions; FLIP removes it.

M6 fold: Absorbs GC34 Q4: `ldb dump_wal --only_print_seqno_gaps` refuses one WAL of an indexed DB (or at N>1), reading the index guard from the file's directory when only `--walfile` is given; `ldb_cmd_test` `DumpWalPrintsIndexedRecords` now expects the refusal (rule 3: it needs this refusal, so it lands here, not at D119600943); GC34 Q5 (b) sweeps in tests owned here.

Also in this diff: `async_wal_precreate` is now sanitized to false whenever `partition_wal_usage` indexes the WAL (documented in include/rocksdb/options.h), because a secondary cannot tell the empty precreated file from a partition WAL whose head is not written yet. `GetSortedWalFiles` (used by checkpoint, backup and GetLiveFiles copies) lists a MANIFEST-tracked WAL that holds only WAL index metadata, such as an idle partition's WAL retired by coupled rotation. A read-only open with WAL tracking off no longer clears the MANIFEST's tracked WALs. `WALIOStatusCheck` applies its failed-sequence-range shortcut only at one partition (GC32#447).

Changes visible to existing users:
- GetUpdatesSince() now opens and reads the head of every WAL in its file list on each call, and returns NotSupported for a WAL whose marker names a partition other than 0.
- Secondary catch-up now opens and reads the head of each new WAL in a round before replaying it.
- RepairDB now reads the MANIFEST WAL-index guard and the head of every WAL before converting any of them.
- `ldb dump_wal --only_print_seqno_gaps` now reads the MANIFEST guard and the head of every WAL first; its help text changed.
- A read-only open with track_and_verify_wals_in_manifest=false no longer queues the MANIFEST edit that clears tracked WALs.

Test Plan:
Final tree: `8358668c9cfe` on `496c3dc34993`; later amends change only this message. Each line says which build it used. The only changes after `b056d7d4ab25` are test assertions in `db_write_test.cc` and `ldb_cmd_test.cc`; the last amend changed only `SecondaryRejectsPartitionedWalsWithoutApplying`.
- `buck2 test` on the 14 required targets plus `log_merge_test`, `log_test`, `db_wal_oracle_test`, `optimistic_transaction_test`, `write_unprepared_transaction_test`, `db_options_test`:
  - At `b16bffcf4d5e`: 8237 passed, 0 failed. `db_write_test` was rerun at the final commit: 292 passed, 0 failed.
  - Earlier run, on the tree of the first local commit `b056d7d4ab25` (only tests changed since): 8237 passed, 0 failed.
  - Required targets: `checkpoint_test`, `backup_engine_test`, `db_secondary_test`, `repair_test`, `ldb_cmd_test`, `wal_manager_test`, `db_log_iter_test`, `external_sst_file_test`, `external_sst_file_basic_test`, `transaction_test`, `write_prepared_transaction_test`, `db_wal_test`, `db_write_test`, `db_basic_test`.
- TSan (`@fbcode//mode/dev-tsan`):
  - Every new or changed test, at `b16bffcf4d5e`: the 22 `DBWritePartitionTest` tests (44 cases, including the N=8 ingestion and concurrent checkpoint), `LdbCmdTest.DumpWalOnPartitionedWals` and `DBWalOracleTest.CatchesLowerBoundWithoutSpans`. All pass with no ThreadSanitizer report.
  - `SecondaryRejectsPartitionedWalsWithoutApplying` under TSan at the final commit: passes, with no ThreadSanitizer report.
  - `LogMergeTest.EmittedRecordsCarrySourceAndChecksum` (4 cases) and `PreparedHeap.*` (3) passed under TSan on the `b056d7d4ab25` tree; their code is unchanged since.
- 100 repeats (`--gtest_repeat=100`) of every new or changed `DBWritePartitionTest` test (all SyncPoint-driven through `AllowWalPartitions`; the ingestion, fault-injection and crash-image tests are included) and of `DumpWalOnPartitionedWals`, at `b16bffcf4d5e`: 100 of 100 iterations passed for both, 0 failures. `SecondaryRejectsPartitionedWalsWithoutApplying` was repeated 100 times at the final commit: 100 of 100 passed.
- Neuters: 24 applied one at a time, each built and run against its named test, then reverted. Every one makes its test fail as described under each question.
  - Three were not caught at first: `ldb`'s per-file check, the floor conditions, and `CheckWals`. The tests were tightened, and all three are now caught.
  - `SecondaryRejects...` covered only two partitions until the last amend; it now writes to all 8, and the peek-only neuter is caught.
- Oracle:
  - `ROCKSDB_WAL_ORACLE_CYCLES=1000`: `RecoveredStateIsPrefixOfHistory` passes. 1000 cycles in 778 s; 147695 writes acknowledged; 97 recoveries stopped at a cross-partition hole; N=2 in 507 and N=8 in 493.
  - Self-tests: safe point off-by-one caught at cycle 3, merge stop off-by-one at cycle 5, lower bound without spans at cycle 2.
  - These used the `b056d7d4ab25` build; the library and oracle are unchanged since.
- N=1 byte-identity: `db_bench` fillseq, `--num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, dev mode. Base `496c3dc34993` and new build give the same hash in both settings:

| `--partition_wal_usage` | SHA-256 of `000004.log` (base and new) |
|---|---|
| `none` | `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09` |
| `partition_by_column_family` | `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796` |

- Crash test: `db_crashtest.py blackbox --duration=180 --wal_partitions=1 --partition_wal_usage=partition_by_column_family --backup_one_in=1000 --checkpoint_one_in=1000 --test_secondary=1`.
  - Also forced: `--enable_blob_direct_write=0 --disable_wal=0 --remote_compaction_worker_threads=0 --use_trie_index=0 --use_txn=0`, because the sanitizer otherwise zeroes backup, checkpoint and secondary.
  - Result: passes, exit 0, 6 db_stress runs.
  - `db_stress` was built from `b056d7d4ab25`, whose non-test tree equals the final commit.
- Repo-pinned clang-format (`clang-format-diff.py` with `tools/third-party/clang-format/clang-format`) on the diff: no changes. `arc lint -a` on every modified file: no issues. No pre-existing violations were touched.

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

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 462 tests, 0 failed.

M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_secondary_test, db_write_test, ldb_cmd_test, ldb); 607 tests, 0 failed.

M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_secondary_test db_write_test ldb_cmd_test: 610/610).

Differential Revision: https://phabricator.intern.facebook.com/D127093323
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.

2 participants