Skip to content

[GC] GC21: Durably explain burned WAL indices before Resume; fence, hide and retire failed gate syncs - #16

Closed
JustinGaoF wants to merge 1 commit into
pwal/gc21-basefrom
pwal/gc21-claude
Closed

JustinGaoF wants to merge 1 commit into
pwal/gc21-basefrom
pwal/gc21-claude

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

[GC] GC21 Resume fix: a released failed WAL range is never a hole after a later recovery

Reviewer question. After a live Resume at N>1, can a later recovery ever see the failed append's index as an unexplained hole and cut acknowledged writes, and are failed gate syncs fenced, hidden and released completely?

No to the first. Before Resume admits any write, every burned index is explained in a WAL that each later recovery reads, and that WAL is fsynced. If the explanation cannot be written, Resume fails and the DB stays stopped. Yes to the second, with the residuals listed under Not done. Every group queued on a failed gate sync is fenced in the critical section that records the error. A failed sync write's point keys and range deletions are hidden from Get, MultiGet, plain iterators and tailing iterators. Once no memtable holding them is left, the mask retires and the read path returns to no mask.

Q1: Is a failed range durably explained before Resume admits writes above it? [FU14 H7]

Guarantee. At N>1, before ResumeImpl calls ClearBGError, every WAL index burned by a failed append (record never landed) is covered by a void record, kWALIndexVoidType [i, i]. The void goes into partition 0's current WAL, which recovery's rotation installs. That WAL and the WAL directory are then fsynced. The WAL is numbered above every WAL that burned an index, so any recovery that reads the hole's WAL reads the void too. This holds in every recovery mode, with or without 2PC, and across repeated failures. If the WAL is unfit (missing, poisoned, already holding data above the index, or not newer than the burning WAL), or the append or sync fails, Resume returns the error and the DB stays write-stopped. The indices stay pending, and a later Resume rotates past that WAL and tries again.

How.

  • CoverBurnedWALIndex (N>1 only, after its "record landed" early return) notes {wal_number, wal_index} in burned_wal_indices_ under sequence_wal_index_mutex_. The leaf is allowed under the partition WAL mutex; the LOCK ORDER rule 3 note is updated.
  • ExplainBurnedWALIndices (new, db_impl_write.cc): copies the list, sorts it (void lower bounds must ascend in a file) and releases mutex_. Under WalWriteMutex(0) it waits out any SyncWAL claim, checks the target, appends one void per index, WriteBuffers and Syncs the file. It sets WalEmpty(0)=false so the next rotation moves past this WAL. It then fsyncs the WAL directory, relocks mutex_, and erases only the entries it copied.
  • ResumeImpl calls it after the flush and quarantine steps, before FindObsoleteFiles/ClearBGError.
  • The cover still fails on the poisoned writer (the repro's precondition log line still appears); a void in a second WAL is a union for the merge, so a duplicate is harmless.

Evidence.

  • Repro ResumedTwoPCHoleKeepsAckedWritesAfterCrash, unmodified. At the base: point-in-time recovery opens but every after* key is NotFound; the other three modes fail with Corruption: WAL index merge: unexplained hole at wal_index 4 with records above it; cannot bound. At this commit: passes in all four modes.
  • New ResumeFailsWhenBurnedIndexCannotBeExplained. The explanation's I/O fails once through the sync point DBImpl::ExplainBurnedWALIndices:io_s. Resume fails, the background error stays, and a write on each partition is rejected and absent. A second Resume succeeds; writes are admitted and survive a reopen.
  • New RepeatedTwoPCHolesStayExplainedAfterCrash. Two failure/Resume cycles on the same partition under an outstanding prepare, each followed by acknowledged writes (sync=true on the failing partition). Every mode opens the crash image with every acknowledged write and the prepared transaction; both failed keys stay absent.
  • Neuter (skip ExplainBurnedWALIndices in ResumeImpl): the repro and RepeatedTwoPCHoles... fail. Strict modes report unexplained hole at wal_index 4; point-in-time loses every after* key, or fails with Column family inconsistency: SST file contains data beyond the point of corruption. ResumeFails... fails because no attempt is made.
  • Neuter (ignore the explanation's status): in ResumeFails... the first Resume returns OK, the background error clears, and the write above is acknowledged ("value").

Q2: Do the non-2PC paths and N=1 stay unchanged?

Guarantee.

  • N=1 runs none of the new code. CoverBurnedWALIndex notes indices only above one partition, ResumeImpl explains only above one partition, the live tailing mask exists only above one partition, and the memtable mask is installed only by InstallFailedGateSyncFence (N>1). The N=1 WAL bytes are identical to the base.
  • Non-2PC N>1 Resume additionally writes one fsynced void into the new WAL. Recovery's flush still retires the hole's WAL, so the void sits below the predecessor-attested lower bound and is ignored. The recovery seed already passes it.

Evidence. WriteAdmittedByRecoveryAllocatesAboveFences, the whole DBWalAppendFailureTest suite and the GC09 gate tests in db_write_test all pass unmodified (see the test plan). The byte-identity table is in the test plan.

Q3: Is a coalesced failed-sync group fenced atomically with the error? [GC20 carry-over]

Guarantee. Every group queued on a gate sync that fails is fenced in the same mutex_ section that records the background error, so no recovery flush can pick a memtable between them.

How.

  • A gate that waits in RunCoalescedGateSync registers a stack WalGateSyncWaiter{low, target, fenced} in wal_gate_sync_waiters_ (under wal_gate_sync_mutex_) and removes it when it leaves.
  • In WALIOStatusCheck's intent branch, after the runner's own fence, wal_gate_sync_mutex_ is taken under mutex_. Each unfenced waiter is marked and copied out; the mutex is released and InstallFailedGateSyncFence runs for each, still in the same mutex_ section. LOCK ORDER rule 8 is updated, and nothing is taken under the leaf.
  • A waiter that sees the shared failure skips its late FenceFailedGateSync when it was fenced. The new sync point DBImpl::RunCoalescedGateSync:SharedFailure marks that spot.

Evidence.

  • New CoalescedFailedGateSyncFencedWithItsError. A (sync, partition 0) runs the gate sync and is held inside its fsync; B (sync, partition 1) queues on it. A's sync fails. Auto-resume is on, and B is held at SharedFailure until recovery has run. Both keys are absent after recovery and after a reopen.
  • Neuter (drop the queued loop, so waiters fence late as at the base): B's key reappears after the reopen ("value_b").

Q4: Does the failed-sync read mask cover every read path, at bounded cost? [GC20 carry-over]

Guarantee. A failed sync write's point keys and range deletions are invisible through Get, MultiGet, plain iterators and tailing iterators until Resume's flush drops them. That includes a tailing iterator created before the failure. The flush now drops the range deletions too; at the base it persisted them. The mask ranges retire once no memtable that held them is left, after which WalGateReadMaskRanges() is null and reads take the one-load fast path again.

How.

  • Range tombstones. ReadOnlyMemTable::SetMaskedSequenceRanges (no-op default). MemTable stores the ranges (AtomicSharedPtrStore plus an atomic flag). While masked, NewRangeTombstoneIteratorInternal fragments only the unmasked tombstones, through a VectorIterator. Every read path and the flush get their range tombstones there. MemTableList::SetMaskedSequenceRanges covers the immutable list. InstallFailedGateSyncFence sets a copy of the ranges on every live CF's mutable and immutable memtables.
  • Flush count. FlushJob::WriteLevel0Table subtracts the hidden tombstones from the expected input count, as it does for SequenceFloorIterator's hidden points.
  • Tailing iterators. LiveWalGateReadMask (in wal_gate_read_mask.h) is a ReadCallback with full checks only. It reloads the ranges when wal_gate_read_mask_version_ moves. Both tailing paths (NewIterator, NewIterators) pass it to DBIter at N>1, and the iterator's cleanup frees it.
  • Retirement. The DB keeps a weak_ptr to the memtables' copy. MaybeRetireWalGateReadMasks runs after each background flush cleans up its job context, and drops the ranges when the weak_ptr has expired. A read that still holds an old superversion keeps those memtables, and so the mask, alive.

Evidence.

  • New FailedGateSyncRangeDeletionStaysHidden. The failed batch is DeleteRange(k1, k3) + Put(w). Before Resume, after Resume, after Resume plus a flush, and after a reopen: Get/MultiGet see k1 and k2 and not w; the plain iterator and a new tailing iterator return {k0, k1, k2, k3} with OK status; the tailing iterator created before the failure returns the same. After Resume plus the flush, TEST_WalGateReadMaskRanges() is null.
  • Neuter (no tailing mask): both tailing iterators return w.
  • Neuter (no memtable mask): Get misses k1 and k2, MultiGet fails, and the iterators return {k0, k3}.
  • Neuter (no retirement): the ranges stay non-null.
  • Read cost: see the test plan. Measured values only; no target was set.

Q5: Do GC20's tests prove what they claim? [GC20 carry-over; test-only]

  • SyncZeroCountWriteAfterSyncWriteSyncs is strengthened in place, using the read-back design of GC20's losing candidate SyncLogDataOnlyBatchSyncsAndSurvivesCrash. The WAL byte-count comparison is replaced: after the power loss (DropUnsyncedFileData), each partition's WAL is read with log::Reader. The LogData record must be found, and an unsynced LogData control written after it must be lost. Neuter (RunCoalescedGateSync returns on wal_gate_synced_upto_ >= target alone, with no sync-start epoch): WAL_FILE_SYNCED does not advance (1 vs 1) and found_record is false.
  • New FailedZeroCountGateSyncRecordsNoIndeterminate. A LogData-only sync write's gate sync fails; after Resume, the WAL manager holds no indeterminate write (TEST_HasIndeterminateWriteSequence, new) and there are no fences. Neuter (fence a zero-count group as [target, target] in place of the low > high return): an indeterminate write and a fence are recorded and both assertions fail. Dropping the return outright trips an assertion in debug instead.

Fold-back split

Diff provenance: git blame at the base plus each commit's Differential Revision: line. Per the doc's map, GC18's and GC20's lines go to D123551605 (gate sync) and D123701876 (fence, mask and release).

  • Q1 → D123701876 (release)
    • db_impl_write.cc ExplainBurnedWALIndices (new, placed after ClearWalDurabilityBGError, blame D123701876).
    • db_impl.h: its declaration, and BurnedWalIndex/burned_wal_indices_ next to failed_wal_ranges_ (D123701876).
  • Q1 → D123928339 (recovery rotation)
    • db_impl.cc ResumeImpl call site (new code, in the recovery path that D123928339's rotation serves; surrounding lines are upstream).
  • Q1 → D119751506
    • db_impl_write.cc CoverBurnedWALIndex noting the burned index (blame D119751506).
    • The LOCK ORDER rule 3 wording in db_impl.h (blame D123701876's note; goes with the cover).
  • Q1 tests (at or above D123079329): ResumeFailsWhenBurnedIndexCannotBeExplained, RepeatedTwoPCHolesStayExplainedAfterCrash.
  • Q3 → D123551605
    • RunCoalescedGateSync waiter registration and shared-failure skip (blame D123551605 and GC18/GC20 lines).
    • db_impl.h WalGateSyncWaiter/wal_gate_sync_waiters_ and the RunCoalescedGateSync comment (D123551605/GC20).
  • Q3 → D123701876
    • WALIOStatusCheck queued-waiter fencing (blame D123701876/GC20).
    • The LOCK ORDER rule 8 line (D123701876).
  • Q3 test: CoalescedFailedGateSyncFencedWithItsError.
  • Q4 → D123701876 (fence and mask code)
    • InstallFailedGateSyncFence memtable masks and version bump; MaybeRetireWalGateReadMasks (new); wal_gate_read_mask.h LiveWalGateReadMask (new, beside GC20's WalGateReadMask).
    • db_impl.h: mask members, retirement and tailing declarations, TEST_WalGateReadMaskRanges.
  • Q4 → the read paths it wraps (new code; the surrounding lines are upstream RocksDB)
    • db_impl.cc tailing NewIterator/NewIterators, NewTailingWalGateReadMask, RegisterTailingWalGateReadMaskCleanup.
    • memtable.{h,cc} masked range tombstones.
    • memtable_list.h SetMaskedSequenceRanges.
    • flush_job.cc hidden-tombstone count (next to D123701876's SequenceFloorIterator).
    • db_impl_compaction_flush.cc retirement call in BackgroundCallFlush.
  • Q4 test: FailedGateSyncRangeDeletionStaysHidden.
  • Q5 → GC20's tests (D123551605 / D123476301)
    • SyncZeroCountWriteAfterSyncWriteSyncs (strengthened), FailedZeroCountGateSyncRecordsNoIndeterminate (new).
    • Test-only accessors WalManager::TEST_HasIndeterminateWriteSequence and DBImpl::TEST_HasIndeterminateWriteSequence.

Assumptions

  1. Target WAL. Which record and which WAL (doc: yours to decide): a void per burned index, in partition 0's current WAL. Recovery's flush always switches memtables (IsRecoveryFlush), and a failed append sets WalEmpty, so the rotation installs fresh WALs above every old one before ClearBGError. If that does not hold, Resume fails closed rather than writing into an unfit WAL.
  2. Buffered cover not trusted. Every burned index is explained again, even when the in-file cover landed in the old writer's buffer, because that buffer is never fsynced. Duplicate voids are a union for the merge.
  3. Landed-but-reported-failed records. An index whose record did land, although the append reported failure, could now meet the void and fail the merge ("bears records and a void cover"). Before this change the in-file cover had the same exposure. This is the accepted D-1 landed-record limit; argued, not tested.
  4. No new background error. A failed explanation is returned from Resume without raising a new background error. The existing hard error keeps the DB stopped, and auto-recovery stops on that status, as for other non-retryable Resume failures.
  5. Indeterminate fence not persisted. It is not needed: the void explains the hole on disk, and the in-process fence still hides the range from the WAL iterator.
  6. Soft-error path. ErrorHandler::RecoverFromBGError clears soft errors without ResumeImpl. A burned index always comes with a hard error at N>1 (D-1), so that path never meets one. Argued, not tested.
  7. Q5 neuter. The zero-count neuter fences the group as [target, target]. Removing the guard outright asserts in debug before the test's assertion can run.
  8. Mask retirement timing. Retirement waits for every memtable that was live at the last install to be freed, including memtables in transaction history (max_write_buffer_size_to_maintain). That is conservative and can delay retirement; it never retires early.

Not done

  • Q3 residual. A group that passed its durability wait before the error but reaches the coalescer only after the failure's section still fences late. Gates that reach their wait after the error park on it instead. Argued, not tested.
  • Q4 residuals.
    • A flush that picked a memtable before the fence still persists the group (GC20's existing limit). After retirement that copy is also visible in-process, as it already is after a reopen.
    • The timestamp-stripping flush path (NewTimestampStrippingRangeTombstoneIterator) and MemPurge do not drop masked range tombstones.
    • Range tombstones added to a mutable memtable after a tailing iterator was built stay unseen by it (upstream ForwardIterator behaviour).
  • Tailing-iterator cost. At N>1 every key a tailing iterator reads now takes one virtual call and one acquire load, even with no failure. Not measured; argued small.

Test plan

Host: 166 cores, shared; every run used -w 83 / -j83 (half the cores), with TEST_TMPDIR under ~/pwal-3p/gc-21-claude-tmp. Load averages are noted where they were high.

Check Command Result
Repro at base ./db_write_test --gtest_filter=*ResumedTwoPCHoleKeepsAckedWritesAfterCrash* at 30634ff FAILS as recorded: PIT has all after* NotFound; the other modes report unexplained hole at wal_index 4
Repro at commit same PASS, all four modes, unmodified
Required suites (debug) gtest-parallel -w 83 ./db_write_test ./db_wal_test ./transaction_test ./write_prepared_transaction_test ./error_handler_fs_test ./db_wal_oracle_test, plus db_range_del_test db_tailing_iter_test flush_job_test db_flush_test memtable_list_test wal_manager_test db_wal_partitions_open_test for the memtable, flush and tailing code touched here PASS: 7108/7108 across the 13 binaries at the final source (gtest-parallel exit 0, no FAILED); an earlier pass before the last cleanups gave 7104/7104
Q2 suites WriteAdmittedByRecoveryAllocatesAboveFences, all of DBWalAppendFailureTest, the GC09 gate tests (in db_write_test) PASS, unmodified (within the run above)
GC20 tests (invariant 5) every GC20 test in db_write_test/transaction_test PASS; only SyncZeroCountWriteAfterSyncWriteSyncs changed (Q5)
TSan (clang) USE_CLANG=1 COMPILE_WITH_TSAN=1 make db_write_test; the 7 new or changed tests plus *FailedGateSync* and *GatePostWaitSyncFailure*, --gtest_repeat=100 1600/1600 OK, 0 ThreadSanitizer reports
100x repeats (debug) the 7 new or changed tests (8 instances) --gtest_repeat=100 800/800 OK; after the test fix below, FailedGateSyncRangeDeletionStaysHidden again 100/100
100x repeats (debug), GC20 fault tests on changed paths *FailedGateSync*:*GatePostWaitSyncFailure*:*AutoResumeRestoresWritesOnEveryPartition*:*WriteAdmittedByRecoveryAllocatesAboveFences* 1200/1200 OK
GC15 oracle ROCKSDB_WAL_ORACLE_CYCLES=1000 ./db_wal_oracle_test PASS (4 tests): 1000 cycles, N=2 in 507 and N=8 in 493, 343 s. The default run (40 cycles) also passes
Neuters see each question above each named test fails with the stated symptom
N=1 byte identity DEBUG_LEVEL=0 make db_bench at base (-base worktree) and commit; db_bench --benchmarks=fillseq --threads=1 --num=10000 --seed=20260928 --disable_auto_compactions=1 --partition_wal_usage=<u> identical: none 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09 (000004.log) both; partition_by_column_family 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796 (000004.log) both
make check-format clang-format 21.1.2 Nothing needs to be reformatted
make check-sources clean
db_stress / crash test not run: deferred by the owner (doc, 2026-10-27)

TSan finding fixed. The first TSan pass (20 repeats) failed FailedGateSyncRangeDeletionStaysHidden 16 times on its retirement assertion; there were no race reports. Flush() returns once the flush is installed, before BackgroundCallFlush reaches the retirement call. The test now waits with TEST_WaitForBackgroundWork() (bg_flush_scheduled_ drops after the call). The 100-repeat TSan run and the debug 100x above are after this fix.

Read cost (Q4), measured values only.

  1. Paired db_bench readrandom A/B, base vs commit, release, N=2 (--wal_partitions=2 --partition_wal_usage=partition_by_column_family --enable_pipelined_write=0 --num=1000000 --value_size=100 --reads=1000000 --threads=4 --use_existing_db=1), one shared DB filled by the base binary, 3 interleaved runs. Load average 17-32 on 166 cores. No failure: this is the normal path.
run base ops/s commit ops/s
1 373890 381298
2 374869 382589
3 373741 379985
  1. db_bench cannot inject a gate-sync failure, so "before vs after one failure plus Resume()" used a temporary harness (not committed). It is a disabled gtest in the default debug build (-O2, assertions on), with a FileSystem wrapper that fails WAL Sync on demand. Each run: N=2, 100k keys flushed plus 50k overwritten in the memtable, then 400k random single-threaded Gets in each of three states: before the failure; masked (after a failed sync write, before Resume); and after Resume() plus a flush, when the mask is retired. 3 runs, the states interleaved within each run. Load average 35-41.
run before failure ops/s masked, before Resume ops/s after Resume + flush ops/s
0 270370 314726 273256
1 303724 303204 263443
2 306695 316029 278954

…ide and retire failed gate syncs

[GC] GC21 Resume fix: a released failed WAL range is never a hole after a later recovery

**Reviewer question.** After a live Resume at N>1, can a later recovery ever see the failed append's index as an unexplained hole and cut acknowledged writes, and are failed gate syncs fenced, hidden and released completely?

No to the first. Before Resume admits any write, every burned index is explained in a WAL that each later recovery reads, and that WAL is fsynced. If the explanation cannot be written, Resume fails and the DB stays stopped. Yes to the second, with the residuals listed under Not done. Every group queued on a failed gate sync is fenced in the critical section that records the error. A failed sync write's point keys and range deletions are hidden from Get, MultiGet, plain iterators and tailing iterators. Once no memtable holding them is left, the mask retires and the read path returns to no mask.

## Q1: Is a failed range durably explained before Resume admits writes above it? [FU14 H7]

**Guarantee.** At N>1, before `ResumeImpl` calls `ClearBGError`, every WAL index burned by a failed append (record never landed) is covered by a void record, `kWALIndexVoidType [i, i]`. The void goes into partition 0's current WAL, which recovery's rotation installs. That WAL and the WAL directory are then fsynced. The WAL is numbered above every WAL that burned an index, so any recovery that reads the hole's WAL reads the void too. This holds in every recovery mode, with or without 2PC, and across repeated failures. If the WAL is unfit (missing, poisoned, already holding data above the index, or not newer than the burning WAL), or the append or sync fails, Resume returns the error and the DB stays write-stopped. The indices stay pending, and a later Resume rotates past that WAL and tries again.

**How.**
- `CoverBurnedWALIndex` (N>1 only, after its "record landed" early return) notes `{wal_number, wal_index}` in `burned_wal_indices_` under `sequence_wal_index_mutex_`. The leaf is allowed under the partition WAL mutex; the LOCK ORDER rule 3 note is updated.
- `ExplainBurnedWALIndices` (new, `db_impl_write.cc`): copies the list, sorts it (void lower bounds must ascend in a file) and releases `mutex_`. Under `WalWriteMutex(0)` it waits out any `SyncWAL` claim, checks the target, appends one void per index, `WriteBuffer`s and `Sync`s the file. It sets `WalEmpty(0)=false` so the next rotation moves past this WAL. It then fsyncs the WAL directory, relocks `mutex_`, and erases only the entries it copied.
- `ResumeImpl` calls it after the flush and quarantine steps, before `FindObsoleteFiles`/`ClearBGError`.
- The cover still fails on the poisoned writer (the repro's precondition log line still appears); a void in a second WAL is a union for the merge, so a duplicate is harmless.

**Evidence.**
- Repro `ResumedTwoPCHoleKeepsAckedWritesAfterCrash`, unmodified. At the base: point-in-time recovery opens but every `after*` key is NotFound; the other three modes fail with `Corruption: WAL index merge: unexplained hole at wal_index 4 with records above it; cannot bound`. At this commit: passes in all four modes.
- New `ResumeFailsWhenBurnedIndexCannotBeExplained`. The explanation's I/O fails once through the sync point `DBImpl::ExplainBurnedWALIndices:io_s`. Resume fails, the background error stays, and a write on each partition is rejected and absent. A second Resume succeeds; writes are admitted and survive a reopen.
- New `RepeatedTwoPCHolesStayExplainedAfterCrash`. Two failure/Resume cycles on the same partition under an outstanding prepare, each followed by acknowledged writes (sync=true on the failing partition). Every mode opens the crash image with every acknowledged write and the prepared transaction; both failed keys stay absent.
- Neuter (skip `ExplainBurnedWALIndices` in `ResumeImpl`): the repro and `RepeatedTwoPCHoles...` fail. Strict modes report `unexplained hole at wal_index 4`; point-in-time loses every `after*` key, or fails with `Column family inconsistency: SST file contains data beyond the point of corruption`. `ResumeFails...` fails because no attempt is made.
- Neuter (ignore the explanation's status): in `ResumeFails...` the first Resume returns OK, the background error clears, and the write above is acknowledged (`"value"`).

## Q2: Do the non-2PC paths and N=1 stay unchanged?

**Guarantee.**
- N=1 runs none of the new code. `CoverBurnedWALIndex` notes indices only above one partition, `ResumeImpl` explains only above one partition, the live tailing mask exists only above one partition, and the memtable mask is installed only by `InstallFailedGateSyncFence` (N>1). The N=1 WAL bytes are identical to the base.
- Non-2PC N>1 Resume additionally writes one fsynced void into the new WAL. Recovery's flush still retires the hole's WAL, so the void sits below the predecessor-attested lower bound and is ignored. The recovery seed already passes it.

**Evidence.** `WriteAdmittedByRecoveryAllocatesAboveFences`, the whole `DBWalAppendFailureTest` suite and the GC09 gate tests in `db_write_test` all pass unmodified (see the test plan). The byte-identity table is in the test plan.

## Q3: Is a coalesced failed-sync group fenced atomically with the error? [GC20 carry-over]

**Guarantee.** Every group queued on a gate sync that fails is fenced in the same `mutex_` section that records the background error, so no recovery flush can pick a memtable between them.

**How.**
- A gate that waits in `RunCoalescedGateSync` registers a stack `WalGateSyncWaiter{low, target, fenced}` in `wal_gate_sync_waiters_` (under `wal_gate_sync_mutex_`) and removes it when it leaves.
- In `WALIOStatusCheck`'s intent branch, after the runner's own fence, `wal_gate_sync_mutex_` is taken under `mutex_`. Each unfenced waiter is marked and copied out; the mutex is released and `InstallFailedGateSyncFence` runs for each, still in the same `mutex_` section. LOCK ORDER rule 8 is updated, and nothing is taken under the leaf.
- A waiter that sees the shared failure skips its late `FenceFailedGateSync` when it was fenced. The new sync point `DBImpl::RunCoalescedGateSync:SharedFailure` marks that spot.

**Evidence.**
- New `CoalescedFailedGateSyncFencedWithItsError`. A (sync, partition 0) runs the gate sync and is held inside its fsync; B (sync, partition 1) queues on it. A's sync fails. Auto-resume is on, and B is held at `SharedFailure` until recovery has run. Both keys are absent after recovery and after a reopen.
- Neuter (drop the queued loop, so waiters fence late as at the base): B's key reappears after the reopen (`"value_b"`).

## Q4: Does the failed-sync read mask cover every read path, at bounded cost? [GC20 carry-over]

**Guarantee.** A failed sync write's point keys and range deletions are invisible through Get, MultiGet, plain iterators and tailing iterators until Resume's flush drops them. That includes a tailing iterator created before the failure. The flush now drops the range deletions too; at the base it persisted them. The mask ranges retire once no memtable that held them is left, after which `WalGateReadMaskRanges()` is null and reads take the one-load fast path again.

**How.**
- **Range tombstones.** `ReadOnlyMemTable::SetMaskedSequenceRanges` (no-op default). `MemTable` stores the ranges (`AtomicSharedPtrStore` plus an atomic flag). While masked, `NewRangeTombstoneIteratorInternal` fragments only the unmasked tombstones, through a `VectorIterator`. Every read path and the flush get their range tombstones there. `MemTableList::SetMaskedSequenceRanges` covers the immutable list. `InstallFailedGateSyncFence` sets a copy of the ranges on every live CF's mutable and immutable memtables.
- **Flush count.** `FlushJob::WriteLevel0Table` subtracts the hidden tombstones from the expected input count, as it does for `SequenceFloorIterator`'s hidden points.
- **Tailing iterators.** `LiveWalGateReadMask` (in `wal_gate_read_mask.h`) is a `ReadCallback` with full checks only. It reloads the ranges when `wal_gate_read_mask_version_` moves. Both tailing paths (`NewIterator`, `NewIterators`) pass it to `DBIter` at N>1, and the iterator's cleanup frees it.
- **Retirement.** The DB keeps a `weak_ptr` to the memtables' copy. `MaybeRetireWalGateReadMasks` runs after each background flush cleans up its job context, and drops the ranges when the `weak_ptr` has expired. A read that still holds an old superversion keeps those memtables, and so the mask, alive.

**Evidence.**
- New `FailedGateSyncRangeDeletionStaysHidden`. The failed batch is `DeleteRange(k1, k3) + Put(w)`. Before Resume, after Resume, after Resume plus a flush, and after a reopen: Get/MultiGet see k1 and k2 and not `w`; the plain iterator and a new tailing iterator return {k0, k1, k2, k3} with OK status; the tailing iterator created before the failure returns the same. After Resume plus the flush, `TEST_WalGateReadMaskRanges()` is null.
- Neuter (no tailing mask): both tailing iterators return `w`.
- Neuter (no memtable mask): Get misses k1 and k2, MultiGet fails, and the iterators return {k0, k3}.
- Neuter (no retirement): the ranges stay non-null.
- Read cost: see the test plan. Measured values only; no target was set.

## Q5: Do GC20's tests prove what they claim? [GC20 carry-over; test-only]

- `SyncZeroCountWriteAfterSyncWriteSyncs` is strengthened in place, using the read-back design of GC20's losing candidate `SyncLogDataOnlyBatchSyncsAndSurvivesCrash`. The WAL byte-count comparison is replaced: after the power loss (`DropUnsyncedFileData`), each partition's WAL is read with `log::Reader`. The LogData record must be found, and an unsynced LogData control written after it must be lost. Neuter (`RunCoalescedGateSync` returns on `wal_gate_synced_upto_ >= target` alone, with no sync-start epoch): `WAL_FILE_SYNCED` does not advance (1 vs 1) and `found_record` is false.
- New `FailedZeroCountGateSyncRecordsNoIndeterminate`. A LogData-only sync write's gate sync fails; after Resume, the WAL manager holds no indeterminate write (`TEST_HasIndeterminateWriteSequence`, new) and there are no fences. Neuter (fence a zero-count group as [target, target] in place of the `low > high` return): an indeterminate write and a fence are recorded and both assertions fail. Dropping the return outright trips an assertion in debug instead.

## Fold-back split

Diff provenance: `git blame` at the base plus each commit's `Differential Revision:` line. Per the doc's map, GC18's and GC20's lines go to D123551605 (gate sync) and D123701876 (fence, mask and release).

- **Q1 → D123701876 (release)**
  - `db_impl_write.cc` `ExplainBurnedWALIndices` (new, placed after `ClearWalDurabilityBGError`, blame D123701876).
  - `db_impl.h`: its declaration, and `BurnedWalIndex`/`burned_wal_indices_` next to `failed_wal_ranges_` (D123701876).
- **Q1 → D123928339 (recovery rotation)**
  - `db_impl.cc` `ResumeImpl` call site (new code, in the recovery path that D123928339's rotation serves; surrounding lines are upstream).
- **Q1 → D119751506**
  - `db_impl_write.cc` `CoverBurnedWALIndex` noting the burned index (blame D119751506).
  - The LOCK ORDER rule 3 wording in `db_impl.h` (blame D123701876's note; goes with the cover).
- **Q1 tests (at or above D123079329):** `ResumeFailsWhenBurnedIndexCannotBeExplained`, `RepeatedTwoPCHolesStayExplainedAfterCrash`.
- **Q3 → D123551605**
  - `RunCoalescedGateSync` waiter registration and shared-failure skip (blame D123551605 and GC18/GC20 lines).
  - `db_impl.h` `WalGateSyncWaiter`/`wal_gate_sync_waiters_` and the `RunCoalescedGateSync` comment (D123551605/GC20).
- **Q3 → D123701876**
  - `WALIOStatusCheck` queued-waiter fencing (blame D123701876/GC20).
  - The LOCK ORDER rule 8 line (D123701876).
- **Q3 test:** `CoalescedFailedGateSyncFencedWithItsError`.
- **Q4 → D123701876 (fence and mask code)**
  - `InstallFailedGateSyncFence` memtable masks and version bump; `MaybeRetireWalGateReadMasks` (new); `wal_gate_read_mask.h` `LiveWalGateReadMask` (new, beside GC20's `WalGateReadMask`).
  - `db_impl.h`: mask members, retirement and tailing declarations, `TEST_WalGateReadMaskRanges`.
- **Q4 → the read paths it wraps (new code; the surrounding lines are upstream RocksDB)**
  - `db_impl.cc` tailing `NewIterator`/`NewIterators`, `NewTailingWalGateReadMask`, `RegisterTailingWalGateReadMaskCleanup`.
  - `memtable.{h,cc}` masked range tombstones.
  - `memtable_list.h` `SetMaskedSequenceRanges`.
  - `flush_job.cc` hidden-tombstone count (next to D123701876's `SequenceFloorIterator`).
  - `db_impl_compaction_flush.cc` retirement call in `BackgroundCallFlush`.
- **Q4 test:** `FailedGateSyncRangeDeletionStaysHidden`.
- **Q5 → GC20's tests (D123551605 / D123476301)**
  - `SyncZeroCountWriteAfterSyncWriteSyncs` (strengthened), `FailedZeroCountGateSyncRecordsNoIndeterminate` (new).
  - Test-only accessors `WalManager::TEST_HasIndeterminateWriteSequence` and `DBImpl::TEST_HasIndeterminateWriteSequence`.

## Assumptions

1. **Target WAL.** Which record and which WAL (doc: yours to decide): a void per burned index, in partition 0's current WAL. Recovery's flush always switches memtables (`IsRecoveryFlush`), and a failed append sets `WalEmpty`, so the rotation installs fresh WALs above every old one before `ClearBGError`. If that does not hold, Resume fails closed rather than writing into an unfit WAL.
2. **Buffered cover not trusted.** Every burned index is explained again, even when the in-file cover landed in the old writer's buffer, because that buffer is never fsynced. Duplicate voids are a union for the merge.
3. **Landed-but-reported-failed records.** An index whose record did land, although the append reported failure, could now meet the void and fail the merge ("bears records and a void cover"). Before this change the in-file cover had the same exposure. This is the accepted D-1 landed-record limit; argued, not tested.
4. **No new background error.** A failed explanation is returned from Resume without raising a new background error. The existing hard error keeps the DB stopped, and auto-recovery stops on that status, as for other non-retryable Resume failures.
5. **Indeterminate fence not persisted.** It is not needed: the void explains the hole on disk, and the in-process fence still hides the range from the WAL iterator.
6. **Soft-error path.** `ErrorHandler::RecoverFromBGError` clears soft errors without `ResumeImpl`. A burned index always comes with a hard error at N>1 (D-1), so that path never meets one. Argued, not tested.
7. **Q5 neuter.** The zero-count neuter fences the group as [target, target]. Removing the guard outright asserts in debug before the test's assertion can run.
8. **Mask retirement timing.** Retirement waits for every memtable that was live at the last install to be freed, including memtables in transaction history (`max_write_buffer_size_to_maintain`). That is conservative and can delay retirement; it never retires early.

## Not done

- **Q3 residual.** A group that passed its durability wait before the error but reaches the coalescer only after the failure's section still fences late. Gates that reach their wait after the error park on it instead. Argued, not tested.
- **Q4 residuals.**
  - A flush that picked a memtable before the fence still persists the group (GC20's existing limit). After retirement that copy is also visible in-process, as it already is after a reopen.
  - The timestamp-stripping flush path (`NewTimestampStrippingRangeTombstoneIterator`) and MemPurge do not drop masked range tombstones.
  - Range tombstones added to a mutable memtable after a tailing iterator was built stay unseen by it (upstream ForwardIterator behaviour).
- **Tailing-iterator cost.** At N>1 every key a tailing iterator reads now takes one virtual call and one acquire load, even with no failure. Not measured; argued small.

## Test plan

Host: 166 cores, shared; every run used `-w 83` / `-j83` (half the cores), with `TEST_TMPDIR` under `~/pwal-3p/gc-21-claude-tmp`. Load averages are noted where they were high.

| Check | Command | Result |
|---|---|---|
| Repro at base | `./db_write_test --gtest_filter=*ResumedTwoPCHoleKeepsAckedWritesAfterCrash*` at 30634ff | FAILS as recorded: PIT has all `after*` NotFound; the other modes report `unexplained hole at wal_index 4` |
| Repro at commit | same | PASS, all four modes, unmodified |
| Required suites (debug) | `gtest-parallel -w 83 ./db_write_test ./db_wal_test ./transaction_test ./write_prepared_transaction_test ./error_handler_fs_test ./db_wal_oracle_test`, plus `db_range_del_test db_tailing_iter_test flush_job_test db_flush_test memtable_list_test wal_manager_test db_wal_partitions_open_test` for the memtable, flush and tailing code touched here | PASS: 7108/7108 across the 13 binaries at the final source (gtest-parallel exit 0, no FAILED); an earlier pass before the last cleanups gave 7104/7104 |
| Q2 suites | `WriteAdmittedByRecoveryAllocatesAboveFences`, all of `DBWalAppendFailureTest`, the GC09 gate tests (in `db_write_test`) | PASS, unmodified (within the run above) |
| GC20 tests (invariant 5) | every GC20 test in `db_write_test`/`transaction_test` | PASS; only `SyncZeroCountWriteAfterSyncWriteSyncs` changed (Q5) |
| TSan (clang) | `USE_CLANG=1 COMPILE_WITH_TSAN=1 make db_write_test`; the 7 new or changed tests plus `*FailedGateSync*` and `*GatePostWaitSyncFailure*`, `--gtest_repeat=100` | 1600/1600 OK, 0 ThreadSanitizer reports |
| 100x repeats (debug) | the 7 new or changed tests (8 instances) `--gtest_repeat=100` | 800/800 OK; after the test fix below, `FailedGateSyncRangeDeletionStaysHidden` again 100/100 |
| 100x repeats (debug), GC20 fault tests on changed paths | `*FailedGateSync*:*GatePostWaitSyncFailure*:*AutoResumeRestoresWritesOnEveryPartition*:*WriteAdmittedByRecoveryAllocatesAboveFences*` | 1200/1200 OK |
| GC15 oracle | `ROCKSDB_WAL_ORACLE_CYCLES=1000 ./db_wal_oracle_test` | PASS (4 tests): 1000 cycles, N=2 in 507 and N=8 in 493, 343 s. The default run (40 cycles) also passes |
| Neuters | see each question above | each named test fails with the stated symptom |
| N=1 byte identity | `DEBUG_LEVEL=0 make db_bench` at base (`-base` worktree) and commit; `db_bench --benchmarks=fillseq --threads=1 --num=10000 --seed=20260928 --disable_auto_compactions=1 --partition_wal_usage=<u>` | identical: `none` 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09 (000004.log) both; `partition_by_column_family` 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796 (000004.log) both |
| `make check-format` | clang-format 21.1.2 | Nothing needs to be reformatted |
| `make check-sources` | | clean |
| db_stress / crash test | | not run: deferred by the owner (doc, 2026-10-27) |

**TSan finding fixed.** The first TSan pass (20 repeats) failed `FailedGateSyncRangeDeletionStaysHidden` 16 times on its retirement assertion; there were no race reports. `Flush()` returns once the flush is installed, before `BackgroundCallFlush` reaches the retirement call. The test now waits with `TEST_WaitForBackgroundWork()` (`bg_flush_scheduled_` drops after the call). The 100-repeat TSan run and the debug 100x above are after this fix.

**Read cost (Q4), measured values only.**

1. Paired `db_bench readrandom` A/B, base vs commit, release, N=2 (`--wal_partitions=2 --partition_wal_usage=partition_by_column_family --enable_pipelined_write=0 --num=1000000 --value_size=100 --reads=1000000 --threads=4 --use_existing_db=1`), one shared DB filled by the base binary, 3 interleaved runs. Load average 17-32 on 166 cores. No failure: this is the normal path.

| run | base ops/s | commit ops/s |
|---|---|---|
| 1 | 373890 | 381298 |
| 2 | 374869 | 382589 |
| 3 | 373741 | 379985 |

2. db_bench cannot inject a gate-sync failure, so "before vs after one failure plus Resume()" used a temporary harness (not committed). It is a disabled gtest in the default debug build (-O2, assertions on), with a FileSystem wrapper that fails WAL Sync on demand. Each run: N=2, 100k keys flushed plus 50k overwritten in the memtable, then 400k random single-threaded Gets in each of three states: before the failure; masked (after a failed sync write, before Resume); and after Resume() plus a flush, when the mask is retired. 3 runs, the states interleaved within each run. Load average 35-41.

| run | before failure ops/s | masked, before Resume ops/s | after Resume + flush ops/s |
|---|---|---|---|
| 0 | 270370 | 314726 | 273256 |
| 1 | 303724 | 303204 | 263443 |
| 2 | 306695 | 316029 | 278954 |
@JustinGaoF JustinGaoF changed the title [claude][GC] GC21: Durably explain burned WAL indices before Resume; fence, hide and retire failed gate syncs [GC] GC21: Durably explain burned WAL indices before Resume; fence, hide and retire failed gate syncs Oct 29, 2026
@JustinGaoF

Copy link
Copy Markdown
Owner Author

Folded at M4 into pwal/m4 @ 7a31be3 (commit D123701876, D123928339, D123971668, D127093323); see the M4 PR #26.

@JustinGaoF JustinGaoF closed this Oct 31, 2026
JustinGaoF added a commit that referenced this pull request Nov 9, 2026
…M2.6)

Summary:
Reviewer question: does every write's completion imply its own record plus
every previous WAL record landed (M2.5), and does every `sync=true` write's
completion imply the same range reached disk on all partitions (M2.6) --
without gating any append, without touching the N=1 path, and without
deadlocking concurrent syncs?

What: a write completes once its own record is written and every previous
WAL record has been completed (prefix property). Groups are sync-
homogeneous, so `sync` selects the frontier: `sync=false` waits on the
buffered frontier (`write()` completion, from 07); `sync=true` waits on the
buffered frontier and then fsyncs all live WALs, which restores the
single-WAL property that a sync flushes all preceding async writes. No
second tracked frontier is needed: the post-wait fsync is guarded by a
pre-sync safe point snapshot, so an uncontended sync pays no extra fsync.

How:
- `WriteGroup::completion_gate` functor, run in `ExitAsBatchGroupLeader`
  after next-leader promotion and before follower completion (R2); one
  waiter per group, followers wake already cleared (R3); follower status
  merges append status with the wait outcome incl. background errors (R4).
- `DBImpl::WaitForWalDurability` (one atomic load fast path, then
  spin/yield/park on `wal_durability_cv_`) + `RunCompletionGate` with the
  conditional post-wait `SyncWAL`/`FlushWAL(true)`. Installed in `WriteImpl`
  and `WriteImplWALOnly` for N > 1 WAL writes with a successful append
  only; N=1, `disableWAL`, and ingestion never install. R1 (append never
  gated) holds by construction: registration/append/Complete precede the
  gate, and `Open` rejects `wal_partitions > 1` with pipelined writes (no
  gate slot in the split exit).
- `SyncWalImpl` claims every live log across all partitions (required now
  that `cur_wal_number_` is the lowest live number), and `MarkLogsSynced`/
  `MarkLogsNotSynced` finish every marked log; without the latter the next
  sync's `PreprocessWrite` hangs on `WalSyncCV`.
- Two base sync-protocol fixes that M2.6 cannot work without (no base test
  covers `sync=true` at N > 1): (1) `wal_sync_mark_mutex_` serializes
  sync-marking -- leadership marks run others-then-own while `SyncWalImpl`
  claims ascending, so concurrent syncs ABBA-deadlock on each other's
  `WalSyncCV` waits; (2) the leadership fsync runs under each partition's
  WAL mutex and `WriteToWAL` takes it around the file records, closing a
  real `AddRecord`-vs-`Sync` buffer race (TSan, heap corruption) on live
  WALs. A wait on `WalSyncCV` parks with the mutex released, so marked
  syncs can always take the mutexes; the take in `WriteToWAL` sits after
  the `log_entry` hook so held-open test appends pin no mutex.

`wal_partitions > 1` is NOT reachable at `Open` in this diff: reopening a
multi-WAL DB (`unindexed multi-WAL recovery`) is still unimplemented, and
stalled-partition handling (09) and rotation (10) are out of scope. N > 1
stays reachable only via the `AllowWalPartitions` test hook, as on the
base. Evidence: `db_impl_open.cc` still rejects such opens; new tests use
the hook.

Neuter checks: `external_sst_file_test` (ingestion is structurally
excluded -- it never enters `WriteImpl`, verified by caller audit, and the
suite passes unmodified); `CompletionGateNeverInstallsAtOnePartition`
(zero installs across sync/async/disableWAL at N=1). Checks without one:
the crash-recovery prefix oracle (no N > 1 recovery exists to crash
against); `db_stress` (no `wal_partitions` support in the tools).

**Folded in from round 12 (D124911745)**
- The N=1 write path takes exactly the locks the parent took. `WriteToWAL` takes the WAL mutex only when N>1 or under `manual_wal_flush_ && !two_write_queues_` (the parent's rule). Both `wal_sync_mark_mutex_` takes and the per-partition leadership takes are gated on N>1, so base sync-protocol fix (2) above now applies only at N>1. No extra N=1 cost remains.
- Tests: `N1DefaultWritePathTakesPre08Locks`, `N1ManualFlushWritePathTakesPre08Locks`, `N2WritePathTakesPartitionLocks`. Each compares lock-take counts with the parent. Neuter: revert the guards -> the N=1 runs fail.
- The LOCK ORDER comment rewrite starts here and finishes in D123701876.

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07 Q1 gate side: `covered()`/`wal_record`, disableWAL publication gate, comments (AMB-M2-7), the `SignalWalDurabilityWaiters()` line in `PublishAppliedPrefix` (exception X6); GC06's `WalPartitionsRejectionsNameTheirOptions` (exception X2: its pipelined row needs this diff's rejection) with GC11's tracking line, GC06's bypasses and the `SyncWriteSyncsAgainOnlyAfterWait` race fix. Exception X12: `IngestionThenWritesKeepLastSequenceMonotone` (fails below the completion gate). Exception X13: GC07's `SwitchWaitsForOtherPartitionsLeaders` rewrite and `FillAndSwitchMemtable`, with a bounded 1 s wait per step here because `TEST_WalDurabilityWaiters` first exists in D123701876. AMB-M2-8(a): `DisableWalWritesBypassCompletionGate` moves to D123701876.

GitHub migration (2026-10-23): two `db_write_test.cc` comments use `--` instead of em dashes, so upstream `make check-sources` (ASCII only) passes. Comment-only.

M3 fold: Absorbs
- GC17 Q1 (D-G11 (c)): above one partition a sync write fsyncs from its completion gate, coalesced (RunCoalescedGateSync, SyncWalsFromCompletionGate, SyncEveryWalPartition); PreprocessWrite and WriteGroupToWAL sync only at N=1; WalContext::pre_sync_safe_point and wal_sync_micros are gone; AsyncWriteDoesNotWaitForOtherPartitionsSync; PostWaitSyncErrorFailsSyncWrite synchronization; the sync_failed_wal_number comment (AMB-M3-7). Exception X9 (AMB-M3-9): SyncEveryWalPartition and the gate's claim are hand-ported to this diff's inline WalLogs(p) loops (with the X5 attribution line); D123971668 re-extracts them into SyncWalPartitionFiles and ClaimWalPartitionForLeadershipSync.
- GC08 Q7: post-memtable callbacks run inside the completion-gate wrapper, the exit loops skip them, and the snapshot-callback assertions flip at N>1.
- GC09 Q2: CancelAllBackgroundWork wakes parked gates; CloseHelper waits for them to leave; the RunCompletionGate:BeforeWait sync point; the waiter-count comment. Exception X8: GC09's park-loop rewrite is hand-ported here as the shutdown exit, the waiter count kept under sequence_wal_index_mutex_ and the last-out signal; D123701876 replaces the background-error exit with the fence exits.
- GC12 IngestionAfterDisableWalWriteFindsRangesIdle (exception X2: it needs the DisableWalPut fixture helper, which this diff adds).

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 98
  (incl. 9 new tests x2 params + `SwitchWaitsForOtherPartitionsLeaders`
  rescripted: fill/switch-trigger puts are now `disableWAL` since WAL puts
  after a held-open pre-record append cannot return by design; plus a
  rendezvous so the switch deterministically meets the open append).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test` -- Pass 346.
- `buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test` -- Pass 3106.
- `buck2 test fbcode//internal_repo_rocksdb/repo:external_sst_file_test` -- Pass 285.
- TSan (`@fbcode//mode/dev-tsan`): partition suite Pass 34, N=1 gate test
  Pass 3. Full-suite TSan: not run (partition concurrency + N=1 cover the
  changed code).
- `arc lint -a` on all 7 touched files: clean.
- R6 `db_bench` `fillseq` A/B at N=1 (base `60bb245c3869` vs this commit):
  base 58.3/61.9/60.7 vs mine 59.2/61.5/63.0 micros/op (means 60.3 vs 61.2, +1.5%, within base run-to-run spread +-3%): no measurable regression.
- Prefix-property crash oracle: not run -- N > 1 recovery is unimplemented
  (`Open` rejects such reopens), so no recovered state exists to assert
  on. In-diff evidence is the completion-gate mechanism tests (a write
  observably does not return until every previous record landed) plus the
  M2.6 post-wait all-partition fsync (a synced write's predecessors are on
  disk before it returns).
- Mixed `sync` `db_stress` + blackbox crash test: not run -- the tools have
  no `wal_partitions` support and N > 1 recovery is unimplemented. Nearest
  in-diff coverage: `MixedSyncWritesCompleteUnderConcurrency` (sync/async
  across 4 partitions + external flush thread + auto-switches).

**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 194, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/13792274068178608).
- 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 GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
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: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 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: 2285 pass.

M4 fold: Absorbs
- GC18 Q8 plumbing (exception X1: RunCompletionGate and RunCoalescedGateSync take `low`), Q10 RunCoalescedGateSync:BeforeWait sync point, Q11 sync-point renames and their tests.
- GC20 Q1: gate-sync epoch coverage (started and synced epochs, needed_epoch; exception X2: hand-split from the failure half, which is D123701876's, AMB-M4-1).
- GC22 Q1: the timestamped-snapshot reservation (CreateTimestampedSnapshotImpl, WriteImpl's post-memtable callback, SnapshotList::New sorted insert, TimestampedSnapshotList::GetLatestAtOrBelow) with the H2 repros and GC22's tests; GC23 Q7 (CommitAndTryCreateSnapshot doc, GC23SnapshotReservationInProperties).
- GC25 Q1/Q2/Q5, the D-9 core (exception X17, AMB-M4-19): WriteGroup::sync_first_sequence, async_writers_gate and CompleteAsyncWriters; WriteImpl's sync-group counting, two-pass sequence and callback assignment, the async, RunSyncGate and disableWAL gates, the sync-group insert of async writers only, PublishOnGroupExit at the group exits, MergeBatch's two passes; WaitForWalDurability's and RunCompletionGate's `published`; RunSyncGate, EndUnpublishedSyncGroup, unpublished_sync_groups_ and WaitForUnpublishedSyncGroups (WaitForPendingWrites, TEST_SwitchMemtable); test SyncLedGroupAsyncWritersReturnBeforeFsync; removal of AsyncWriteDoesNotWaitForOtherPartitionsSync (exception X18: this diff's test by histogram blame).
- X17 hand-port: here RunSyncGate's failure branch publishes the failed range as a hole (FailUnpublishedSyncRange's no-background-error branch) and calls the one-argument HandleMemTableInsertFailure; D123701876 replaces both. The comments that name FailUnpublishedSyncRange or GC20 Q5's failure sharing carry this diff's wording until D123701876.
- Net-zero pairs dropped here (rule 2.7): 6 (GC18#15, #16, #24, #32, meta#85, meta#86).
Known verification gap: this diff's text of the D-9 gate was first built at M4.

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, transaction_test); 5402 tests, 0 failed.

M5 fold: Absorbs 34 A.1 entries (GC28 1, GC27 7, GC29a 5, GC31 10, GC33 1, GC29b 10): GC28 Q8: wal_durability_wait_mutex_, WalDurabilityParking, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation; GC27 Q2 (LockWAL, SetDBOptions and import wait for unpublished sync groups, LockWalWaitsForPendingSyncGroup) and Q4's tailing bound (its two tailing tests go to D123701876, X25-M5); GC31 Q3 (EndUnpublishedSyncGroup signals only an announced waiter), A10/A13; GC33's N>1-only waiter announcement; GC29a/GC29b transaction-test cleanup (JoinThreadsOnExit), SyncLedGroupAsyncMembersReturnBeforeFsync, ImportWaitsForPendingSyncGroup. Not here after B.1: GC28 Q8's parking cluster (WalDurabilityParking, wal_durability_wait_mutex_, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation) goes to D123701876 (X33-M5), and JoinThreadsOnExit to D123079329 (X32-M5). Exceptions: GC28's gate-sync rework is not here (X1-M5); GC27's 2PC wait is not here (X6-M5); X25-M5. Hand-splits (rows below the hunk's top row get their slice by a per-row edit): GC31#347 (db_impl.h test accessors): TEST_wals_total_size via WalsTotalSize() at D121858039, TEST_CachedRecoverableStateEmpty at D123079329, TEST_UnpublishedSyncGroups at D123551605.

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, transaction_test); 5413 tests, 0 failed.

M6 fold: Absorbs GC34 Q3 comments (`CancelAllBackgroundWork`, `CloseHelper`: an applied waiter keeps waiting until covered or fenced) and GC34 Q5 (b): the two named `db_wal_test` tests use EXPECT while a thread is joinable, and `SyncClosedWalsEmptiedByWaitLeavesLaterMark` releases its parked threads and fails when the flush did not rotate; `SyncLedGroupAsyncWritersReturnBeforeFsync` releases and fails when W0 never reaches its append; EXPECT sweeps in `LockWalWaitsFor...` and `SwitchWaitsForOther...`.

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

Reviewers: jkangs, rbanerjee2, jewoongh, #rocksdb, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

Differential Revision: https://phabricator.intern.facebook.com/D123551605
JustinGaoF added a commit 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 that referenced this pull request Nov 10, 2026
…M2.6)

Summary:
Reviewer question: does every write's completion imply its own record plus
every previous WAL record landed (M2.5), and does every `sync=true` write's
completion imply the same range reached disk on all partitions (M2.6) --
without gating any append, without touching the N=1 path, and without
deadlocking concurrent syncs?

What: a write completes once its own record is written and every previous
WAL record has been completed (prefix property). Groups are sync-
homogeneous, so `sync` selects the frontier: `sync=false` waits on the
buffered frontier (`write()` completion, from 07); `sync=true` waits on the
buffered frontier and then fsyncs all live WALs, which restores the
single-WAL property that a sync flushes all preceding async writes. No
second tracked frontier is needed: the post-wait fsync is guarded by a
pre-sync safe point snapshot, so an uncontended sync pays no extra fsync.

How:
- `WriteGroup::completion_gate` functor, run in `ExitAsBatchGroupLeader`
  after next-leader promotion and before follower completion (R2); one
  waiter per group, followers wake already cleared (R3); follower status
  merges append status with the wait outcome incl. background errors (R4).
- `DBImpl::WaitForWalDurability` (one atomic load fast path, then
  spin/yield/park on `wal_durability_cv_`) + `RunCompletionGate` with the
  conditional post-wait `SyncWAL`/`FlushWAL(true)`. Installed in `WriteImpl`
  and `WriteImplWALOnly` for N > 1 WAL writes with a successful append
  only; N=1, `disableWAL`, and ingestion never install. R1 (append never
  gated) holds by construction: registration/append/Complete precede the
  gate, and `Open` rejects `wal_partitions > 1` with pipelined writes (no
  gate slot in the split exit).
- `SyncWalImpl` claims every live log across all partitions (required now
  that `cur_wal_number_` is the lowest live number), and `MarkLogsSynced`/
  `MarkLogsNotSynced` finish every marked log; without the latter the next
  sync's `PreprocessWrite` hangs on `WalSyncCV`.
- Two base sync-protocol fixes that M2.6 cannot work without (no base test
  covers `sync=true` at N > 1): (1) `wal_sync_mark_mutex_` serializes
  sync-marking -- leadership marks run others-then-own while `SyncWalImpl`
  claims ascending, so concurrent syncs ABBA-deadlock on each other's
  `WalSyncCV` waits; (2) the leadership fsync runs under each partition's
  WAL mutex and `WriteToWAL` takes it around the file records, closing a
  real `AddRecord`-vs-`Sync` buffer race (TSan, heap corruption) on live
  WALs. A wait on `WalSyncCV` parks with the mutex released, so marked
  syncs can always take the mutexes; the take in `WriteToWAL` sits after
  the `log_entry` hook so held-open test appends pin no mutex.

`wal_partitions > 1` is NOT reachable at `Open` in this diff: reopening a
multi-WAL DB (`unindexed multi-WAL recovery`) is still unimplemented, and
stalled-partition handling (09) and rotation (10) are out of scope. N > 1
stays reachable only via the `AllowWalPartitions` test hook, as on the
base. Evidence: `db_impl_open.cc` still rejects such opens; new tests use
the hook.

Neuter checks: `external_sst_file_test` (ingestion is structurally
excluded -- it never enters `WriteImpl`, verified by caller audit, and the
suite passes unmodified); `CompletionGateNeverInstallsAtOnePartition`
(zero installs across sync/async/disableWAL at N=1). Checks without one:
the crash-recovery prefix oracle (no N > 1 recovery exists to crash
against); `db_stress` (no `wal_partitions` support in the tools).

**Folded in from round 12 (D124911745)**
- The N=1 write path takes exactly the locks the parent took. `WriteToWAL` takes the WAL mutex only when N>1 or under `manual_wal_flush_ && !two_write_queues_` (the parent's rule). Both `wal_sync_mark_mutex_` takes and the per-partition leadership takes are gated on N>1, so base sync-protocol fix (2) above now applies only at N>1. No extra N=1 cost remains.
- Tests: `N1DefaultWritePathTakesPre08Locks`, `N1ManualFlushWritePathTakesPre08Locks`, `N2WritePathTakesPartitionLocks`. Each compares lock-take counts with the parent. Neuter: revert the guards -> the N=1 runs fail.
- The LOCK ORDER comment rewrite starts here and finishes in D123701876.

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07 Q1 gate side: `covered()`/`wal_record`, disableWAL publication gate, comments (AMB-M2-7), the `SignalWalDurabilityWaiters()` line in `PublishAppliedPrefix` (exception X6); GC06's `WalPartitionsRejectionsNameTheirOptions` (exception X2: its pipelined row needs this diff's rejection) with GC11's tracking line, GC06's bypasses and the `SyncWriteSyncsAgainOnlyAfterWait` race fix. Exception X12: `IngestionThenWritesKeepLastSequenceMonotone` (fails below the completion gate). Exception X13: GC07's `SwitchWaitsForOtherPartitionsLeaders` rewrite and `FillAndSwitchMemtable`, with a bounded 1 s wait per step here because `TEST_WalDurabilityWaiters` first exists in D123701876. AMB-M2-8(a): `DisableWalWritesBypassCompletionGate` moves to D123701876.

GitHub migration (2026-10-23): two `db_write_test.cc` comments use `--` instead of em dashes, so upstream `make check-sources` (ASCII only) passes. Comment-only.

M3 fold: Absorbs
- GC17 Q1 (D-G11 (c)): above one partition a sync write fsyncs from its completion gate, coalesced (RunCoalescedGateSync, SyncWalsFromCompletionGate, SyncEveryWalPartition); PreprocessWrite and WriteGroupToWAL sync only at N=1; WalContext::pre_sync_safe_point and wal_sync_micros are gone; AsyncWriteDoesNotWaitForOtherPartitionsSync; PostWaitSyncErrorFailsSyncWrite synchronization; the sync_failed_wal_number comment (AMB-M3-7). Exception X9 (AMB-M3-9): SyncEveryWalPartition and the gate's claim are hand-ported to this diff's inline WalLogs(p) loops (with the X5 attribution line); D123971668 re-extracts them into SyncWalPartitionFiles and ClaimWalPartitionForLeadershipSync.
- GC08 Q7: post-memtable callbacks run inside the completion-gate wrapper, the exit loops skip them, and the snapshot-callback assertions flip at N>1.
- GC09 Q2: CancelAllBackgroundWork wakes parked gates; CloseHelper waits for them to leave; the RunCompletionGate:BeforeWait sync point; the waiter-count comment. Exception X8: GC09's park-loop rewrite is hand-ported here as the shutdown exit, the waiter count kept under sequence_wal_index_mutex_ and the last-out signal; D123701876 replaces the background-error exit with the fence exits.
- GC12 IngestionAfterDisableWalWriteFindsRangesIdle (exception X2: it needs the DisableWalPut fixture helper, which this diff adds).

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 98
  (incl. 9 new tests x2 params + `SwitchWaitsForOtherPartitionsLeaders`
  rescripted: fill/switch-trigger puts are now `disableWAL` since WAL puts
  after a held-open pre-record append cannot return by design; plus a
  rendezvous so the switch deterministically meets the open append).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test` -- Pass 346.
- `buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test` -- Pass 3106.
- `buck2 test fbcode//internal_repo_rocksdb/repo:external_sst_file_test` -- Pass 285.
- TSan (`@fbcode//mode/dev-tsan`): partition suite Pass 34, N=1 gate test
  Pass 3. Full-suite TSan: not run (partition concurrency + N=1 cover the
  changed code).
- `arc lint -a` on all 7 touched files: clean.
- R6 `db_bench` `fillseq` A/B at N=1 (base `60bb245c3869` vs this commit):
  base 58.3/61.9/60.7 vs mine 59.2/61.5/63.0 micros/op (means 60.3 vs 61.2, +1.5%, within base run-to-run spread +-3%): no measurable regression.
- Prefix-property crash oracle: not run -- N > 1 recovery is unimplemented
  (`Open` rejects such reopens), so no recovered state exists to assert
  on. In-diff evidence is the completion-gate mechanism tests (a write
  observably does not return until every previous record landed) plus the
  M2.6 post-wait all-partition fsync (a synced write's predecessors are on
  disk before it returns).
- Mixed `sync` `db_stress` + blackbox crash test: not run -- the tools have
  no `wal_partitions` support and N > 1 recovery is unimplemented. Nearest
  in-diff coverage: `MixedSyncWritesCompleteUnderConcurrency` (sync/async
  across 4 partitions + external flush thread + auto-switches).

**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 194, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/13792274068178608).
- 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 GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
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: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 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: 2285 pass.

M4 fold: Absorbs
- GC18 Q8 plumbing (exception X1: RunCompletionGate and RunCoalescedGateSync take `low`), Q10 RunCoalescedGateSync:BeforeWait sync point, Q11 sync-point renames and their tests.
- GC20 Q1: gate-sync epoch coverage (started and synced epochs, needed_epoch; exception X2: hand-split from the failure half, which is D123701876's, AMB-M4-1).
- GC22 Q1: the timestamped-snapshot reservation (CreateTimestampedSnapshotImpl, WriteImpl's post-memtable callback, SnapshotList::New sorted insert, TimestampedSnapshotList::GetLatestAtOrBelow) with the H2 repros and GC22's tests; GC23 Q7 (CommitAndTryCreateSnapshot doc, GC23SnapshotReservationInProperties).
- GC25 Q1/Q2/Q5, the D-9 core (exception X17, AMB-M4-19): WriteGroup::sync_first_sequence, async_writers_gate and CompleteAsyncWriters; WriteImpl's sync-group counting, two-pass sequence and callback assignment, the async, RunSyncGate and disableWAL gates, the sync-group insert of async writers only, PublishOnGroupExit at the group exits, MergeBatch's two passes; WaitForWalDurability's and RunCompletionGate's `published`; RunSyncGate, EndUnpublishedSyncGroup, unpublished_sync_groups_ and WaitForUnpublishedSyncGroups (WaitForPendingWrites, TEST_SwitchMemtable); test SyncLedGroupAsyncWritersReturnBeforeFsync; removal of AsyncWriteDoesNotWaitForOtherPartitionsSync (exception X18: this diff's test by histogram blame).
- X17 hand-port: here RunSyncGate's failure branch publishes the failed range as a hole (FailUnpublishedSyncRange's no-background-error branch) and calls the one-argument HandleMemTableInsertFailure; D123701876 replaces both. The comments that name FailUnpublishedSyncRange or GC20 Q5's failure sharing carry this diff's wording until D123701876.
- Net-zero pairs dropped here (rule 2.7): 6 (GC18#15, #16, #24, #32, meta#85, meta#86).
Known verification gap: this diff's text of the D-9 gate was first built at M4.

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, transaction_test); 5402 tests, 0 failed.

M5 fold: Absorbs 34 A.1 entries (GC28 1, GC27 7, GC29a 5, GC31 10, GC33 1, GC29b 10): GC28 Q8: wal_durability_wait_mutex_, WalDurabilityParking, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation; GC27 Q2 (LockWAL, SetDBOptions and import wait for unpublished sync groups, LockWalWaitsForPendingSyncGroup) and Q4's tailing bound (its two tailing tests go to D123701876, X25-M5); GC31 Q3 (EndUnpublishedSyncGroup signals only an announced waiter), A10/A13; GC33's N>1-only waiter announcement; GC29a/GC29b transaction-test cleanup (JoinThreadsOnExit), SyncLedGroupAsyncMembersReturnBeforeFsync, ImportWaitsForPendingSyncGroup. Not here after B.1: GC28 Q8's parking cluster (WalDurabilityParking, wal_durability_wait_mutex_, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation) goes to D123701876 (X33-M5), and JoinThreadsOnExit to D123079329 (X32-M5). Exceptions: GC28's gate-sync rework is not here (X1-M5); GC27's 2PC wait is not here (X6-M5); X25-M5. Hand-splits (rows below the hunk's top row get their slice by a per-row edit): GC31#347 (db_impl.h test accessors): TEST_wals_total_size via WalsTotalSize() at D121858039, TEST_CachedRecoverableStateEmpty at D123079329, TEST_UnpublishedSyncGroups at D123551605.

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, transaction_test); 5413 tests, 0 failed.

M6 fold: Absorbs GC34 Q3 comments (`CancelAllBackgroundWork`, `CloseHelper`: an applied waiter keeps waiting until covered or fenced) and GC34 Q5 (b): the two named `db_wal_test` tests use EXPECT while a thread is joinable, and `SyncClosedWalsEmptiedByWaitLeavesLaterMark` releases its parked threads and fails when the flush did not rotate; `SyncLedGroupAsyncWritersReturnBeforeFsync` releases and fails when W0 never reaches its append; EXPECT sweeps in `LockWalWaitsFor...` and `SwitchWaitsForOther...`.

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

Reviewers: jkangs, rbanerjee2, jewoongh, #rocksdb, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

Differential Revision: https://phabricator.intern.facebook.com/D123551605
JustinGaoF added a commit 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 that referenced this pull request Nov 19, 2026
Summary:
Reviewer question: does every write's completion imply its own record plus
every previous WAL record landed (M2.5), and does every `sync=true` write's
completion imply the same range reached disk on all partitions (M2.6) --
without gating any append, without touching the N=1 path, and without
deadlocking concurrent syncs?

What: a write completes once its own record is written and every previous
WAL record has been completed (prefix property). Groups are sync-
homogeneous, so `sync` selects the frontier: `sync=false` waits on the
buffered frontier (`write()` completion, from 07); `sync=true` waits on the
buffered frontier and then fsyncs all live WALs, which restores the
single-WAL property that a sync flushes all preceding async writes. No
second tracked frontier is needed: the post-wait fsync is guarded by a
pre-sync safe point snapshot, so an uncontended sync pays no extra fsync.

How:
- `WriteGroup::completion_gate` functor, run in `ExitAsBatchGroupLeader`
  after next-leader promotion and before follower completion (R2); one
  waiter per group, followers wake already cleared (R3); follower status
  merges append status with the wait outcome incl. background errors (R4).
- `DBImpl::WaitForWalDurability` (one atomic load fast path, then
  spin/yield/park on `wal_durability_cv_`) + `RunCompletionGate` with the
  conditional post-wait `SyncWAL`/`FlushWAL(true)`. Installed in `WriteImpl`
  and `WriteImplWALOnly` for N > 1 WAL writes with a successful append
  only; N=1, `disableWAL`, and ingestion never install. R1 (append never
  gated) holds by construction: registration/append/Complete precede the
  gate, and `Open` rejects `wal_partitions > 1` with pipelined writes (no
  gate slot in the split exit).
- `SyncWalImpl` claims every live log across all partitions (required now
  that `cur_wal_number_` is the lowest live number), and `MarkLogsSynced`/
  `MarkLogsNotSynced` finish every marked log; without the latter the next
  sync's `PreprocessWrite` hangs on `WalSyncCV`.
- Two base sync-protocol fixes that M2.6 cannot work without (no base test
  covers `sync=true` at N > 1): (1) `wal_sync_mark_mutex_` serializes
  sync-marking -- leadership marks run others-then-own while `SyncWalImpl`
  claims ascending, so concurrent syncs ABBA-deadlock on each other's
  `WalSyncCV` waits; (2) the leadership fsync runs under each partition's
  WAL mutex and `WriteToWAL` takes it around the file records, closing a
  real `AddRecord`-vs-`Sync` buffer race (TSan, heap corruption) on live
  WALs. A wait on `WalSyncCV` parks with the mutex released, so marked
  syncs can always take the mutexes; the take in `WriteToWAL` sits after
  the `log_entry` hook so held-open test appends pin no mutex.

`wal_partitions > 1` is NOT reachable at `Open` in this diff: reopening a
multi-WAL DB (`unindexed multi-WAL recovery`) is still unimplemented, and
stalled-partition handling (09) and rotation (10) are out of scope. N > 1
stays reachable only via the `AllowWalPartitions` test hook or the `experimental_allow_wal_partitions_for_testing` opt-in (indexed WALs only), as on the
base. Evidence: `db_impl_open.cc` still rejects such opens; new tests use
the hook.

Neuter checks: `external_sst_file_test` (ingestion is structurally
excluded -- it never enters `WriteImpl`, verified by caller audit, and the
suite passes unmodified); `CompletionGateNeverInstallsAtOnePartition`
(zero installs across sync/async/disableWAL at N=1). Checks without one:
the crash-recovery prefix oracle (no N > 1 recovery exists to crash
against); `db_stress` (no `wal_partitions` support in the tools).

**Folded in from round 12 (D124911745)**
- The N=1 write path takes exactly the locks the parent took. `WriteToWAL` takes the WAL mutex only when N>1 or under `manual_wal_flush_ && !two_write_queues_` (the parent's rule). Both `wal_sync_mark_mutex_` takes and the per-partition leadership takes are gated on N>1, so base sync-protocol fix (2) above now applies only at N>1. No extra N=1 cost remains.
- Tests: `N1DefaultWritePathTakesPre08Locks`, `N1ManualFlushWritePathTakesPre08Locks`, `N2WritePathTakesPartitionLocks`. Each compares lock-take counts with the parent. Neuter: revert the guards -> the N=1 runs fail.
- The LOCK ORDER comment rewrite starts here and finishes in D123701876.

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07 Q1 gate side: `covered()`/`wal_record`, disableWAL publication gate, comments (AMB-M2-7), the `SignalWalDurabilityWaiters()` line in `PublishAppliedPrefix` (exception X6); GC06's `WalPartitionsRejectionsNameTheirOptions` (exception X2: its pipelined row needs this diff's rejection) with GC11's tracking line, GC06's bypasses and the `SyncWriteSyncsAgainOnlyAfterWait` race fix. Exception X12: `IngestionThenWritesKeepLastSequenceMonotone` (fails below the completion gate). Exception X13: GC07's `SwitchWaitsForOtherPartitionsLeaders` rewrite and `FillAndSwitchMemtable`, with a bounded 1 s wait per step here because `TEST_WalDurabilityWaiters` first exists in D123701876. AMB-M2-8(a): `DisableWalWritesBypassCompletionGate` moves to D123701876.

GitHub migration (2026-10-23): two `db_write_test.cc` comments use `--` instead of em dashes, so upstream `make check-sources` (ASCII only) passes. Comment-only.

M3 fold: Absorbs
- GC17 Q1 (D-G11 (c)): above one partition a sync write fsyncs from its completion gate, coalesced (RunCoalescedGateSync, SyncWalsFromCompletionGate, SyncEveryWalPartition); PreprocessWrite and WriteGroupToWAL sync only at N=1; WalContext::pre_sync_safe_point and wal_sync_micros are gone; AsyncWriteDoesNotWaitForOtherPartitionsSync; PostWaitSyncErrorFailsSyncWrite synchronization; the sync_failed_wal_number comment (AMB-M3-7). Exception X9 (AMB-M3-9): SyncEveryWalPartition and the gate's claim are hand-ported to this diff's inline WalLogs(p) loops (with the X5 attribution line); D123971668 re-extracts them into SyncWalPartitionFiles and ClaimWalPartitionForLeadershipSync.
- GC08 Q7: post-memtable callbacks run inside the completion-gate wrapper, the exit loops skip them, and the snapshot-callback assertions flip at N>1.
- GC09 Q2: CancelAllBackgroundWork wakes parked gates; CloseHelper waits for them to leave; the RunCompletionGate:BeforeWait sync point; the waiter-count comment. Exception X8: GC09's park-loop rewrite is hand-ported here as the shutdown exit, the waiter count kept under sequence_wal_index_mutex_ and the last-out signal; D123701876 replaces the background-error exit with the fence exits.
- GC12 IngestionAfterDisableWalWriteFindsRangesIdle (exception X2: it needs the DisableWalPut fixture helper, which this diff adds).

Changes visible to existing users:
- WriteThread::WriteGroup grows by two std::function members and a Status. Group leader and follower exits each check one more condition. No gate is installed at wal_partitions = 1.
- SnapshotList::New() now inserts in sequence order by walking from the tail instead of appending. When snapshots arrive in order (always at wal_partitions = 1) this costs one comparison.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 98
  (incl. 9 new tests x2 params + `SwitchWaitsForOtherPartitionsLeaders`
  rescripted: fill/switch-trigger puts are now `disableWAL` since WAL puts
  after a held-open pre-record append cannot return by design; plus a
  rendezvous so the switch deterministically meets the open append).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test` -- Pass 346.
- `buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test` -- Pass 3106.
- `buck2 test fbcode//internal_repo_rocksdb/repo:external_sst_file_test` -- Pass 285.
- TSan (`@fbcode//mode/dev-tsan`): partition suite Pass 34, N=1 gate test
  Pass 3. Full-suite TSan: not run (partition concurrency + N=1 cover the
  changed code).
- `arc lint -a` on all 7 touched files: clean.
- R6 `db_bench` `fillseq` A/B at N=1 (base `60bb245c3869` vs this commit):
  base 58.3/61.9/60.7 vs mine 59.2/61.5/63.0 micros/op (means 60.3 vs 61.2, +1.5%, within base run-to-run spread +-3%): no measurable regression.
- Prefix-property crash oracle: not run -- N > 1 recovery is unimplemented
  (`Open` rejects such reopens), so no recovered state exists to assert
  on. In-diff evidence is the completion-gate mechanism tests (a write
  observably does not return until every previous record landed) plus the
  M2.6 post-wait all-partition fsync (a synced write's predecessors are on
  disk before it returns).
- Mixed `sync` `db_stress` + blackbox crash test: not run -- the tools have
  no `wal_partitions` support and N > 1 recovery is unimplemented. Nearest
  in-diff coverage: `MixedSyncWritesCompleteUnderConcurrency` (sync/async
  across 4 partitions + external flush thread + auto-switches).

**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 194, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/13792274068178608).
- 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 GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
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: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 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: 2285 pass.

M4 fold: Absorbs
- GC18 Q8 plumbing (exception X1: RunCompletionGate and RunCoalescedGateSync take `low`), Q10 RunCoalescedGateSync:BeforeWait sync point, Q11 sync-point renames and their tests.
- GC20 Q1: gate-sync epoch coverage (started and synced epochs, needed_epoch; exception X2: hand-split from the failure half, which is D123701876's, AMB-M4-1).
- GC22 Q1: the timestamped-snapshot reservation (CreateTimestampedSnapshotImpl, WriteImpl's post-memtable callback, SnapshotList::New sorted insert, TimestampedSnapshotList::GetLatestAtOrBelow) with the H2 repros and GC22's tests; GC23 Q7 (CommitAndTryCreateSnapshot doc, GC23SnapshotReservationInProperties).
- GC25 Q1/Q2/Q5, the D-9 core (exception X17, AMB-M4-19): WriteGroup::sync_first_sequence, async_writers_gate and CompleteAsyncWriters; WriteImpl's sync-group counting, two-pass sequence and callback assignment, the async, RunSyncGate and disableWAL gates, the sync-group insert of async writers only, PublishOnGroupExit at the group exits, MergeBatch's two passes; WaitForWalDurability's and RunCompletionGate's `published`; RunSyncGate, EndUnpublishedSyncGroup, unpublished_sync_groups_ and WaitForUnpublishedSyncGroups (WaitForPendingWrites, TEST_SwitchMemtable); test SyncLedGroupAsyncWritersReturnBeforeFsync; removal of AsyncWriteDoesNotWaitForOtherPartitionsSync (exception X18: this diff's test by histogram blame).
- X17 hand-port: here RunSyncGate's failure branch publishes the failed range as a hole (FailUnpublishedSyncRange's no-background-error branch) and calls the one-argument HandleMemTableInsertFailure; D123701876 replaces both. The comments that name FailUnpublishedSyncRange or GC20 Q5's failure sharing carry this diff's wording until D123701876.
- Net-zero pairs dropped here (rule 2.7): 6 (GC18#15, #16, #24, #32, meta#85, meta#86).
Known verification gap: this diff's text of the D-9 gate was first built at M4.

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, transaction_test); 5402 tests, 0 failed.

M5 fold: Absorbs 34 A.1 entries (GC28 1, GC27 7, GC29a 5, GC31 10, GC33 1, GC29b 10): GC28 Q8: wal_durability_wait_mutex_, WalDurabilityParking, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation; GC27 Q2 (LockWAL, SetDBOptions and import wait for unpublished sync groups, LockWalWaitsForPendingSyncGroup) and Q4's tailing bound (its two tailing tests go to D123701876, X25-M5); GC31 Q3 (EndUnpublishedSyncGroup signals only an announced waiter), A10/A13; GC33's N>1-only waiter announcement; GC29a/GC29b transaction-test cleanup (JoinThreadsOnExit); SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup first exist at D123928339, not here. Not here after B.1: GC28 Q8's parking cluster (WalDurabilityParking, wal_durability_wait_mutex_, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation) goes to D123701876 (X33-M5), and JoinThreadsOnExit to D123079329 (X32-M5). Exceptions: GC28's gate-sync rework is not here (X1-M5); GC27's 2PC wait is not here (X6-M5); X25-M5. Hand-splits (rows below the hunk's top row get their slice by a per-row edit): GC31#347 (db_impl.h test accessors): TEST_wals_total_size via WalsTotalSize() at D121858039, TEST_CachedRecoverableStateEmpty at D123079329, TEST_UnpublishedSyncGroups at D123551605.

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, transaction_test); 5413 tests, 0 failed.

M6 fold: Absorbs GC34 Q3 comments (`CancelAllBackgroundWork`, `CloseHelper`: an applied waiter keeps waiting until covered or fenced) and GC34 Q5 (b): the two named `db_wal_test` tests use EXPECT while a thread is joinable, and `SyncClosedWalsEmptiedByWaitLeavesLaterMark` releases its parked threads and fails when the flush did not rotate; `SyncLedGroupAsyncWritersReturnBeforeFsync` releases and fails when W0 never reaches its append; EXPECT sweeps in `LockWalWaitsFor...` and `SwitchWaitsForOther...`.

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

Reviewers: jkangs, rbanerjee2, jewoongh, #rocksdb, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

Differential Revision: https://phabricator.intern.facebook.com/D123551605
JustinGaoF added a commit 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 that referenced this pull request Nov 19, 2026
Summary:
Reviewer question: does every write's completion imply its own record plus
every previous WAL record landed (M2.5), and does every `sync=true` write's
completion imply the same range reached disk on all partitions (M2.6) --
without gating any append, without touching the N=1 path, and without
deadlocking concurrent syncs?

What: a write completes once its own record is written and every previous
WAL record has been completed (prefix property). Groups are sync-
homogeneous, so `sync` selects the frontier: `sync=false` waits on the
buffered frontier (`write()` completion, from 07); `sync=true` waits on the
buffered frontier and then fsyncs all live WALs, which restores the
single-WAL property that a sync flushes all preceding async writes. No
second tracked frontier is needed: the post-wait fsync is guarded by a
pre-sync safe point snapshot, so an uncontended sync pays no extra fsync.

How:
- `WriteGroup::completion_gate` functor, run in `ExitAsBatchGroupLeader`
  after next-leader promotion and before follower completion (R2); one
  waiter per group, followers wake already cleared (R3); follower status
  merges append status with the wait outcome incl. background errors (R4).
- `DBImpl::WaitForWalDurability` (one atomic load fast path, then
  spin/yield/park on `wal_durability_cv_`) + `RunCompletionGate` with the
  conditional post-wait `SyncWAL`/`FlushWAL(true)`. Installed in `WriteImpl`
  and `WriteImplWALOnly` for N > 1 WAL writes with a successful append
  only; N=1, `disableWAL`, and ingestion never install. R1 (append never
  gated) holds by construction: registration/append/Complete precede the
  gate, and `Open` rejects `wal_partitions > 1` with pipelined writes (no
  gate slot in the split exit).
- `SyncWalImpl` claims every live log across all partitions (required now
  that `cur_wal_number_` is the lowest live number), and `MarkLogsSynced`/
  `MarkLogsNotSynced` finish every marked log; without the latter the next
  sync's `PreprocessWrite` hangs on `WalSyncCV`.
- Two base sync-protocol fixes that M2.6 cannot work without (no base test
  covers `sync=true` at N > 1): (1) `wal_sync_mark_mutex_` serializes
  sync-marking -- leadership marks run others-then-own while `SyncWalImpl`
  claims ascending, so concurrent syncs ABBA-deadlock on each other's
  `WalSyncCV` waits; (2) the leadership fsync runs under each partition's
  WAL mutex and `WriteToWAL` takes it around the file records, closing a
  real `AddRecord`-vs-`Sync` buffer race (TSan, heap corruption) on live
  WALs. A wait on `WalSyncCV` parks with the mutex released, so marked
  syncs can always take the mutexes; the take in `WriteToWAL` sits after
  the `log_entry` hook so held-open test appends pin no mutex.

`wal_partitions > 1` is NOT reachable at `Open` in this diff: reopening a
multi-WAL DB (`unindexed multi-WAL recovery`) is still unimplemented, and
stalled-partition handling (09) and rotation (10) are out of scope. N > 1
stays reachable only via the `AllowWalPartitions` test hook or the `experimental_allow_wal_partitions_for_testing` opt-in (indexed WALs only), as on the
base. Evidence: `db_impl_open.cc` still rejects such opens; new tests use
the hook.

Neuter checks: `external_sst_file_test` (ingestion is structurally
excluded -- it never enters `WriteImpl`, verified by caller audit, and the
suite passes unmodified); `CompletionGateNeverInstallsAtOnePartition`
(zero installs across sync/async/disableWAL at N=1). Checks without one:
the crash-recovery prefix oracle (no N > 1 recovery exists to crash
against); `db_stress` (no `wal_partitions` support in the tools).

**Folded in from round 12 (D124911745)**
- The N=1 write path takes exactly the locks the parent took. `WriteToWAL` takes the WAL mutex only when N>1 or under `manual_wal_flush_ && !two_write_queues_` (the parent's rule). Both `wal_sync_mark_mutex_` takes and the per-partition leadership takes are gated on N>1, so base sync-protocol fix (2) above now applies only at N>1. No extra N=1 cost remains.
- Tests: `N1DefaultWritePathTakesPre08Locks`, `N1ManualFlushWritePathTakesPre08Locks`, `N2WritePathTakesPartitionLocks`. Each compares lock-take counts with the parent. Neuter: revert the guards -> the N=1 runs fail.
- The LOCK ORDER comment rewrite starts here and finishes in D123701876.

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07 Q1 gate side: `covered()`/`wal_record`, disableWAL publication gate, comments (AMB-M2-7), the `SignalWalDurabilityWaiters()` line in `PublishAppliedPrefix` (exception X6); GC06's `WalPartitionsRejectionsNameTheirOptions` (exception X2: its pipelined row needs this diff's rejection) with GC11's tracking line, GC06's bypasses and the `SyncWriteSyncsAgainOnlyAfterWait` race fix. Exception X12: `IngestionThenWritesKeepLastSequenceMonotone` (fails below the completion gate). Exception X13: GC07's `SwitchWaitsForOtherPartitionsLeaders` rewrite and `FillAndSwitchMemtable`, with a bounded 1 s wait per step here because `TEST_WalDurabilityWaiters` first exists in D123701876. AMB-M2-8(a): `DisableWalWritesBypassCompletionGate` moves to D123701876.

GitHub migration (2026-10-23): two `db_write_test.cc` comments use `--` instead of em dashes, so upstream `make check-sources` (ASCII only) passes. Comment-only.

M3 fold: Absorbs
- GC17 Q1 (D-G11 (c)): above one partition a sync write fsyncs from its completion gate, coalesced (RunCoalescedGateSync, SyncWalsFromCompletionGate, SyncEveryWalPartition); PreprocessWrite and WriteGroupToWAL sync only at N=1; WalContext::pre_sync_safe_point and wal_sync_micros are gone; AsyncWriteDoesNotWaitForOtherPartitionsSync; PostWaitSyncErrorFailsSyncWrite synchronization; the sync_failed_wal_number comment (AMB-M3-7). Exception X9 (AMB-M3-9): SyncEveryWalPartition and the gate's claim are hand-ported to this diff's inline WalLogs(p) loops (with the X5 attribution line); D123971668 re-extracts them into SyncWalPartitionFiles and ClaimWalPartitionForLeadershipSync.
- GC08 Q7: post-memtable callbacks run inside the completion-gate wrapper, the exit loops skip them, and the snapshot-callback assertions flip at N>1.
- GC09 Q2: CancelAllBackgroundWork wakes parked gates; CloseHelper waits for them to leave; the RunCompletionGate:BeforeWait sync point; the waiter-count comment. Exception X8: GC09's park-loop rewrite is hand-ported here as the shutdown exit, the waiter count kept under sequence_wal_index_mutex_ and the last-out signal; D123701876 replaces the background-error exit with the fence exits.
- GC12 IngestionAfterDisableWalWriteFindsRangesIdle (exception X2: it needs the DisableWalPut fixture helper, which this diff adds).

Changes visible to existing users:
- WriteThread::WriteGroup grows by two std::function members and a Status. Group leader and follower exits each check one more condition. No gate is installed at wal_partitions = 1.
- SnapshotList::New() now inserts in sequence order by walking from the tail instead of appending. When snapshots arrive in order (always at wal_partitions = 1) this costs one comparison.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` -- Pass 98
  (incl. 9 new tests x2 params + `SwitchWaitsForOtherPartitionsLeaders`
  rescripted: fill/switch-trigger puts are now `disableWAL` since WAL puts
  after a held-open pre-record append cannot return by design; plus a
  rendezvous so the switch deterministically meets the open append).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test` -- Pass 2031.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test` -- Pass 346.
- `buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test` -- Pass 3106.
- `buck2 test fbcode//internal_repo_rocksdb/repo:external_sst_file_test` -- Pass 285.
- TSan (`@fbcode//mode/dev-tsan`): partition suite Pass 34, N=1 gate test
  Pass 3. Full-suite TSan: not run (partition concurrency + N=1 cover the
  changed code).
- `arc lint -a` on all 7 touched files: clean.
- R6 `db_bench` `fillseq` A/B at N=1 (base `60bb245c3869` vs this commit):
  base 58.3/61.9/60.7 vs mine 59.2/61.5/63.0 micros/op (means 60.3 vs 61.2, +1.5%, within base run-to-run spread +-3%): no measurable regression.
- Prefix-property crash oracle: not run -- N > 1 recovery is unimplemented
  (`Open` rejects such reopens), so no recovered state exists to assert
  on. In-diff evidence is the completion-gate mechanism tests (a write
  observably does not return until every previous record landed) plus the
  M2.6 post-wait all-partition fsync (a synced write's predecessors are on
  disk before it returns).
- Mixed `sync` `db_stress` + blackbox crash test: not run -- the tools have
  no `wal_partitions` support and N > 1 recovery is unimplemented. Nearest
  in-diff coverage: `MixedSyncWritesCompleteUnderConcurrency` (sync/async
  across 4 partitions + external flush thread + auto-switches).

**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 194, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/13792274068178608).
- 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 GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
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: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 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: 2285 pass.

M4 fold: Absorbs
- GC18 Q8 plumbing (exception X1: RunCompletionGate and RunCoalescedGateSync take `low`), Q10 RunCoalescedGateSync:BeforeWait sync point, Q11 sync-point renames and their tests.
- GC20 Q1: gate-sync epoch coverage (started and synced epochs, needed_epoch; exception X2: hand-split from the failure half, which is D123701876's, AMB-M4-1).
- GC22 Q1: the timestamped-snapshot reservation (CreateTimestampedSnapshotImpl, WriteImpl's post-memtable callback, SnapshotList::New sorted insert, TimestampedSnapshotList::GetLatestAtOrBelow) with the H2 repros and GC22's tests; GC23 Q7 (CommitAndTryCreateSnapshot doc, GC23SnapshotReservationInProperties).
- GC25 Q1/Q2/Q5, the D-9 core (exception X17, AMB-M4-19): WriteGroup::sync_first_sequence, async_writers_gate and CompleteAsyncWriters; WriteImpl's sync-group counting, two-pass sequence and callback assignment, the async, RunSyncGate and disableWAL gates, the sync-group insert of async writers only, PublishOnGroupExit at the group exits, MergeBatch's two passes; WaitForWalDurability's and RunCompletionGate's `published`; RunSyncGate, EndUnpublishedSyncGroup, unpublished_sync_groups_ and WaitForUnpublishedSyncGroups (WaitForPendingWrites, TEST_SwitchMemtable); test SyncLedGroupAsyncWritersReturnBeforeFsync; removal of AsyncWriteDoesNotWaitForOtherPartitionsSync (exception X18: this diff's test by histogram blame).
- X17 hand-port: here RunSyncGate's failure branch publishes the failed range as a hole (FailUnpublishedSyncRange's no-background-error branch) and calls the one-argument HandleMemTableInsertFailure; D123701876 replaces both. The comments that name FailUnpublishedSyncRange or GC20 Q5's failure sharing carry this diff's wording until D123701876.
- Net-zero pairs dropped here (rule 2.7): 6 (GC18#15, #16, #24, #32, meta#85, meta#86).
Known verification gap: this diff's text of the D-9 gate was first built at M4.

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, transaction_test); 5402 tests, 0 failed.

M5 fold: Absorbs 34 A.1 entries (GC28 1, GC27 7, GC29a 5, GC31 10, GC33 1, GC29b 10): GC28 Q8: wal_durability_wait_mutex_, WalDurabilityParking, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation; GC27 Q2 (LockWAL, SetDBOptions and import wait for unpublished sync groups, LockWalWaitsForPendingSyncGroup) and Q4's tailing bound (its two tailing tests go to D123701876, X25-M5); GC31 Q3 (EndUnpublishedSyncGroup signals only an announced waiter), A10/A13; GC33's N>1-only waiter announcement; GC29a/GC29b transaction-test cleanup (JoinThreadsOnExit); SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup first exist at D123928339, not here. Not here after B.1: GC28 Q8's parking cluster (WalDurabilityParking, wal_durability_wait_mutex_, WalDurabilityCovered, the targeted wake, CloseHelper's and CancelAllBackgroundWork's lock lines, FrontierLockTakenOnlyForAllocation) goes to D123701876 (X33-M5), and JoinThreadsOnExit to D123079329 (X32-M5). Exceptions: GC28's gate-sync rework is not here (X1-M5); GC27's 2PC wait is not here (X6-M5); X25-M5. Hand-splits (rows below the hunk's top row get their slice by a per-row edit): GC31#347 (db_impl.h test accessors): TEST_wals_total_size via WalsTotalSize() at D121858039, TEST_CachedRecoverableStateEmpty at D123079329, TEST_UnpublishedSyncGroups at D123551605.

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, transaction_test); 5413 tests, 0 failed.

M6 fold: Absorbs GC34 Q3 comments (`CancelAllBackgroundWork`, `CloseHelper`: an applied waiter keeps waiting until covered or fenced) and GC34 Q5 (b): the two named `db_wal_test` tests use EXPECT while a thread is joinable, and `SyncClosedWalsEmptiedByWaitLeavesLaterMark` releases its parked threads and fails when the flush did not rotate; `SyncLedGroupAsyncWritersReturnBeforeFsync` releases and fails when W0 never reaches its append; EXPECT sweeps in `LockWalWaitsFor...` and `SwitchWaitsForOther...`.

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

Reviewers: jkangs, rbanerjee2, jewoongh, #rocksdb, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

Differential Revision: https://phabricator.intern.facebook.com/D123551605
JustinGaoF added a commit 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant